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 "TerrainOverlay.h"
21 :
22 : #include "graphics/Camera.h"
23 : #include "graphics/Color.h"
24 : #include "graphics/SColor.h"
25 : #include "graphics/ShaderDefines.h"
26 : #include "graphics/ShaderManager.h"
27 : #include "graphics/ShaderTechnique.h"
28 : #include "graphics/Terrain.h"
29 : #include "maths/MathUtil.h"
30 : #include "maths/Matrix3D.h"
31 : #include "maths/Vector2D.h"
32 : #include "maths/Vector3D.h"
33 : #include "ps/CStrIntern.h"
34 : #include "ps/CStrInternStatic.h"
35 : #include "ps/Game.h"
36 : #include "ps/Profile.h"
37 : #include "ps/World.h"
38 : #include "renderer/Renderer.h"
39 : #include "renderer/SceneRenderer.h"
40 : #include "renderer/TerrainRenderer.h"
41 : #include "renderer/backend/Format.h"
42 : #include "renderer/backend/IDevice.h"
43 : #include "renderer/backend/IDeviceCommandContext.h"
44 : #include "renderer/backend/IShaderProgram.h"
45 : #include "renderer/backend/ITexture.h"
46 : #include "renderer/backend/PipelineState.h"
47 : #include "renderer/backend/Sampler.h"
48 : #include "simulation2/system/Component.h"
49 :
50 : #include <algorithm>
51 : #include <array>
52 : #include <bit>
53 : #include <cstdint>
54 : #include <cstdlib>
55 : #include <iterator>
56 : #include <utility>
57 : #include <vector>
58 :
59 : namespace
60 : {
61 :
62 : // Global overlay list management:
63 : std::vector<std::pair<ITerrainOverlay*, int>> g_TerrainOverlayList;
64 :
65 0 : void AdjustOverlayGraphicsPipelineState(
66 : Renderer::Backend::SGraphicsPipelineStateDesc& pipelineStateDesc, const bool drawHidden)
67 : {
68 0 : pipelineStateDesc.depthStencilState.depthTestEnabled = !drawHidden;
69 0 : pipelineStateDesc.blendState.enabled = true;
70 0 : pipelineStateDesc.blendState.srcColorBlendFactor = pipelineStateDesc.blendState.srcAlphaBlendFactor =
71 : Renderer::Backend::BlendFactor::SRC_ALPHA;
72 0 : pipelineStateDesc.blendState.dstColorBlendFactor = pipelineStateDesc.blendState.dstAlphaBlendFactor =
73 : Renderer::Backend::BlendFactor::ONE_MINUS_SRC_ALPHA;
74 0 : pipelineStateDesc.blendState.colorBlendOp = pipelineStateDesc.blendState.alphaBlendOp =
75 : Renderer::Backend::BlendOp::ADD;
76 0 : pipelineStateDesc.rasterizationState.cullMode =
77 0 : drawHidden ? Renderer::Backend::CullMode::NONE : Renderer::Backend::CullMode::BACK;
78 : }
79 :
80 0 : CShaderTechniquePtr CreateOverlayTileShaderTechnique(const bool drawHidden)
81 : {
82 0 : return g_Renderer.GetShaderManager().LoadEffect(
83 : str_debug_line, {},
84 0 : [drawHidden](Renderer::Backend::SGraphicsPipelineStateDesc& pipelineStateDesc)
85 : {
86 0 : AdjustOverlayGraphicsPipelineState(pipelineStateDesc, drawHidden);
87 : // To ensure that outlines are drawn on top of the terrain correctly (and
88 : // don't Z-fight and flicker nastily), use detph bias to pull them towards
89 : // the camera.
90 0 : pipelineStateDesc.rasterizationState.depthBiasEnabled = true;
91 0 : pipelineStateDesc.rasterizationState.depthBiasConstantFactor = -1.0f;
92 0 : pipelineStateDesc.rasterizationState.depthBiasSlopeFactor = -1.0f;
93 0 : });
94 : }
95 :
96 0 : CShaderTechniquePtr CreateOverlayOutlineShaderTechnique(const bool drawHidden)
97 : {
98 0 : return g_Renderer.GetShaderManager().LoadEffect(
99 : str_debug_line, {},
100 0 : [drawHidden](Renderer::Backend::SGraphicsPipelineStateDesc& pipelineStateDesc)
101 : {
102 0 : AdjustOverlayGraphicsPipelineState(pipelineStateDesc, drawHidden);
103 0 : pipelineStateDesc.rasterizationState.polygonMode = Renderer::Backend::PolygonMode::LINE;
104 0 : });
105 : }
106 :
107 : } // anonymous namespace
108 :
109 0 : ITerrainOverlay::ITerrainOverlay(int priority)
110 : {
111 : // Add to global list of overlays
112 0 : g_TerrainOverlayList.emplace_back(this, priority);
113 : // Sort by overlays by priority. Do stable sort so that adding/removing
114 : // overlays doesn't randomly disturb all the existing ones (which would
115 : // be noticeable if they have the same priority and overlap).
116 0 : std::stable_sort(g_TerrainOverlayList.begin(), g_TerrainOverlayList.end(),
117 0 : [](const std::pair<ITerrainOverlay*, int>& a, const std::pair<ITerrainOverlay*, int>& b) {
118 0 : return a.second < b.second;
119 : });
120 0 : }
121 :
122 0 : ITerrainOverlay::~ITerrainOverlay()
123 : {
124 0 : std::vector<std::pair<ITerrainOverlay*, int> >::iterator newEnd =
125 0 : std::remove_if(g_TerrainOverlayList.begin(), g_TerrainOverlayList.end(),
126 0 : [this](const std::pair<ITerrainOverlay*, int>& a) { return a.first == this; });
127 0 : g_TerrainOverlayList.erase(newEnd, g_TerrainOverlayList.end());
128 0 : }
129 :
130 :
131 0 : void ITerrainOverlay::RenderOverlaysBeforeWater(
132 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
133 : {
134 0 : if (g_TerrainOverlayList.empty())
135 0 : return;
136 :
137 0 : PROFILE3("terrain overlays (before)");
138 0 : GPU_SCOPED_LABEL(deviceCommandContext, "Render terrain overlays before water");
139 :
140 0 : for (size_t i = 0; i < g_TerrainOverlayList.size(); ++i)
141 0 : g_TerrainOverlayList[i].first->RenderBeforeWater(deviceCommandContext);
142 0 : }
143 :
144 0 : void ITerrainOverlay::RenderOverlaysAfterWater(
145 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext, int cullGroup)
146 : {
147 0 : if (g_TerrainOverlayList.empty())
148 0 : return;
149 :
150 0 : PROFILE3("terrain overlays (after)");
151 0 : GPU_SCOPED_LABEL(deviceCommandContext, "Render terrain overlays after water");
152 :
153 0 : for (size_t i = 0; i < g_TerrainOverlayList.size(); ++i)
154 0 : g_TerrainOverlayList[i].first->RenderAfterWater(deviceCommandContext, cullGroup);
155 0 : }
156 :
157 : //////////////////////////////////////////////////////////////////////////
158 :
159 0 : TerrainOverlay::TerrainOverlay(
160 0 : const CSimContext& simContext, int priority /* = 100 */)
161 0 : : ITerrainOverlay(priority), m_Terrain(&simContext.GetTerrain())
162 : {
163 0 : m_OverlayTechTile = CreateOverlayTileShaderTechnique(false);
164 0 : m_OverlayTechTileHidden = CreateOverlayTileShaderTechnique(true);
165 :
166 0 : m_OverlayTechOutline = CreateOverlayOutlineShaderTechnique(false);
167 0 : m_OverlayTechOutlineHidden = CreateOverlayOutlineShaderTechnique(true);
168 :
169 0 : const std::array<Renderer::Backend::SVertexAttributeFormat, 1> attributes{{
170 : {Renderer::Backend::VertexAttributeStream::POSITION,
171 : Renderer::Backend::Format::R32G32B32_SFLOAT, 0, sizeof(float) * 3,
172 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
173 : }};
174 :
175 0 : m_VertexInputLayout = g_Renderer.GetVertexInputLayout(attributes);
176 0 : }
177 :
178 0 : void TerrainOverlay::StartRender()
179 : {
180 0 : }
181 :
182 0 : void TerrainOverlay::EndRender()
183 : {
184 0 : }
185 :
186 0 : void TerrainOverlay::GetTileExtents(
187 : ssize_t& min_i_inclusive, ssize_t& min_j_inclusive,
188 : ssize_t& max_i_inclusive, ssize_t& max_j_inclusive)
189 : {
190 : // Default to whole map
191 0 : min_i_inclusive = min_j_inclusive = 0;
192 0 : max_i_inclusive = max_j_inclusive = m_Terrain->GetTilesPerSide()-1;
193 0 : }
194 :
195 0 : void TerrainOverlay::RenderBeforeWater(
196 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
197 : {
198 0 : if (!m_Terrain)
199 0 : return; // should never happen, but let's play it safe
200 :
201 0 : StartRender();
202 :
203 0 : ssize_t min_i, min_j, max_i, max_j;
204 0 : GetTileExtents(min_i, min_j, max_i, max_j);
205 : // Clamp the min to 0, but the max to -1 - so tile -1 can never be rendered,
206 : // but if unclamped_max<0 then no tiles at all will be rendered. And the same
207 : // for the upper limit.
208 0 : min_i = Clamp<ssize_t>(min_i, 0, m_Terrain->GetTilesPerSide());
209 0 : min_j = Clamp<ssize_t>(min_j, 0, m_Terrain->GetTilesPerSide());
210 0 : max_i = Clamp<ssize_t>(max_i, -1, m_Terrain->GetTilesPerSide()-1);
211 0 : max_j = Clamp<ssize_t>(max_j, -1, m_Terrain->GetTilesPerSide()-1);
212 :
213 0 : for (m_j = min_j; m_j <= max_j; ++m_j)
214 0 : for (m_i = min_i; m_i <= max_i; ++m_i)
215 0 : ProcessTile(deviceCommandContext, m_i, m_j);
216 :
217 0 : EndRender();
218 : }
219 :
220 0 : void TerrainOverlay::RenderTile(
221 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
222 : const CColor& color, bool drawHidden)
223 : {
224 0 : RenderTile(deviceCommandContext, color, drawHidden, m_i, m_j);
225 0 : }
226 :
227 0 : void TerrainOverlay::RenderTile(
228 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
229 : const CColor& color, bool drawHidden, ssize_t i, ssize_t j)
230 : {
231 : // TODO: unnecessary computation calls has been removed but we should use
232 : // a vertex buffer or a vertex shader with a texture.
233 : // Not sure if it's possible on old OpenGL.
234 :
235 0 : CVector3D pos[2][2];
236 0 : for (int di = 0; di < 2; ++di)
237 0 : for (int dj = 0; dj < 2; ++dj)
238 0 : m_Terrain->CalcPosition(i + di, j + dj, pos[di][dj]);
239 :
240 0 : std::vector<float> vertices;
241 : #define ADD(position) \
242 : vertices.emplace_back((position).X); \
243 : vertices.emplace_back((position).Y); \
244 : vertices.emplace_back((position).Z);
245 :
246 0 : if (m_Terrain->GetTriangulationDir(i, j))
247 : {
248 0 : ADD(pos[0][0]);
249 0 : ADD(pos[1][0]);
250 0 : ADD(pos[0][1]);
251 :
252 0 : ADD(pos[1][0]);
253 0 : ADD(pos[1][1]);
254 0 : ADD(pos[0][1]);
255 : }
256 : else
257 : {
258 0 : ADD(pos[0][0]);
259 0 : ADD(pos[1][0]);
260 0 : ADD(pos[1][1]);
261 :
262 0 : ADD(pos[1][1]);
263 0 : ADD(pos[0][1]);
264 0 : ADD(pos[0][0]);
265 : }
266 : #undef ADD
267 :
268 0 : const CShaderTechniquePtr& shaderTechnique = drawHidden ? m_OverlayTechTileHidden : m_OverlayTechTile;
269 0 : deviceCommandContext->SetGraphicsPipelineState(
270 : shaderTechnique->GetGraphicsPipelineState());
271 0 : deviceCommandContext->BeginPass();
272 :
273 0 : Renderer::Backend::IShaderProgram* overlayShader = shaderTechnique->GetShader();
274 :
275 0 : const CMatrix3D transform =
276 0 : g_Renderer.GetSceneRenderer().GetViewCamera().GetViewProjection();
277 0 : deviceCommandContext->SetUniform(
278 0 : overlayShader->GetBindingSlot(str_transform), transform.AsFloatArray());
279 0 : deviceCommandContext->SetUniform(
280 0 : overlayShader->GetBindingSlot(str_color), color.AsFloatArray());
281 :
282 0 : deviceCommandContext->SetVertexInputLayout(m_VertexInputLayout);
283 :
284 0 : deviceCommandContext->SetVertexBufferData(
285 0 : 0, vertices.data(), vertices.size() * sizeof(vertices[0]));
286 :
287 0 : deviceCommandContext->Draw(0, vertices.size() / 3);
288 :
289 0 : deviceCommandContext->EndPass();
290 0 : }
291 :
292 0 : void TerrainOverlay::RenderTileOutline(
293 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
294 : const CColor& color, bool drawHidden)
295 : {
296 0 : RenderTileOutline(deviceCommandContext, color, drawHidden, m_i, m_j);
297 0 : }
298 :
299 0 : void TerrainOverlay::RenderTileOutline(
300 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
301 : const CColor& color, bool drawHidden, ssize_t i, ssize_t j)
302 : {
303 0 : std::vector<float> vertices;
304 : #define ADD(i, j) \
305 : m_Terrain->CalcPosition(i, j, position); \
306 : vertices.emplace_back(position.X); \
307 : vertices.emplace_back(position.Y); \
308 : vertices.emplace_back(position.Z);
309 :
310 0 : CVector3D position;
311 0 : ADD(i, j);
312 0 : ADD(i + 1, j);
313 0 : ADD(i + 1, j + 1);
314 0 : ADD(i, j);
315 0 : ADD(i + 1, j + 1);
316 0 : ADD(i, j + 1);
317 : #undef ADD
318 :
319 0 : const CShaderTechniquePtr& shaderTechnique = drawHidden ? m_OverlayTechOutlineHidden : m_OverlayTechOutline;
320 0 : deviceCommandContext->SetGraphicsPipelineState(
321 : shaderTechnique->GetGraphicsPipelineState());
322 0 : deviceCommandContext->BeginPass();
323 :
324 0 : Renderer::Backend::IShaderProgram* overlayShader = shaderTechnique->GetShader();
325 :
326 0 : const CMatrix3D transform =
327 0 : g_Renderer.GetSceneRenderer().GetViewCamera().GetViewProjection();
328 0 : deviceCommandContext->SetUniform(
329 0 : overlayShader->GetBindingSlot(str_transform), transform.AsFloatArray());
330 0 : deviceCommandContext->SetUniform(
331 0 : overlayShader->GetBindingSlot(str_color), color.AsFloatArray());
332 :
333 0 : deviceCommandContext->SetVertexInputLayout(m_VertexInputLayout);
334 :
335 0 : deviceCommandContext->SetVertexBufferData(
336 0 : 0, vertices.data(), vertices.size() * sizeof(vertices[0]));
337 :
338 0 : deviceCommandContext->Draw(0, vertices.size() / 3);
339 :
340 0 : deviceCommandContext->EndPass();
341 0 : }
342 :
343 : //////////////////////////////////////////////////////////////////////////
344 :
345 0 : TerrainTextureOverlay::TerrainTextureOverlay(float texelsPerTile,
346 0 : std::function<void(std::uint8_t*, std::size_t, std::size_t)> buildTextureRGBA) :
347 : ITerrainOverlay{100},
348 0 : m_BuildTextureRGBA{std::move(buildTextureRGBA)},
349 0 : m_TexelsPerTile{texelsPerTile}
350 : {
351 0 : }
352 :
353 0 : TerrainTextureOverlay::~TerrainTextureOverlay() = default;
354 :
355 0 : void TerrainTextureOverlay::RenderAfterWater(
356 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext, int cullGroup)
357 : {
358 0 : const CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
359 :
360 0 : const ssize_t w = static_cast<ssize_t>(terrain.GetTilesPerSide() * m_TexelsPerTile);
361 0 : const ssize_t h = static_cast<ssize_t>(terrain.GetTilesPerSide() * m_TexelsPerTile);
362 :
363 0 : const uint32_t requiredWidth = std::bit_ceil(static_cast<uint32_t>(w));
364 0 : const uint32_t requiredHeight = std::bit_ceil(static_cast<uint32_t>(h));
365 :
366 : // Recreate the texture with new size if necessary
367 0 : if (!m_Texture || m_Texture->GetWidth() != requiredWidth || m_Texture->GetHeight() != requiredHeight)
368 : {
369 0 : m_Texture = deviceCommandContext->GetDevice()->CreateTexture2D("TerrainOverlayTexture",
370 : Renderer::Backend::ITexture::Usage::TRANSFER_DST |
371 : Renderer::Backend::ITexture::Usage::SAMPLED,
372 : Renderer::Backend::Format::R8G8B8A8_UNORM, requiredWidth, requiredHeight,
373 0 : Renderer::Backend::Sampler::MakeDefaultSampler(
374 : Renderer::Backend::Sampler::Filter::NEAREST,
375 0 : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE));
376 : }
377 :
378 0 : std::uint8_t* data = static_cast<std::uint8_t*>(calloc(w * h, 4));
379 0 : m_BuildTextureRGBA(data, w, h);
380 :
381 0 : deviceCommandContext->UploadTextureRegion(
382 0 : m_Texture.get(), Renderer::Backend::Format::R8G8B8A8_UNORM, data, w * h * 4, 0, 0, w, h);
383 :
384 0 : free(data);
385 :
386 0 : const CVector2D textureTransform{
387 0 : m_TexelsPerTile / (m_Texture->GetWidth() * TERRAIN_TILE_SIZE),
388 0 : m_TexelsPerTile / (m_Texture->GetHeight() * TERRAIN_TILE_SIZE)};
389 0 : g_Renderer.GetSceneRenderer().GetTerrainRenderer().RenderTerrainOverlayTexture(
390 : deviceCommandContext, cullGroup, textureTransform, m_Texture.get());
391 0 : }
392 :
393 0 : SColor4ub TerrainTextureOverlay::GetColor(std::size_t idx, std::uint8_t alpha)
394 : {
395 0 : static std::uint8_t colors[][3] =
396 : {
397 : { 255, 0, 0 },
398 : { 0, 255, 0 },
399 : { 0, 0, 255 },
400 : { 255, 255, 0 },
401 : { 255, 0, 255 },
402 : { 0, 255, 255 },
403 : { 255, 255, 255 },
404 :
405 : { 127, 0, 0 },
406 : { 0, 127, 0 },
407 : { 0, 0, 127 },
408 : { 127, 127, 0 },
409 : { 127, 0, 127 },
410 : { 0, 127, 127 },
411 : { 127, 127, 127},
412 :
413 : { 255, 127, 0 },
414 : { 127, 255, 0 },
415 : { 255, 0, 127 },
416 : { 127, 0, 255},
417 : { 0, 255, 127 },
418 : { 0, 127, 255},
419 : { 255, 127, 127},
420 : { 127, 255, 127},
421 : { 127, 127, 255},
422 :
423 : { 127, 255, 255 },
424 : { 255, 127, 255 },
425 : { 255, 255, 127 },
426 : };
427 :
428 0 : size_t c = idx % ARRAY_SIZE(colors);
429 0 : return SColor4ub(colors[c][0], colors[c][1], colors[c][2], alpha);
430 : }
|