Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
TextPlugin.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 "TextPlugin.hpp"
8#include "../rhi/Texture.hpp"
14#include "../../text/Utf8.hpp"
15
16#include <cmath>
17#include <limits>
18
19namespace esengine {
20
21namespace {
22bool containsBox(const Frustum& frustum, const glm::vec3& center, const glm::vec3& half) {
23 for (const auto& plane : frustum.planes) {
24 const f32 radius = glm::dot(glm::abs(plane.normal), half);
25 if (plane.signedDistance(center) < radius) return false;
26 }
27 return true;
28}
29}
30
31void TextPlugin::rebuildLayout(const text::BitmapFont& font, const ecs::BitmapText& bt,
32 f32 texW, f32 texH, TextLayoutCache& cache) {
33 cache.vertices.clear();
34 cache.indices.clear();
35 cache.blocks.clear();
36
37 cache.min = glm::vec3(std::numeric_limits<f32>::max());
38 cache.max = glm::vec3(std::numeric_limits<f32>::lowest());
39
40 const f32 fs = bt.fontSize;
41 const f32 spacing = bt.spacing;
42 const f32 fontBase = font.getBase();
43 const char* textData = bt.text.c_str();
44 const usize textLen = bt.text.size();
45
46 f32 totalWidth = 0;
47 if (bt.align != ecs::TextAlign::Left) {
48 u32 prevChar = 0;
49 for (usize j = 0; j < textLen;) {
50 u32 charCode = text::nextCodepoint(textData, textLen, j);
51 auto* glyph = font.getGlyph(charCode);
52 if (!glyph) continue;
53 if (prevChar) {
54 totalWidth += font.getKerning(prevChar, charCode) * fs;
55 }
56 totalWidth += (glyph->xAdvance + spacing) * fs;
57 prevChar = charCode;
58 }
59 }
60
61 f32 cursorX = 0;
62 if (bt.align == ecs::TextAlign::Center) {
63 cursorX = -totalWidth * 0.5f;
64 } else if (bt.align == ecs::TextAlign::Right) {
65 cursorX = -totalWidth;
66 }
67
68 u32 prevChar = 0;
69 for (usize j = 0; j < textLen;) {
70 u32 charCode = text::nextCodepoint(textData, textLen, j);
71 auto* glyph = font.getGlyph(charCode);
72 if (!glyph) continue;
73
74 if (prevChar) {
75 cursorX += font.getKerning(prevChar, charCode) * fs;
76 }
77
78 if (glyph->width > 0 && glyph->height > 0) {
79 f32 halfW = glyph->width * fs * 0.5f;
80 f32 halfH = glyph->height * fs * 0.5f;
81 f32 cx = cursorX + (glyph->xOffset + glyph->width * 0.5f) * fs;
82 f32 cy = (fontBase - glyph->yOffset - glyph->height * 0.5f) * fs;
83 cache.min = glm::min(cache.min, glm::vec3(cx - halfW, cy - halfH, 0.0f));
84 cache.max = glm::max(cache.max, glm::vec3(cx + halfW, cy + halfH, 0.0f));
85 const glm::vec3 low{cx - halfW, cy - halfH, 0}, high{cx + halfW, cy + halfH, 0};
86 if (cache.vertices.size() % (GLYPHS_PER_BLOCK * 4) == 0) {
87 cache.blocks.push_back({low, high});
88 } else {
89 auto& block = cache.blocks.back();
90 block.min = glm::min(block.min, low);
91 block.max = glm::max(block.max, high);
92 }
93
94 // Glyph rows are top-down in the atlas, so v is flipped (top at vMin).
95 f32 uMin = glyph->x / texW;
96 f32 uMax = (glyph->x + glyph->width) / texW;
97 f32 vTop = glyph->y / texH;
98 f32 vBottom = (glyph->y + glyph->height) / texH;
99
100 u32 baseVertex = static_cast<u32>(cache.vertices.size());
101 cache.vertices.push_back({ {cx - halfW, cy - halfH, 0.0f}, 0, {uMin, vBottom} });
102 cache.vertices.push_back({ {cx + halfW, cy - halfH, 0.0f}, 0, {uMax, vBottom} });
103 cache.vertices.push_back({ {cx + halfW, cy + halfH, 0.0f}, 0, {uMax, vTop} });
104 cache.vertices.push_back({ {cx - halfW, cy + halfH, 0.0f}, 0, {uMin, vTop} });
105 for (u32 i = 0; i < 6; ++i) {
106 cache.indices.push_back(baseVertex + BATCH_QUAD_INDICES[i]);
107 }
108 }
109
110 cursorX += (glyph->xAdvance + spacing) * fs;
111 prevChar = charCode;
112 }
113}
114
116 auto& registry = collect_ctx.registry;
117 auto& clips = collect_ctx.clip_state;
118 auto& buffers = collect_ctx.buffer_pool;
119 auto& draw_list = collect_ctx.draw_list;
120 auto& ctx = collect_ctx.frame_context;
121 auto textView = registry.activeView<ecs::Transform, ecs::BitmapText>();
122 const ecs::GroupOpacityLookup groupOpacity(registry);
123
124 for (auto entity : textView) {
125 const auto& bt = textView.get<ecs::BitmapText>(entity);
126 if (!bt.enabled) continue;
127 if (bt.text.empty() || !bt.font.isValid()) continue;
128 if (!batchEntityVisible(draw_list, clips, entity, bt.layer, 0)) continue;
129 auto& transform = textView.get<ecs::Transform>(entity);
130 const bool parented = registry.has<ecs::Parent>(entity);
131 if (!ecs::hasFlatGeometryArea(registry, entity, transform)) continue;
132
133 auto* font = ctx.resources.getBitmapFont(bt.font);
134 if (!font) continue;
135
136 auto* tex = ctx.resources.getTexture(font->getTexture());
137 if (!tex) continue;
138
139 f32 texW = static_cast<f32>(font->getTexWidth());
140 f32 texH = static_cast<f32>(font->getTexHeight());
141 if (texW == 0 || texH == 0) continue;
142
143 auto& cache = layout_cache_[entity];
144 if (cache.text != bt.text || cache.font_id != bt.font.id()
145 || cache.font_size != bt.fontSize || cache.spacing != bt.spacing
146 || cache.align != static_cast<u8>(bt.align)) {
147 rebuildLayout(*font, bt, texW, texH, cache);
148 cache.text = bt.text;
149 cache.font_id = bt.font.id();
150 cache.font_size = bt.fontSize;
151 cache.spacing = bt.spacing;
152 cache.align = static_cast<u8>(bt.align);
153 }
154 if (cache.indices.empty()) continue;
155
156 glm::vec3 position = parallaxedWorldPosition(transform, bt.parallax, collect_ctx.camera);
157 glm::vec3 axisX, axisY;
158 if (parented) {
159 axisX = glm::vec3(transform.cachedMatrix_[0]);
160 axisY = glm::vec3(transform.cachedMatrix_[1]);
161 } else {
162 const auto rotation = glm::mat3_cast(transform.worldRotation);
163 axisX = rotation[0] * transform.worldScale.x;
164 axisY = rotation[1] * transform.worldScale.y;
165 }
166 const glm::vec3 localCenter = (cache.min + cache.max) * 0.5f;
167 const glm::vec3 localHalf = (cache.max - cache.min) * 0.5f;
168 const glm::vec3 center = position + axisX * localCenter.x + axisY * localCenter.y;
169 const glm::vec3 halfExtents = glm::abs(axisX) * localHalf.x + glm::abs(axisY) * localHalf.y;
170 if (!collect_ctx.visible(center, halfExtents, false)) {
171 ++collect_ctx.culled;
172 continue;
173 }
174
175 glm::vec4 textColor = bt.color;
176 textColor.a *= groupOpacity.of(entity);
177 if (textColor.a <= 0.0f) continue;
178 u32 packedColor = packColor(textColor);
179 scratch_.clear();
180 index_scratch_.clear();
181 const bool allVisible = collect_ctx.isOverlay() || containsBox(collect_ctx.frustum, center, halfExtents);
182 if (allVisible) {
183 scratch_.reserve(cache.vertices.size());
184 for (const BatchVertex& v : cache.vertices) {
185 scratch_.push_back({position + axisX * v.position.x + axisY * v.position.y, packedColor, v.texCoord});
186 }
187 } else {
188 const glm::vec3 absX = glm::abs(axisX), absY = glm::abs(axisY);
189 const auto bounds = [&](const glm::vec3& low, const glm::vec3& high) {
190 const auto mid = (low + high) * .5f, half = (high - low) * .5f;
191 return std::pair{position + axisX * mid.x + axisY * mid.y, absX * half.x + absY * half.y};
192 };
193 for (u32 blockIndex = 0; blockIndex < cache.blocks.size(); ++blockIndex) {
194 const auto& block = cache.blocks[blockIndex];
195 const auto [blockCenter, blockHalf] = bounds(block.min, block.max);
196 if (!collect_ctx.visible(blockCenter, blockHalf, false)) continue;
197 const bool wholeBlock = containsBox(collect_ctx.frustum, blockCenter, blockHalf);
198 const u32 first = blockIndex * GLYPHS_PER_BLOCK * 4;
199 const u32 end = std::min(first + GLYPHS_PER_BLOCK * 4, static_cast<u32>(cache.vertices.size()));
200 for (u32 i = first; i < end; i += 4) {
201 if (!wholeBlock) {
202 const auto [glyphCenter, glyphHalf] = bounds(cache.vertices[i].position, cache.vertices[i + 2].position);
203 if (!collect_ctx.visible(glyphCenter, glyphHalf, false)) continue;
204 }
205 const u32 base = static_cast<u32>(scratch_.size());
206 for (u32 j = 0; j < 4; ++j) {
207 const auto& v = cache.vertices[i + j];
208 scratch_.push_back({position + axisX * v.position.x + axisY * v.position.y, packedColor, v.texCoord});
209 }
210 for (u32 index : BATCH_QUAD_INDICES) index_scratch_.push_back(base + index);
211 }
212 }
213 }
214 if (scratch_.empty()) continue;
215 const auto& indices = allVisible ? cache.indices : index_scratch_;
216
217 appendIndexedBatch(buffers, draw_list, clips,
218 scratch_.data(), static_cast<u32>(scratch_.size()),
219 indices.data(), static_cast<u32>(indices.size()),
221 .stage = ctx.current_stage,
222 .layer = bt.layer,
223 .shaderId = batch_shader_id_,
224 .blend = BlendMode::Normal,
225 .textureId = tex->getId(),
226 .depth = collect_ctx.camera.viewDepth(position),
227 .y = position.y,
228 .entity = entity,
229 .type = RenderType::Text,
230 });
231 }
232
233 for (auto it = layout_cache_.begin(); it != layout_cache_.end(); ) {
234 if (!registry.valid(it->first) || !registry.has<ecs::BitmapText>(it->first)) {
235 it = layout_cache_.erase(it);
236 } else {
237 ++it;
238 }
239 }
240}
241
242} // namespace esengine
The single submission face: the ONLY place a DrawCommand is assembled.
Hierarchy components for parent-child relationships.
Rendering context containing all renderer state.
Frame resources and the shared scene rendering contract.
GPU texture abstraction for 2D images.
Unified Transform component with local and world-space data.
void collect(RenderCollectContext &ctx) override
The opacity a draw inherits from the GroupOpacity above it.
bool hasFlatGeometryArea(Transform &transform, bool parented)
f32 radius(const glm::vec3 &lo, const glm::vec3 &hi, f32 displacement)
constexpr u32 nextCodepoint(const char *data, usize length, usize &pos)
Definition Utf8.hpp:11
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
glm::vec3 parallaxedWorldPosition(ecs::Transform &transform, const glm::vec2 &parallax, const CameraView &camera)
u32 packColor(f32 r, f32 g, f32 b, f32 a)
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
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)
static EstellaContext & ctx()
constexpr u32 BATCH_QUAD_INDICES[6]
Canonical two-triangle quad winding shared by every batch path.
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.
One vertex of the shared batch stream.
u32 culled
How many renderables this collect's frustum rejected.
bool visible(const glm::vec3 &centre, const glm::vec3 &halfExtents, bool depthTested)
Whether a renderable bounded by centre / halfExtents is drawn.
bool isOverlay() const
Whether this collect is the frame's screen overlay.
Parent reference component.
Definition Hierarchy.hpp:46
Unified transform component.
Definition Transform.hpp:45