Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "TextRenderer.h"
21 :
22 : #include "graphics/Font.h"
23 : #include "graphics/FontManager.h"
24 : #include "graphics/TextureManager.h"
25 : #include "lib/code_annotation.h"
26 : #include "lib/debug.h"
27 : #include "lib/utf8.h"
28 : #include "ps/CStr.h"
29 : #include "ps/CStrIntern.h"
30 : #include "ps/CStrInternStatic.h"
31 : #include "ps/ConfigDB.h"
32 : #include "renderer/Renderer.h"
33 : #include "renderer/backend/IDeviceCommandContext.h"
34 : #include "renderer/backend/IShaderProgram.h"
35 :
36 : #include <algorithm>
37 : #include <cerrno>
38 : #include <cmath>
39 : #include <cstdarg>
40 : #include <cstdint>
41 : #include <cwchar>
42 : #include <iterator>
43 : #include <vector>
44 :
45 : namespace
46 : {
47 :
48 : // We can't draw chars more than vertices, currently we use 4 vertices per char.
49 : constexpr size_t MAX_CHAR_COUNT_PER_BATCH = 65536 / 4;
50 :
51 : } // anonymous namespace
52 :
53 0 : CTextRenderer::CTextRenderer()
54 0 : : m_ScopedLinearAllocator{g_Renderer.GetLinearAllocator()}, m_Batches(m_ScopedLinearAllocator)
55 : {
56 0 : ResetTranslate();
57 0 : SetCurrentColor(CColor(1.0f, 1.0f, 1.0f, 1.0f));
58 0 : SetCurrentFont(str_sans_10, CStrIntern{});
59 0 : }
60 :
61 0 : void CTextRenderer::ResetTranslate(const CVector2D& translate)
62 : {
63 0 : m_Translate = translate;
64 0 : m_Dirty = true;
65 0 : }
66 :
67 0 : void CTextRenderer::Translate(float x, float y)
68 : {
69 0 : m_Translate += CVector2D{x, y};
70 0 : m_Dirty = true;
71 0 : }
72 :
73 0 : void CTextRenderer::SetClippingRect(const CRect& rect)
74 : {
75 0 : m_Clipping = rect;
76 0 : }
77 :
78 0 : void CTextRenderer::SetCurrentColor(const CColor& color)
79 : {
80 0 : if (m_Color != color)
81 : {
82 0 : m_Color = color;
83 0 : m_Dirty = true;
84 : }
85 0 : }
86 :
87 0 : void CTextRenderer::SetCurrentFont(CStrIntern font, CStrIntern locale)
88 : {
89 0 : if (font != m_FontName)
90 : {
91 0 : m_FontName = font;
92 0 : m_Font = g_Renderer.GetFontManager().LoadFont(font, locale);
93 0 : m_Dirty = true;
94 : }
95 0 : }
96 :
97 0 : void CTextRenderer::PrintfAdvance(const wchar_t* fmt, ...)
98 : {
99 0 : wchar_t buf[1024] = {0};
100 :
101 0 : va_list args;
102 0 : va_start(args, fmt);
103 0 : int ret = vswprintf(buf, ARRAY_SIZE(buf)-1, fmt, args);
104 0 : va_end(args);
105 :
106 0 : if (ret < 0)
107 0 : debug_printf("CTextRenderer::Printf vswprintf failed (buffer size exceeded?) - return value %d, errno %d\n", ret, errno);
108 :
109 0 : PutAdvance(buf);
110 0 : }
111 :
112 :
113 0 : void CTextRenderer::PrintfAt(float x, float y, const wchar_t* fmt, ...)
114 : {
115 0 : wchar_t buf[1024] = {0};
116 :
117 0 : va_list args;
118 0 : va_start(args, fmt);
119 0 : int ret = vswprintf(buf, ARRAY_SIZE(buf)-1, fmt, args);
120 0 : va_end(args);
121 :
122 0 : if (ret < 0)
123 0 : debug_printf("CTextRenderer::PrintfAt vswprintf failed (buffer size exceeded?) - return value %d, errno %d\n", ret, errno);
124 :
125 0 : Put(x, y, buf);
126 0 : }
127 :
128 0 : void CTextRenderer::PutAdvance(const wchar_t* buf)
129 : {
130 0 : Put(0.0f, 0.0f, buf);
131 :
132 0 : float w, h;
133 0 : m_Font->CalculateStringSize(buf, w, h);
134 0 : Translate(w, 0.0f);
135 0 : }
136 :
137 0 : void CTextRenderer::Put(float x, float y, const wchar_t* buf)
138 : {
139 0 : if (buf[0] == 0)
140 : return; // empty string; don't bother storing
141 :
142 0 : PutString(x, y, new std::wstring(buf), true);
143 : }
144 :
145 0 : void CTextRenderer::Put(float x, float y, const char* buf)
146 : {
147 0 : if (buf[0] == 0)
148 : return; // empty string; don't bother storing
149 :
150 0 : PutString(x, y, new std::wstring(wstring_from_utf8(buf)), true);
151 : }
152 :
153 0 : void CTextRenderer::Put(float x, float y, const std::wstring* buf)
154 : {
155 0 : if (buf->empty())
156 : return; // empty string; don't bother storing
157 :
158 0 : PutString(x, y, buf, false);
159 : }
160 :
161 0 : void CTextRenderer::PutString(float x, float y, const std::wstring* buf, bool owned)
162 : {
163 0 : if (!m_Font)
164 0 : return; // invalid font; can't render
165 :
166 0 : if (m_Clipping != CRect())
167 : {
168 0 : float x0, y0, x1, y1;
169 0 : m_Font->GetGlyphBounds(x0, y0, x1, y1);
170 0 : if (y + y1 < m_Clipping.top && y + y0 > m_Clipping.bottom)
171 0 : return;
172 : }
173 :
174 : // If any state has changed since the last batch, start a new batch
175 0 : if (m_Dirty)
176 : {
177 0 : SBatch batch{m_ScopedLinearAllocator};
178 0 : batch.chars = 0;
179 0 : batch.translate = m_Translate;
180 0 : batch.color = m_Color;
181 0 : batch.font = m_Font;
182 0 : m_Batches.emplace_back(batch);
183 0 : m_Dirty = false;
184 0 : }
185 :
186 : // Push a new run onto the latest batch
187 0 : SBatchRun run;
188 0 : run.x = x;
189 0 : run.y = y;
190 0 : m_Batches.back().runs.emplace_back(run);
191 0 : m_Batches.back().runs.back().text = buf;
192 0 : m_Batches.back().runs.back().owned = owned;
193 0 : m_Batches.back().chars += buf->size();
194 0 : }
195 :
196 : struct SBatchCompare
197 : {
198 0 : bool operator()(const CTextRenderer::SBatch& a, const CTextRenderer::SBatch& b)
199 : {
200 0 : if (a.font != b.font)
201 0 : return a.font < b.font;
202 : // TODO: is it worth sorting by color/translate too?
203 : return false;
204 : }
205 : };
206 :
207 0 : void CTextRenderer::Render(
208 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
209 : Renderer::Backend::IShaderProgram* shader,
210 : const CVector2D& transformScale, const CVector2D& translation,
211 : const bool debugFontBox, const CColor& debugBoxColor)
212 : {
213 0 : std::vector<std::uint16_t, PS::Memory::AllocatorAdapter<std::uint16_t, PS::Memory::ScopedLinearAllocator>> indices{m_ScopedLinearAllocator};
214 0 : std::vector<CVector2D, PS::Memory::AllocatorAdapter<CVector2D, PS::Memory::ScopedLinearAllocator>> positions{m_ScopedLinearAllocator};
215 0 : std::vector<CVector2D, PS::Memory::AllocatorAdapter<CVector2D, PS::Memory::ScopedLinearAllocator>> uvs{m_ScopedLinearAllocator};
216 :
217 : // Try to merge non-consecutive batches that share the same font/color/translate:
218 : // sort the batch list by font, then merge the runs of adjacent compatible batches
219 0 : m_Batches.sort(SBatchCompare());
220 0 : for (SBatchList::iterator it = m_Batches.begin(); it != m_Batches.end(); )
221 : {
222 0 : SBatchList::iterator next = std::next(it);
223 0 : if (next != m_Batches.end() && it->chars + next->chars <= MAX_CHAR_COUNT_PER_BATCH && it->font == next->font && it->color == next->color && it->translate == next->translate)
224 : {
225 0 : it->chars += next->chars;
226 0 : it->runs.splice(it->runs.end(), next->runs);
227 0 : m_Batches.erase(next);
228 : }
229 : else
230 0 : ++it;
231 : }
232 :
233 0 : const int32_t texBindingSlot = shader->GetBindingSlot(str_tex);
234 0 : const int32_t translationBindingSlot = shader->GetBindingSlot(str_translation);
235 0 : const int32_t colorAddBindingSlot = shader->GetBindingSlot(str_colorAdd);
236 0 : const int32_t colorMulBindingSlot = shader->GetBindingSlot(str_colorMul);
237 :
238 0 : bool translationChanged = false;
239 :
240 0 : CTexture* lastTexture = nullptr;
241 0 : for (SBatch& batch : m_Batches)
242 : {
243 0 : if (lastTexture != batch.font->GetTexture().get())
244 : {
245 0 : batch.font->InitalizeAtlasTextureIfNeeded(deviceCommandContext);
246 0 : lastTexture = batch.font->GetTexture().get();
247 0 : lastTexture->UploadBackendTextureIfNeeded(deviceCommandContext);
248 0 : deviceCommandContext->SetTexture(texBindingSlot, lastTexture->GetBackendTexture());
249 : }
250 :
251 0 : if (batch.translate.X != 0.0f || batch.translate.Y != 0.0f)
252 : {
253 0 : const CVector2D localTranslation =
254 0 : translation + CVector2D(batch.translate.X * transformScale.X, batch.translate.Y * transformScale.Y);
255 0 : deviceCommandContext->SetUniform(translationBindingSlot, localTranslation.AsFloatArray());
256 0 : translationChanged = true;
257 : }
258 :
259 0 : CColor boxColor;
260 :
261 : // ALPHA-only textures will have .rgb sampled as 0, so we need to
262 : // replace it with white (but not affect RGBA textures)
263 0 : if (!debugFontBox && batch.font->HasRGB())
264 0 : boxColor = CColor(0.0f, 0.0f, 0.0f, 0.0f);
265 0 : else if (debugFontBox && batch.font->HasRGB())
266 0 : boxColor = debugBoxColor;
267 : else
268 0 : boxColor = CColor(batch.color.r, batch.color.g, batch.color.b, debugFontBox ? debugBoxColor.r : 0);
269 :
270 0 : deviceCommandContext->SetUniform(colorAddBindingSlot, boxColor.AsFloatArray());
271 0 : deviceCommandContext->SetUniform(colorMulBindingSlot, batch.color.AsFloatArray());
272 :
273 0 : positions.resize(std::min(MAX_CHAR_COUNT_PER_BATCH, batch.chars) * 4);
274 0 : uvs.resize(std::min(MAX_CHAR_COUNT_PER_BATCH, batch.chars) * 4);
275 0 : indices.resize(std::min(MAX_CHAR_COUNT_PER_BATCH, batch.chars) * 6);
276 :
277 0 : size_t idx = 0;
278 :
279 0 : auto flush = [deviceCommandContext, &idx, &positions, &uvs, &indices]() -> void
280 : {
281 0 : if (idx == 0)
282 : return;
283 :
284 0 : deviceCommandContext->SetVertexBufferData(
285 0 : 0, positions.data(), positions.size() * sizeof(positions[0]));
286 0 : deviceCommandContext->SetVertexBufferData(
287 0 : 1, uvs.data(), uvs.size() * sizeof(uvs[0]));
288 0 : deviceCommandContext->SetIndexBufferData(
289 0 : indices.data(), indices.size() * sizeof(indices[0]));
290 :
291 0 : deviceCommandContext->DrawIndexed(0, idx * 6, 0);
292 0 : idx = 0;
293 0 : };
294 :
295 0 : for (SBatchRun& run : batch.runs)
296 : {
297 0 : float x{std::ceil(run.x)};
298 0 : float y{std::ceil(run.y)};
299 0 : for (size_t i = 0; i < run.text->size(); ++i)
300 : {
301 0 : const CFont::GlyphData* g = batch.font->GetGlyph((*run.text)[i]);
302 :
303 : // Use the missing glyph symbol.
304 0 : if (!g)
305 0 : g = batch.font->GetGlyph(0xFFFD);
306 :
307 : // Missing the missing glyph symbol - give up.
308 0 : if (!g)
309 0 : continue;
310 :
311 0 : uvs[idx*4].X = g->u1;
312 0 : uvs[idx*4].Y = g->v0;
313 0 : positions[idx*4].X = g->x1 + x;
314 0 : positions[idx*4].Y = g->y0 + y;
315 :
316 0 : uvs[idx*4+1].X = g->u0;
317 0 : uvs[idx*4+1].Y = g->v0;
318 0 : positions[idx*4+1].X = g->x0 + x;
319 0 : positions[idx*4+1].Y = g->y0 + y;
320 :
321 0 : uvs[idx*4+2].X = g->u0;
322 0 : uvs[idx*4+2].Y = g->v1;
323 0 : positions[idx*4+2].X = g->x0 + x;
324 0 : positions[idx*4+2].Y = g->y1 + y;
325 :
326 0 : uvs[idx*4+3].X = g->u1;
327 0 : uvs[idx*4+3].Y = g->v1;
328 0 : positions[idx*4+3].X = g->x1 + x;
329 0 : positions[idx*4+3].Y = g->y1 + y;
330 :
331 0 : indices[idx*6+0] = static_cast<std::uint16_t>(idx * 4 + 0);
332 0 : indices[idx*6+1] = static_cast<std::uint16_t>(idx * 4 + 1);
333 0 : indices[idx*6+2] = static_cast<std::uint16_t>(idx * 4 + 2);
334 0 : indices[idx*6+3] = static_cast<std::uint16_t>(idx * 4 + 2);
335 0 : indices[idx*6+4] = static_cast<std::uint16_t>(idx * 4 + 3);
336 0 : indices[idx*6+5] = static_cast<std::uint16_t>(idx * 4 + 0);
337 :
338 0 : x += g->xadvance;
339 :
340 0 : ++idx;
341 0 : if (idx == MAX_CHAR_COUNT_PER_BATCH)
342 0 : flush();
343 : }
344 : }
345 :
346 0 : flush();
347 : }
348 :
349 0 : m_Batches.clear();
350 :
351 0 : if (translationChanged)
352 0 : deviceCommandContext->SetUniform(translationBindingSlot, translation.AsFloatArray());
353 0 : }
|