Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
BatchBuilder.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
13#include "./BatchBuilder.hpp"
14
15#include <vector>
16
17namespace esengine {
18
19bool batchEntityVisible(const DrawList& drawList, const ClipState& clips,
20 Entity entity, i32 layer, u32 cullBit) {
21 if (clips.isEmptyScissor(entity)) return false;
22 if (cullBit) return drawList.layerVisible(cullBit);
23 const auto identity = drawList.sortIdentity(entity.id(), layer, 0);
24 return drawList.layerVisible(DrawList::layerBit(identity.layer));
25}
26
27namespace {
28
29// Reused across calls so offsetting local indices into the target stream costs no
30// per-call heap allocation. The renderer collects single-threaded and each call fully
31// consumes the scratch before returning, so a file-local buffer is safe — and it amortizes
32// the allocation across the frame, mirroring DrawList::sorted_scratch_.
33std::vector<u32> g_indexScratch;
34
35template <typename IndexT>
36void pushBatchCommandImpl(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
37 u32 vertexByteOffset, u32 vertexCount,
38 const IndexT* localIndices, u32 indexCount,
39 const BatchDrawKey& key) {
40 if (indexCount == 0 || !batchEntityVisible(drawList, clips, key.entity, key.layer, key.cullBit)) return;
41
42 u32 baseVertex = vertexByteOffset / pool.vertexStride(key.layoutId);
43 g_indexScratch.resize(indexCount);
44 for (u32 i = 0; i < indexCount; ++i) {
45 g_indexScratch[i] = baseVertex + static_cast<u32>(localIndices[i]);
46 }
47 u32 indexOffset = pool.appendIndices(key.layoutId, g_indexScratch.data(), indexCount);
48
49 pushBatchDraw(drawList, clips, vertexByteOffset, vertexCount, indexOffset, indexCount, key);
50}
51
52} // namespace
53
54void pushBatchDraw(DrawList& drawList, const ClipState& clips,
55 u32 vertexByteOffset, u32 vertexCount, u32 indexOffset, u32 indexCount,
56 const BatchDrawKey& key) {
57 if (indexCount == 0 || clips.isEmptyScissor(key.entity)) return;
58
59 // A group takes over its members' outward identity, so EVERY layer-derived decision
60 // below asks the group's layer: the culling bit, the ordering rule, the key's top field.
61 // Leaving one on the member y-sorts a group through one sprite and not the next.
62 const DrawList::SortIdentity identity =
63 drawList.sortIdentity(key.entity.id(), key.layer, key.order);
64 const i32 layer = identity.layer;
65 const i32 order = identity.order;
66 const DrawList::GroupIdentity* group = drawList.sortingGroupOf(key.entity.id());
67
68 // The camera's culling mask, applied at the one place draws are produced, so no
69 // render path can be added that forgets it.
70 if (!drawList.layerVisible(key.cullBit ? key.cullBit : DrawList::layerBit(layer))) return;
71
72 DrawCommand cmd{};
73 const auto resolve = drawList.layerOrder(layer);
74
75 // A depth layer decides its own stage and depth state; every other layer takes
76 // what the caller resolved from the material. The rule is the physical one, so
77 // it is derived rather than declared: an opaque draw may write depth and sorts
78 // front-to-back (the key inverts its depth bits for the Opaque stage, which is
79 // what makes early-z pay off), while a blended draw MUST NOT write — writing is
80 // how translucent sprites clip each other into black edges — so it only tests,
81 // and stays in back-to-front painter's order. Nobody should have to declare a
82 // fact about alpha compositing per material.
83 RenderStage stage = key.stage;
84 bool depthTest = key.depthTest;
85 bool depthWrite = key.depthWrite;
86 if (resolve == DrawList::LayerOrder::Depth) {
87 const bool opaque = key.blend == BlendMode::None;
89 depthTest = true;
90 depthWrite = opaque;
91 }
92
93 // stateFlags is 0: ClipState stamps the real scissor/stencil below, after the key
94 // exists. A stencil write still precedes the draws testing it because UI pre-order
95 // puts a mask below its descendants in LAYER, the key's top field. Not so on one layer.
97 ? DrawCommand::buildSortKeyYSorted(stage, layer, key.y, key.shaderId,
98 key.blend, 0, order)
100 ? DrawCommand::buildSortKeyTree(stage, layer, drawList.treeSequenceOf(key.entity), key.shaderId,
101 key.blend, 0, order)
102 : DrawCommand::buildSortKey(stage, layer, key.shaderId,
103 key.blend, 0, key.depth, key.materialId, order,
105 ? ((static_cast<u32>(key.vertexBuffer) * 2654435761u) ^ (indexOffset * 2246822519u)) >> 24 | 1u
106 : 0u);
107 // Inside a group the member's own order is all that separates siblings. Under a NESTED
108 // group it is the inner group's instead — a block does not come apart around another
109 // block's contents.
110 if (group) {
112 cmd.sort_key, group->blockOrder ? group->block : key.order);
113 }
114 cmd.stage = stage;
115 cmd.index_offset = indexOffset;
116 cmd.index_count = indexCount;
117 cmd.vertex_byte_offset = vertexByteOffset;
118 cmd.vertex_count = vertexCount;
122 cmd.vertex_buffer = key.vertexBuffer;
123 cmd.index_buffer = key.indexBuffer;
124 cmd.vertex_layout = key.vertexLayout;
125 cmd.skin_offset = key.skinOffset;
126 cmd.skin_count = key.skinCount;
127 cmd.morph_index = key.morphIndex;
128 cmd.probe_index = key.probeIndex;
129 cmd.planar_index = key.planarIndex;
130 cmd.shader_id = key.shaderId;
132 cmd.blend_mode = key.blend;
133 cmd.layout_id = key.layoutId;
134 cmd.material_id = key.materialId;
135 cmd.depth_test = depthTest;
136 cmd.depth_write = depthWrite;
137 cmd.cull = key.cull;
138 cmd.depth_bias = key.depthBias;
139 cmd.topology = key.topology;
140 // The Batch stream always samples a texture (white fallback at minimum); other
141 // streams bind one only when the draw actually has one (the shape stream is
142 // textureless, so execute() must not touch sampler units for it).
143 cmd.texture_count = (key.layoutId == LayoutId::Batch || key.textureId != 0) ? 1 : 0;
144 cmd.texture_ids[0] = key.textureId;
145 // Slot 1 belongs to the draw, so it is only ever bound where the shader
146 // declares it — the Batch stream picks its extra slots per vertex instead.
147 if (key.normalTextureId != 0 && cmd.texture_count == 1 && key.layoutId != LayoutId::Batch) {
148 cmd.texture_ids[1] = key.normalTextureId;
149 cmd.texture_count = 2;
150 }
151 // The shadow map's unit is pinned in the shader, so the gap below it is filled
152 // rather than the slot moved: a draw with no normal map still samples slot 2.
153 if (key.shadowTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
154 if (cmd.texture_count == 1) cmd.texture_ids[1] = key.textureId;
155 cmd.texture_ids[2] = key.shadowTextureId;
156 cmd.texture_count = 3;
157 }
158 // The reflection atlas is pinned one slot further on, filled the same way.
159 if (key.envTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
160 for (u8 slot = cmd.texture_count; slot < 3; ++slot) cmd.texture_ids[slot] = key.textureId;
161 cmd.texture_ids[3] = key.envTextureId;
162 cmd.texture_count = 4;
163 }
164 // The mesh's own deltas, one slot further still. Read in the VERTEX stage,
165 // unlike the three above — the only sampler here that is.
166 if (key.morphTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
167 for (u8 slot = cmd.texture_count; slot < 4; ++slot) cmd.texture_ids[slot] = key.textureId;
168 cmd.texture_ids[4] = key.morphTextureId;
169 cmd.texture_count = 5;
170 }
171 // The baked atlas, on the last slot below the frame's two masks. A draw whose
172 // geometry can read one but has none binds nothing here: the fill is white,
173 // and its record's rectangle is what says the bake does not apply.
174 if (key.lightmapTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
175 for (u8 slot = cmd.texture_count; slot < 5; ++slot) cmd.texture_ids[slot] = key.textureId;
176 cmd.texture_ids[5] = key.lightmapTextureId;
177 cmd.texture_count = 6;
178 } else if (key.probeGridTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
179 for (u8 slot = cmd.texture_count; slot < 5; ++slot) cmd.texture_ids[slot] = key.textureId;
180 cmd.texture_ids[5] = key.probeGridTextureId;
181 cmd.texture_count = 6;
182 }
183 cmd.entity = key.entity;
184 cmd.type = key.type;
185 cmd.layer = layer;
186
187 clips.applyTo(key.entity, cmd);
188 drawList.push(cmd);
189}
190
191void pushBatchCommand(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
192 u32 vertexByteOffset, u32 vertexCount,
193 const u32* localIndices, u32 indexCount,
194 const BatchDrawKey& key) {
195 pushBatchCommandImpl(pool, drawList, clips, vertexByteOffset, vertexCount, localIndices, indexCount, key);
196}
197
198void pushBatchCommand(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
199 u32 vertexByteOffset, u32 vertexCount,
200 const u16* localIndices, u32 indexCount,
201 const BatchDrawKey& key) {
202 pushBatchCommandImpl(pool, drawList, clips, vertexByteOffset, vertexCount, localIndices, indexCount, key);
203}
204
205void appendIndexedDraw(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
206 const void* verts, u32 vertexCount,
207 const u32* localIndices, u32 indexCount,
208 const BatchDrawKey& key) {
209 if (vertexCount == 0 || indexCount == 0
210 || !batchEntityVisible(drawList, clips, key.entity, key.layer, key.cullBit)) return;
211 u32 vertexByteOffset = pool.appendVertices(
212 key.layoutId, verts, vertexCount * pool.vertexStride(key.layoutId));
213 pushBatchCommandImpl(pool, drawList, clips, vertexByteOffset, vertexCount, localIndices, indexCount, key);
214}
215
216void appendIndexedBatch(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
217 const BatchVertex* verts, u32 vertexCount,
218 const u32* localIndices, u32 indexCount,
219 const BatchDrawKey& key) {
220 appendIndexedDraw(pool, drawList, clips, verts, vertexCount, localIndices, indexCount, key);
221}
222
223void appendQuads(TransientBufferPool& pool, DrawList& drawList, const ClipState& clips,
224 const BatchVertex* quads, u32 quadCount, const BatchDrawKey& key) {
225 if (quadCount == 0 || !batchEntityVisible(drawList, clips, key.entity, key.layer, key.cullBit)) return;
226 const u32 vertexCount = quadCount * 4;
227 const u32 vertexByteOffset = pool.appendVertices(key.layoutId, quads, vertexCount * pool.vertexStride(key.layoutId));
228 const u32 baseVertex = vertexByteOffset / pool.vertexStride(key.layoutId);
229 const u32 indexCount = quadCount * 6;
230 g_indexScratch.resize(indexCount);
231 for (u32 q = 0; q < quadCount; ++q) {
232 for (u32 i = 0; i < 6; ++i) g_indexScratch[q * 6 + i] = baseVertex + q * 4 + BATCH_QUAD_INDICES[i];
233 }
234 const u32 indexOffset = pool.appendIndices(key.layoutId, g_indexScratch.data(), indexCount);
235 pushBatchDraw(drawList, clips, vertexByteOffset, vertexCount, indexOffset, indexCount, key);
236}
237
238} // namespace esengine
The single submission face: the ONLY place a DrawCommand is assembled.
bool isEmptyScissor(Entity entity) const
void applyTo(Entity entity, DrawCommand &cmd) const
Definition ClipState.hpp:84
const GroupIdentity * sortingGroupOf(u32 entity) const
The group entity belongs to, or null when it sorts on its own.
Definition DrawList.hpp:275
static u32 layerBit(i32 layer)
The mask bit of a sorting layer, or 0 when it has none (outside 0..31).
Definition DrawList.hpp:227
SortIdentity sortIdentity(u32 entity, i32 ownLayer, i32 ownOrder) const
The one answer to "where does this draw sit". Asked by the draw path when it builds a key,...
Definition DrawList.hpp:294
LayerOrder layerOrder(i32 layer) const
The one answer for layer, from two masks that are two spellings of the same question.
Definition DrawList.hpp:245
void push(const DrawCommand &cmd)
Definition DrawList.cpp:102
u32 treeSequenceOf(Entity entity) const
Definition DrawList.hpp:194
bool layerVisible(u32 layerBit) const
Whether a draw belonging to layerBit survives this camera's mask. Bit 0 means "no layer" (outside 0....
Definition DrawList.hpp:222
u32 appendVertices(LayoutId layout, const void *data, u32 byteSize)
u32 vertexStride(LayoutId layout) const
u32 appendIndices(LayoutId layout, const u32 *data, u32 count)
void appendQuads(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const BatchVertex *quads, u32 quadCount, const BatchDrawKey &key)
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
void appendIndexedDraw(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const void *verts, u32 vertexCount, const u32 *localIndices, u32 indexCount, const BatchDrawKey &key)
Copies raw vertices into the key's stream, then pushes one DrawCommand spanning them.
void pushBatchDraw(DrawList &drawList, const ClipState &clips, u32 vertexByteOffset, u32 vertexCount, u32 indexOffset, u32 indexCount, const BatchDrawKey &key)
Atomic primitive: assemble + clip + push one DrawCommand for an index range ALREADY written into (or,...
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
std::uint16_t u16
Unsigned 16-bit integer.
Definition Types.hpp:43
void pushBatchCommand(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, u32 vertexByteOffset, u32 vertexCount, const u32 *localIndices, u32 indexCount, const BatchDrawKey &key)
Pushes a DrawCommand for vertices ALREADY resident in the Batch stream at vertexByteOffset.
void appendIndexedBatch(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const BatchVertex *verts, u32 vertexCount, const u32 *localIndices, u32 indexCount, const BatchDrawKey &key)
Copies verts into the Batch stream, then pushes one DrawCommand spanning them.
bool batchEntityVisible(const DrawList &drawList, const ClipState &clips, Entity entity, i32 layer, u32 cullBit)
constexpr u32 BATCH_QUAD_INDICES[6]
Canonical two-triangle quad winding shared by every batch path.
Non-geometry attributes of a batch draw — everything needed to build the sort key + DrawCommand.
i16 depthBias
Depth-buffer units toward the eye.
GfxTopology topology
How the indices assemble.
u8 cull
CullMode: 0 = none, 1 = back, 2 = front.
VertexLayoutHandle vertexLayout
One vertex of the shared batch stream.
static u64 buildSortKey(RenderStage stage, i32 layer, u32 shaderId, BlendMode blend, u16 stateFlags, f32 depth, u32 materialId=0, i32 order=0, u32 geometry=0)
BufferHandle instance_buffer
static u64 buildSortKeyTree(RenderStage stage, i32 layer, u32 sequence, u32 shaderId, BlendMode blend, u16 stateFlags, i32 order=0)
static u64 withGroupOrder(u64 key, i32 memberOrder)
Re-stamps a member's own order into a key whose top fields a SortingGroup has taken over.
i16 depth_bias
Depth-buffer units toward the eye.
VertexLayoutHandle vertex_layout
u32 texture_ids[MAX_CMD_TEXTURE_SLOTS]
static u64 buildSortKeyYSorted(RenderStage stage, i32 layer, f32 worldY, u32 shaderId, BlendMode blend, u16 stateFlags, i32 order=0)
BufferHandle index_buffer
GfxTopology topology
Triangles or lines.
u8 cull
CullMode: 0 = none, 1 = back, 2 = front.
BufferHandle vertex_buffer
The sorting identity a SortingGroup imposes on one of its members.
Definition DrawList.hpp:256
Where a draw sits in the frame's order, once any group has had its say.
Definition DrawList.hpp:282
Entity identifier with packed index + generation.
Definition Types.hpp:135
constexpr u32 id() const
Returns the raw packed value for FFI serialization.
Definition Types.hpp:159