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 "SilhouetteRenderer.h"
21 :
22 : #include "graphics/Camera.h"
23 : #include "graphics/HFTracer.h"
24 : #include "graphics/Model.h"
25 : #include "graphics/Overlay.h"
26 : #include "graphics/Patch.h"
27 : #include "graphics/RenderableObject.h"
28 : #include "graphics/ShaderDefines.h"
29 : #include "graphics/ShaderManager.h"
30 : #include "graphics/ShaderTechnique.h"
31 : #include "lib/debug.h"
32 : #include "lib/posix/posix_types.h"
33 : #include "maths/MathUtil.h"
34 : #include "maths/Matrix3D.h"
35 : #include "maths/Vector3D.h"
36 : #include "maths/Vector4D.h"
37 : #include "ps/CStrIntern.h"
38 : #include "ps/CStrInternStatic.h"
39 : #include "ps/Profile.h"
40 : #include "ps/VideoMode.h"
41 : #include "renderer/DebugRenderer.h"
42 : #include "renderer/Renderer.h"
43 : #include "renderer/Scene.h"
44 : #include "renderer/backend/Format.h"
45 : #include "renderer/backend/IDeviceCommandContext.h"
46 : #include "renderer/backend/IShaderProgram.h"
47 : #include "renderer/backend/PipelineState.h"
48 :
49 : #include <algorithm>
50 : #include <array>
51 : #include <cstddef>
52 : #include <cstdint>
53 : #include <iterator>
54 : #include <limits>
55 :
56 : // For debugging
57 : static const bool g_DisablePreciseIntersections = false;
58 :
59 10 : SilhouetteRenderer::SilhouetteRenderer()
60 : {
61 10 : m_DebugEnabled = false;
62 10 : }
63 :
64 0 : void SilhouetteRenderer::AddOccluder(CPatch* patch)
65 : {
66 0 : m_SubmittedPatchOccluders.push_back(patch);
67 0 : }
68 :
69 0 : void SilhouetteRenderer::AddOccluder(CModel* model)
70 : {
71 0 : m_SubmittedModelOccluders.push_back(model);
72 0 : }
73 :
74 0 : void SilhouetteRenderer::AddCaster(CModel* model)
75 : {
76 0 : m_SubmittedModelCasters.push_back(model);
77 0 : }
78 :
79 : /*
80 : * Silhouettes are the solid-colored versions of units that are rendered when
81 : * standing behind a building or terrain, so the player won't lose them.
82 : *
83 : * The rendering is done in CRenderer::RenderSilhouettes, by rendering the
84 : * units (silhouette casters) and buildings/terrain (silhouette occluders)
85 : * in an extra pass using depth and stencil buffers. It's very inefficient to
86 : * render those objects when they're not actually going to contribute to a
87 : * silhouette.
88 : *
89 : * This class is responsible for finding the subset of casters/occluders
90 : * that might contribute to a silhouette and will need to be rendered.
91 : *
92 : * The algorithm is largely based on sweep-and-prune for detecting intersection
93 : * along a single axis:
94 : *
95 : * First we compute the 2D screen-space bounding box of every occluder, and
96 : * their minimum distance from the camera. We also compute the screen-space
97 : * position of each caster (approximating them as points, which is not perfect
98 : * but almost always good enough).
99 : *
100 : * We split each occluder's screen-space bounds into a left ('in') edge and
101 : * right ('out') edge. We put those edges plus the caster points into a list,
102 : * and sort by x coordinate.
103 : *
104 : * Then we walk through the list, maintaining an active set of occluders.
105 : * An 'in' edge will add an occluder to the set, an 'out' edge will remove it.
106 : * When we reach a caster point, the active set contains all the occluders that
107 : * intersect it in x. We do a quick test of y and depth coordinates against
108 : * each occluder in the set. If they pass that test, we do a more precise ray
109 : * vs bounding box test (for model occluders) or ray vs patch (for terrain
110 : * occluders) to see if we really need to render that caster and occluder.
111 : *
112 : * Performance relies on the active set being quite small. Given the game's
113 : * typical occluder sizes and camera angles, this works out okay.
114 : *
115 : * We have to do precise ray/patch intersection tests for terrain, because
116 : * if we just used the patch's bounding box, pretty much every unit would
117 : * be seen as intersecting the patch it's standing on.
118 : *
119 : * We store screen-space coordinates as 14-bit integers (0..16383) because
120 : * that lets us pack and sort the edge/point list efficiently.
121 : */
122 :
123 : static const std::uint16_t g_MaxCoord = 1 << 14;
124 : static const std::uint16_t g_HalfMaxCoord = g_MaxCoord / 2;
125 :
126 : struct Occluder
127 : {
128 : CRenderableObject* renderable;
129 : bool isPatch;
130 : std::uint16_t x0, y0, x1, y1;
131 : float z;
132 : bool rendered;
133 : };
134 :
135 : struct Caster
136 : {
137 : CModel* model;
138 : std::uint16_t x, y;
139 : float z;
140 : bool rendered;
141 : };
142 :
143 : enum { EDGE_IN, EDGE_OUT, POINT };
144 :
145 : // Entry is essentially:
146 : // struct Entry {
147 : // std::uint16_t id; // index into occluders array
148 : // std::uint16_t type : 2;
149 : // std::uint16_t x : 14;
150 : // };
151 : // where x is in the most significant bits, so that sorting as a uint32_t
152 : // is the same as sorting by x. To avoid worrying about endianness and the
153 : // compiler's ability to handle bitfields efficiently, we use uint32_t instead
154 : // of the actual struct.
155 :
156 : typedef uint32_t Entry;
157 :
158 0 : static Entry EntryCreate(int type, std::uint16_t id, std::uint16_t x)
159 : {
160 0 : return (x << 18) | (type << 16) | id;
161 : }
162 0 : static int EntryGetId(Entry e) { return e & 0xffff; }
163 0 : static int EntryGetType(Entry e) { return (e >> 16) & 3; }
164 :
165 0 : struct ActiveList
166 : {
167 : std::vector<std::uint16_t> m_Ids;
168 :
169 0 : void Add(std::uint16_t id)
170 : {
171 0 : m_Ids.push_back(id);
172 0 : }
173 :
174 0 : void Remove(std::uint16_t id)
175 : {
176 0 : ssize_t sz = m_Ids.size();
177 0 : for (ssize_t i = sz-1; i >= 0; --i)
178 : {
179 0 : if (m_Ids[i] == id)
180 : {
181 0 : m_Ids[i] = m_Ids[sz-1];
182 0 : m_Ids.pop_back();
183 0 : return;
184 : }
185 : }
186 0 : debug_warn(L"Failed to find id");
187 : }
188 : };
189 :
190 0 : static void ComputeScreenBounds(Occluder& occluder, const CBoundingBoxAligned& bounds, CMatrix3D& proj)
191 : {
192 0 : std::uint16_t x0 = std::numeric_limits<std::uint16_t>::max();
193 0 : std::uint16_t y0 = std::numeric_limits<std::uint16_t>::max();
194 0 : std::uint16_t x1 = std::numeric_limits<std::uint16_t>::min();
195 0 : std::uint16_t y1 = std::numeric_limits<std::uint16_t>::min();
196 0 : float z0 = std::numeric_limits<float>::max();
197 0 : for (size_t ix = 0; ix <= 1; ++ix)
198 : {
199 0 : for (size_t iy = 0; iy <= 1; ++iy)
200 : {
201 0 : for (size_t iz = 0; iz <= 1; ++iz)
202 : {
203 0 : CVector4D svec = proj.Transform(CVector4D(bounds[ix].X, bounds[iy].Y, bounds[iz].Z, 1.0f));
204 : // Avoid overflows
205 0 : std::uint16_t svx = static_cast<std::uint16_t>(Clamp(g_HalfMaxCoord +
206 0 : g_HalfMaxCoord * (svec.X / svec.W), 0.f,
207 0 : static_cast<float>(g_MaxCoord - 1)));
208 0 : std::uint16_t svy = static_cast<std::uint16_t>(Clamp(g_HalfMaxCoord +
209 0 : g_HalfMaxCoord * (svec.Y / svec.W), 0.f,
210 0 : static_cast<float>(g_MaxCoord - 1)));
211 0 : x0 = std::min(x0, svx);
212 0 : y0 = std::min(y0, svy);
213 0 : x1 = std::max(x1, svx);
214 0 : y1 = std::max(y1, svy);
215 0 : z0 = std::min(z0, svec.Z / svec.W);
216 : }
217 : }
218 : }
219 : // TODO: there must be a quicker way to do this than to test every vertex,
220 : // given the symmetry of the bounding box
221 :
222 0 : occluder.x0 = Clamp(x0, std::numeric_limits<std::uint16_t>::min(),
223 : static_cast<std::uint16_t>(g_MaxCoord - 1));
224 0 : occluder.y0 = Clamp(y0, std::numeric_limits<std::uint16_t>::min(),
225 : static_cast<std::uint16_t>(g_MaxCoord - 1));
226 0 : occluder.x1 = Clamp(x1, std::numeric_limits<std::uint16_t>::min(),
227 : static_cast<std::uint16_t>(g_MaxCoord - 1));
228 0 : occluder.y1 = Clamp(y1, std::numeric_limits<std::uint16_t>::min(),
229 : static_cast<std::uint16_t>(g_MaxCoord - 1));
230 0 : occluder.z = z0;
231 0 : }
232 :
233 0 : static void ComputeScreenPos(Caster& caster, const CVector3D& pos, CMatrix3D& proj)
234 : {
235 0 : CVector4D svec = proj.Transform(CVector4D(pos.X, pos.Y, pos.Z, 1.0f));
236 0 : caster.x = static_cast<std::uint16_t>(Clamp(g_HalfMaxCoord + g_HalfMaxCoord * (svec.X / svec.W), 0.f,
237 : static_cast<float>(g_MaxCoord - 1)));
238 0 : caster.y = static_cast<std::uint16_t>(Clamp(g_HalfMaxCoord + g_HalfMaxCoord * (svec.Y / svec.W), 0.f,
239 : static_cast<float>(g_MaxCoord - 1)));
240 0 : caster.z = svec.Z / svec.W;
241 0 : }
242 :
243 0 : void SilhouetteRenderer::ComputeSubmissions(const CCamera& camera)
244 : {
245 0 : PROFILE3("compute silhouettes");
246 :
247 0 : m_DebugBounds.clear();
248 0 : m_DebugRects.clear();
249 0 : m_DebugSpheres.clear();
250 :
251 0 : m_VisiblePatchOccluders.clear();
252 0 : m_VisibleModelOccluders.clear();
253 0 : m_VisibleModelCasters.clear();
254 :
255 0 : std::vector<Occluder> occluders;
256 0 : std::vector<Caster> casters;
257 0 : std::vector<Entry> entries;
258 :
259 0 : occluders.reserve(m_SubmittedModelOccluders.size() + m_SubmittedPatchOccluders.size());
260 0 : casters.reserve(m_SubmittedModelCasters.size());
261 0 : entries.reserve((m_SubmittedModelOccluders.size() + m_SubmittedPatchOccluders.size()) * 2 + m_SubmittedModelCasters.size());
262 :
263 0 : CMatrix3D proj = camera.GetViewProjection();
264 :
265 : // Bump the positions of unit casters upwards a bit, so they're not always
266 : // detected as intersecting the terrain they're standing on
267 0 : CVector3D posOffset(0.0f, 0.1f, 0.0f);
268 :
269 : #if 0
270 : // For debugging ray-patch intersections - casts a ton of rays and draws
271 : // a sphere where they intersect
272 : for (int y = 0; y < g_VideoMode.GetWindowHeight(); y += 8)
273 : {
274 : for (int x = 0; x < g_VideoMode.GetWindowWidth(); x += 8)
275 : {
276 : SOverlaySphere sphere;
277 : sphere.m_Color = CColor(1, 0, 0, 1);
278 : sphere.m_Radius = 0.25f;
279 : sphere.m_Center = camera.GetWorldCoordinates(x, y, false);
280 :
281 : CVector3D origin, dir;
282 : camera.BuildCameraRay(x, y, origin, dir);
283 :
284 : for (size_t i = 0; i < m_SubmittedPatchOccluders.size(); ++i)
285 : {
286 : CPatch* occluder = m_SubmittedPatchOccluders[i];
287 : if (CHFTracer::PatchRayIntersect(occluder, origin, dir, &sphere.m_Center))
288 : sphere.m_Color = CColor(0, 0, 1, 1);
289 : }
290 : m_DebugSpheres.push_back(sphere);
291 : }
292 : }
293 : #endif
294 :
295 0 : {
296 0 : PROFILE("compute bounds");
297 :
298 0 : for (size_t i = 0; i < m_SubmittedModelOccluders.size(); ++i)
299 : {
300 0 : CModel* occluder = m_SubmittedModelOccluders[i];
301 :
302 0 : Occluder d;
303 0 : d.renderable = occluder;
304 0 : d.isPatch = false;
305 0 : d.rendered = false;
306 0 : ComputeScreenBounds(d, occluder->GetWorldBounds(), proj);
307 :
308 : // Skip zero-sized occluders, so we don't need to worry about EDGE_OUT
309 : // getting sorted before EDGE_IN
310 0 : if (d.x0 == d.x1 || d.y0 == d.y1)
311 0 : continue;
312 :
313 0 : std::uint16_t id = static_cast<std::uint16_t>(occluders.size());
314 0 : occluders.push_back(d);
315 :
316 0 : entries.push_back(EntryCreate(EDGE_IN, id, d.x0));
317 0 : entries.push_back(EntryCreate(EDGE_OUT, id, d.x1));
318 : }
319 :
320 0 : for (size_t i = 0; i < m_SubmittedPatchOccluders.size(); ++i)
321 : {
322 0 : CPatch* occluder = m_SubmittedPatchOccluders[i];
323 :
324 0 : Occluder d;
325 0 : d.renderable = occluder;
326 0 : d.isPatch = true;
327 0 : d.rendered = false;
328 0 : ComputeScreenBounds(d, occluder->GetWorldBounds(), proj);
329 :
330 : // Skip zero-sized occluders
331 0 : if (d.x0 == d.x1 || d.y0 == d.y1)
332 0 : continue;
333 :
334 0 : std::uint16_t id = static_cast<std::uint16_t>(occluders.size());
335 0 : occluders.push_back(d);
336 :
337 0 : entries.push_back(EntryCreate(EDGE_IN, id, d.x0));
338 0 : entries.push_back(EntryCreate(EDGE_OUT, id, d.x1));
339 : }
340 :
341 0 : for (size_t i = 0; i < m_SubmittedModelCasters.size(); ++i)
342 : {
343 0 : CModel* model = m_SubmittedModelCasters[i];
344 0 : CVector3D pos = model->GetTransform().GetTranslation() + posOffset;
345 :
346 0 : Caster d;
347 0 : d.model = model;
348 0 : d.rendered = false;
349 0 : ComputeScreenPos(d, pos, proj);
350 :
351 0 : std::uint16_t id = static_cast<std::uint16_t>(casters.size());
352 0 : casters.push_back(d);
353 :
354 0 : entries.push_back(EntryCreate(POINT, id, d.x));
355 : }
356 0 : }
357 :
358 : // Make sure the std::uint16_t id didn't overflow
359 0 : ENSURE(occluders.size() < 65536 && casters.size() < 65536);
360 :
361 0 : {
362 0 : PROFILE("sorting");
363 0 : std::sort(entries.begin(), entries.end());
364 0 : }
365 :
366 0 : {
367 0 : PROFILE("sweeping");
368 :
369 0 : ActiveList active;
370 0 : CVector3D cameraPos = camera.GetOrientation().GetTranslation();
371 :
372 0 : for (size_t i = 0; i < entries.size(); ++i)
373 : {
374 0 : Entry e = entries[i];
375 0 : int type = EntryGetType(e);
376 0 : std::uint16_t id = EntryGetId(e);
377 0 : if (type == EDGE_IN)
378 0 : active.Add(id);
379 0 : else if (type == EDGE_OUT)
380 0 : active.Remove(id);
381 : else
382 : {
383 0 : Caster& caster = casters[id];
384 0 : for (size_t j = 0; j < active.m_Ids.size(); ++j)
385 : {
386 0 : Occluder& occluder = occluders[active.m_Ids[j]];
387 :
388 0 : if (caster.y < occluder.y0 || caster.y > occluder.y1)
389 0 : continue;
390 :
391 0 : if (caster.z < occluder.z)
392 0 : continue;
393 :
394 : // No point checking further if both are already being rendered
395 0 : if (caster.rendered && occluder.rendered)
396 0 : continue;
397 :
398 0 : if (!g_DisablePreciseIntersections)
399 : {
400 0 : CVector3D pos = caster.model->GetTransform().GetTranslation() + posOffset;
401 0 : if (occluder.isPatch)
402 : {
403 0 : CPatch* patch = static_cast<CPatch*>(occluder.renderable);
404 0 : if (!CHFTracer::PatchRayIntersect(patch, pos, cameraPos - pos, NULL))
405 0 : continue;
406 : }
407 : else
408 : {
409 0 : float tmin, tmax;
410 0 : if (!occluder.renderable->GetWorldBounds().RayIntersect(pos, cameraPos - pos, tmin, tmax))
411 0 : continue;
412 : }
413 : }
414 :
415 0 : caster.rendered = true;
416 0 : occluder.rendered = true;
417 : }
418 : }
419 : }
420 0 : }
421 :
422 0 : if (m_DebugEnabled)
423 : {
424 0 : for (size_t i = 0; i < occluders.size(); ++i)
425 : {
426 0 : DebugRect r;
427 0 : r.color = occluders[i].rendered ? CColor(1.0f, 1.0f, 0.0f, 1.0f) : CColor(0.2f, 0.2f, 0.0f, 1.0f);
428 0 : r.x0 = occluders[i].x0;
429 0 : r.y0 = occluders[i].y0;
430 0 : r.x1 = occluders[i].x1;
431 0 : r.y1 = occluders[i].y1;
432 0 : m_DebugRects.push_back(r);
433 :
434 0 : DebugBounds b;
435 0 : b.color = r.color;
436 0 : b.bounds = occluders[i].renderable->GetWorldBounds();
437 0 : m_DebugBounds.push_back(b);
438 : }
439 : }
440 :
441 0 : for (size_t i = 0; i < occluders.size(); ++i)
442 : {
443 0 : if (occluders[i].rendered)
444 : {
445 0 : if (occluders[i].isPatch)
446 0 : m_VisiblePatchOccluders.push_back(static_cast<CPatch*>(occluders[i].renderable));
447 : else
448 0 : m_VisibleModelOccluders.push_back(static_cast<CModel*>(occluders[i].renderable));
449 : }
450 : }
451 :
452 0 : for (size_t i = 0; i < casters.size(); ++i)
453 0 : if (casters[i].rendered)
454 0 : m_VisibleModelCasters.push_back(casters[i].model);
455 0 : }
456 :
457 0 : void SilhouetteRenderer::RenderSubmitOverlays(SceneCollector& collector)
458 : {
459 0 : for (size_t i = 0; i < m_DebugSpheres.size(); i++)
460 0 : collector.Submit(&m_DebugSpheres[i]);
461 0 : }
462 :
463 0 : void SilhouetteRenderer::RenderSubmitOccluders(SceneCollector& collector)
464 : {
465 0 : for (size_t i = 0; i < m_VisiblePatchOccluders.size(); ++i)
466 0 : collector.Submit(m_VisiblePatchOccluders[i]);
467 :
468 0 : for (size_t i = 0; i < m_VisibleModelOccluders.size(); ++i)
469 0 : collector.SubmitNonRecursive(m_VisibleModelOccluders[i]);
470 0 : }
471 :
472 0 : void SilhouetteRenderer::RenderSubmitCasters(SceneCollector& collector)
473 : {
474 0 : for (size_t i = 0; i < m_VisibleModelCasters.size(); ++i)
475 0 : collector.SubmitNonRecursive(m_VisibleModelCasters[i]);
476 0 : }
477 :
478 0 : void SilhouetteRenderer::RenderDebugBounds(Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
479 : {
480 0 : if (m_DebugBounds.empty())
481 : return;
482 :
483 0 : for (size_t i = 0; i < m_DebugBounds.size(); ++i)
484 0 : g_Renderer.GetDebugRenderer().DrawBoundingBox(*deviceCommandContext, m_DebugBounds[i].bounds, m_DebugBounds[i].color, true);
485 : }
486 :
487 0 : void SilhouetteRenderer::RenderDebugOverlays(
488 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
489 : {
490 0 : if (m_DebugRects.empty())
491 0 : return;
492 :
493 : // TODO: use CCanvas2D for drawing rects.
494 0 : CMatrix3D m;
495 0 : m.SetIdentity();
496 0 : m.Scale(1.0f, -1.f, 1.0f);
497 0 : m.Translate(0.0f, static_cast<float>(g_VideoMode.GetWindowHeight()), -1000.0f);
498 :
499 0 : CMatrix3D proj;
500 0 : proj.SetOrtho(0.f, g_MaxCoord, 0.f, g_MaxCoord, -1.f, 1000.f);
501 0 : m = proj * m;
502 :
503 0 : if (!m_ShaderTech)
504 : {
505 0 : m_ShaderTech = g_Renderer.GetShaderManager().LoadEffect(
506 : str_solid, {},
507 0 : [](Renderer::Backend::SGraphicsPipelineStateDesc& pipelineStateDesc)
508 : {
509 0 : pipelineStateDesc.rasterizationState.polygonMode = Renderer::Backend::PolygonMode::LINE;
510 0 : pipelineStateDesc.rasterizationState.cullMode = Renderer::Backend::CullMode::NONE;
511 0 : });
512 :
513 0 : const std::array<Renderer::Backend::SVertexAttributeFormat, 1> attributes{{
514 : {Renderer::Backend::VertexAttributeStream::POSITION,
515 : Renderer::Backend::Format::R32G32_SFLOAT, 0, sizeof(float) * 2,
516 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
517 : }};
518 0 : m_VertexInputLayout = g_Renderer.GetVertexInputLayout(attributes);
519 : }
520 :
521 0 : deviceCommandContext->BeginPass();
522 0 : deviceCommandContext->SetGraphicsPipelineState(
523 0 : m_ShaderTech->GetGraphicsPipelineState());
524 :
525 0 : Renderer::Backend::IShaderProgram* shader = m_ShaderTech->GetShader();
526 0 : deviceCommandContext->SetUniform(
527 0 : shader->GetBindingSlot(str_transform), proj.AsFloatArray());
528 :
529 0 : const int32_t colorBindingSlot = shader->GetBindingSlot(str_color);
530 0 : for (const DebugRect& r : m_DebugRects)
531 : {
532 0 : deviceCommandContext->SetUniform(
533 0 : colorBindingSlot, r.color.AsFloatArray());
534 0 : const float vertices[] =
535 : {
536 0 : r.x0, r.y0,
537 0 : r.x1, r.y0,
538 0 : r.x1, r.y1,
539 0 : r.x0, r.y0,
540 0 : r.x1, r.y1,
541 0 : r.x0, r.y1,
542 0 : };
543 :
544 0 : deviceCommandContext->SetVertexInputLayout(m_VertexInputLayout);
545 :
546 0 : deviceCommandContext->SetVertexBufferData(
547 : 0, vertices, std::size(vertices) * sizeof(vertices[0]));
548 :
549 0 : deviceCommandContext->Draw(0, 6);
550 : }
551 :
552 0 : deviceCommandContext->EndPass();
553 : }
554 :
555 0 : void SilhouetteRenderer::EndFrame()
556 : {
557 0 : m_SubmittedPatchOccluders.clear();
558 0 : m_SubmittedModelOccluders.clear();
559 0 : m_SubmittedModelCasters.clear();
560 0 : }
|