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): the same mesh drawn again is one more instance, not one more draw

esengine4023d38fcbff
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 228d38be5..c5ad017be 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,26 @@ published separately; it ships inside the editor.
### Changed
+- **The same mesh drawn again is one more instance, not one more draw call.**
+ Every resident mesh took its own draw: a hundred crates were a hundred calls,
+ a hundred pipeline resolves and a hundred buffer rebinds, for one cube's worth
+ of geometry. The per-object record was already an instance stream — the shape
+ the particle emitter draws thousands from — and nothing consumed it that way,
+ because the merge pass refused every instanced command outright.
+
+ Draws of the same geometry now coalesce into one instanced call. They rarely
+ sit next to each other in the frame's pool (the sort reorders them by depth
+ long after the records were written), so merging relocates the records to the
+ end of the stream, where the run being built is growing — cheap next to the
+ draw call it removes, and in the same window the multi-texture merge already
+ rewrites staged vertices in.
+
+ Only where the order cannot matter: an opaque draw replaces what it covers and
+ depth decides what covers what, so which of them happens first is not the
+ result. A blended draw's order **is** its result, and a skinned draw carries a
+ pose written per draw — both keep their own call. Four cubes in a scene are one
+ call where they were four; all 60 pixel gates on both backends are unchanged.
+
- **The transform gizmo is built from the view's own basis.** Rotate already read
where the world axes point on screen and drew a ring per axis. Move and scale
did not: their arrows were two written-down screen directions, `+X is right` and
diff --git a/desktop/public/scenes/mesh-instanced.esscene b/desktop/public/scenes/mesh-instanced.esscene
new file mode 100644
index 000000000..6eb47591f
--- /dev/null
+++ b/desktop/public/scenes/mesh-instanced.esscene
@@ -0,0 +1,174 @@
+{
+ "version": 1,
+ "name": "MeshInstanced",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 300
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 150,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Cube1",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -75,
+ "y": 75,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Mesh2D",
+ "data": {
+ "mesh": "builtin:cube",
+ "color": {
+ "r": 1,
+ "g": 0,
+ "b": 0,
+ "a": 1
+ },
+ "lit": false,
+ "opaque": true,
+ "cullBackfaces": true,
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Cube2",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 75,
+ "y": 75,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Mesh2D",
+ "data": {
+ "mesh": "builtin:cube",
+ "color": {
+ "r": 0,
+ "g": 1,
+ "b": 0,
+ "a": 1
+ },
+ "lit": false,
+ "opaque": true,
+ "cullBackfaces": true,
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "Cube3",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -75,
+ "y": -75,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Mesh2D",
+ "data": {
+ "mesh": "builtin:cube",
+ "color": {
+ "r": 0,
+ "g": 0,
+ "b": 1,
+ "a": 1
+ },
+ "lit": false,
+ "opaque": true,
+ "cullBackfaces": true,
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 4,
+ "name": "Cube4",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 75,
+ "y": -75,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Mesh2D",
+ "data": {
+ "mesh": "builtin:cube",
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 0,
+ "a": 1
+ },
+ "lit": false,
+ "opaque": true,
+ "cullBackfaces": true,
+ "enabled": true
+ }
+ }
+ ]
+ }
+ ]
+}
diff --git a/desktop/scripts/headless-verify.mjs b/desktop/scripts/headless-verify.mjs
index 48aa21e8a..d9e8c4615 100644
--- a/desktop/scripts/headless-verify.mjs
+++ b/desktop/scripts/headless-verify.mjs
@@ -144,7 +144,7 @@ function finish(result, server) {
const ok = result.ok && renderedOk && (result.expect?.ok ?? true) &&
(result.resize?.ok ?? true) && (result.preview?.ok ?? true) &&
(result.meshPreview?.ok ?? true) && (result.grid?.ok ?? true) &&
- deviceLossOk && meshOk && pickOk;
+ (result.draws?.ok ?? true) && deviceLossOk && meshOk && pickOk;
console.log(`\n[verify:render] ${ok ? 'PASS' : 'FAIL'} — ${SCENE} (${BACKEND})`);
console.log('DRIVE_RESULT ' + JSON.stringify(result));
try {
@@ -468,6 +468,12 @@ app.whenReady().then(async () => {
return { w, h, totalPixels: px.length / 4, nonZeroPixels: nonZero, min, max, spread, rendered: spread > 16 };
`);
const drawCalls = await exec('window.__estellaHeadless.api.getStats().drawCalls');
+ // What the frame COST, which no pixel shows: the same geometry drawn N times
+ // is one instanced call, and the picture is identical either way. Asserted as
+ // an exact number so a regression in EITHER direction is a failure.
+ const wantDrawCalls = process.env.ESTELLA_VERIFY_DRAW_CALLS;
+ const draws = wantDrawCalls === undefined ? null
+ : { want: Number(wantDrawCalls), got: drawCalls, ok: drawCalls === Number(wantDrawCalls) };
// Optional color/orientation assertion: ESTELLA_VERIFY_EXPECT is a JSON array of
// { x, y, rgb:[r,g,b], tol? } where x,y are normalized [0,1] from the TOP-LEFT.
// This is the guard the all-textures-upside-down upload bug would have tripped
@@ -597,7 +603,7 @@ app.whenReady().then(async () => {
return { differingPixels: differing, ok: differing > 300 };
`);
}
- finish({ ok: true, entityCount, drawCalls, capture, expect, resize, preview, meshPreview, grid, deviceLoss, meshResident, meshAsset, meshMaterial, meshPrefab, setField, pick }, server);
+ finish({ ok: true, entityCount, drawCalls, draws, capture, expect, resize, preview, meshPreview, grid, deviceLoss, meshResident, meshAsset, meshMaterial, meshPrefab, setField, pick }, server);
} catch (e) {
finish({ ok: false, error: String((e && e.stack) || e) }, server);
}
diff --git a/src/esengine/renderer/draw/BatchBuilder.cpp b/src/esengine/renderer/draw/BatchBuilder.cpp
index 36b65202a..e0bac7ff5 100644
--- a/src/esengine/renderer/draw/BatchBuilder.cpp
+++ b/src/esengine/renderer/draw/BatchBuilder.cpp
@@ -86,6 +86,7 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,
cmd.vertex_byte_offset = vertexByteOffset;
cmd.vertex_count = vertexCount;
cmd.instance_count = key.instanceCount;
+ cmd.instance_stride = key.instanceStride;
cmd.vertex_buffer = key.vertexBuffer;
cmd.index_buffer = key.indexBuffer;
cmd.vertex_layout = key.vertexLayout;
diff --git a/src/esengine/renderer/draw/BatchBuilder.hpp b/src/esengine/renderer/draw/BatchBuilder.hpp
index 3d3ab73ec..dd51a7103 100644
--- a/src/esengine/renderer/draw/BatchBuilder.hpp
+++ b/src/esengine/renderer/draw/BatchBuilder.hpp
@@ -114,6 +114,9 @@ struct BatchDrawKey {
// > 0 selects an instanced draw: indexCount indices drawn instanceCount times, with
// per-instance attributes based at the vertex byte offset (see DrawCommand).
u32 instanceCount = 0;
+ // Bytes one instance record occupies. Needed to coalesce two such draws into
+ // one: the merge relocates their records so they sit next to each other.
+ u32 instanceStride = 0;
// Geometry the GPU already holds. Set together with a MeshInstance stream, whose
// offset is the draw's vertexByteOffset: the mesh supplies the vertices and the
// frame supplies only the transforms.
diff --git a/src/esengine/renderer/draw/DrawCommand.hpp b/src/esengine/renderer/draw/DrawCommand.hpp
index f7058d242..ebdc3e779 100644
--- a/src/esengine/renderer/draw/DrawCommand.hpp
+++ b/src/esengine/renderer/draw/DrawCommand.hpp
@@ -103,11 +103,16 @@ struct DrawCommand {
RenderStage stage = RenderStage::Transparent;
i32 layer = 0;
u32 entity_count = 1;
- bool merged = false;
+ /// This draw's instance records have been moved to the end of the stream,
+ /// where the run it heads is growing. Set by the merge, read by it alone.
+ bool instances_relocated = false;
// > 0 selects an instanced draw: index_count indices drawn instance_count times,
// with per-instance attributes based at vertex_byte_offset (see LayoutId::ParticleInstance).
u32 instance_count = 0;
+ // Bytes one of those records occupies; 0 = the stream's own stride, which the
+ // merge would have to guess. Set by whoever wrote them.
+ u32 instance_stride = 0;
// Geometry on the GPU rather than in this frame's pool. Set together or not
// at all; index_offset/index_count then index INTO these. Sorting, material and
@@ -232,11 +237,61 @@ struct DrawCommand {
* some number of draw calls, and the only actionable thing about that number
* is what kept them apart. canMergeWith is this, read as a bool.
*/
+ /**
+ * Whether this draw's result is the same wherever it happens among its
+ * peers: it replaces what it covers rather than reading it, and depth
+ * decides what covers what. Only such draws can be merged into one — a
+ * merge is exactly the loss of their relative order.
+ */
+ bool orderIndependent() const {
+ return blend_mode == BlendMode::None && depth_test && depth_write;
+ }
+
+ /**
+ * Whether two instanced draws are the same geometry drawn again — what a
+ * second instance record answers, rather than a second draw. Both must be
+ * order-independent, since merging is the loss of their relative order; a
+ * skinned draw is out because one draw can only be in one pose.
+ */
+ bool sameInstancedGeometry(const DrawCommand& next) const {
+ if (!hasPersistentGeometry() || !next.hasPersistentGeometry()) return false;
+ if (instance_stride == 0 || instance_stride != next.instance_stride) return false;
+ if (skin_count != 0 || next.skin_count != 0) return false;
+ // BOTH, not just this one: an opaque head asked about a draw whose
+ // result depends on when it happens would otherwise swallow it and
+ // paint it with the head's own state.
+ if (!orderIndependent() || !next.orderIndependent()) return false;
+ if (vertex_buffer != next.vertex_buffer || index_buffer != next.index_buffer) return false;
+ if (vertex_layout != next.vertex_layout) return false;
+ // The same range of the same buffer: a draw is one instance of THIS.
+ if (index_offset != next.index_offset || index_count != next.index_count) return false;
+ // Textures are per draw here, not selected per vertex the way the Batch
+ // stream selects them, so instances sharing one draw share its samplers.
+ if (texture_count != next.texture_count) return false;
+ for (u8 s = 0; s < texture_count; ++s) {
+ if (texture_ids[s] != next.texture_ids[s]) return false;
+ }
+ return true;
+ }
+
BatchBreak mergeBlocker(const DrawCommand& next) const {
- // Instanced draws are one command per emitter — never coalesce them. This
- // covers resident meshes too: their per-object transform IS the instance
- // stream, so every such draw carries a count.
- if (instance_count != 0 || next.instance_count != 0) return BatchBreak::Instanced;
+ // An instanced draw is one command per emitter, except where a second
+ // command is the same geometry again — see sameInstancedGeometry, which
+ // the merge answers by relocating the records rather than by a draw.
+ if (instance_count != 0 || next.instance_count != 0) {
+ if (!sameInstancedGeometry(next)) return BatchBreak::Instanced;
+ if (shader_id != next.shader_id) return BatchBreak::Shader;
+ if (material_id != next.material_id) return BatchBreak::Material;
+ if (cull != next.cull) return BatchBreak::Cull;
+ if (state_flags != next.state_flags) return BatchBreak::State;
+ if (state_flags & CMD_STATE_SCISSOR) {
+ if (scissor != next.scissor) return BatchBreak::Scissor;
+ }
+ if (state_flags & (CMD_STATE_STENCIL_WRITE | CMD_STATE_STENCIL_TEST)) {
+ if (stencil_ref != next.stencil_ref) return BatchBreak::Stencil;
+ }
+ return BatchBreak::None;
+ }
if (shader_id != next.shader_id) return BatchBreak::Shader;
if (blend_mode != next.blend_mode) return BatchBreak::Blend;
if (layout_id != next.layout_id) return BatchBreak::Layout;
diff --git a/src/esengine/renderer/draw/DrawList.cpp b/src/esengine/renderer/draw/DrawList.cpp
index 90be3ec2a..cfdb24f92 100644
--- a/src/esengine/renderer/draw/DrawList.cpp
+++ b/src/esengine/renderer/draw/DrawList.cpp
@@ -7,10 +7,14 @@
#include <glm/glm.hpp>
#include <algorithm>
+#include <cstring>
namespace esengine {
namespace {
+/// relocateInstance: the first record of a run lands wherever the pool has room.
+constexpr u32 NO_EXPECTED_OFFSET = 0xFFFFFFFFu;
+
// Stamp a merged sampler slot onto every vertex of a Batch-layout command. The vertices
// are still in CPU staging at finalize time (finalize runs before upload), so the shader
// later samples u_textures[texIndex]. Only the Batch layout carries a texIndex attribute.
@@ -19,6 +23,22 @@ void rewriteTexIndex(TransientBufferPool& pool, const DrawCommand& cmd, i32 slot
f32 fslot = static_cast<f32>(slot);
for (u32 k = 0; k < cmd.vertex_count; ++k) verts[k].texIndex = fslot;
}
+
+/**
+ * Move one instance record to the end of its stream, where the run being built
+ * is growing — the sort reordered the draws, so a run adjacent after it is
+ * almost never adjacent here. False when the allocation did not land where the
+ * run needs it: the caller leaves the draws apart rather than draw stray bytes.
+ */
+bool relocateInstance(TransientBufferPool& pool, DrawCommand& cmd, u32 expectedAt) {
+ const u32 at = pool.allocVertices(LayoutId::MeshInstance, cmd.instance_stride);
+ if (expectedAt != NO_EXPECTED_OFFSET && at != expectedAt) return false;
+ // After the alloc: growing the staging can move it.
+ u8* base = pool.vertexData(LayoutId::MeshInstance);
+ std::memmove(base + at, base + cmd.vertex_byte_offset, cmd.instance_stride);
+ cmd.vertex_byte_offset = at;
+ return true;
+}
} // namespace
void DrawList::clear() {
@@ -76,7 +96,25 @@ void DrawList::finalize(TransientBufferPool& pool) {
if (writeIdx > 0) {
DrawCommand& head = commands_[writeIdx - 1];
blocker = head.mergeBlocker(commands_[i]);
- if (blocker == BatchBreak::None) {
+ if (blocker == BatchBreak::None && head.instance_count != 0) {
+ // One more instance of geometry already being drawn. The head's
+ // own record moves first, so the run has somewhere to grow.
+ const u32 stride = head.instance_stride;
+ bool ok = head.instances_relocated
+ || relocateInstance(pool, head, NO_EXPECTED_OFFSET);
+ if (ok) {
+ ok = relocateInstance(pool, commands_[i],
+ head.vertex_byte_offset + head.instance_count * stride);
+ }
+ if (ok) {
+ head.instances_relocated = true;
+ head.instance_count += commands_[i].instance_count;
+ head.entity_count += commands_[i].entity_count;
+ didMerge = true;
+ } else {
+ blocker = BatchBreak::Instanced;
+ }
+ } else if (blocker == BatchBreak::None) {
if (head.layout_id == LayoutId::Batch && commands_[i].texture_count >= 1) {
// Multi-texture: give this command's texture a slot in the head's set
// (or bail to a new draw if all 8 slots are taken), then stamp its verts.
diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cpp
index 7cdf45a20..fb566ffe8 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.cpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp
@@ -330,6 +330,7 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
key.shaderId = materialProgram != 0 ? materialProgram : residentShader;
key.layoutId = LayoutId::MeshInstance;
key.instanceCount = 1;
+ key.instanceStride = stride;
key.vertexBuffer = resident->vertexBuffer;
key.indexBuffer = resident->indexBuffer;
key.vertexLayout = resident->layout;
diff --git a/tests/renderer/test_batch_builder.cpp b/tests/renderer/test_batch_builder.cpp
index 6658f4de7..34daf6758 100644
--- a/tests/renderer/test_batch_builder.cpp
+++ b/tests/renderer/test_batch_builder.cpp
@@ -15,6 +15,10 @@
#include "esengine/renderer/store/MaterialStore.hpp"
#include "esengine/renderer/rhi/TransientBufferPool.hpp"
+#include <functional>
+#include <utility>
+#include <vector>
+
using namespace esengine;
namespace {
@@ -173,6 +177,206 @@ TEST_CASE("finalize: different streams never coalesce; instanced draws stay one
CHECK(h.list.mergedDrawCallCount() == 4);
}
+/**
+ * A resident-mesh draw as MeshPlugin submits one: the mesh's own buffers, one
+ * per-object record in the frame's stream, opaque so its order does not matter.
+ * `z` goes into the record so a test can see WHICH instances a merged draw holds.
+ */
+BatchDrawKey meshKey(u32 meshBuffer, u32 textureId = 0) {
+ BatchDrawKey key{};
+ key.stage = RenderStage::Opaque;
+ key.shaderId = 11;
+ key.blend = BlendMode::None;
+ key.depthTest = true;
+ key.depthWrite = true;
+ key.textureId = textureId;
+ key.type = RenderType::Mesh;
+ key.layoutId = LayoutId::MeshInstance;
+ key.instanceCount = 1;
+ key.instanceStride = 68;
+ key.vertexBuffer = BufferHandle{meshBuffer};
+ key.indexBuffer = BufferHandle{meshBuffer + 100};
+ // ONE layout for every mesh with these channels, which is what the resource
+ // layer hands out: two meshes differ by their buffers, not by their shape.
+ // A fixture giving each its own would let a missing buffer check pass.
+ key.vertexLayout = VertexLayoutHandle{200};
+ return key;
+}
+
+/** Submits one instance of `key`'s mesh, tagging its record with `mark`. */
+u32 pushMeshInstance(Harness& h, const BatchDrawKey& key, f32 mark, f32 depth = 0.0f) {
+ const u32 at = h.pool.allocVertices(LayoutId::MeshInstance, key.instanceStride);
+ auto* rec = reinterpret_cast<f32*>(h.pool.vertexData(LayoutId::MeshInstance) + at);
+ *rec = mark;
+ BatchDrawKey k = key;
+ k.depth = depth;
+ pushBatchDraw(h.list, h.clips, at, 0, 0, 36, k);
+ return at;
+}
+
+/** The mark each instance of a merged draw carries, read back from the stream. */
+std::vector<f32> instanceMarks(Harness& h, const DrawCommand& cmd) {
+ std::vector<f32> out;
+ const u8* base = h.pool.vertexData(LayoutId::MeshInstance) + cmd.vertex_byte_offset;
+ for (u32 i = 0; i < cmd.instance_count; ++i) {
+ out.push_back(*reinterpret_cast<const f32*>(base + i * cmd.instance_stride));
+ }
+ return out;
+}
+
+TEST_CASE("finalize: the same mesh drawn three times is one instanced draw") {
+ Harness h;
+ BatchDrawKey key = meshKey(5);
+ // Depths chosen so the sort REORDERS them: written 1,2,3 and drawn nearest
+ // first (opaque is front-to-back), so the run is z=30,20,10 — marks 2,3,1,
+ // with no two records adjacent in the pool. Relocation is why this merges.
+ pushMeshInstance(h, key, 1.0f, 10.0f);
+ pushMeshInstance(h, key, 2.0f, 30.0f);
+ pushMeshInstance(h, key, 3.0f, 20.0f);
+
+ h.list.finalize(h.pool);
+
+ REQUIRE(h.list.mergedDrawCallCount() == 1);
+ const DrawCommand& cmd = h.list.command(0);
+ CHECK(cmd.instance_count == 3);
+ CHECK(cmd.index_count == 36); // one mesh's indices, not three meshes' worth
+ CHECK(cmd.entity_count == 3);
+ // Every instance is present, in the order the draw will read them.
+ CHECK(instanceMarks(h, cmd) == std::vector<f32>{2.0f, 3.0f, 1.0f});
+}
+
+/** Two mesh draws, the second differing only as `vary` says. How many draws survive. */
+u32 drawsAfterMerge(const std::function<void(BatchDrawKey&, u32&)>& vary) {
+ Harness h;
+ const BatchDrawKey base = meshKey(5);
+ BatchDrawKey second = base;
+ u32 indexOffset = 0;
+ vary(second, indexOffset);
+
+ for (const auto& [key, at] : { std::pair{base, 0u}, std::pair{second, indexOffset} }) {
+ const u32 rec = h.pool.allocVertices(LayoutId::MeshInstance, key.instanceStride);
+ pushBatchDraw(h.list, h.clips, rec, 0, at, 36, key);
+ }
+ h.list.finalize(h.pool);
+ return h.list.mergedDrawCallCount();
+}
+
+TEST_CASE("finalize: two mesh draws alike but for one thing stay two draws") {
+ // Each case varies ONE thing and leaves the pair adjacent in the sort, so
+ // the check under test is the only thing that can separate them. A fixture
+ // where something else also differs would pass with the check deleted.
+ CHECK(drawsAfterMerge([](BatchDrawKey&, u32&) {}) == 1); // the control
+
+ CHECK(drawsAfterMerge([](BatchDrawKey& k, u32&) {
+ k.vertexBuffer = BufferHandle{6}; // another mesh
+ }) == 2);
+ CHECK(drawsAfterMerge([](BatchDrawKey& k, u32&) {
+ k.indexBuffer = BufferHandle{106};
+ }) == 2);
+ CHECK(drawsAfterMerge([](BatchDrawKey&, u32& indexOffset) {
+ indexOffset = 36; // another range of it
+ }) == 2);
+ CHECK(drawsAfterMerge([](BatchDrawKey& k, u32&) {
+ k.textureId = 42; // samplers are per draw
+ }) == 2);
+ CHECK(drawsAfterMerge([](BatchDrawKey& k, u32&) {
+ k.materialId = 9;
+ }) == 2);
+ CHECK(drawsAfterMerge([](BatchDrawKey& k, u32&) {
+ k.cull = 1;
+ }) == 2);
+ CHECK(drawsAfterMerge([](BatchDrawKey& k, u32&) {
+ k.shaderId = 12;
+ }) == 2);
+
+ // Order-dependence, one property at a time. Each of these alone makes the
+ // second draw one whose result depends on when it happens, and the head is
+ // the opaque one — so a check that asks only about ITSELF passes them all.
+ CHECK(drawsAfterMerge([](BatchDrawKey& k, u32&) {
+ k.blend = BlendMode::Normal;
+ }) == 2);
+ CHECK(drawsAfterMerge([](BatchDrawKey& k, u32&) {
+ k.depthTest = false;
+ }) == 2);
+ CHECK(drawsAfterMerge([](BatchDrawKey& k, u32&) {
+ k.depthWrite = false;
+ }) == 2);
+}
+
+TEST_CASE("finalize: the HEAD's own order-dependence stops a merge too") {
+ // A material can say `blend: none, depthWrite: false`: nothing reads what
+ // is behind and nothing records what is in front, so the last draw wins.
+ // Submitted first it is the head, which only a check on ITS state refuses.
+ Harness h;
+ BatchDrawKey unordered = meshKey(5);
+ unordered.depthWrite = false;
+ pushMeshInstance(h, unordered, 1.0f, 20.0f);
+ pushMeshInstance(h, meshKey(5), 2.0f, 20.0f);
+
+ h.list.finalize(h.pool);
+ CHECK(h.list.mergedDrawCallCount() == 2);
+}
+
+TEST_CASE("finalize: a blended mesh keeps its own draw, because its order is the result") {
+ Harness h;
+ BatchDrawKey key = meshKey(5);
+ key.stage = RenderStage::Transparent;
+ key.blend = BlendMode::Normal;
+ key.depthWrite = false;
+ pushMeshInstance(h, key, 1.0f, 10.0f);
+ pushMeshInstance(h, key, 2.0f, 20.0f);
+
+ h.list.finalize(h.pool);
+ CHECK(h.list.mergedDrawCallCount() == 2);
+}
+
+TEST_CASE("finalize: an opaque head does not swallow a blended draw of the same mesh") {
+ // The asymmetric case, and the one a pixel gate caught: asking only whether
+ // THIS draw is opaque lets an opaque head absorb a blended sibling and paint
+ // it with the head's own state — the blended one then hides what is behind it.
+ Harness h;
+ pushMeshInstance(h, meshKey(5), 1.0f, 20.0f);
+
+ // Same stage on purpose — what MeshPlugin submits when one of two meshes
+ // has `opaque` off, and what puts the pair next to each other. Giving the
+ // blended one its own stage would sort them apart and prove nothing.
+ BatchDrawKey blended = meshKey(5);
+ blended.blend = BlendMode::Normal;
+ blended.depthTest = false;
+ pushMeshInstance(h, blended, 2.0f, 10.0f);
+
+ h.list.finalize(h.pool);
+ CHECK(h.list.mergedDrawCallCount() == 2);
+}
+
+TEST_CASE("finalize: a skinned mesh keeps its own draw, because a pose is per draw") {
+ Harness h;
+ BatchDrawKey key = meshKey(5);
+ key.instanceStride = 4;
+ key.skinCount = 2;
+ key.skinOffset = 0;
+ pushMeshInstance(h, key, 1.0f);
+ pushMeshInstance(h, key, 2.0f);
+
+ h.list.finalize(h.pool);
+ CHECK(h.list.mergedDrawCallCount() == 2);
+}
+
+TEST_CASE("execute: a merged mesh draw asks the device for its instances in one call") {
+ Harness h;
+ BatchDrawKey key = meshKey(5);
+ for (int i = 0; i < 4; ++i) pushMeshInstance(h, key, static_cast<f32>(i));
+
+ h.list.finalize(h.pool);
+ h.pool.upload();
+ MaterialStore materials;
+ h.list.execute(h.device, h.pool, materials, 1);
+
+ CHECK(h.device.drawElementsInstancedCalls == 1);
+ CHECK(h.device.lastDrawInstanceCount == 4);
+ CHECK(h.device.lastDrawIndexCount == 36);
+}
+
TEST_CASE("clip state is stamped onto commands from every stream") {
Harness h;
Entity clipped{5};
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index d975c8619..f7dfaabc1 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -72,6 +72,7 @@ export const SCENES = [
// Geometry with no file under it. Sun 22.5° off the view axis: the cube's two faces
// read 255·cos22.5 and 255·cos67.5, swapped if the winding is inside out; the sphere
// reads 155 at -25 against 236 at its middle, which a flat quad could not.
+ { id: "mesh-instanced", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-instanced.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_DRAW_CALLS: "1", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.25,\"y\":0.25,\"rgb\":[255,0,0],\"tol\":20},{\"x\":0.75,\"y\":0.25,\"rgb\":[0,255,0],\"tol\":20},{\"x\":0.25,\"y\":0.75,\"rgb\":[0,0,255],\"tol\":20},{\"x\":0.75,\"y\":0.75,\"rgb\":[255,255,0],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },
{ id: "mesh-builtin", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-builtin.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.3667,\"y\":0.5,\"rgb\":[236,236,236],\"tol\":20},{\"x\":0.1333,\"y\":0.5,\"rgb\":[98,98,98],\"tol\":20},{\"x\":0.75,\"y\":0.5,\"rgb\":[236,236,236],\"tol\":20},{\"x\":0.6667,\"y\":0.5,\"rgb\":[155,155,155],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },
// A baked panorama lighting a surface BY DIRECTION: two coplanar triangles, one
// white colour, normals up and down under a sky blue above and red below. A flat