Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
RenderFrameSubmit.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#include "./RenderFrame.hpp"
9
10#include <glm/gtc/type_ptr.hpp>
14#include "./RenderContext.hpp"
15
16#include <glm/gtc/type_ptr.hpp>
17
18#include <algorithm>
19
20namespace esengine {
21
23 const glm::vec2& position, const glm::vec2& size,
24 const glm::vec2& uvOffset, const glm::vec2& uvScale,
25 const glm::vec4& color, u32 textureId,
26 Entity entity, i32 layer, f32 depth
27) {
28 f32 hw = size.x * 0.5f;
29 f32 hh = size.y * 0.5f;
30 u32 pc = packColor(color);
31
32 BatchVertex verts[4] = {
33 { {position.x - hw, position.y - hh, depth}, pc, uvOffset },
34 { {position.x + hw, position.y - hh, depth}, pc, {uvOffset.x + uvScale.x, uvOffset.y} },
35 { {position.x + hw, position.y + hh, depth}, pc, {uvOffset.x + uvScale.x, uvOffset.y + uvScale.y} },
36 { {position.x - hw, position.y + hh, depth}, pc, {uvOffset.x, uvOffset.y + uvScale.y} },
37 };
38
39 appendQuad(pool_, draw_list_, clip_state_, verts, BatchDrawKey{
40 .stage = current_stage_,
41 .layer = layer,
42 .shaderId = batch_shader_id_,
43 .blend = BlendMode::Normal,
44 .textureId = textureId,
45 .depth = depth,
46 .entity = entity,
47 .type = RenderType::Sprite,
48 });
49}
50
51void RenderFrame::submitRetainedText(ecs::Registry& registry, bool screen, const f32* projection, u32 onlyRoot) {
52 // Scratch that outlives the call: a frame of labels would otherwise allocate them each time.
53 static RetainedTextClip clip;
54 static std::vector<f32> faded;
55 double planes[36];
56 const ecs::GroupOpacityLookup groupOpacity(registry);
57 for (auto& [raw, text] : retained_text_.entries()) {
58 if (text.screen != screen) continue;
59 if (onlyRoot != 0 && screenRootAt(raw) != onlyRoot) continue;
60 const Entity entity = Entity::fromRaw(raw);
61 if (!registry.valid(entity)) continue;
62 const auto* node = registry.tryGet<ecs::UINode>(entity);
63 if (node && node->hidden_in_tree_) continue;
64 const f32 opacity = (node ? node->alpha_in_tree_ : 1.0f) * groupOpacity.of(entity);
65 if (opacity <= 0.0f) continue;
66 glm::mat4 matrix;
67 if (!ecs::copyFlatRenderMatrix(registry, entity, matrix)) continue;
68 const auto* visual = registry.tryGet<ecs::UIVisual>(entity);
69 i32 layer = text.layer;
70 if (text.hasBox) {
71 const i32 order = visual ? visual->uiOrder : -1;
73 }
74 // Screen draws all share one depth: their order is the UI tree's, and a z left on a screen root would outrank a sibling.
75 f32 depth = 0.0f;
76 if (!text.screen) {
77 if (auto* transform = registry.tryGet<ecs::Transform>(entity)) {
78 transform->ensureDecomposed();
79 depth = transform->worldPosition.z;
80 }
81 }
82 const u32 cullBit = visual ? visual->uiCullBit : 0u;
83 const f32* model = glm::value_ptr(matrix);
84 const bool clipped = projection && retainedTextClipPlanes(planes, projection, model);
85 for (const RetainedTextBatch& batch : text.batches) {
86 const RetainedTextKept kept = retainedTextClip(batch, clipped ? planes : nullptr, clip);
87 if (kept == RetainedTextKept::None) continue;
88 const f32* vertices = kept == RetainedTextKept::All ? batch.vertices.data() : clip.vertices.data();
89 const u16* indices = kept == RetainedTextKept::All ? batch.indices.data() : clip.indices.data();
90 const usize vertexCount = (kept == RetainedTextKept::All ? batch.vertices.size() : clip.vertices.size()) / TEXT_VERTEX_FLOATS;
91 if (opacity != 1.0f) {
92 faded.assign(vertices, vertices + vertexCount * TEXT_VERTEX_FLOATS);
93 for (usize i = 7; i < faded.size(); i += TEXT_VERTEX_FLOATS) faded[i] *= opacity;
94 vertices = faded.data();
95 }
96 submitTextBatch(vertices, static_cast<i32>(vertexCount), indices, static_cast<i32>(vertexCount / 4 * 6),
97 batch.pageId, model, entity, layer, depth, batch.mode, cullBit);
98 }
99 }
100}
101
103 const f32* vertices, i32 vertexCount,
104 const u16* indices, i32 indexCount,
105 u32 textureId, const f32* transform16,
106 Entity entity, i32 layer, f32 depth, TextGlyphMode mode, u32 cullBit
107) {
108 if (vertexCount <= 0 || indexCount <= 0
109 || !batchEntityVisible(draw_list_, clip_state_, entity, layer, cullBit)) return;
110
111 glm::mat4 model = glm::make_mat4(transform16);
112
113 u32 vBytes = static_cast<u32>(vertexCount) * sizeof(BatchVertex);
114 u32 vOff = pool_.allocVertices(LayoutId::Batch, vBytes);
115 auto* dst = reinterpret_cast<BatchVertex*>(pool_.vertexData(LayoutId::Batch) + vOff);
116
117 const f32 glyphMode = static_cast<f32>(batchGlyphModeBits(mode));
118 for (i32 i = 0; i < vertexCount; ++i) {
119 const f32* v = vertices + i * TEXT_VERTEX_FLOATS;
120 glm::vec4 worldPos = model * glm::vec4(v[0], v[1], 0.0f, 1.0f);
121 u32 pc = packColor(glm::vec4(v[4], v[5], v[6], v[7]));
122 dst[i] = { {worldPos.x, worldPos.y, worldPos.z}, pc, {v[2], v[3]}, glyphMode, v[8] };
123 }
124
125 pushBatchCommand(pool_, draw_list_, clip_state_, vOff, static_cast<u32>(vertexCount), indices,
126 static_cast<u32>(indexCount), BatchDrawKey{
127 .stage = current_stage_,
128 .layer = layer,
129 .shaderId = batch_shader_id_,
130 .blend = BlendMode::Normal,
131 .textureId = textureId,
132 .depth = depth,
133 .cullBit = cullBit,
134 .entity = entity,
135 .type = RenderType::Text,
136 });
137}
138
140 const f32* vertices, i32 vertexCount,
141 const u16* indices, i32 indexCount,
142 u32 textureId, i32 blendMode,
143 const f32* transform16,
144 Entity entity, i32 layer, f32 depth, u32 materialId, bool premultipliedColor,
145 f32 treeAlpha, u32 cullBit
146) {
147 // The screen overlay and the cameras partition the world (RenderCollectContext::accepts):
148 // a skeleton under a screen Canvas is the overlay's, and a camera drawing it too is how it
149 // showed in the world at the Canvas' pixel coordinates while missing from the UI.
150 const bool screen = screen_domain_ && screen_domain_->count(entity.id()) != 0;
151 if (screen != overlay_active_) return;
152 if (layer == 0 && ui_tree_layers_) {
153 if (const auto it = ui_tree_layers_->find(entity.id()); it != ui_tree_layers_->end()) layer = it->second;
154 }
155 if (vertexCount <= 0 || indexCount <= 0 || treeAlpha <= 0.0f
156 || !batchEntityVisible(draw_list_, clip_state_, entity, layer, cullBit)) return;
157
158 constexpr i32 FLOATS_PER_VERTEX = 8;
159 glm::mat4 model = glm::make_mat4(transform16);
160 BlendMode blend = static_cast<BlendMode>(std::clamp(blendMode, 0, 5));
161
162 const MaterialRecord* material = materialId != 0 ? context_.materials().find(materialId) : nullptr;
163 const bool builtinColor = !material || material->shader == 0;
164
165 // Format the transformed vertices in place — a complex skeleton can carry many
166 // vertices, so we avoid staging them into a temporary before the pool copy.
167 u32 vBytes = static_cast<u32>(vertexCount) * sizeof(BatchVertex);
168 u32 vOff = pool_.allocVertices(LayoutId::Batch, vBytes);
169 auto* dst = reinterpret_cast<BatchVertex*>(pool_.vertexData(LayoutId::Batch) + vOff);
170
171 for (i32 i = 0; i < vertexCount; ++i) {
172 const f32* v = vertices + i * FLOATS_PER_VERTEX;
173 glm::vec4 worldPos = model * glm::vec4(v[0], v[1], 0.0f, 1.0f);
174 // The UI tree's opacity, as a control's quad takes it: premultiplied colour scales whole.
175 glm::vec4 color = glm::vec4(v[4], v[5], v[6], v[7]) * (premultipliedColor ? glm::vec4(treeAlpha) : glm::vec4(1.0f, 1.0f, 1.0f, treeAlpha));
176 if (premultipliedColor && builtinColor) {
177 // Recover straight color before 8-bit packing and the shader EOTF.
178 color = color.a > 0.0f ? glm::vec4(glm::vec3(color) / color.a, color.a)
179 : glm::vec4(0.0f);
180 }
181 u32 pc = packColor(color);
182 dst[i] = { {worldPos.x, worldPos.y, worldPos.z}, pc, {v[2], v[3]} };
183 }
184
185 const u32 defaultShader = !builtinColor ? material->shader
186 : premultipliedColor ? batchProgram(BatchVariant::PremultipliedColor) : batch_shader_id_;
187 BatchDrawKey key{
188 .stage = current_stage_,
189 .layer = layer,
190 .shaderId = defaultShader,
191 .blend = blend,
192 .textureId = textureId,
193 .depth = depth,
194 .cullBit = cullBit,
195 .entity = entity,
196 .type = RenderType::Skeletal,
197 };
198 // The same resolution a Sprite gets: a material owns shading fully, and a
199 // handle nothing registered falls back to the batch shader rather than
200 // binding a program that was never built.
201 if (materialId != 0) {
202 if (const MaterialRecord* m = material) {
203 key.shaderId = (m->shader != 0) ? m->shader : defaultShader;
204 key.blend = m->blend;
205 key.materialId = materialId;
206 key.depthTest = m->depthTest;
207 key.depthWrite = m->depthWrite;
208 key.cull = static_cast<u8>(m->cull);
209 }
210 }
211
212 pushBatchCommand(pool_, draw_list_, clip_state_, vOff, static_cast<u32>(vertexCount), indices,
213 static_cast<u32>(indexCount), key);
214}
215
216} // namespace esengine
The single submission face: the ONLY place a DrawCommand is assembled.
Rendering context containing all renderer state.
Frame resources and the shared scene rendering contract.
void submitTileQuad(const glm::vec2 &position, const glm::vec2 &size, const glm::vec2 &uvOffset, const glm::vec2 &uvScale, const glm::vec4 &color, u32 textureId, Entity entity, i32 layer, f32 depth)
void submitRetainedText(ecs::Registry &registry, bool screen, const f32 *projection, u32 onlyRoot=0)
Every retained label laid out for one domain into the open list, culled against projection (world,...
void submitSkeletalBatch(const f32 *vertices, i32 vertexCount, const u16 *indices, i32 indexCount, u32 textureId, i32 blendMode, const f32 *transform16, Entity entity, i32 layer, f32 depth, u32 materialId=0, bool premultipliedColor=false, f32 treeAlpha=1.0f, u32 cullBit=0)
Batch vertices posed by a skeletal runtime, drawn as one entity's geometry.
u32 batchProgram(BatchVariant variant)
void submitTextBatch(const f32 *vertices, i32 vertexCount, const u16 *indices, i32 indexCount, u32 textureId, const f32 *transform16, Entity entity, i32 layer, f32 depth, TextGlyphMode mode, u32 cullBit=0)
static constexpr i32 UI_BASE_LAYER
The opacity a draw inherits from the GroupOpacity above it.
f32 of(Entity entity) const
1 when no enabled group encloses entity (itself included).
Central container for all entities and components.
Definition Registry.hpp:73
bool valid(Entity entity) const
Checks if an entity is currently valid.
Definition Registry.hpp:518
T * tryGet(Entity entity)
Tries to get a component from an entity.
Definition Registry.hpp:670
bool copyFlatRenderMatrix(Registry &registry, Entity entity, glm::mat4 &output)
void appendQuad(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const BatchVertex quad[4], const BatchDrawKey &key)
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
i32 batchGlyphModeBits(TextGlyphMode mode)
constexpr i32 TEXT_VERTEX_FLOATS
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
u32 packColor(f32 r, f32 g, f32 b, f32 a)
RetainedTextKept
What a view keeps of a batch: nothing, all of it (read the batch itself), or a subset copied into scr...
RetainedTextKept retainedTextClip(const RetainedTextBatch &batch, const double *planes, RetainedTextClip &scratch)
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
bool retainedTextClipPlanes(double *out, const f32 *view, const f32 *model)
BlendMode
Predefined blend modes for rendering.
Definition BlendMode.hpp:22
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.
bool batchEntityVisible(const DrawList &drawList, const ClipState &clips, Entity entity, i32 layer, u32 cullBit)
float f32
32-bit floating point
Definition Types.hpp:59
Non-geometry attributes of a batch draw — everything needed to build the sort key + DrawCommand.
u8 cull
CullMode: 0 = none, 1 = back, 2 = front.
One vertex of the shared batch stream.
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
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
Definition Types.hpp:162
A material's resolved render state (P0) plus its packed std140 constants (P1).
u32 shader
Program id; 0 means "use the path's default batch shader".
std::vector< f32 > vertices
TEXT_VERTEX_FLOATS floats a vertex, four a quad.
TextGlyphMode mode
How the page's pixels become coverage. A label may mix them: an outline's ring, then its fill.
std::vector< u16 > indices
Six a quad, naming this batch's own vertices.
u32 pageId
The atlas page, which is the draw's texture.
Where the quads a view keeps are copied to, reused across batches and frames.
std::vector< f32 > vertices
std::vector< u16 > indices
Unified transform component.
Definition Transform.hpp:45
UINode — the CSS box-model layout input (the CSS/Flex primary layout model).
Definition UINode.hpp:79
UIVisual — the single UI visual component, merging the former low-level UIRenderer (what the renderer...
Definition UIVisual.hpp:84