Identical-draw batching
Open the live demo · Read the source · View on GitHub
A hundred identical crates drawn one at a time are a hundred pipeline binds,
hundreds of uniform writes and a hundred draw calls. RenderSettings.batchIdenticalDraws
finds the runs of nodes that share a mesh, a material, a mirroring and a
reflection probe, and draws each run through one instanced call instead.
Step 1: A grid of identical crates #
Twelve boxes, sharing one uploaded mesh and one material, arranged in a grid. Nothing about any single crate is unique, which is exactly the case this setting looks for.
final DeviceMesh crateMesh = DeviceMesh.upload(
context.device,
CuboidShape(size: Vector3(0.8, 0.8, 0.8)).build(),
);
final Material crateMaterial = Material(
name: 'crate',
baseColor: Vector4(0.7, 0.55, 0.3, 1.0),
roughness: 0.7,
);
final Scene scene = Scene();
for (var row = 0; row < _rows; row++) {
for (var column = 0; column < _columns; column++) {
scene.add(
MeshNode(crateMesh, crateMaterial, name: 'crate $row-$column')
..setPosition(
(column - (_columns - 1) / 2) * 1.1,
0.0,
(row - (_rows - 1) / 2) * 1.1,
),
);
}
}
Step 2: The switch #
One flag, and the renderer decides for itself which draws qualify.
batchIdenticalDraws: batch,
Step 3: What the frame says it did #
FrameResult.batchedDraws counts how many individual draws the batcher
replaced. With the switch on, a dozen crates collapse into far fewer calls;
with it off, nothing is merged and the count is zero.
final int crates = _rows * _columns;
if (scene.meshes.length != crates) {
throw StateError('expected $crates crates, found ${scene.meshes.length}');
}
if (batch && frame.batchedDraws < RenderSettings.batchRunMinimum) {
throw StateError(
'batching was on but only ${frame.batchedDraws} draws were merged',
);
}
if (!batch && frame.batchedDraws != 0) {
throw StateError(
'batching was off but ${frame.batchedDraws} draws merged',
);
}
Note. A run has to be at least
RenderSettings.batchRunMinimumdraws long before merging it is worth the pipeline switch on either side. Two identical crates next to each other are drawn as two crates, not batched.