Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
DrawList.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#pragma once
4
6#include "./DrawCommand.hpp"
14#include "../../math/Math.hpp"
15
16#include <algorithm>
17#include <functional>
18#include <string>
19#include <utility>
20#include <unordered_map>
21#include <span>
22#include <vector>
23
24namespace esengine {
25
26class MaterialStore;
27
28class DrawList {
29public:
30 void clear();
31 void push(const DrawCommand& cmd);
32
33 // Sorts, then coalesces contiguous compatible commands — combining up to 8 textures
34 // into one multi-texture batch and stamping each command's per-vertex sampler slot
35 // (hence the pool, whose staging it rewrites; call before upload()).
36 void finalize(TransientBufferPool& pool);
37
38 template <typename Remap>
39 void remapPrograms(Remap&& remap) {
40 for (auto& command : commands_) command.shader_id = remap(command.shader_id);
41 }
42
46 void reserveMask2DSlots(u32 count) { mask_2d_slots_ = std::min(count, MAX_CMD_TEXTURE_SLOTS); }
47
50 bool sortKeyRange(u64& lo, u64& hi) const {
51 if (commands_.empty()) return false;
52 lo = ~u64{0};
53 hi = 0;
54 for (const DrawCommand& command : commands_) {
55 lo = std::min(lo, command.sort_key);
56 hi = std::max(hi, command.sort_key);
57 }
58 return true;
59 }
60
63 void copySettingsFrom(const DrawList& other) {
64 shader_run_sink_ = other.shader_run_sink_;
65 defer_screen_color_ = other.defer_screen_color_;
66 layer_alpha_ = other.layer_alpha_;
67 layerless_visible_ = other.layerless_visible_;
68 std::copy(std::begin(other.mask_2d_textures_), std::end(other.mask_2d_textures_), std::begin(mask_2d_textures_));
69 gbuffer_pass_ = other.gbuffer_pass_;
70 mask_2d_slots_ = other.mask_2d_slots_;
71 ysort_mask_ = other.ysort_mask_;
72 tree_mask_ = other.tree_mask_;
73 depth_mask_ = other.depth_mask_;
74 culling_mask_ = other.culling_mask_;
75 }
76
80 void setGBufferPass(bool on) { gbuffer_pass_ = on; }
81
84 void setMask2DTexture(u32 unit, u32 textureId) {
85 if (unit < MAX_CMD_TEXTURE_SLOTS) mask_2d_textures_[unit] = textureId;
86 }
87
88 // Each merged command resolves to an immutable pipeline (program + layout + blend +
89 // depth + stencil + cull) bound via GfxDevice::setPipeline; per-draw dynamic state
90 // (scissor, stencil ref, textures) is applied directly. Per-frame constants come from
91 // the FrameConstants UBO bound by RenderContext; per-material constants from each
92 // command's material UBO, bound here via MaterialStore::bindForDraw.
93 // white_texture_id fills a Batch draw's unused sampler slots — a STABLE texture
94 // so those slots stay pinned across draws and the bind cache dedups them
95 // (filling with the draw's own tex re-pointed all 8 units on every tex change).
103 void execute(GfxDevice& device, TransientBufferPool& buffers,
104 MaterialStore& materials, u32 white_texture_id = 0,
105 FrameCapture* capture = nullptr,
106 const PerDrawBlockSet& blocks = {}, Phase phase = Phase::All, DrawPass pass = DrawPass::Color);
107
110 void setShaderRunSink(std::function<void(const char*)> sink) { shader_run_sink_ = std::move(sink); }
111
113 u32 skippedForProgram() const { return skipped_for_program_; }
114
116 u32 depthPrepassDraws() const;
117
119 bool anyUsesSceneColor(const MaterialStore& materials) const;
120 bool anyUsesScreenColor(const MaterialStore& materials) const;
121 void setDeferScreenColor(bool defer) { defer_screen_color_ = defer; }
122 void setLayerAlpha(bool layer) { layer_alpha_ = layer; }
123 void setLayerlessVisible(bool visible) { layerless_visible_ = visible; }
125 bool anyNeedsScenePicture(const MaterialStore& materials) const;
127 bool anyBlendedWithoutSceneColor(const MaterialStore& materials) const;
129 bool anyUsesSceneDepth(const MaterialStore& materials) const;
130
133 u32 addSkinMatrices(const glm::mat4* matrices, u32 count);
134 const glm::mat4* skinMatrices() const { return skin_matrices_.data(); }
135
138 u32 addMorphShapes(const MorphConstants& shapes);
139
142 u32 addProbe(const ProbeConstants& probe);
143 u32 addPlanar(const PlanarConstants& value) { planar_.push_back(value); return static_cast<u32>(planar_.size()); }
144
145 u32 commandCount() const { return static_cast<u32>(commands_.size()); }
148 const auto index = static_cast<u32>(type);
149 return index < entity_counts_.size() ? entity_counts_[index] : 0;
150 }
151 u32 mergedDrawCallCount() const { return merged_draw_calls_; }
153 u32 breakCount(BatchBreak reason) const { return breaks_[static_cast<u32>(reason)]; }
155 u32 mergedAwayCount() const { return merged_away_; }
157 std::span<const Entity> runEntities(u32 index) const;
158
159
160 const DrawCommand* commands() const { return commands_.data(); }
161
169 u64 contentHash(u64 seed) const;
170
178 u64 contentHashOfRecords(u64 seed, TransientBufferPool& pool, bool& trusted) const;
179 const DrawCommand& command(u32 index) const { return commands_[index]; }
180
181 // Bit i set ⇒ layer i (0..31) sorts by world Y within the layer (top-down
182 // occlusion) instead of material/depth. Lives here so pushBatchDraw — the one
183 // key-building site — consults it for every render path uniformly.
184 void setYSortMask(u32 mask) { ysort_mask_ = mask; }
185 u32 ySortMask() const { return ysort_mask_; }
186
187 // Bit i set ⇒ layer i (0..31) is painted in TREE order: its draws sort by where their entity stands in the hierarchy (a preorder walk,
188 // children in their list order), whatever they are — a sprite, a label, a shape. That is how a scene of nodes is stacked in an authoring
189 // tool that has no per-material or per-depth ordering, and it is the only order in which a panel can cover the text of the panel
190 // beneath it: ordered by shader, every label would land above every image of the layer.
191 void setTreeMask(u32 mask) { tree_mask_ = mask; }
192 u32 treeMask() const { return tree_mask_; }
193 std::vector<u32>& treeSequence() { return tree_sequence_; }
194 u32 treeSequenceOf(Entity entity) const {
195 const u32 index = entity.index();
196 return index < tree_sequence_.size() ? tree_sequence_[index] : 0u;
197 }
198
199 // Bit i set ⇒ layer i resolves its contents by real depth: opaque draws write
200 // the depth buffer and sort front-to-back, blended ones test against it without
201 // writing and stay in painter's order. This is the 2.5D opt-in.
202 void setDepthMask(u32 mask) { depth_mask_ = mask; }
203 u32 depthMask() const { return depth_mask_; }
204
213 bool needsDepth() const { return depth_mask_ != 0 || depth_required_; }
214
215 // Bit i set ⇒ the camera being rendered draws layer i. A camera property, not a
216 // scene one, so it is set per camera (RenderFrame::begin clears the list each time).
217 void setCullingMask(u32 mask) { culling_mask_ = mask; }
218 u32 cullingMask() const { return culling_mask_; }
219
223 return layerBit == 0 ? layerless_visible_ : (culling_mask_ & layerBit) != 0;
224 }
225
227 static u32 layerBit(i32 layer) {
228 return (layer < 0 || layer >= 32) ? 0u : (1u << layer);
229 }
230
232 enum class LayerOrder : u8 { Painter, YSort, Depth, Tree };
233
245 LayerOrder layerOrder(i32 layer) const {
246 if (layer < 0 || layer >= 32) return LayerOrder::Painter;
247 const u32 bit = 1u << layer;
248 if (ysort_mask_ & bit) return LayerOrder::YSort;
249 // Tree order is a stated painter's order and depth is a measured one; a layer saying both has asked for the stated one.
250 if (tree_mask_ & bit) return LayerOrder::Tree;
251 if (depth_mask_ & bit) return LayerOrder::Depth;
252 return LayerOrder::Painter;
253 }
254
263 bool blockOrder = false;
265 };
266
269 void setSortingGroup(u32 entity, const GroupIdentity& identity) {
270 group_identities_[entity] = identity;
271 }
272 void clearSortingGroups() { group_identities_.clear(); }
273
275 const GroupIdentity* sortingGroupOf(u32 entity) const {
276 if (group_identities_.empty()) return nullptr;
277 auto it = group_identities_.find(entity);
278 return it != group_identities_.end() ? &it->second : nullptr;
279 }
280
285 bool operator<(const SortIdentity& o) const {
286 return layer != o.layer ? layer < o.layer : order < o.order;
287 }
288 bool operator<=(const SortIdentity& o) const { return !(o < *this); }
289 };
290
294 SortIdentity sortIdentity(u32 entity, i32 ownLayer, i32 ownOrder) const {
295 if (const GroupIdentity* g = sortingGroupOf(entity)) return {g->layer, g->order};
296 return {ownLayer, ownOrder};
297 }
298
299private:
300 std::function<void(const char*)> shader_run_sink_;
301 u32 skipped_for_program_ = 0;
304 std::vector<u8> prepass_skipped_;
305 bool defer_screen_color_ = false;
306 bool layer_alpha_ = false;
307 bool layerless_visible_ = true;
308 struct SortEntry {
309 u64 key;
310 u32 index;
311 };
312
313 std::vector<DrawCommand> commands_;
314 std::array<u32, static_cast<u32>(RenderType::Trail) + 1> entity_counts_{};
316 std::vector<glm::mat4> skin_matrices_;
317 std::vector<MorphConstants> morph_shapes_;
318 std::vector<ProbeConstants> probes_;
319 std::vector<PlanarConstants> planar_;
323 std::vector<u32> probe_slots_;
326 std::vector<Entity> run_entities_;
327 std::vector<u32> run_first_;
330 std::vector<glm::vec4> probe_run_;
332 struct StagedBlocks {
333 PerDrawBlocks::Range skin, probe, instance, planar;
334 };
335 std::vector<StagedBlocks> staged_;
337 std::vector<u32> run_length_;
339 std::vector<u32> entry_texel_;
340 std::vector<u32> run_counts_, run_offsets_, run_instances_;
342 static bool joinsRun(const DrawCommand& prev, const DrawCommand& next);
344 static bool readsRecords(const DrawCommand& cmd);
346 bool probeLitAt(const DrawCommand& cmd) const;
348 void writeEntries(TransientBufferPool& pool);
349 void stageBlocks(const PerDrawBlockSet& blocks, bool drawRuns);
352 std::vector<SortEntry> sort_entries_;
353 std::vector<u64> sorted_keys_;
354 std::vector<DrawCommand> sorted_scratch_; // reused across frames to avoid a
355 // per-frame heap alloc in finalize()
356 std::vector<DrawCommand> stencil_commands_scratch_;
357 std::vector<DrawCommand> stencil_stack_scratch_;
358 std::vector<u32> stencil_level_first_;
359 bool ui_stencil_required_ = false;
361 u32 mask_2d_textures_[MAX_CMD_TEXTURE_SLOTS] = {};
363 bool gbuffer_pass_ = false;
364 u32 mask_2d_slots_ = 0;
365 u32 merged_draw_calls_ = 0;
366 u32 merged_away_ = 0;
367 u32 breaks_[static_cast<u32>(BatchBreak::Count)] = {};
369 std::unordered_map<u32, GroupIdentity> group_identities_;
370 u32 ysort_mask_ = 0;
371 u32 tree_mask_ = 0;
372 std::vector<u32> tree_sequence_;
373 u32 depth_mask_ = 0;
375 bool depth_required_ = false;
376 u32 culling_mask_ = 0xFFFFFFFFu; // every layer, until a camera says otherwise
377};
378
379} // namespace esengine
One frame's draw calls as the device received them, for the frame debugger.
Abstract graphics device interface.
WHERE one draw's entry is in the frame's per-object record texture, and what an entry says.
Math utilities and GLM configuration for ESEngine.
The shapes one draw is blended towards: which targets, and how far.
A uniform range per draw, so two draws never write into one block.
The indirect light where ONE draw stands, when a grid was baked for it.
Core type definitions and utilities for ESEngine.
u32 ySortMask() const
Definition DrawList.hpp:185
const DrawCommand * commands() const
Definition DrawList.hpp:160
u32 skippedForProgram() const
How many merged draws the last execute left out because their program was not ready (GfxDevice::setSk...
Definition DrawList.hpp:113
const GroupIdentity * sortingGroupOf(u32 entity) const
The group entity belongs to, or null when it sorts on its own.
Definition DrawList.hpp:275
bool anyUsesScreenColor(const MaterialStore &materials) const
Definition DrawList.cpp:518
bool sortKeyRange(u64 &lo, u64 &hi) const
Definition DrawList.hpp:50
u32 mergedDrawCallCount() const
Definition DrawList.hpp:151
u32 commandCount() const
Definition DrawList.hpp:145
u32 addProbe(const ProbeConstants &probe)
Definition DrawList.cpp:97
u64 contentHashOfRecords(u64 seed, TransientBufferPool &pool, bool &trusted) const
contentHash with the instance records each command reads from pool in place of where they lie in it: ...
Definition DrawList.cpp:785
void finalize(TransientBufferPool &pool)
Definition DrawList.cpp:113
void setDeferScreenColor(bool defer)
Definition DrawList.hpp:121
u32 sourceEntityCount(RenderType type) const
Definition DrawList.hpp:147
bool anyUsesSceneColor(const MaterialStore &materials) const
Whether any merged draw reads the picture behind it.
Definition DrawList.cpp:511
const glm::mat4 * skinMatrices() const
Definition DrawList.hpp:134
void setDepthMask(u32 mask)
Definition DrawList.hpp:202
u32 depthMask() const
Definition DrawList.hpp:203
void setYSortMask(u32 mask)
Definition DrawList.hpp:184
std::vector< u32 > & treeSequence()
Definition DrawList.hpp:193
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
u32 addSkinMatrices(const glm::mat4 *matrices, u32 count)
Definition DrawList.cpp:86
u32 depthPrepassDraws() const
How many of the merged draws take part in a depth prepass; 0 means a prepass has nothing to draw.
Definition DrawList.cpp:544
void clearSortingGroups()
Definition DrawList.hpp:272
const DrawCommand & command(u32 index) const
Definition DrawList.hpp:179
void remapPrograms(Remap &&remap)
Definition DrawList.hpp:39
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 execute(GfxDevice &device, TransientBufferPool &buffers, MaterialStore &materials, u32 white_texture_id=0, FrameCapture *capture=nullptr, const PerDrawBlockSet &blocks={}, Phase phase=Phase::All, DrawPass pass=DrawPass::Color)
Definition DrawList.cpp:559
void setTreeMask(u32 mask)
Definition DrawList.hpp:191
u32 mergedAwayCount() const
Definition DrawList.hpp:155
bool anyBlendedWithoutSceneColor(const MaterialStore &materials) const
Whether the list holds a blended draw that does not refract: what has to be ordered against a refract...
Definition DrawList.cpp:531
u32 addMorphShapes(const MorphConstants &shapes)
Definition DrawList.cpp:92
u32 addPlanar(const PlanarConstants &value)
Definition DrawList.hpp:143
bool needsDepth() const
Whether a frame holding these draws has to be handed a depth buffer.
Definition DrawList.hpp:213
void setSortingGroup(u32 entity, const GroupIdentity &identity)
Resolved once per collect, by the one walk that knows the hierarchy — the draw path only reads it,...
Definition DrawList.hpp:269
bool anyUsesSceneDepth(const MaterialStore &materials) const
Whether any merged draw reads the distance to the opaque scene behind it.
Definition DrawList.cpp:552
void setMask2DTexture(u32 unit, u32 textureId)
Definition DrawList.hpp:84
void push(const DrawCommand &cmd)
Definition DrawList.cpp:102
u32 cullingMask() const
Definition DrawList.hpp:218
void setGBufferPass(bool on)
Definition DrawList.hpp:80
void reserveMask2DSlots(u32 count)
Definition DrawList.hpp:46
bool anyNeedsScenePicture(const MaterialStore &materials) const
Whether a draw is of a material that does not work without a picture of the scene (MaterialStore::nee...
Definition DrawList.cpp:504
void setShaderRunSink(std::function< void(const char *)> sink)
Definition DrawList.hpp:110
u32 treeSequenceOf(Entity entity) const
Definition DrawList.hpp:194
void setCullingMask(u32 mask)
Definition DrawList.hpp:217
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
LayerOrder
How one sorting layer resolves the draws inside it.
Definition DrawList.hpp:232
void setLayerlessVisible(bool visible)
Definition DrawList.hpp:123
void copySettingsFrom(const DrawList &other)
Definition DrawList.hpp:63
void setLayerAlpha(bool layer)
Definition DrawList.hpp:122
u64 contentHash(u64 seed) const
A hash of what the list draws: each command's program, geometry, state and ranges,...
Definition DrawList.cpp:824
std::span< const Entity > runEntities(u32 index) const
Definition DrawList.cpp:307
u32 breakCount(BatchBreak reason) const
Definition DrawList.hpp:153
u32 treeMask() const
Definition DrawList.hpp:192
Abstract graphics device interface.
Definition GfxDevice.hpp:75
Maps a material handle to its resolved record. Owned by RenderContext so it is reachable from both th...
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
static constexpr u32 MAX_CMD_TEXTURE_SLOTS
auto sink(SignalType &signal)
Create a sink for a signal.
Definition Sink.hpp:175
The sorting identity a SortingGroup imposes on one of its members.
Definition DrawList.hpp:256
i32 layer
What the whole group presents outward — the key's top two fields.
Definition DrawList.hpp:258
Where a draw sits in the frame's order, once any group has had its say.
Definition DrawList.hpp:282
bool operator<(const SortIdentity &o) const
Definition DrawList.hpp:285
bool operator<=(const SortIdentity &o) const
Definition DrawList.hpp:288
Entity identifier with packed index + generation.
Definition Types.hpp:135
constexpr u32 index() const
Gets the entity index.
Definition Types.hpp:150
One draw's shapes, laid out as the texels they are written as.
The uniform blocks a draw rewrites immediately before it.
The indirect light one instance stands in — both halves of it.