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 "Canvas2D.h"
21 :
22 : #include "graphics/Color.h"
23 : #include "graphics/ShaderDefines.h"
24 : #include "graphics/ShaderManager.h"
25 : #include "graphics/ShaderTechnique.h"
26 : #include "graphics/ShaderTechniquePtr.h"
27 : #include "graphics/TextRenderer.h"
28 : #include "graphics/TextureManager.h"
29 : #include "lib/debug.h"
30 : #include "maths/Matrix3D.h"
31 : #include "maths/Rect.h"
32 : #include "maths/Vector2D.h"
33 : #include "ps/ConfigDB.h"
34 : #include "ps/CStrIntern.h"
35 : #include "ps/CStrInternStatic.h"
36 : #include "ps/containers/StaticVector.h"
37 : #include "renderer/Renderer.h"
38 : #include "renderer/backend/Format.h"
39 : #include "renderer/backend/IDeviceCommandContext.h"
40 : #include "renderer/backend/IShaderProgram.h"
41 :
42 : #include <algorithm>
43 : #include <array>
44 : #include <cmath>
45 : #include <cstddef>
46 :
47 : namespace
48 : {
49 :
50 : // Array of 2D elements unrolled into 1D array.
51 : using PlaneArray2D = std::array<float, 12>;
52 :
53 : struct SBindingSlots
54 : {
55 : int32_t transform;
56 : int32_t translation;
57 : int32_t colorAdd;
58 : int32_t colorMul;
59 : int32_t grayscaleFactor;
60 : int32_t tex;
61 : };
62 :
63 0 : inline void DrawTextureImpl(
64 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
65 : const CTexturePtr& texture, const PlaneArray2D& vertices, PlaneArray2D uvs,
66 : const CColor& multiply, const CColor& add, const float grayscaleFactor,
67 : const SBindingSlots& bindingSlots)
68 : {
69 0 : texture->UploadBackendTextureIfNeeded(deviceCommandContext);
70 0 : deviceCommandContext->SetTexture(
71 0 : bindingSlots.tex, texture->GetBackendTexture());
72 0 : for (size_t idx = 0; idx < uvs.size(); idx += 2)
73 : {
74 0 : if (texture->GetWidth() > 0.0f)
75 0 : uvs[idx + 0] /= texture->GetWidth();
76 0 : if (texture->GetHeight() > 0.0f)
77 0 : uvs[idx + 1] /= texture->GetHeight();
78 : }
79 :
80 0 : deviceCommandContext->SetUniform(bindingSlots.colorAdd, add.AsFloatArray());
81 0 : deviceCommandContext->SetUniform(bindingSlots.colorMul, multiply.AsFloatArray());
82 0 : deviceCommandContext->SetUniform(bindingSlots.grayscaleFactor, grayscaleFactor);
83 :
84 0 : deviceCommandContext->SetVertexBufferData(
85 0 : 0, vertices.data(), vertices.size() * sizeof(vertices[0]));
86 0 : deviceCommandContext->SetVertexBufferData(
87 0 : 1, uvs.data(), uvs.size() * sizeof(uvs[0]));
88 :
89 0 : deviceCommandContext->Draw(0, vertices.size() / 2);
90 0 : }
91 :
92 : } // anonymous namespace
93 :
94 0 : class CCanvas2D::Impl
95 : {
96 : public:
97 0 : Impl(
98 : const uint32_t widthInPixels, const uint32_t heightInPixels, const float scale,
99 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
100 0 : : WidthInPixels(widthInPixels), HeightInPixels(heightInPixels),
101 0 : Scale(scale), DeviceCommandContext(deviceCommandContext),
102 0 : DebugFontBox(g_ConfigDB.Get("fonts.debugbox", false))
103 : {
104 0 : constexpr std::array<Renderer::Backend::SVertexAttributeFormat, 2> attributes{{
105 : {Renderer::Backend::VertexAttributeStream::POSITION,
106 : Renderer::Backend::Format::R32G32_SFLOAT, 0, sizeof(float) * 2,
107 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
108 : {Renderer::Backend::VertexAttributeStream::UV0,
109 : Renderer::Backend::Format::R32G32_SFLOAT, 0, sizeof(float) * 2,
110 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 1}
111 : }};
112 0 : m_VertexInputLayout = g_Renderer.GetVertexInputLayout(attributes);
113 :
114 0 : const std::string debugFontBoxColor{g_ConfigDB.Get("fonts.debugboxcolor", std::string{"128 0 128"})};
115 0 : DebugBoxColor.ParseString(debugFontBoxColor.c_str());
116 0 : }
117 :
118 0 : void BindTechIfNeeded()
119 : {
120 0 : if (Tech)
121 0 : return;
122 :
123 0 : CShaderDefines defines;
124 0 : Tech = g_Renderer.GetShaderManager().LoadEffect(str_canvas2d, defines);
125 : // The canvas technique must be loaded because we can't render UI without it.
126 0 : ENSURE(Tech);
127 0 : DeviceCommandContext->SetGraphicsPipelineState(
128 0 : Tech->GetGraphicsPipelineState());
129 0 : DeviceCommandContext->BeginPass();
130 0 : Renderer::Backend::IShaderProgram* shader = Tech->GetShader();
131 :
132 0 : BindingSlots.transform = shader->GetBindingSlot(str_transform);
133 0 : BindingSlots.translation = shader->GetBindingSlot(str_translation);
134 0 : BindingSlots.colorAdd = shader->GetBindingSlot(str_colorAdd);
135 0 : BindingSlots.colorMul = shader->GetBindingSlot(str_colorMul);
136 0 : BindingSlots.grayscaleFactor = shader->GetBindingSlot(str_grayscaleFactor);
137 0 : BindingSlots.tex = shader->GetBindingSlot(str_tex);
138 :
139 0 : const CMatrix3D transform = GetTransform();
140 0 : TransformScale = CVector2D(transform._11, transform._22);
141 0 : Translation = CVector2D(transform._14, transform._24);
142 0 : DeviceCommandContext->SetUniform(
143 : BindingSlots.transform,
144 0 : transform._11, transform._21, transform._12, transform._22);
145 0 : DeviceCommandContext->SetUniform(
146 0 : BindingSlots.translation, Translation.AsFloatArray());
147 :
148 0 : DeviceCommandContext->SetVertexInputLayout(m_VertexInputLayout);
149 : }
150 :
151 0 : void UnbindTech()
152 : {
153 0 : if (!Tech)
154 : return;
155 :
156 0 : DeviceCommandContext->EndPass();
157 0 : Tech.reset();
158 : }
159 :
160 : /**
161 : * Returns model-view-projection matrix with (0,0) in top-left of screen.
162 : */
163 0 : CMatrix3D GetTransform()
164 : {
165 0 : const float width = static_cast<float>(WidthInPixels) / Scale;
166 0 : const float height = static_cast<float>(HeightInPixels) / Scale;
167 :
168 0 : CMatrix3D transform;
169 0 : transform.SetIdentity();
170 0 : transform.Scale(1.0f, -1.f, 1.0f);
171 0 : transform.Translate(0.0f, height, -1000.0f);
172 :
173 0 : CMatrix3D projection;
174 0 : projection.SetOrtho(0.f, width, 0.f, height, -1.f, 1000.f);
175 0 : transform = projection * transform;
176 :
177 0 : return transform;
178 : }
179 :
180 0 : void ApplyScissors()
181 : {
182 0 : if (!Scissors.empty())
183 : {
184 0 : CRect rect = Scissors.back();
185 0 : Renderer::Backend::IDeviceCommandContext::Rect scissorRect;
186 0 : scissorRect.x = std::ceil(rect.left * Scale);
187 0 : scissorRect.y = std::ceil(static_cast<float>(HeightInPixels) - rect.bottom * Scale);
188 0 : scissorRect.width = std::floor(rect.GetWidth() * Scale);
189 0 : scissorRect.height = std::floor(rect.GetHeight() * Scale);
190 0 : DeviceCommandContext->SetScissors(1, &scissorRect);
191 : }
192 : else
193 0 : DeviceCommandContext->SetScissors(0, nullptr);
194 0 : }
195 :
196 : uint32_t WidthInPixels = 1;
197 : uint32_t HeightInPixels = 1;
198 : float Scale = 1.0f;
199 : CVector2D TransformScale;
200 : CVector2D Translation;
201 :
202 : Renderer::Backend::IVertexInputLayout* m_VertexInputLayout = nullptr;
203 :
204 : Renderer::Backend::IDeviceCommandContext* DeviceCommandContext = nullptr;
205 : CShaderTechniquePtr Tech;
206 :
207 : // We assume that the shader can't be destroyed while it's bound. So these
208 : // bindings remain valid while the shader is alive.
209 : SBindingSlots BindingSlots;
210 :
211 : PS::StaticVector<CRect, 4> Scissors;
212 :
213 : bool DebugFontBox;
214 : CColor DebugBoxColor;
215 : };
216 :
217 0 : CCanvas2D::CCanvas2D(
218 : const uint32_t widthInPixels, const uint32_t heightInPixels, const float scale,
219 0 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
220 0 : : m(std::make_unique<Impl>(widthInPixels, heightInPixels, scale, deviceCommandContext))
221 : {
222 :
223 0 : }
224 :
225 0 : CCanvas2D::~CCanvas2D()
226 : {
227 0 : Flush();
228 0 : ENSURE(m->Scissors.empty());
229 0 : }
230 :
231 0 : void CCanvas2D::DrawLine(const std::vector<CVector2D>& points, const float width, const CColor& color)
232 : {
233 0 : if (points.empty())
234 0 : return;
235 :
236 : // We could reuse the terrain line building, but it uses 3D space instead of
237 : // 2D. So it can be less optimal for a canvas.
238 :
239 : // Adding a single pixel line with alpha gradient to reduce the aliasing
240 : // effect.
241 0 : const float halfWidth = width * 0.5f + 1.0f;
242 :
243 0 : struct PointIndex
244 : {
245 : size_t index;
246 : float length;
247 : CVector2D normal;
248 : };
249 : // Normal for the last index is undefined.
250 0 : std::vector<PointIndex> pointsIndices;
251 0 : pointsIndices.reserve(points.size());
252 0 : pointsIndices.emplace_back(PointIndex{0, 0.0f, CVector2D()});
253 0 : for (size_t index = 0; index < points.size();)
254 : {
255 0 : size_t nextIndex = index + 1;
256 0 : CVector2D direction;
257 0 : float length = 0.0f;
258 0 : while (nextIndex < points.size())
259 : {
260 0 : direction = points[nextIndex] - points[pointsIndices.back().index];
261 0 : length = direction.Length();
262 0 : if (length >= halfWidth * 2.0f)
263 : {
264 0 : direction /= length;
265 : break;
266 : }
267 0 : ++nextIndex;
268 : }
269 0 : if (nextIndex == points.size())
270 : break;
271 0 : pointsIndices.back().length = length;
272 0 : pointsIndices.back().normal = CVector2D(-direction.Y, direction.X);
273 0 : pointsIndices.emplace_back(PointIndex{nextIndex, 0.0f, CVector2D()});
274 0 : index = nextIndex;
275 : }
276 :
277 0 : if (pointsIndices.size() <= 1)
278 0 : return;
279 :
280 0 : std::vector<std::array<CVector2D, 3>> vertices;
281 0 : std::vector<std::array<CVector2D, 3>> uvs;
282 0 : std::vector<std::uint16_t> indices;
283 0 : const size_t reserveSize = 2 * pointsIndices.size() - 1;
284 0 : vertices.reserve(reserveSize);
285 0 : uvs.reserve(reserveSize);
286 0 : indices.reserve(reserveSize * 12);
287 :
288 0 : auto addVertices = [&vertices, &uvs, &indices, &halfWidth](const CVector2D& p1, const CVector2D& p2)
289 : {
290 0 : if (!vertices.empty())
291 : {
292 0 : const std::uint16_t lastVertexIndex = static_cast<std::uint16_t>(vertices.size() * 3 - 1);
293 0 : ENSURE(lastVertexIndex >= 2);
294 : // First vertical half of the segment.
295 0 : indices.emplace_back(lastVertexIndex - 2);
296 0 : indices.emplace_back(lastVertexIndex - 1);
297 0 : indices.emplace_back(lastVertexIndex + 2);
298 0 : indices.emplace_back(lastVertexIndex - 2);
299 0 : indices.emplace_back(lastVertexIndex + 2);
300 0 : indices.emplace_back(lastVertexIndex + 1);
301 : // Second vertical half of the segment.
302 0 : indices.emplace_back(lastVertexIndex - 1);
303 0 : indices.emplace_back(lastVertexIndex);
304 0 : indices.emplace_back(lastVertexIndex + 3);
305 0 : indices.emplace_back(lastVertexIndex - 1);
306 0 : indices.emplace_back(lastVertexIndex + 3);
307 0 : indices.emplace_back(lastVertexIndex + 2);
308 : }
309 0 : vertices.emplace_back(std::array<CVector2D, 3>{p1, (p1 + p2) / 2.0f, p2});
310 0 : uvs.emplace_back(std::array<CVector2D, 3>{
311 : CVector2D(0.0f, 0.0f),
312 0 : CVector2D(std::max(1.0f, halfWidth - 1.0f), 0.0f),
313 : CVector2D(0.0f, 0.0f)});
314 0 : };
315 :
316 0 : addVertices(
317 0 : points[pointsIndices.front().index] - pointsIndices.front().normal * halfWidth,
318 0 : points[pointsIndices.front().index] + pointsIndices.front().normal * halfWidth);
319 : // For each pair of adjacent segments we need to add smooth transition.
320 0 : for (size_t index = 0; index + 2 < pointsIndices.size(); ++index)
321 : {
322 0 : const PointIndex& pointIndex = pointsIndices[index];
323 0 : const PointIndex& nextPointIndex = pointsIndices[index + 1];
324 : // Angle between adjacent segments.
325 0 : const float cosAlpha = pointIndex.normal.Dot(nextPointIndex.normal);
326 0 : constexpr float EPS = 1e-3f;
327 : // Use a simple segment if adjacent segments are almost codirectional.
328 0 : if (cosAlpha > 1.0f - EPS)
329 : {
330 0 : addVertices(
331 0 : points[pointIndex.index] - pointIndex.normal * halfWidth,
332 0 : points[pointIndex.index] + pointIndex.normal * halfWidth);
333 : }
334 : else
335 : {
336 0 : addVertices(
337 0 : points[nextPointIndex.index] - pointIndex.normal * halfWidth,
338 0 : points[nextPointIndex.index] + pointIndex.normal * halfWidth);
339 : // Average normal between adjacent segments. We might want to rotate it but
340 : // for now we assume that it's enough for current line widths.
341 0 : const CVector2D normal = cosAlpha < -1.0f + EPS
342 0 : ? CVector2D(pointIndex.normal.Y, -pointIndex.normal.X)
343 0 : : ((pointIndex.normal + nextPointIndex.normal) / 2.0f).Normalized();
344 0 : addVertices(
345 0 : points[nextPointIndex.index] - normal * halfWidth,
346 0 : points[nextPointIndex.index] + normal * halfWidth);
347 0 : addVertices(
348 0 : points[nextPointIndex.index] - nextPointIndex.normal * halfWidth,
349 0 : points[nextPointIndex.index] + nextPointIndex.normal * halfWidth);
350 : }
351 : // We use 16-bit indices, it means that we can't use more than 64K vertices.
352 0 : const size_t requiredFreeSpace = 3 * 4;
353 0 : if (vertices.size() * 3 + requiredFreeSpace >= 65536)
354 : break;
355 : }
356 0 : addVertices(
357 0 : points[pointsIndices.back().index] - pointsIndices[pointsIndices.size() - 2].normal * halfWidth,
358 0 : points[pointsIndices.back().index] + pointsIndices[pointsIndices.size() - 2].normal * halfWidth);
359 :
360 0 : m->BindTechIfNeeded();
361 :
362 0 : m->DeviceCommandContext->SetTexture(
363 0 : m->BindingSlots.tex,
364 0 : g_Renderer.GetTextureManager().GetAlphaGradientTexture()->GetBackendTexture());
365 0 : const CColor colorAdd(0.0f, 0.0f, 0.0f, 0.0f);
366 0 : m->DeviceCommandContext->SetUniform(
367 0 : m->BindingSlots.colorAdd, colorAdd.AsFloatArray());
368 0 : m->DeviceCommandContext->SetUniform(
369 0 : m->BindingSlots.colorMul, color.AsFloatArray());
370 0 : m->DeviceCommandContext->SetUniform(
371 0 : m->BindingSlots.grayscaleFactor, 0.0f);
372 :
373 0 : m->DeviceCommandContext->SetVertexBufferData(0, vertices.data(), vertices.size() * sizeof(vertices[0]));
374 0 : m->DeviceCommandContext->SetVertexBufferData(1, uvs.data(), uvs.size() * sizeof(uvs[0]));
375 :
376 0 : m->DeviceCommandContext->SetIndexBufferData(indices.data(), indices.size() * sizeof(indices[0]));
377 0 : m->DeviceCommandContext->DrawIndexed(0, indices.size(), 0);
378 0 : }
379 :
380 0 : void CCanvas2D::DrawRect(const CRect& rect, const CColor& color)
381 : {
382 0 : const PlaneArray2D uvs
383 : {
384 : 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
385 : 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f
386 : };
387 0 : const PlaneArray2D vertices =
388 : {
389 0 : rect.left, rect.bottom,
390 0 : rect.right, rect.bottom,
391 0 : rect.right, rect.top,
392 : rect.left, rect.bottom,
393 : rect.right, rect.top,
394 : rect.left, rect.top
395 0 : };
396 :
397 0 : m->BindTechIfNeeded();
398 0 : DrawTextureImpl(
399 0 : m->DeviceCommandContext,
400 0 : g_Renderer.GetTextureManager().GetTransparentTexture(),
401 0 : vertices, uvs, CColor(0.0f, 0.0f, 0.0f, 0.0f), color, 0.0f,
402 0 : m->BindingSlots);
403 0 : }
404 :
405 0 : void CCanvas2D::DrawTexture(const CTexturePtr& texture, const CRect& destination)
406 : {
407 0 : DrawTexture(texture,
408 0 : destination, CRect(0, 0, texture->GetWidth(), texture->GetHeight()),
409 0 : CColor(1.0f, 1.0f, 1.0f, 1.0f), CColor(0.0f, 0.0f, 0.0f, 0.0f), 0.0f);
410 0 : }
411 :
412 0 : void CCanvas2D::DrawTexture(
413 : const CTexturePtr& texture, const CRect& destination, const CRect& source,
414 : const CColor& multiply, const CColor& add, const float grayscaleFactor)
415 : {
416 0 : const PlaneArray2D uvs =
417 : {
418 0 : source.left, source.bottom,
419 0 : source.right, source.bottom,
420 0 : source.right, source.top,
421 : source.left, source.bottom,
422 : source.right, source.top,
423 : source.left, source.top
424 0 : };
425 0 : const PlaneArray2D vertices =
426 : {
427 0 : destination.left, destination.bottom,
428 0 : destination.right, destination.bottom,
429 0 : destination.right, destination.top,
430 : destination.left, destination.bottom,
431 : destination.right, destination.top,
432 : destination.left, destination.top
433 0 : };
434 :
435 0 : m->BindTechIfNeeded();
436 0 : DrawTextureImpl(
437 0 : m->DeviceCommandContext, texture, vertices, uvs,
438 0 : multiply, add, grayscaleFactor, m->BindingSlots);
439 0 : }
440 :
441 0 : void CCanvas2D::DrawRotatedTexture(
442 : const CTexturePtr& texture, const CRect& destination, const CRect& source,
443 : const CColor& multiply, const CColor& add, const float grayscaleFactor,
444 : const CVector2D& origin, const float angle)
445 : {
446 0 : const PlaneArray2D uvs =
447 : {
448 0 : source.left, source.bottom,
449 0 : source.right, source.bottom,
450 0 : source.right, source.top,
451 : source.left, source.bottom,
452 : source.right, source.top,
453 : source.left, source.top
454 0 : };
455 0 : std::array<CVector2D, 6> corners =
456 : {
457 0 : destination.BottomLeft(),
458 0 : destination.BottomRight(),
459 0 : destination.TopRight(),
460 0 : destination.BottomLeft(),
461 0 : destination.TopRight(),
462 0 : destination.TopLeft()
463 : };
464 : PlaneArray2D vertices;
465 : static_assert(vertices.size() == corners.size() * 2, "We need two coordinates from each corner.");
466 : auto it = vertices.begin();
467 0 : for (const CVector2D& corner : corners)
468 : {
469 0 : const CVector2D vertex = origin + (corner - origin).Rotated(angle);
470 0 : *it++ = vertex.X;
471 0 : *it++ = vertex.Y;
472 : }
473 :
474 0 : m->BindTechIfNeeded();
475 0 : DrawTextureImpl(
476 0 : m->DeviceCommandContext, texture, vertices, uvs,
477 0 : multiply, add, grayscaleFactor, m->BindingSlots);
478 0 : }
479 :
480 0 : void CCanvas2D::DrawText(CTextRenderer& textRenderer)
481 : {
482 0 : m->BindTechIfNeeded();
483 :
484 0 : m->DeviceCommandContext->SetUniform(
485 0 : m->BindingSlots.grayscaleFactor, 0.0f);
486 :
487 0 : textRenderer.Render(
488 0 : m->DeviceCommandContext, m->Tech->GetShader(), m->TransformScale, m->Translation,
489 0 : m->DebugFontBox, m->DebugBoxColor);
490 0 : }
491 :
492 0 : void CCanvas2D::PushScissor(const CRect& scissor)
493 : {
494 0 : ENSURE(!m->Scissors.full());
495 0 : m->Scissors.emplace_back(scissor);
496 0 : m->ApplyScissors();
497 0 : }
498 :
499 0 : void CCanvas2D::PopScissor()
500 : {
501 0 : ENSURE(!m->Scissors.empty());
502 0 : m->Scissors.pop_back();
503 0 : m->ApplyScissors();
504 0 : }
505 :
506 0 : void CCanvas2D::Flush()
507 : {
508 0 : m->UnbindTech();
509 0 : }
|