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(render): a run of mesh draws that differ only by their geometry and records is one call - with WEBGL_multi_draw, each draw reads its record base and probe offset by gl_DrawID from one block staged for the run, so a run binds its blocks once and draws once

yhhc2cf48f56d23
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4deebc24b..ef33c6ee9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -41,6 +41,7 @@ published separately; it ships inside the editor.
- **A model's report is its steps as written, and names a step that undoes a decimate.** `report.steps` of a baked model listed every plain step its repeats came to, by an index among those: a spruce of thirteen rows of branches reported a hundred and thirty-eight steps, most the same line, and none under the index `model_edit` takes. It is now one entry for each step as written, by that index, a repeat counted once with how many steps it `made`, and each entry says the `triangles` the mesh had after it. And a step that splits faces to carry its own detail (a stain by a pattern, a displace, a sculpt) after a `decimate` took the decimate's triangles back in silence: a rock thinned to 1100 came out at 214,534, under the 300,000 the report calls heavy, and a field of them would have been gigabytes. The report now warns of each such step, with what it was given, what it left and which decimate it undid, and says how to keep the detail (before the decimate, carried by `normalBake`) or bound it (`detail`). The test also notes what the advice costs: a pattern stained before a decimate leaves colour seams the decimate will not cross, so it is `normalBake`'s `color: true` that carries it.
- **A playable's start-screen bar moves through the whole boot.** The bar's stages were weighed for a web page, most of whose start is fetching the engine. A playable has the engine inlined, so its bar stood at 82% within a second and crawled to 95% over the twenty-five that followed. A playable now weighs its own stages (the scene's is four fifths of the bar), and that stage is followed in three stretches: assets being read and made (eased by the clock, since nothing counts them), shaders compiled against the most seen compiling, and the world prepared against the most its makers said was left. For that, a hold given to `holdShaderWarmup` may answer a number (pages, cells) where it answered yes, and `warmShaders` passes the sum to `onProgress`; Terrain and Foliage count theirs. One lake scene's bar went from 18% to 95% over its 22 seconds, with one stretch of four seconds standing still. `attachSplash` takes the weights.
- **An effect chain keeps its uniform buffers from frame to frame.** A camera's post-process chain is said again every frame, and each of its passes made a uniform buffer for its parameters and deleted it when the chain was cleared: seventeen buffers created and seventeen deleted every frame for a lake scene with a volume's usual effects, counted in the GL calls of an exported page. The buffers of a cleared chain are now taken over by the passes of the next chain that need one the same size, and one that nothing has taken in eight clears is deleted. The same scene creates none in a steady frame.
+- **A run of mesh draws is one call on WebGL2.** Consecutive mesh draws that differ only in which range of a shared buffer they draw and which objects they place (the same program, material, textures and state) were each a call of their own, with two blocks bound for each: where its objects' records start, and the light probes its objects stand in. Where the browser offers `WEBGL_multi_draw`, such a run is now one call: a block staged once for the run says, for each draw, where its records and its instances' probes begin, and the vertex stage finds its own by `gl_DrawID`. A run of draws that carry probe light shares one probe block, so it holds at most as many objects as that block does. WebGPU, and a browser without the extension, draw as before. On Bistro at 640x360 the instanced draw calls a frame went from 538 to 71 plus 73 multi-draw calls, uniform-range binds from 1,022 to 276, and the WebGL calls from about 3,100 to about 1,920; the renderer's CPU time went from 1.2 to 1.1 ms. `render.multiDraw.calls` counts the runs drawn.
- **Meshes of one vertex shape share their buffers.** Every mesh was given a vertex buffer, an index buffer and a vertex layout of its own, and a layout is part of a pipeline's key: a scene of five hundred meshes switched vertex arrays five hundred times a frame, and pipelines with them, though most of its meshes had the same few shapes of vertex. Meshes loaded from an asset now take ranges of shared pages, one page set per vertex shape (pages start at 1 MB and double, so a small game pays for little), and a run of them is drawn without switching vertex array, buffers or pipeline. Indices are rebased onto the page when a mesh is placed, since WebGL2 has no base vertex; a mesh with morph targets (whose deltas are found by vertex number) and a mesh built in the running game keep buffers of their own. After a lost device a page is rebuilt from its meshes' sources, each into a page of the new device. On Bistro at 640x360 the vertex-array binds a frame went from 540 to 55 and the WebGL calls from 3,627 to 3,102, and the renderer's CPU time from 1.6-1.8 ms to 1.2 ms in three runs each (the frame, which something else bounds at this size, stayed at 6.0 ms). `ResourceManager::meshPageCount` and `meshPageBytes` say what the pages hold.
- **A shadow map is drawn again only when what it holds changed.** Every shadow-casting mesh was drawn into the shadow atlas every frame for every light, though in most frames nothing in a map had moved: Bistro drew 891 casters a frame for a sun and a scene that were both still. The atlas is now kept from frame to frame, and the frame compares what its squares would draw (where each looks from, the casters, their transforms, bones and shapes, the materials of cut-out casters) with what was last drawn into them, and skips the pass when they are the same. A caster that moves, a light that turns, a camera that walks the sun's cascades on to the next texel, a lost device or geometry rewritten in place draw it again. A material that moves its vertices (wind, a ground's height) is assumed to move them every frame, so a map it casts into is always drawn. On Bistro at 640x360 the WebGL calls a frame went from 7,139 to 3,627 and the renderer's CPU time from 3.3 to 2.3 ms. `render.shadow.reused` says whether a frame drew the atlas.
- **Walking a frame's meshes costs less, and the profiler says what it costs.** Every mesh, in every view, asked its material's layout several questions by name (does it read the picture behind it, is its alpha coverage, does it cut out a shadow), each a string search; they are answered once when the layout is registered, and the last material and layout asked for are kept. A child of a model (most of an imported scene's meshes) was decomposed afresh by every view of every frame though its matrix had not changed; it is decomposed again only when it moves. And the mesh walk read the clock at every phase of every mesh while profiled, which was four in ten samples of a profiled frame and most of the time it reported; it is timed whole (the split by phase is the build option `ES_PROFILE_COLLECT_PHASES`). On the Bistro scene at 640x360, the best of seven interleaved runs went from 9.97 to 6.83 ms a frame, and a grid of 4096 meshes on one material from 4.08 to 3.09 ms. `render-submit-cost.mjs --wall` times frames with the profiler off.
diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cpp
index 83ebc75cc..b70e24e6a 100644
--- a/src/esengine/renderer/draw/DrawList.cpp
+++ b/src/esengine/renderer/draw/DrawList.cpp
@@ -308,11 +308,90 @@ std::span<const Entity> DrawList::runEntities(u32 index) const {
return {run_entities_.data() + first, end - first};
}
-void DrawList::stageBlocks(const PerDrawBlockSet& blocks) {
+bool DrawList::joinsRun(const DrawCommand& p, const DrawCommand& c) {
+ // A mesh drawn through its records, with nothing of its own that lives in a block but its records and its light: a pose, shapes
+ // and a mirror each are a block per draw. In one call the draws are still drawn in order, so blended ones may share one too.
+ const auto runnable = [](const DrawCommand& d) {
+ return d.hasPersistentGeometry() && d.instance_count != 0 && d.instance_buffer == BufferHandle::Invalid
+ && d.layout_id == LayoutId::MeshInstance && d.skin_count == 0 && d.morph_index == 0 && d.planar_index == 0;
+ };
+ if (!runnable(p) || !runnable(c)) return false;
+ // Everything the draw binds or sets, the same: the pipeline's every input, its textures, its material, its dynamic state.
+ return p.vertex_buffer == c.vertex_buffer && p.index_buffer == c.index_buffer && p.vertex_layout == c.vertex_layout
+ && p.shader_id == c.shader_id && p.depth_shader_id == c.depth_shader_id && p.material_id == c.material_id
+ && p.blend_mode == c.blend_mode && p.depth_test == c.depth_test && p.depth_write == c.depth_write && p.cull == c.cull
+ && p.depth_bias == c.depth_bias && p.topology == c.topology && p.stage == c.stage && p.state_flags == c.state_flags
+ && (!(p.state_flags & CMD_STATE_SCISSOR) || p.scissor == c.scissor) && p.stencil_ref == c.stencil_ref
+ && p.texture_count == c.texture_count && std::equal(p.texture_ids, p.texture_ids + p.texture_count, c.texture_ids);
+}
+
+void DrawList::stageBlocks(const PerDrawBlockSet& blocks, bool runs) {
staged_.assign(merged_draw_calls_, StagedBlocks{});
+ run_length_.assign(merged_draw_calls_, 1u);
+ const auto probeLitAt = [&](const DrawCommand& cmd) {
+ const u32 n = std::min(cmd.instance_count > 0 ? cmd.instance_count : 1u, PROBE_MAX_INSTANCES);
+ for (u32 k = 0; k < n; ++k) {
+ const size_t at = static_cast<size_t>(cmd.probe_base) + k;
+ if (at < probe_slots_.size() && probe_slots_[at] != 0) return true;
+ }
+ return false;
+ };
+ // The runs: draws that differ only by their geometry's range and their records, drawn by one call where the device can. Their
+ // instances share the run's probe block, so a run that carries light holds no more instances than the block does.
+ if (runs && blocks.instance && blocks.probe) {
+ u32 head = 0, instances = 0;
+ bool lit = false;
+ for (u32 i = 0; i < merged_draw_calls_; ++i) {
+ const DrawCommand& cmd = commands_[i];
+ const bool cmdLit = probeLitAt(cmd);
+ if (i > 0 && run_length_[head] < MULTI_DRAW_MAX && joinsRun(commands_[i - 1], cmd)
+ && !((lit || cmdLit) && instances + cmd.instance_count > PROBE_MAX_INSTANCES)) {
+ ++run_length_[head];
+ run_length_[i] = 0;
+ instances += cmd.instance_count;
+ lit = lit || cmdLit;
+ continue;
+ }
+ head = i;
+ instances = cmd.instance_count;
+ lit = cmdLit;
+ }
+ }
for (u32 i = 0; i < merged_draw_calls_; ++i) {
const auto& cmd = commands_[i];
StagedBlocks& staged = staged_[i];
+ const u32 length = run_length_[i];
+ if (length == 0) continue; // inside a run: its head staged for it
+ if (length > 1) {
+ // One probe block for the run, its draws' instances one after another, and an entry per draw saying where its records
+ // and its instances begin.
+ run_entries_.assign(length, InstanceConstants{});
+ bool anyLit = false;
+ u32 instances = 0;
+ for (u32 k = 0; k < length; ++k) {
+ const DrawCommand& member = commands_[i + k];
+ run_entries_[k].base = member.vertex_byte_offset / MESH_INSTANCE_STRIDE;
+ run_entries_[k].pad[0] = instances;
+ instances += member.instance_count;
+ anyLit = anyLit || probeLitAt(member);
+ }
+ if (anyLit) {
+ probe_run_.assign(static_cast<size_t>(instances) * PROBE_TEXELS, glm::vec4(0.0f));
+ u32 at = 0;
+ for (u32 k = 0; k < length; ++k) {
+ const DrawCommand& member = commands_[i + k];
+ for (u32 n = 0; n < member.instance_count; ++n, ++at) {
+ const size_t slot = static_cast<size_t>(member.probe_base) + n;
+ const u32 index = slot < probe_slots_.size() ? probe_slots_[slot] : 0u;
+ if (index == 0) continue;
+ std::memcpy(&probe_run_[static_cast<size_t>(at) * PROBE_TEXELS], &probes_[index - 1], sizeof(ProbeConstants));
+ }
+ }
+ staged.probe = blocks.probe->stage(probe_run_.data(), static_cast<u32>(probe_run_.size() * sizeof(glm::vec4)));
+ }
+ staged.instance = blocks.instance->stage(run_entries_.data(), static_cast<u32>(length * sizeof(InstanceConstants)));
+ continue;
+ }
if (blocks.planar && cmd.planar_index > 0) {
staged.planar = blocks.planar->stage(&planar_[cmd.planar_index - 1], sizeof(PlanarConstants));
@@ -444,10 +523,17 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
device.bindTexture(MESH_INSTANCE_TEXTURE_UNIT, buffers.instanceTexture());
}
- // The colour pass after a prepass is the same list the prepass staged the per-draw blocks for.
- if (!afterPrepass) stageBlocks(blocks);
-
- for (u32 i = 0; i < merged_draw_calls_; ++i) {
+ // The colour pass after a prepass is the same list the prepass staged the per-draw blocks for. Runs where the device draws them
+ // as one call, and not while a capture records or replays draw by draw.
+ const bool capturing = capture && (capture->isCapturing() || capture->isReplaying());
+ if (!afterPrepass) stageBlocks(blocks, device.supportsMultiDraw() && !capturing);
+ if (run_length_.size() != merged_draw_calls_) run_length_.assign(merged_draw_calls_, 1u);
+ u32 runCalls = 0;
+
+ for (u32 i = 0, next = 0; i < merged_draw_calls_; i = next) {
+ // A run is taken or passed over whole: its draws agree on everything a pass or a phase asks of them.
+ next = i + std::max(run_length_[i], 1u);
+ const u32 runLength = std::max(run_length_[i], 1u);
const auto& cmd = commands_[i];
const StagedBlocks& staged = staged_[i];
if (prepass && !takesPartInPrepass(cmd)) continue;
@@ -587,7 +673,20 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
device.setVertexBuffer(0, cmd.vertex_buffer, 0);
device.setIndexBuffer(cmd.index_buffer);
const u32 firstIndexByte = static_cast<u32>(static_cast<uintptr_t>(cmd.index_offset) * sizeof(u32));
- if (cmd.instance_count != 0) {
+ if (runLength > 1) {
+ run_counts_.resize(runLength);
+ run_offsets_.resize(runLength);
+ run_instances_.resize(runLength);
+ for (u32 k = 0; k < runLength; ++k) {
+ const DrawCommand& member = commands_[i + k];
+ run_counts_[k] = member.index_count;
+ run_offsets_[k] = static_cast<u32>(static_cast<uintptr_t>(member.index_offset) * sizeof(u32));
+ run_instances_[k] = member.instance_count;
+ }
+ device.drawElementsInstancedMulti(GfxDataType::UnsignedInt, run_counts_.data(), run_offsets_.data(),
+ run_instances_.data(), runLength);
+ ++runCalls;
+ } else if (cmd.instance_count != 0) {
device.drawElementsInstanced(cmd.index_count, GfxDataType::UnsignedInt, firstIndexByte, cmd.instance_count);
} else {
device.drawElements(cmd.index_count, GfxDataType::UnsignedInt, firstIndexByte);
@@ -613,10 +712,11 @@ void DrawList::execute(GfxDevice& device, TransientBufferPool& buffers,
if (capture->isReplaying()) {
if (capture->stepReplay()) break;
} else if (capture->isCapturing()) {
- capture->record(cmd, runEntities(i));
+ for (u32 k = 0; k < runLength; ++k) capture->record(commands_[i + k], runEntities(i + k));
}
}
}
+ if (runCalls > 0) FrameProfiler::get().counter("render.multiDraw.calls", runCalls);
}
u64 DrawList::contentHash(u64 h) const {
diff --git a/src/esengine/renderer/draw/DrawList.hpp b/src/esengine/renderer/draw/DrawList.hpp
index fda352df8..b6907b8ff 100644
--- a/src/esengine/renderer/draw/DrawList.hpp
+++ b/src/esengine/renderer/draw/DrawList.hpp
@@ -9,6 +9,7 @@
#include "../frame/FrameCapture.hpp"
#include "../store/MorphConstants.hpp"
#include "../store/ProbeConstants.hpp"
+#include "../store/InstanceConstants.hpp"
#include "../rhi/PerDrawBlocks.hpp"
#include "../../math/Math.hpp"
@@ -281,7 +282,13 @@ private:
PerDrawBlocks::Range skin, morph, probe, instance, planar;
};
std::vector<StagedBlocks> staged_;
- void stageBlocks(const PerDrawBlockSet& blocks);
+ /// Per merged draw: how many draws the run it heads holds (drawn as one call, see stageBlocks), 0 for a draw inside a run.
+ std::vector<u32> run_length_;
+ std::vector<u32> run_counts_, run_offsets_, run_instances_;
+ std::vector<InstanceConstants> run_entries_;
+ /** Whether @p next can be drawn in the same call as @p prev: everything but its geometry's range and its records the same. */
+ static bool joinsRun(const DrawCommand& prev, const DrawCommand& next);
+ void stageBlocks(const PerDrawBlockSet& blocks, bool runs);
/// The sorted order of the last finalize and the keys, in emit order, it was sorted from. The order is a function of the keys alone (ties break on
/// emit index), and in 2D the key holds no position, so a frame of moving sprites has the keys of the frame before it.
std::vector<SortEntry> sort_entries_;
diff --git a/src/esengine/renderer/frame/RenderContext.cpp b/src/esengine/renderer/frame/RenderContext.cpp
index 48b553cd3..8276d8281 100644
--- a/src/esengine/renderer/frame/RenderContext.cpp
+++ b/src/esengine/renderer/frame/RenderContext.cpp
@@ -185,7 +185,10 @@ void RenderContext::initFrameUbo() {
// A run per instance, not one for the draw: the block is what a merged draw
// says about every object in it, and GL wants the whole declared block bound.
probeBlocks_.init(device_, PROBE_BLOCK_BYTES);
- instanceBlocks_.init(device_, static_cast<u32>(sizeof(InstanceConstants)));
+ // An entry per draw of a run where the device draws runs: GL wants the whole declared block bound, and the programs declare
+ // the array exactly when the device enabled them (glslMultiDraw).
+ instanceBlocks_.init(device_, static_cast<u32>(sizeof(InstanceConstants))
+ * (device_.supportsMultiDraw() && glslMultiDraw() ? MULTI_DRAW_MAX : 1u));
planarBlocks_.init(device_, static_cast<u32>(sizeof(PlanarConstants)));
// 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.
diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cpp
index 151274efa..b4bdb8603 100644
--- a/src/esengine/renderer/rhi/GLDevice.cpp
+++ b/src/esengine/renderer/rhi/GLDevice.cpp
@@ -14,9 +14,11 @@
#include "./GLDevice.hpp"
#include "./OpenGLHeaders.hpp"
#include "../../core/Log.hpp"
+#include "../store/InstanceConstants.hpp"
#ifdef __EMSCRIPTEN__
#include <emscripten/html5.h>
+#include <webgl/webgl1_ext.h>
#endif
#include <chrono>
@@ -322,6 +324,15 @@ void GLDevice::init() {
// Depth test and blend were just turned on, but a new context knows nothing the old one was told: nothing is assumed held.
resetDrawStateCaches();
captureDeviceIdentity();
+#ifdef __EMSCRIPTEN__
+ // Runs of mesh draws as one call: a scene's draws mostly differ by nothing but their geometry's range and their records,
+ // and each was a call of its own with a block bound for it. Before any program is assembled, which reads the same answer.
+ {
+ const EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
+ multi_draw_ = ctx != 0 && emscripten_webgl_enable_WEBGL_multi_draw(ctx);
+ glslMultiDraw() = multi_draw_;
+ }
+#endif
ES_LOG_DEBUG("GLDevice initialized");
}
@@ -415,6 +426,7 @@ bool GLDevice::recreateDevice() {
}
free(names);
}
+ if (multi_draw_) multi_draw_ = emscripten_webgl_enable_WEBGL_multi_draw(ctx);
#endif
// Every name belonged to the old context. The registry rebuilds each object
// behind its id; nothing here survives but the maps' shape.
@@ -1400,6 +1412,32 @@ void GLDevice::drawArrays(u32 first, u32 vertexCount) {
glDrawArrays(primitiveMode(), static_cast<GLint>(first), static_cast<GLsizei>(vertexCount));
}
+void GLDevice::drawElementsInstancedMulti(GfxDataType indexType, const u32* counts, const u32* byteOffsets,
+ const u32* instanceCounts, u32 drawCount) {
+#ifdef __EMSCRIPTEN__
+ if (!multi_draw_) {
+ GfxDevice::drawElementsInstancedMulti(indexType, counts, byteOffsets, instanceCounts, drawCount);
+ return;
+ }
+ if (!isDeviceUsable() || drawCount == 0) return;
+ prepareVertexState();
+ multi_counts_.resize(drawCount);
+ multi_instances_.resize(drawCount);
+ multi_offsets_.resize(drawCount);
+ for (u32 k = 0; k < drawCount; ++k) {
+ multi_counts_[k] = static_cast<i32>(counts[k]);
+ multi_instances_[k] = static_cast<i32>(instanceCounts[k]);
+ multi_offsets_[k] = reinterpret_cast<const void*>(static_cast<uintptr_t>(byteOffsets[k]));
+ // Counted as the draws they are: a draw count that halved because they shared a call would read as work saved on the GPU.
+ countDraw();
+ }
+ glMultiDrawElementsInstancedWEBGL(primitiveMode(), multi_counts_.data(), toGLDataType(indexType), multi_offsets_.data(),
+ multi_instances_.data(), static_cast<GLsizei>(drawCount));
+#else
+ GfxDevice::drawElementsInstancedMulti(indexType, counts, byteOffsets, instanceCounts, drawCount);
+#endif
+}
+
void GLDevice::drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) {
if (!isDeviceUsable()) return;
prepareVertexState();
diff --git a/src/esengine/renderer/rhi/GLDevice.hpp b/src/esengine/renderer/rhi/GLDevice.hpp
index 51292410f..b02c74c1d 100644
--- a/src/esengine/renderer/rhi/GLDevice.hpp
+++ b/src/esengine/renderer/rhi/GLDevice.hpp
@@ -75,6 +75,9 @@ public:
void drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset) override;
void drawArrays(u32 first, u32 vertexCount) override;
void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) override;
+ bool supportsMultiDraw() const override { return multi_draw_; }
+ void drawElementsInstancedMulti(GfxDataType indexType, const u32* counts, const u32* byteOffsets,
+ const u32* instanceCounts, u32 drawCount) override;
void beginRenderPass(const RenderPassDesc& desc) override;
void endRenderPass() override;
@@ -331,6 +334,10 @@ private:
u32 pending_vbo_offset_[MAX_VERTEX_BUFFER_SLOTS] = {};
u32 pending_ibo_ = 0;
u32 bound_vao_ = 0;
+ /// WEBGL_multi_draw is enabled: a run of mesh draws is one call, and mesh programs read their entry by gl_DrawID.
+ bool multi_draw_ = false;
+ std::vector<i32> multi_counts_, multi_instances_;
+ std::vector<const void*> multi_offsets_;
// Where a multisampled framebuffer resolves to, and how big, by framebuffer id.
// The blit runs whenever the target is left, which is the only reason anything
diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hpp
index 57254ddde..93258c3bf 100644
--- a/src/esengine/renderer/rhi/GfxDevice.hpp
+++ b/src/esengine/renderer/rhi/GfxDevice.hpp
@@ -703,6 +703,20 @@ public:
/** @brief Draws indexed triangles with instancing */
virtual void drawElementsInstanced(u32 indexCount, GfxDataType indexType, u32 byteOffset, u32 instanceCount) = 0;
+ /** @brief Whether drawElementsInstancedMulti is one call here, its draws told apart by gl_DrawID (WEBGL_multi_draw). */
+ virtual bool supportsMultiDraw() const { return false; }
+
+ /**
+ * @brief @p drawCount indexed instanced draws through the bound pipeline and buffers, as one call where supportsMultiDraw().
+ * @details Draw k reads counts[k] indices from byteOffsets[k], instanceCounts[k] times, and its vertex stage sees gl_DrawID
+ * = k. Elsewhere it is the draws one after another, which is the same picture only for a program that does not read
+ * gl_DrawID; the draw list asks for runs only where the device has said it draws them.
+ */
+ virtual void drawElementsInstancedMulti(GfxDataType indexType, const u32* counts, const u32* byteOffsets,
+ const u32* instanceCounts, u32 drawCount) {
+ for (u32 k = 0; k < drawCount; ++k) drawElementsInstanced(counts[k], indexType, byteOffsets[k], instanceCounts[k]);
+ }
+
// =========================================================================
// Framebuffers
// =========================================================================
diff --git a/src/esengine/renderer/store/InstanceConstants.hpp b/src/esengine/renderer/store/InstanceConstants.hpp
index 75291b29d..a9aa500e3 100644
--- a/src/esengine/renderer/store/InstanceConstants.hpp
+++ b/src/esengine/renderer/store/InstanceConstants.hpp
@@ -41,4 +41,25 @@ struct InstanceConstants {
static_assert(sizeof(InstanceConstants) == 16,
"InstanceConstants must be one vec4 to match std140");
+/**
+ * @brief The most draws one call may carry where the device draws runs (WEBGL_multi_draw).
+ *
+ * @details There the block is an array, one entry per draw of the run, which the vertex stage indexes by gl_DrawID: x is where
+ * that draw's records start, y where its instances start in the run's probe block. A draw on its own is a run of one,
+ * and gl_DrawID is 0 for it.
+ */
+inline constexpr u32 MULTI_DRAW_MAX = 64;
+
+/**
+ * @brief Whether this process's GLSL mesh programs read their draw's entry by gl_DrawID.
+ *
+ * @details Set by the GL device when it enables WEBGL_multi_draw, before any program is assembled, and read by the shader
+ * assembly and by the block pool, which must agree: a program that declares the array is refused a binding the size
+ * of one entry.
+ */
+inline bool& glslMultiDraw() {
+ static bool on = false;
+ return on;
+}
+
} // namespace esengine
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index 8f2126ff6..b847109b5 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -133,10 +133,39 @@ std::string instanceRecordWGSL() {
* them for every program sharing the layout.
*/
std::string instanceRecordGLSLDecls() {
+ // Where the device draws runs (glslMultiDraw), the block is an entry per draw of the run, read by gl_DrawID: x the draw's first
+ // record, y its first instance in the run's probe block, which is what the probe slot (ES_INSTANCE_ID) then counts from. Not
+ // under VULKAN, where the twin generator compiles this and gl_DrawID is not GLSL's.
+ if (glslMultiDraw()) {
+ return
+ "#ifndef VULKAN\n"
+ "layout(std140) uniform InstanceConstants {\n"
+ " highp uvec4 u_drawEntry[" + std::to_string(MULTI_DRAW_MAX) + "];\n"
+ "};\n"
+ "#define ES_DRAW_RECORD int(u_drawEntry[gl_DrawID].x)\n"
+ "#undef ES_INSTANCE_ID\n"
+ "#define ES_INSTANCE_ID (gl_InstanceID + int(u_drawEntry[gl_DrawID].y))\n"
+ "#define ES_RECORD_ID gl_InstanceID\n"
+ "#else\n"
+ "layout(std140) uniform InstanceConstants {\n"
+ " highp uvec4 u_instanceBase;\n"
+ "};\n"
+ "#define ES_DRAW_RECORD int(u_instanceBase.x)\n"
+ "#define ES_RECORD_ID ES_INSTANCE_ID\n"
+ "#endif\n"
+ "uniform highp sampler2D u_instanceData;\n"
+ "highp vec4 esInstanceTexel(int texel);\n"
+ "highp mat4 esInstanceModel();\n"
+ "highp mat3 esInstanceNormalMatrix();\n"
+ "highp vec4 esInstanceTint();\n"
+ "highp vec4 esInstanceLightmapRect();\n";
+ }
return
"layout(std140) uniform InstanceConstants {\n"
" highp uvec4 u_instanceBase;\n"
"};\n"
+ "#define ES_DRAW_RECORD int(u_instanceBase.x)\n"
+ "#define ES_RECORD_ID ES_INSTANCE_ID\n"
"uniform highp sampler2D u_instanceData;\n"
"highp vec4 esInstanceTexel(int texel);\n"
"highp mat4 esInstanceModel();\n"
@@ -150,7 +179,7 @@ std::string instanceRecordGLSLBodies() {
const std::string width = std::to_string(MESH_INSTANCE_TEXTURE_WIDTH);
return
"highp vec4 esInstanceTexel(int texel) {\n"
- " int at = (int(u_instanceBase.x) + ES_INSTANCE_ID) * " + texels + " + texel;\n"
+ " int at = (ES_DRAW_RECORD + ES_RECORD_ID) * " + texels + " + texel;\n"
" return texelFetch(u_instanceData, ivec2(at % " + width + ", at / " + width + "), 0);\n"
"}\n"
"highp mat4 esInstanceModel() {\n"
@@ -2892,6 +2921,14 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p
assembled << "#version " << parsed.version << "\n";
++headerLines;
}
+ // gl_DrawID, for a vertex stage that reads a record (see instanceRecordGLSLDecls).
+ if (glslMultiDraw() && stage == ShaderStage::Vertex) {
+ const auto named = parsed.stages.find(stage);
+ if (named != parsed.stages.end() && named->second.find("esInstance") != std::string::npos) {
+ assembled << "#ifndef VULKAN\n#extension GL_ANGLE_multi_draw : require\n#endif\n";
+ headerLines += 3;
+ }
+ }
// Feature #defines go right after #version (GLSL requires #version first), so the
// shader body can #ifdef compile-time variants. Counted into headerLines so the
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 1183e7c7d..49f140523 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -4816,4 +4816,6 @@ export const NOTED = {
{"internal": "The lite WeChat engine stopped building after the last release and builds again before the next; no release shipped without it."},
"fix(transform): a child whose transform a script wrote moves when its new place is the identity - the write left an identity cache beside the old world fields, and a child whose new matrix was the identity read as unchanged and stayed where it had been":
{"internal": "The transform cache this restores was made lazy after the last release; no release kept a child in its old place."},
+ "perf(render): a run of mesh draws that differ only by their geometry and records is one call - with WEBGL_multi_draw, each draw reads its record base and probe offset by gl_DrawID from one block staged for the run, so a run binds its blocks once and draws once":
+ {"note": "A run of mesh draws is one call on WebGL2."},
};