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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file BatchBuilder.cpp
* @brief Implementation of the single submission face — the only DrawCommand producer.
*
* @author ESEngine Team
* @date 2026
*
* @copyright Copyright (c) 2026 ESEngine Team
* Licensed under the Apache License, Version 2.0.
*/
#include "./BatchBuilder.hpp"
#include <vector>
namespace esengine {
bool batchEntityVisible(const DrawList& drawList, const ClipState& clips,
Entity entity, i32 layer, u32 cullBit) {
if (clips.isEmptyScissor(entity)) return false;
if (cullBit) return drawList.layerVisible(cullBit);
const auto identity = drawList.sortIdentity(entity.id(), layer, 0);
return drawList.layerVisible(DrawList::layerBit(identity.layer));
}
namespace {
// Reused across calls so offsetting local indices into the target stream costs no
// per-call heap allocation. The renderer collects single-threaded and each call fully
// consumes the scratch before returning, so a file-local buffer is safe — and it amortizes
// the allocation across the frame, mirroring DrawList::sorted_scratch_.
std::vector<u32> g_indexScratch;
template <typename IndexT>
void pushBatchCommandImpl(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
u32 vertexByteOffset, u32 vertexCount,
const IndexT* localIndices, u32 indexCount,
const BatchDrawKey& key) {
if (indexCount == 0 || !batchEntityVisible(drawList, clips, key.entity, key.layer, key.cullBit)) return;
u32 baseVertex = vertexByteOffset / pool.vertexStride(key.layoutId);
g_indexScratch.resize(indexCount);
for (u32 i = 0; i < indexCount; ++i) {
g_indexScratch[i] = baseVertex + static_cast<u32>(localIndices[i]);
}
u32 indexOffset = pool.appendIndices(key.layoutId, g_indexScratch.data(), indexCount);
pushBatchDraw(drawList, clips, vertexByteOffset, vertexCount, indexOffset, indexCount, key);
}
} // namespace
void pushBatchDraw(DrawList& drawList, const ClipState& clips,
u32 vertexByteOffset, u32 vertexCount, u32 indexOffset, u32 indexCount,
const BatchDrawKey& key) {
if (indexCount == 0 || clips.isEmptyScissor(key.entity)) return;
// A group takes over its members' outward identity, so EVERY layer-derived decision
// below asks the group's layer: the culling bit, the ordering rule, the key's top field.
// Leaving one on the member y-sorts a group through one sprite and not the next.
const DrawList::SortIdentity identity =
drawList.sortIdentity(key.entity.id(), key.layer, key.order);
const i32 layer = identity.layer;
const i32 order = identity.order;
const DrawList::GroupIdentity* group = drawList.sortingGroupOf(key.entity.id());
// The camera's culling mask, applied at the one place draws are produced, so no
// render path can be added that forgets it.
if (!drawList.layerVisible(key.cullBit ? key.cullBit : DrawList::layerBit(layer))) return;
DrawCommand cmd{};
const auto resolve = drawList.layerOrder(layer);
// A depth layer decides its own stage and depth state; every other layer takes
// what the caller resolved from the material. The rule is the physical one, so
// it is derived rather than declared: an opaque draw may write depth and sorts
// front-to-back (the key inverts its depth bits for the Opaque stage, which is
// what makes early-z pay off), while a blended draw MUST NOT write — writing is
// how translucent sprites clip each other into black edges — so it only tests,
// and stays in back-to-front painter's order. Nobody should have to declare a
// fact about alpha compositing per material.
RenderStage stage = key.stage;
bool depthTest = key.depthTest;
bool depthWrite = key.depthWrite;
if (resolve == DrawList::LayerOrder::Depth) {
const bool opaque = key.blend == BlendMode::None;
stage = opaque ? RenderStage::Opaque : RenderStage::Transparent;
depthTest = true;
depthWrite = opaque;
}
// stateFlags is 0: ClipState stamps the real scissor/stencil below, after the key
// exists. A stencil write still precedes the draws testing it because UI pre-order
// puts a mask below its descendants in LAYER, the key's top field. Not so on one layer.
cmd.sort_key = resolve == DrawList::LayerOrder::YSort
? DrawCommand::buildSortKeyYSorted(stage, layer, key.y, key.shaderId,
key.blend, 0, order)
: resolve == DrawList::LayerOrder::Tree
? DrawCommand::buildSortKeyTree(stage, layer, drawList.treeSequenceOf(key.entity), key.shaderId,
key.blend, 0, order)
: DrawCommand::buildSortKey(stage, layer, key.shaderId,
key.blend, 0, key.depth, key.materialId, order,
key.instanceCount != 0 && key.vertexBuffer != BufferHandle::Invalid
? ((static_cast<u32>(key.vertexBuffer) * 2654435761u) ^ (indexOffset * 2246822519u)) >> 24 | 1u
: 0u);
// Inside a group the member's own order is all that separates siblings. Under a NESTED
// group it is the inner group's instead — a block does not come apart around another
// block's contents.
if (group) {
cmd.sort_key = DrawCommand::withGroupOrder(
cmd.sort_key, group->blockOrder ? group->block : key.order);
}
cmd.stage = stage;
cmd.index_offset = indexOffset;
cmd.index_count = indexCount;
cmd.vertex_byte_offset = vertexByteOffset;
cmd.vertex_count = vertexCount;
cmd.instance_count = key.instanceCount;
cmd.instance_stride = key.instanceStride;
cmd.instance_buffer = key.instanceBuffer;
cmd.vertex_buffer = key.vertexBuffer;
cmd.index_buffer = key.indexBuffer;
cmd.vertex_layout = key.vertexLayout;
cmd.skin_offset = key.skinOffset;
cmd.skin_count = key.skinCount;
cmd.morph_index = key.morphIndex;
cmd.probe_index = key.probeIndex;
cmd.planar_index = key.planarIndex;
cmd.shader_id = key.shaderId;
cmd.depth_shader_id = key.depthShaderId;
cmd.blend_mode = key.blend;
cmd.layout_id = key.layoutId;
cmd.material_id = key.materialId;
cmd.depth_test = depthTest;
cmd.depth_write = depthWrite;
cmd.cull = key.cull;
cmd.depth_bias = key.depthBias;
cmd.topology = key.topology;
// The Batch stream always samples a texture (white fallback at minimum); other
// streams bind one only when the draw actually has one (the shape stream is
// textureless, so execute() must not touch sampler units for it).
cmd.texture_count = (key.layoutId == LayoutId::Batch || key.textureId != 0) ? 1 : 0;
cmd.texture_ids[0] = key.textureId;
// Slot 1 belongs to the draw, so it is only ever bound where the shader
// declares it — the Batch stream picks its extra slots per vertex instead.
if (key.normalTextureId != 0 && cmd.texture_count == 1 && key.layoutId != LayoutId::Batch) {
cmd.texture_ids[1] = key.normalTextureId;
cmd.texture_count = 2;
}
// The shadow map's unit is pinned in the shader, so the gap below it is filled
// rather than the slot moved: a draw with no normal map still samples slot 2.
if (key.shadowTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
if (cmd.texture_count == 1) cmd.texture_ids[1] = key.textureId;
cmd.texture_ids[2] = key.shadowTextureId;
cmd.texture_count = 3;
}
// The reflection atlas is pinned one slot further on, filled the same way.
if (key.envTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
for (u8 slot = cmd.texture_count; slot < 3; ++slot) cmd.texture_ids[slot] = key.textureId;
cmd.texture_ids[3] = key.envTextureId;
cmd.texture_count = 4;
}
// The mesh's own deltas, one slot further still. Read in the VERTEX stage,
// unlike the three above — the only sampler here that is.
if (key.morphTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
for (u8 slot = cmd.texture_count; slot < 4; ++slot) cmd.texture_ids[slot] = key.textureId;
cmd.texture_ids[4] = key.morphTextureId;
cmd.texture_count = 5;
}
// The baked atlas, on the last slot below the frame's two masks. A draw whose
// geometry can read one but has none binds nothing here: the fill is white,
// and its record's rectangle is what says the bake does not apply.
if (key.lightmapTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
for (u8 slot = cmd.texture_count; slot < 5; ++slot) cmd.texture_ids[slot] = key.textureId;
cmd.texture_ids[5] = key.lightmapTextureId;
cmd.texture_count = 6;
} else if (key.probeGridTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
for (u8 slot = cmd.texture_count; slot < 5; ++slot) cmd.texture_ids[slot] = key.textureId;
cmd.texture_ids[5] = key.probeGridTextureId;
cmd.texture_count = 6;
}
cmd.entity = key.entity;
cmd.type = key.type;
cmd.layer = layer;
clips.applyTo(key.entity, cmd);
drawList.push(cmd);
}
void pushBatchCommand(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
u32 vertexByteOffset, u32 vertexCount,
const u32* localIndices, u32 indexCount,
const BatchDrawKey& key) {
pushBatchCommandImpl(pool, drawList, clips, vertexByteOffset, vertexCount, localIndices, indexCount, key);
}
void pushBatchCommand(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
u32 vertexByteOffset, u32 vertexCount,
const u16* localIndices, u32 indexCount,
const BatchDrawKey& key) {
pushBatchCommandImpl(pool, drawList, clips, vertexByteOffset, vertexCount, localIndices, indexCount, key);
}
void appendIndexedDraw(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
const void* verts, u32 vertexCount,
const u32* localIndices, u32 indexCount,
const BatchDrawKey& key) {
if (vertexCount == 0 || indexCount == 0
|| !batchEntityVisible(drawList, clips, key.entity, key.layer, key.cullBit)) return;
u32 vertexByteOffset = pool.appendVertices(
key.layoutId, verts, vertexCount * pool.vertexStride(key.layoutId));
pushBatchCommandImpl(pool, drawList, clips, vertexByteOffset, vertexCount, localIndices, indexCount, key);
}
void appendIndexedBatch(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
const BatchVertex* verts, u32 vertexCount,
const u32* localIndices, u32 indexCount,
const BatchDrawKey& key) {
appendIndexedDraw(pool, drawList, clips, verts, vertexCount, localIndices, indexCount, key);
}
} // namespace esengine