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 "ShadowMap.h"
21 :
22 : #include "graphics/Camera.h"
23 : #include "graphics/Color.h"
24 : #include "lib/config2.h"
25 : #include "lib/debug.h"
26 : #include "maths/BoundingBoxAligned.h"
27 : #include "maths/Brush.h"
28 : #include "maths/Frustum.h"
29 : #include "maths/MathUtil.h"
30 : #include "maths/Matrix3D.h"
31 : #include "maths/Vector3D.h"
32 : #include "ps/CLogger.h"
33 : #include "ps/CStrIntern.h"
34 : #include "ps/CStrInternStatic.h"
35 : #include "ps/ConfigDB.h"
36 : #include "renderer/DebugRenderer.h"
37 : #include "renderer/Renderer.h"
38 : #include "renderer/RenderingOptions.h"
39 : #include "renderer/SceneRenderer.h"
40 : #include "renderer/backend/Backend.h"
41 : #include "renderer/backend/CompareOp.h"
42 : #include "renderer/backend/Format.h"
43 : #include "renderer/backend/IDevice.h"
44 : #include "renderer/backend/IDeviceCommandContext.h"
45 : #include "renderer/backend/IFramebuffer.h"
46 : #include "renderer/backend/IShaderProgram.h"
47 : #include "renderer/backend/ITexture.h"
48 : #include "renderer/backend/Sampler.h"
49 :
50 : #include <algorithm>
51 : #include <array>
52 : #include <bit>
53 : #include <cmath>
54 : #include <cstdint>
55 : #include <memory>
56 : #include <span>
57 : #include <vector>
58 :
59 : namespace
60 : {
61 :
62 : constexpr int MAX_CASCADE_COUNT = 4;
63 :
64 : constexpr float DEFAULT_SHADOWS_CUTOFF_DISTANCE = 300.0f;
65 : constexpr float DEFAULT_CASCADE_DISTANCE_RATIO = 1.7f;
66 :
67 : } // anonymous namespace
68 :
69 : /**
70 : * Struct ShadowMapInternals: Internal data for the ShadowMap implementation
71 : */
72 : struct ShadowMapInternals
73 : {
74 : Renderer::Backend::IDevice* Device = nullptr;
75 :
76 : std::unique_ptr<Renderer::Backend::IFramebuffer> Framebuffer;
77 : std::unique_ptr<Renderer::Backend::ITexture> Texture;
78 :
79 : // bit depth for the depth texture
80 : int DepthTextureBits;
81 : // width, height of shadow map
82 : int Width, Height;
83 : // Shadow map quality (-1 - Low, 0 - Medium, 1 - High, 2 - Very High)
84 : int QualityLevel;
85 : // used width, height of shadow map
86 : int EffectiveWidth, EffectiveHeight;
87 :
88 : // Transform world space into light space; calculated on SetupFrame
89 : CMatrix3D LightTransform;
90 :
91 : // transform light space into world space
92 : CMatrix3D InvLightTransform;
93 : CBoundingBoxAligned ShadowReceiverBound;
94 :
95 : int CascadeCount;
96 : float CascadeDistanceRatio;
97 : float ShadowsCutoffDistance;
98 : bool ShadowsCoverMap;
99 :
100 : struct Cascade
101 : {
102 : // transform light space into projected light space
103 : // in projected light space, the shadowbound box occupies the [-1..1] cube
104 : // calculated on BeginRender, after the final shadow bounds are known
105 : CMatrix3D LightProjection;
106 : float Distance;
107 : CBoundingBoxAligned FrustumBBAA;
108 : CBoundingBoxAligned ConvexBounds;
109 : CBoundingBoxAligned ShadowRenderBound;
110 : // Bounding box of shadowed objects in the light space.
111 : CBoundingBoxAligned ShadowCasterBound;
112 : // Transform world space into texture space of the shadow map;
113 : // calculated on BeginRender, after the final shadow bounds are known
114 : CMatrix3D TextureMatrix;
115 : // View port of the shadow texture where the cascade should be rendered.
116 : SViewPort ViewPort;
117 : };
118 : std::array<Cascade, MAX_CASCADE_COUNT> Cascades;
119 :
120 : // Camera transformed into light space
121 : CCamera LightspaceCamera;
122 :
123 : // Some drivers (at least some Intel Mesa ones) appear to handle alpha testing
124 : // incorrectly when the FBO has only a depth attachment.
125 : // When m_ShadowAlphaFix is true, we use DummyTexture to store a useless
126 : // alpha texture which is attached to the FBO as a workaround.
127 : std::unique_ptr<Renderer::Backend::ITexture> DummyTexture;
128 :
129 : // Copy of renderer's standard view camera, saved between
130 : // BeginRender and EndRender while we replace it with the shadow camera
131 : CCamera SavedViewCamera;
132 :
133 : void CalculateShadowMatrices(const int cascade);
134 : void CreateTexture(const uint32_t width, const uint32_t height);
135 : void UpdateCascadesParameters();
136 : };
137 :
138 20 : void ShadowMapInternals::UpdateCascadesParameters()
139 : {
140 20 : CascadeCount = g_ConfigDB.Get("shadowscascadecount", 1);
141 :
142 20 : if (CascadeCount < 1 || CascadeCount > MAX_CASCADE_COUNT)
143 0 : CascadeCount = 1;
144 :
145 20 : ShadowsCoverMap = g_ConfigDB.Get("shadowscovermap", false);
146 20 : }
147 :
148 0 : void CalculateBoundsForCascade(
149 : const CCamera& camera, const CMatrix3D& lightTransform,
150 : const float nearPlane, const float farPlane, CBoundingBoxAligned* bbaa,
151 : CBoundingBoxAligned* frustumBBAA)
152 : {
153 0 : frustumBBAA->SetEmpty();
154 :
155 : // We need to calculate a circumscribed sphere for the camera to
156 : // create a rotation stable bounding box.
157 0 : const CVector3D cameraIn = camera.m_Orientation.GetIn();
158 0 : const CVector3D cameraTranslation = camera.m_Orientation.GetTranslation();
159 0 : const CVector3D centerNear = cameraTranslation + cameraIn * nearPlane;
160 0 : const CVector3D centerDist = cameraTranslation + cameraIn * farPlane;
161 :
162 : // We can solve 3D problem in 2D space, because the frustum is
163 : // symmetric by 2 planes. Than means we can use only one corner
164 : // to find a circumscribed sphere.
165 0 : CCamera::Quad nearCorners{camera.GetViewQuad(nearPlane)};
166 0 : for (CVector3D& corner : nearCorners)
167 0 : corner = camera.GetOrientation().Transform(corner);
168 0 : const CVector3D cornerNear = nearCorners[0];
169 0 : for (const CVector3D& corner : nearCorners)
170 0 : *frustumBBAA += lightTransform.Transform(corner);
171 :
172 0 : CCamera::Quad farCorners{camera.GetViewQuad(farPlane)};
173 0 : for (CVector3D& corner : farCorners)
174 0 : corner = camera.GetOrientation().Transform(corner);
175 0 : const CVector3D cornerDist = farCorners[0];
176 0 : for (const CVector3D& corner : farCorners)
177 0 : *frustumBBAA += lightTransform.Transform(corner);
178 :
179 : // We solve 2D case for the right trapezoid.
180 0 : const float firstBase = (cornerNear - centerNear).Length();
181 0 : const float secondBase = (cornerDist - centerDist).Length();
182 0 : const float height = (centerDist - centerNear).Length();
183 0 : const float distanceToCenter =
184 0 : (height * height + secondBase * secondBase - firstBase * firstBase) * 0.5f / height;
185 :
186 0 : CVector3D position = cameraTranslation + cameraIn * (nearPlane + distanceToCenter);
187 0 : const float radius = (cornerNear - position).Length();
188 :
189 : // We need to convert the bounding box to the light space.
190 0 : position = lightTransform.Rotate(position);
191 :
192 0 : const float insets = 0.2f;
193 0 : *bbaa = CBoundingBoxAligned(position, position);
194 0 : bbaa->Expand(radius);
195 0 : bbaa->Expand(insets);
196 0 : }
197 :
198 10 : ShadowMap::ShadowMap(Renderer::Backend::IDevice* device)
199 : {
200 10 : m = new ShadowMapInternals;
201 10 : m->Device = device;
202 10 : m->Framebuffer = 0;
203 10 : m->Width = 0;
204 10 : m->Height = 0;
205 10 : m->QualityLevel = 0;
206 10 : m->EffectiveWidth = 0;
207 10 : m->EffectiveHeight = 0;
208 10 : m->DepthTextureBits = 0;
209 : // DepthTextureBits: 24/32 are very much faster than 16, on GeForce 4 and FX;
210 : // but they're very much slower on Radeon 9800.
211 : // In both cases, the default (no specified depth) is fast, so we just use
212 : // that by default and hope it's alright. (Otherwise, we'd probably need to
213 : // do some kind of hardware detection to work out what to use.)
214 :
215 : // Avoid using uninitialised values in AddShadowedBound if SetupFrame wasn't called first
216 10 : m->LightTransform.SetIdentity();
217 :
218 10 : m->UpdateCascadesParameters();
219 10 : }
220 :
221 10 : ShadowMap::~ShadowMap()
222 : {
223 10 : m->Framebuffer.reset();
224 10 : m->Texture.reset();
225 10 : m->DummyTexture.reset();
226 :
227 10 : delete m;
228 10 : }
229 :
230 10 : void ShadowMap::CreateViewSizeDependentObjects(const uint32_t width, const uint32_t height)
231 : {
232 10 : m->UpdateCascadesParameters();
233 :
234 10 : m->CreateTexture(width, height);
235 10 : }
236 :
237 0 : void ShadowMap::DestroyViewSizeDependentObjects()
238 : {
239 0 : m->Framebuffer.reset();
240 0 : m->Texture.reset();
241 0 : m->DummyTexture.reset();
242 0 : }
243 :
244 0 : void ShadowMap::RecreateTexture()
245 : {
246 0 : DestroyViewSizeDependentObjects();
247 0 : CreateViewSizeDependentObjects(g_Renderer.GetWidth(), g_Renderer.GetHeight());
248 0 : }
249 :
250 : // SetupFrame: camera and light direction for this frame
251 0 : void ShadowMap::SetupFrame(const CCamera& camera, const CVector3D& lightdir)
252 : {
253 0 : CVector3D x(0, 1, 0), eyepos;
254 :
255 0 : CVector3D z = lightdir;
256 0 : z.Normalize();
257 0 : x -= z * z.Dot(x);
258 0 : if (x.Length() < 0.001)
259 : {
260 : // this is invoked if the camera and light directions almost coincide
261 : // assumption: light direction has a significant Z component
262 0 : x = CVector3D(1.0, 0.0, 0.0);
263 0 : x -= z * z.Dot(x);
264 : }
265 0 : x.Normalize();
266 0 : CVector3D y = z.Cross(x);
267 :
268 : // X axis perpendicular to light direction, flowing along with view direction
269 0 : m->LightTransform._11 = x.X;
270 0 : m->LightTransform._12 = x.Y;
271 0 : m->LightTransform._13 = x.Z;
272 :
273 : // Y axis perpendicular to light and view direction
274 0 : m->LightTransform._21 = y.X;
275 0 : m->LightTransform._22 = y.Y;
276 0 : m->LightTransform._23 = y.Z;
277 :
278 : // Z axis is in direction of light
279 0 : m->LightTransform._31 = z.X;
280 0 : m->LightTransform._32 = z.Y;
281 0 : m->LightTransform._33 = z.Z;
282 :
283 : // eye is at the origin of the coordinate system
284 0 : m->LightTransform._14 = -x.Dot(eyepos);
285 0 : m->LightTransform._24 = -y.Dot(eyepos);
286 0 : m->LightTransform._34 = -z.Dot(eyepos);
287 :
288 0 : m->LightTransform._41 = 0.0;
289 0 : m->LightTransform._42 = 0.0;
290 0 : m->LightTransform._43 = 0.0;
291 0 : m->LightTransform._44 = 1.0;
292 :
293 0 : m->LightTransform.GetInverse(m->InvLightTransform);
294 0 : m->ShadowReceiverBound.SetEmpty();
295 :
296 0 : m->LightspaceCamera = camera;
297 0 : m->LightspaceCamera.m_Orientation = m->LightTransform * camera.m_Orientation;
298 0 : m->LightspaceCamera.UpdateFrustum();
299 :
300 0 : m->ShadowsCutoffDistance = DEFAULT_SHADOWS_CUTOFF_DISTANCE;
301 0 : m->CascadeDistanceRatio = DEFAULT_CASCADE_DISTANCE_RATIO;
302 0 : m->ShadowsCutoffDistance = g_ConfigDB.Get("shadowscutoffdistance", m->ShadowsCutoffDistance);
303 0 : m->CascadeDistanceRatio = g_ConfigDB.Get("shadowscascadedistanceratio", m->CascadeDistanceRatio);
304 0 : m->CascadeDistanceRatio = Clamp(m->CascadeDistanceRatio, 1.1f, 16.0f);
305 :
306 0 : m->Cascades[GetCascadeCount() - 1].Distance = m->ShadowsCutoffDistance;
307 0 : for (int cascade = GetCascadeCount() - 2; cascade >= 0; --cascade)
308 0 : m->Cascades[cascade].Distance = m->Cascades[cascade + 1].Distance / m->CascadeDistanceRatio;
309 :
310 0 : if (GetCascadeCount() == 1 || m->ShadowsCoverMap)
311 : {
312 0 : m->Cascades[0].ViewPort =
313 0 : SViewPort{1, 1, m->EffectiveWidth - 2, m->EffectiveHeight - 2};
314 0 : if (m->ShadowsCoverMap)
315 0 : m->Cascades[0].Distance = camera.GetFarPlane();
316 : }
317 : else
318 : {
319 0 : for (int cascade = 0; cascade < GetCascadeCount(); ++cascade)
320 : {
321 0 : const int offsetX = (cascade & 0x1) ? m->EffectiveWidth / 2 : 0;
322 0 : const int offsetY = (cascade & 0x2) ? m->EffectiveHeight / 2 : 0;
323 0 : m->Cascades[cascade].ViewPort =
324 0 : SViewPort{offsetX + 1, offsetY + 1,
325 0 : m->EffectiveWidth / 2 - 2, m->EffectiveHeight / 2 - 2};
326 : }
327 : }
328 :
329 0 : for (int cascadeIdx = 0; cascadeIdx < GetCascadeCount(); ++cascadeIdx)
330 : {
331 0 : ShadowMapInternals::Cascade& cascade = m->Cascades[cascadeIdx];
332 :
333 0 : const float nearPlane = cascadeIdx > 0 ?
334 0 : m->Cascades[cascadeIdx - 1].Distance : camera.GetNearPlane();
335 0 : const float farPlane = cascade.Distance;
336 :
337 0 : CalculateBoundsForCascade(camera, m->LightTransform,
338 : nearPlane, farPlane, &cascade.ConvexBounds, &cascade.FrustumBBAA);
339 0 : cascade.ShadowCasterBound.SetEmpty();
340 : }
341 0 : }
342 :
343 : // AddShadowedBound: add a world-space bounding box to the bounds of shadowed
344 : // objects
345 0 : void ShadowMap::AddShadowCasterBound(const int cascade, const CBoundingBoxAligned& bounds)
346 : {
347 0 : CBoundingBoxAligned lightspacebounds;
348 :
349 0 : bounds.Transform(m->LightTransform, lightspacebounds);
350 0 : m->Cascades[cascade].ShadowCasterBound += lightspacebounds;
351 0 : }
352 :
353 0 : void ShadowMap::AddShadowReceiverBound(const CBoundingBoxAligned& bounds)
354 : {
355 0 : CBoundingBoxAligned lightspacebounds;
356 :
357 0 : bounds.Transform(m->LightTransform, lightspacebounds);
358 0 : m->ShadowReceiverBound += lightspacebounds;
359 0 : }
360 :
361 0 : CFrustum ShadowMap::GetShadowCasterCullFrustum(const int cascade)
362 : {
363 : // Get the bounds of all objects that can receive shadows
364 0 : CBoundingBoxAligned bound = m->ShadowReceiverBound;
365 :
366 : // Intersect with the camera frustum, so the shadow map doesn't have to get
367 : // stretched to cover the off-screen parts of large models
368 0 : bound.IntersectFrustumConservative(m->Cascades[cascade].FrustumBBAA.ToFrustum());
369 :
370 : // ShadowBound might have been empty to begin with, producing an empty result
371 0 : if (bound.IsEmpty())
372 : {
373 : // CFrustum can't easily represent nothingness, so approximate it with
374 : // a single point which won't match many objects
375 0 : bound += CVector3D(0.0f, 0.0f, 0.0f);
376 0 : return bound.ToFrustum();
377 : }
378 :
379 : // Extend the bounds a long way towards the light source, to encompass
380 : // all objects that might cast visible shadows.
381 : // (The exact constant was picked entirely arbitrarily.)
382 0 : bound[0].Z -= 1000.f;
383 :
384 0 : CFrustum frustum = bound.ToFrustum();
385 0 : frustum.Transform(m->InvLightTransform);
386 0 : return frustum;
387 0 : }
388 :
389 : // CalculateShadowMatrices: calculate required matrices for shadow map generation - the light's
390 : // projection and transformation matrices
391 0 : void ShadowMapInternals::CalculateShadowMatrices(const int cascade)
392 : {
393 0 : CBoundingBoxAligned& shadowRenderBound = Cascades[cascade].ShadowRenderBound;
394 0 : shadowRenderBound = Cascades[cascade].ConvexBounds;
395 :
396 0 : if (ShadowsCoverMap)
397 : {
398 : // Start building the shadow map to cover all objects that will receive shadows
399 0 : CBoundingBoxAligned receiverBound = ShadowReceiverBound;
400 :
401 : // Intersect with the camera frustum, so the shadow map doesn't have to get
402 : // stretched to cover the off-screen parts of large models
403 0 : receiverBound.IntersectFrustumConservative(LightspaceCamera.GetFrustum());
404 :
405 : // Intersect with the shadow caster bounds, because there's no point
406 : // wasting space around the edges of the shadow map that we're not going
407 : // to draw into
408 0 : shadowRenderBound[0].X = std::max(receiverBound[0].X, Cascades[cascade].ShadowCasterBound[0].X);
409 0 : shadowRenderBound[0].Y = std::max(receiverBound[0].Y, Cascades[cascade].ShadowCasterBound[0].Y);
410 0 : shadowRenderBound[1].X = std::min(receiverBound[1].X, Cascades[cascade].ShadowCasterBound[1].X);
411 0 : shadowRenderBound[1].Y = std::min(receiverBound[1].Y, Cascades[cascade].ShadowCasterBound[1].Y);
412 : }
413 0 : else if (CascadeCount > 1)
414 : {
415 : // We need to offset the cascade to its place on the texture.
416 0 : const CVector3D size = (shadowRenderBound[1] - shadowRenderBound[0]) * 0.5f;
417 0 : if (!(cascade & 0x1))
418 0 : shadowRenderBound[1].X += size.X * 2.0f;
419 : else
420 0 : shadowRenderBound[0].X -= size.X * 2.0f;
421 0 : if (!(cascade & 0x2))
422 0 : shadowRenderBound[1].Y += size.Y * 2.0f;
423 : else
424 0 : shadowRenderBound[0].Y -= size.Y * 2.0f;
425 : }
426 :
427 : // Set the near and far planes to include just the shadow casters,
428 : // so we make full use of the depth texture's range. Add a bit of a
429 : // delta so we don't accidentally clip objects that are directly on
430 : // the planes.
431 0 : shadowRenderBound[0].Z = Cascades[cascade].ShadowCasterBound[0].Z - 2.f;
432 0 : shadowRenderBound[1].Z = Cascades[cascade].ShadowCasterBound[1].Z + 2.f;
433 :
434 : // Setup orthogonal projection (lightspace -> clip space) for shadowmap rendering
435 0 : CVector3D scale = shadowRenderBound[1] - shadowRenderBound[0];
436 0 : CVector3D shift = (shadowRenderBound[1] + shadowRenderBound[0]) * -0.5;
437 :
438 0 : if (scale.X < 1.0)
439 0 : scale.X = 1.0;
440 0 : if (scale.Y < 1.0)
441 0 : scale.Y = 1.0;
442 0 : if (scale.Z < 1.0)
443 0 : scale.Z = 1.0;
444 :
445 0 : scale.X = 2.0 / scale.X;
446 0 : scale.Y = 2.0 / scale.Y;
447 0 : scale.Z = 2.0 / scale.Z;
448 :
449 : // make sure a given world position falls on a consistent shadowmap texel fractional offset
450 0 : float offsetX = fmod(shadowRenderBound[0].X - LightTransform._14, 2.0f/(scale.X*EffectiveWidth));
451 0 : float offsetY = fmod(shadowRenderBound[0].Y - LightTransform._24, 2.0f/(scale.Y*EffectiveHeight));
452 :
453 0 : CMatrix3D& lightProjection = Cascades[cascade].LightProjection;
454 0 : lightProjection.SetZero();
455 0 : lightProjection._11 = scale.X;
456 0 : lightProjection._14 = (shift.X + offsetX) * scale.X;
457 0 : lightProjection._22 = scale.Y;
458 0 : lightProjection._24 = (shift.Y + offsetY) * scale.Y;
459 0 : lightProjection._33 = scale.Z;
460 0 : lightProjection._34 = shift.Z * scale.Z;
461 0 : lightProjection._44 = 1.0;
462 :
463 : // Calculate texture matrix by creating the clip space to texture coordinate matrix
464 : // and then concatenating all matrices that have been calculated so far
465 :
466 0 : float texscalex = scale.X * 0.5f * (float)EffectiveWidth / (float)Width;
467 0 : float texscaley = scale.Y * 0.5f * (float)EffectiveHeight / (float)Height;
468 0 : float texscalez = scale.Z * 0.5f;
469 :
470 0 : CMatrix3D lightToTex;
471 0 : lightToTex.SetZero();
472 0 : lightToTex._11 = texscalex;
473 0 : lightToTex._14 = (offsetX - shadowRenderBound[0].X) * texscalex;
474 0 : lightToTex._22 = texscaley;
475 0 : lightToTex._24 = (offsetY - shadowRenderBound[0].Y) * texscaley;
476 0 : lightToTex._33 = texscalez;
477 0 : lightToTex._34 = -shadowRenderBound[0].Z * texscalez;
478 0 : lightToTex._44 = 1.0;
479 :
480 0 : if (Device->GetBackend() == Renderer::Backend::Backend::VULKAN)
481 : {
482 0 : CMatrix3D flip;
483 0 : flip.SetIdentity();
484 0 : flip._22 = -1.0f;
485 0 : flip._24 = 1.0;
486 0 : lightToTex = flip * lightToTex;
487 : }
488 :
489 0 : Cascades[cascade].TextureMatrix = lightToTex * LightTransform;
490 0 : }
491 :
492 : // Create the shadow map
493 10 : void ShadowMapInternals::CreateTexture(const uint32_t width, const uint32_t height)
494 : {
495 : // Cleanup
496 10 : Framebuffer.reset();
497 10 : Texture.reset();
498 10 : DummyTexture.reset();
499 :
500 10 : QualityLevel = g_ConfigDB.Get("shadowquality", QualityLevel);
501 :
502 : // Get shadow map size as next power of two up from view width/height.
503 10 : int shadowMapSize;
504 10 : switch (QualityLevel)
505 : {
506 : // Low
507 0 : case -1:
508 0 : shadowMapSize = 512;
509 0 : break;
510 : // High
511 0 : case 1:
512 0 : shadowMapSize = 2048;
513 0 : break;
514 : // Ultra
515 0 : case 2:
516 0 : shadowMapSize = std::max(std::bit_ceil(static_cast<uint32_t>(std::max(width, height))), 4096u);
517 0 : break;
518 : // Medium as is
519 10 : default:
520 10 : shadowMapSize = 1024;
521 10 : break;
522 : }
523 :
524 : // Clamp to the maximum texture size.
525 20 : shadowMapSize = std::min(
526 10 : shadowMapSize, static_cast<int>(Device->GetCapabilities().maxTextureSize));
527 :
528 10 : Width = Height = shadowMapSize;
529 :
530 : // Since we're using a framebuffer object, the whole texture is available
531 10 : EffectiveWidth = Width;
532 10 : EffectiveHeight = Height;
533 :
534 10 : const char* formatName;
535 10 : Renderer::Backend::Format backendFormat = Renderer::Backend::Format::UNDEFINED;
536 : #if CONFIG2_GLES
537 : formatName = "Format::D24_UNORM";
538 : backendFormat = Renderer::Backend::Format::D24_UNORM;
539 : #else
540 10 : switch (DepthTextureBits)
541 : {
542 : case 16: formatName = "Format::D16_UNORM"; backendFormat = Renderer::Backend::Format::D16_UNORM; break;
543 : case 24: formatName = "Format::D24_UNORM"; backendFormat = Renderer::Backend::Format::D24_UNORM; break;
544 : case 32: formatName = "Format::D32_SFLOAT"; backendFormat = Renderer::Backend::Format::D32_SFLOAT; break;
545 10 : default:
546 10 : formatName = "Default";
547 10 : backendFormat = Device->GetPreferredDepthStencilFormat(
548 : Renderer::Backend::ITexture::Usage::SAMPLED |
549 : Renderer::Backend::ITexture::Usage::DEPTH_STENCIL_ATTACHMENT,
550 : true, false);
551 : break;
552 : }
553 : #endif
554 10 : ENSURE(formatName);
555 :
556 10 : LOGMESSAGE("Creating shadow texture (size {}x{}) (format = {})",
557 : Width, Height, formatName);
558 :
559 10 : if (g_RenderingOptions.GetShadowAlphaFix())
560 : {
561 0 : DummyTexture = Device->CreateTexture2D("ShadowMapDummy",
562 : Renderer::Backend::ITexture::Usage::COLOR_ATTACHMENT,
563 0 : Renderer::Backend::Format::R8G8B8A8_UNORM, Width, Height,
564 0 : Renderer::Backend::Sampler::MakeDefaultSampler(
565 : Renderer::Backend::Sampler::Filter::NEAREST,
566 0 : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE));
567 : }
568 :
569 : #if CONFIG2_GLES
570 : // GLES doesn't do depth comparisons, so treat it as a
571 : // basic unfiltered depth texture
572 : const Renderer::Backend::Sampler::Filter depthFilter{
573 : Device->GetBackend() == Renderer::Backend::Backend::GL
574 : ? Renderer::Backend::Sampler::Filter::NEAREST
575 : : Renderer::Backend::Sampler::Filter::LINEAR};
576 : #else
577 : // Use LINEAR to trigger automatic PCF on some devices.
578 10 : const Renderer::Backend::Sampler::Filter depthFilter{
579 : Renderer::Backend::Sampler::Filter::LINEAR};
580 : #endif
581 :
582 10 : Renderer::Backend::Sampler::Desc samplerDesc =
583 10 : Renderer::Backend::Sampler::MakeDefaultSampler(
584 : depthFilter,
585 : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
586 : // Enable automatic depth comparisons
587 10 : samplerDesc.compareEnabled = true;
588 10 : samplerDesc.compareOp = Renderer::Backend::CompareOp::LESS_OR_EQUAL;
589 :
590 20 : Texture = Device->CreateTexture2D("ShadowMapDepth",
591 : Renderer::Backend::ITexture::Usage::SAMPLED |
592 : Renderer::Backend::ITexture::Usage::DEPTH_STENCIL_ATTACHMENT,
593 10 : backendFormat, Width, Height, samplerDesc);
594 :
595 10 : const bool useDummyTexture = g_RenderingOptions.GetShadowAlphaFix();
596 :
597 : // In case we used ShadowAlphaFix, we ought to clear the unused
598 : // color buffer too, else Mali 400 drivers get confused.
599 : // Might as well clear stencil too for completeness.
600 10 : Renderer::Backend::SColorAttachment colorAttachment{};
601 10 : colorAttachment.texture = DummyTexture.get();
602 10 : colorAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::CLEAR;
603 10 : colorAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::DONT_CARE;
604 10 : colorAttachment.clearColor = CColor{0.0f, 0.0f, 0.0f, 0.0f};
605 :
606 10 : Renderer::Backend::SDepthStencilAttachment depthStencilAttachment{};
607 10 : depthStencilAttachment.texture = Texture.get();
608 10 : depthStencilAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::CLEAR;
609 10 : depthStencilAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::STORE;
610 :
611 20 : Framebuffer = Device->CreateFramebuffer("ShadowMapFramebuffer",
612 10 : useDummyTexture ? &colorAttachment : nullptr, &depthStencilAttachment);
613 10 : if (!Framebuffer)
614 : {
615 0 : LOGERROR("Failed to create shadows framebuffer");
616 :
617 : // Disable shadow rendering (but let the user try again if they want).
618 0 : g_RenderingOptions.SetShadows(false);
619 : }
620 10 : }
621 :
622 0 : void ShadowMap::BeginRender(
623 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
624 : {
625 0 : ENSURE(m->Framebuffer);
626 0 : deviceCommandContext->BeginFramebufferPass(m->Framebuffer.get());
627 :
628 0 : m->SavedViewCamera = g_Renderer.GetSceneRenderer().GetViewCamera();
629 0 : }
630 :
631 0 : void ShadowMap::PrepareCamera(
632 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext, const int cascade)
633 : {
634 0 : m->CalculateShadowMatrices(cascade);
635 :
636 0 : Renderer::Backend::IDeviceCommandContext::Rect viewportRect{};
637 0 : viewportRect.width = m->EffectiveWidth;
638 0 : viewportRect.height = m->EffectiveHeight;
639 0 : deviceCommandContext->SetViewports(1, &viewportRect);
640 :
641 0 : CCamera camera = m->SavedViewCamera;
642 0 : camera.SetProjection(m->Cascades[cascade].LightProjection);
643 0 : camera.GetOrientation() = m->InvLightTransform;
644 0 : camera.UpdateFrustum();
645 0 : g_Renderer.GetSceneRenderer().SetViewCamera(camera);
646 :
647 0 : const SViewPort& cascadeViewPort = m->Cascades[cascade].ViewPort;
648 0 : Renderer::Backend::IDeviceCommandContext::Rect scissorRect;
649 0 : scissorRect.x = cascadeViewPort.m_X;
650 0 : scissorRect.y = cascadeViewPort.m_Y;
651 0 : scissorRect.width = cascadeViewPort.m_Width;
652 0 : scissorRect.height = cascadeViewPort.m_Height;
653 0 : deviceCommandContext->SetScissors(1, &scissorRect);
654 0 : }
655 :
656 0 : void ShadowMap::EndRender(
657 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
658 : {
659 0 : deviceCommandContext->SetScissors(0, nullptr);
660 :
661 0 : deviceCommandContext->EndFramebufferPass();
662 :
663 0 : g_Renderer.GetSceneRenderer().SetViewCamera(m->SavedViewCamera);
664 0 : }
665 :
666 0 : void ShadowMap::BindTo(
667 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
668 : Renderer::Backend::IShaderProgram* shader) const
669 : {
670 0 : const int32_t shadowTexBindingSlot = shader->GetBindingSlot(str_shadowTex);
671 0 : if (shadowTexBindingSlot < 0 || !m->Texture)
672 0 : return;
673 :
674 0 : deviceCommandContext->SetTexture(shadowTexBindingSlot, m->Texture.get());
675 0 : deviceCommandContext->SetUniform(
676 0 : shader->GetBindingSlot(str_shadowScale), m->Width, m->Height, 1.0f / m->Width, 1.0f / m->Height);
677 0 : const CVector3D cameraForward = g_Renderer.GetSceneRenderer().GetCullCamera().GetOrientation().GetIn();
678 0 : deviceCommandContext->SetUniform(
679 0 : shader->GetBindingSlot(str_cameraForward), cameraForward.X, cameraForward.Y, cameraForward.Z,
680 0 : cameraForward.Dot(g_Renderer.GetSceneRenderer().GetCullCamera().GetOrientation().GetTranslation()));
681 :
682 0 : if (GetCascadeCount() == 1)
683 : {
684 0 : deviceCommandContext->SetUniform(
685 0 : shader->GetBindingSlot(str_shadowTransform),
686 0 : m->Cascades[0].TextureMatrix.AsFloatArray());
687 0 : deviceCommandContext->SetUniform(
688 0 : shader->GetBindingSlot(str_shadowDistance), m->Cascades[0].Distance);
689 : }
690 : else
691 : {
692 0 : std::vector<float> shadowDistances;
693 0 : std::vector<CMatrix3D> shadowTransforms;
694 0 : for (const ShadowMapInternals::Cascade& cascade : m->Cascades)
695 : {
696 0 : shadowDistances.emplace_back(cascade.Distance);
697 0 : shadowTransforms.emplace_back(cascade.TextureMatrix);
698 : }
699 0 : deviceCommandContext->SetUniform(
700 0 : shader->GetBindingSlot(str_shadowTransform),
701 : std::span<const float>(
702 0 : shadowTransforms[0]._data,
703 0 : shadowTransforms[0].AsFloatArray().size() * GetCascadeCount()));
704 0 : deviceCommandContext->SetUniform(
705 0 : shader->GetBindingSlot(str_shadowDistance),
706 : std::span<const float>(shadowDistances.data(), shadowDistances.size()));
707 0 : }
708 : }
709 :
710 0 : void ShadowMap::RenderDebugBounds(Renderer::Backend::IDeviceCommandContext& deviceCommandContext)
711 : {
712 : // Render various shadow bounds:
713 : // Yellow = bounds of objects in view frustum that receive shadows
714 : // Red = culling frustum used to find potential shadow casters
715 : // Blue = frustum used for rendering the shadow map
716 :
717 0 : const CMatrix3D transform = g_Renderer.GetSceneRenderer().GetViewCamera().GetViewProjection() * m->InvLightTransform;
718 :
719 0 : g_Renderer.GetDebugRenderer().DrawBoundingBox(
720 : deviceCommandContext,
721 0 : m->ShadowReceiverBound, CColor(1.0f, 1.0f, 0.0f, 1.0f), transform, true);
722 :
723 0 : for (int cascade = 0; cascade < GetCascadeCount(); ++cascade)
724 : {
725 0 : g_Renderer.GetDebugRenderer().DrawBoundingBox(
726 : deviceCommandContext,
727 0 : m->Cascades[cascade].ShadowRenderBound, CColor(0.0f, 0.0f, 1.0f, 0.10f), transform);
728 0 : g_Renderer.GetDebugRenderer().DrawBoundingBox(
729 : deviceCommandContext,
730 0 : m->Cascades[cascade].ShadowRenderBound, CColor(0.0f, 0.0f, 1.0f, 0.5f), transform, true);
731 :
732 0 : const CFrustum frustum = GetShadowCasterCullFrustum(cascade);
733 : // We don't have a function to create a brush directly from a frustum, so use
734 : // the ugly approach of creating a large cube and then intersecting with the frustum
735 0 : const CBoundingBoxAligned dummy(CVector3D(-1e4, -1e4, -1e4), CVector3D(1e4, 1e4, 1e4));
736 0 : CBrush brush(dummy);
737 0 : CBrush frustumBrush;
738 0 : brush.Intersect(frustum, frustumBrush);
739 :
740 0 : g_Renderer.GetDebugRenderer().DrawBrush(deviceCommandContext, frustumBrush, CColor(1.0f, 0.0f, 0.0f, 0.1f));
741 0 : g_Renderer.GetDebugRenderer().DrawBrush(deviceCommandContext, frustumBrush, CColor(1.0f, 0.0f, 0.0f, 0.1f), true);
742 0 : }
743 0 : }
744 :
745 0 : int ShadowMap::GetCascadeCount() const
746 : {
747 : #if CONFIG2_GLES
748 : return 1;
749 : #else
750 0 : return m->ShadowsCoverMap ? 1 : m->CascadeCount;
751 : #endif
752 : }
|