ShadowMapping.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. // Copyright (C) 2009-2023, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Renderer/ShadowMapping.h>
  6. #include <AnKi/Renderer/Renderer.h>
  7. #include <AnKi/Renderer/GBuffer.h>
  8. #include <AnKi/Renderer/PrimaryNonRenderableVisibility.h>
  9. #include <AnKi/Core/App.h>
  10. #include <AnKi/Core/StatsSet.h>
  11. #include <AnKi/Core/GpuMemory/GpuVisibleTransientMemoryPool.h>
  12. #include <AnKi/Util/Tracer.h>
  13. #include <AnKi/Scene/Components/LightComponent.h>
  14. #include <AnKi/Scene/Components/CameraComponent.h>
  15. #include <AnKi/Scene/RenderStateBucket.h>
  16. namespace anki {
  17. static NumericCVar<U32> g_shadowMappingTileResolutionCVar(CVarSubsystem::kRenderer, "ShadowMappingTileResolution", (ANKI_PLATFORM_MOBILE) ? 128 : 256,
  18. 16, 2048, "Shadowmapping tile resolution");
  19. static NumericCVar<U32> g_shadowMappingTileCountPerRowOrColumnCVar(CVarSubsystem::kRenderer, "ShadowMappingTileCountPerRowOrColumn", 32, 1, 256,
  20. "Shadowmapping atlas will have this number squared number of tiles");
  21. NumericCVar<U32> g_shadowMappingPcfCVar(CVarSubsystem::kRenderer, "ShadowMappingPcf", (ANKI_PLATFORM_MOBILE) ? 0 : 1, 0, 1,
  22. "Shadow PCF (CVarSubsystem::kRenderer, 0: off, 1: on)");
  23. static StatCounter g_tilesAllocatedStatVar(StatCategory::kRenderer, "Shadow tiles (re)allocated", StatFlag::kMainThreadUpdates);
  24. class LightHash
  25. {
  26. public:
  27. class Unpacked
  28. {
  29. public:
  30. U64 m_uuid : 31;
  31. U64 m_componentIndex : 30;
  32. U64 m_faceIdx : 3;
  33. };
  34. union
  35. {
  36. Unpacked m_unpacked;
  37. U64 m_packed;
  38. };
  39. };
  40. static U64 encodeTileHash(U32 lightUuid, U32 componentIndex, U32 faceIdx)
  41. {
  42. ANKI_ASSERT(faceIdx < 6);
  43. LightHash c;
  44. c.m_unpacked.m_uuid = lightUuid;
  45. c.m_unpacked.m_componentIndex = componentIndex;
  46. c.m_unpacked.m_faceIdx = faceIdx;
  47. return c.m_packed;
  48. }
  49. static LightHash decodeTileHash(U64 hash)
  50. {
  51. LightHash c;
  52. c.m_packed = hash;
  53. return c;
  54. }
  55. Error ShadowMapping::init()
  56. {
  57. const Error err = initInternal();
  58. if(err)
  59. {
  60. ANKI_R_LOGE("Failed to initialize shadowmapping");
  61. }
  62. return err;
  63. }
  64. Error ShadowMapping::initInternal()
  65. {
  66. // Init RT
  67. {
  68. m_tileResolution = g_shadowMappingTileResolutionCVar.get();
  69. m_tileCountBothAxis = g_shadowMappingTileCountPerRowOrColumnCVar.get();
  70. ANKI_R_LOGV("Initializing shadowmapping. Atlas resolution %ux%u", m_tileResolution * m_tileCountBothAxis,
  71. m_tileResolution * m_tileCountBothAxis);
  72. // RT
  73. const TextureUsageBit usage = TextureUsageBit::kSampledFragment | TextureUsageBit::kSampledCompute | TextureUsageBit::kAllFramebuffer;
  74. TextureInitInfo texinit = getRenderer().create2DRenderTargetInitInfo(
  75. m_tileResolution * m_tileCountBothAxis, m_tileResolution * m_tileCountBothAxis, Format::kD16_Unorm, usage, "ShadowAtlas");
  76. ClearValue clearVal;
  77. clearVal.m_colorf[0] = 1.0f;
  78. m_atlasTex = getRenderer().createAndClearRenderTarget(texinit, TextureUsageBit::kSampledFragment, clearVal);
  79. }
  80. // Tiles
  81. m_tileAlloc.init(m_tileCountBothAxis, m_tileCountBothAxis, kTileAllocHierarchyCount, true);
  82. ANKI_CHECK(loadShaderProgram("ShaderBinaries/ShadowMappingClearDepth.ankiprogbin", m_clearDepthProg, m_clearDepthGrProg));
  83. ANKI_CHECK(loadShaderProgram("ShaderBinaries/ShadowMappingVetVisibility.ankiprogbin", m_vetVisibilityProg, m_vetVisibilityGrProg));
  84. for(U32 i = 0; i < kMaxShadowCascades; ++i)
  85. {
  86. RendererString name;
  87. name.sprintf("DirLight HZB #%d", i);
  88. const U32 cascadeResolution = (m_tileResolution * (1 << (kTileAllocHierarchyCount - 1))) >> chooseDirectionalLightShadowCascadeDetail(i);
  89. UVec2 size(min(cascadeResolution, 1024u));
  90. size /= 2;
  91. m_cascadeHzbRtDescrs[i] = getRenderer().create2DRenderTargetDescription(size.x(), size.y(), Format::kR32_Sfloat, name);
  92. m_cascadeHzbRtDescrs[i].m_mipmapCount = U8(computeMaxMipmapCount2d(m_cascadeHzbRtDescrs[i].m_width, m_cascadeHzbRtDescrs[i].m_height));
  93. m_cascadeHzbRtDescrs[i].bake();
  94. }
  95. return Error::kNone;
  96. }
  97. Mat4 ShadowMapping::createSpotLightTextureMatrix(const UVec4& viewport) const
  98. {
  99. const F32 atlasSize = F32(m_tileResolution * m_tileCountBothAxis);
  100. #if ANKI_COMPILER_GCC_COMPATIBLE
  101. # pragma GCC diagnostic push
  102. # pragma GCC diagnostic ignored "-Wpedantic" // Because GCC and clang throw an incorrect warning
  103. #endif
  104. const Vec2 uv(F32(viewport[0]) / atlasSize, F32(viewport[1]) / atlasSize);
  105. #if ANKI_COMPILER_GCC_COMPATIBLE
  106. # pragma GCC diagnostic pop
  107. #endif
  108. ANKI_ASSERT(uv >= Vec2(0.0f) && uv <= Vec2(1.0f));
  109. ANKI_ASSERT(viewport[2] == viewport[3]);
  110. const F32 sizeTextureSpace = F32(viewport[2]) / atlasSize;
  111. const Mat4 biasMat4(0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);
  112. return Mat4(sizeTextureSpace, 0.0f, 0.0f, uv.x(), 0.0f, sizeTextureSpace, 0.0f, uv.y(), 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f)
  113. * biasMat4;
  114. }
  115. void ShadowMapping::populateRenderGraph(RenderingContext& ctx)
  116. {
  117. ANKI_TRACE_SCOPED_EVENT(ShadowMapping);
  118. RenderGraphDescription& rgraph = ctx.m_renderGraphDescr;
  119. // Import
  120. if(m_rtImportedOnce) [[likely]]
  121. {
  122. m_runCtx.m_rt = rgraph.importRenderTarget(m_atlasTex.get());
  123. }
  124. else
  125. {
  126. m_runCtx.m_rt = rgraph.importRenderTarget(m_atlasTex.get(), TextureUsageBit::kSampledFragment);
  127. m_rtImportedOnce = true;
  128. }
  129. // First process the lights
  130. processLights(ctx);
  131. }
  132. void ShadowMapping::chooseDetail(const Vec3& cameraOrigin, const LightComponent& lightc, Vec2 lodDistances, U32& tileAllocatorHierarchy) const
  133. {
  134. if(lightc.getLightComponentType() == LightComponentType::kPoint)
  135. {
  136. const F32 distFromTheCamera = (cameraOrigin - lightc.getWorldPosition()).getLength() - lightc.getRadius();
  137. if(distFromTheCamera < lodDistances[0])
  138. {
  139. tileAllocatorHierarchy = kPointLightMaxTileAllocHierarchy;
  140. }
  141. else
  142. {
  143. tileAllocatorHierarchy = max(kPointLightMaxTileAllocHierarchy, 1u) - 1;
  144. }
  145. }
  146. else
  147. {
  148. ANKI_ASSERT(lightc.getLightComponentType() == LightComponentType::kSpot);
  149. // Get some data
  150. const Vec3 coneOrigin = lightc.getWorldPosition();
  151. const Vec3 coneDir = lightc.getDirection();
  152. const F32 coneAngle = lightc.getOuterAngle();
  153. // Compute the distance from the camera to the light cone
  154. const Vec3 V = cameraOrigin - coneOrigin;
  155. const F32 VlenSq = V.dot(V);
  156. const F32 V1len = V.dot(coneDir);
  157. const F32 distFromTheCamera = cos(coneAngle) * sqrt(VlenSq - V1len * V1len) - V1len * sin(coneAngle);
  158. if(distFromTheCamera < lodDistances[0])
  159. {
  160. tileAllocatorHierarchy = kSpotLightMaxTileAllocHierarchy;
  161. }
  162. else if(distFromTheCamera < lodDistances[1])
  163. {
  164. tileAllocatorHierarchy = max(kSpotLightMaxTileAllocHierarchy, 1u) - 1;
  165. }
  166. else
  167. {
  168. tileAllocatorHierarchy = max(kSpotLightMaxTileAllocHierarchy, 2u) - 2;
  169. }
  170. }
  171. }
  172. TileAllocatorResult2 ShadowMapping::allocateAtlasTiles(U32 lightUuid, U32 componentIndex, U32 faceCount, const U32* hierarchies,
  173. UVec4* atlasTileViewports)
  174. {
  175. ANKI_ASSERT(lightUuid > 0);
  176. ANKI_ASSERT(faceCount > 0);
  177. ANKI_ASSERT(hierarchies);
  178. TileAllocatorResult2 goodResult = TileAllocatorResult2::kAllocationSucceded | TileAllocatorResult2::kTileCached;
  179. for(U32 i = 0; i < faceCount; ++i)
  180. {
  181. TileAllocator::ArrayOfLightUuids kickedOutLights(&getRenderer().getFrameMemoryPool());
  182. Array<U32, 4> tileViewport;
  183. const TileAllocatorResult2 result = m_tileAlloc.allocate(
  184. GlobalFrameIndex::getSingleton().m_value, encodeTileHash(lightUuid, componentIndex, i), hierarchies[i], tileViewport, kickedOutLights);
  185. for(U64 kickedLightHash : kickedOutLights)
  186. {
  187. const LightHash hash = decodeTileHash(kickedLightHash);
  188. const Bool found = SceneGraph::getSingleton().getComponentArrays().getLights().indexExists(hash.m_unpacked.m_componentIndex);
  189. if(found)
  190. {
  191. LightComponent& lightc = SceneGraph::getSingleton().getComponentArrays().getLights()[hash.m_unpacked.m_componentIndex];
  192. if(lightc.getUuid() == hash.m_unpacked.m_uuid)
  193. {
  194. lightc.setShadowAtlasUvViewports({});
  195. }
  196. }
  197. }
  198. if(!!(result & TileAllocatorResult2::kAllocationFailed))
  199. {
  200. ANKI_R_LOGW("There is not enough space in the shadow atlas for more shadow maps. Increase the %s or decrease the scene's shadow casters",
  201. g_shadowMappingTileCountPerRowOrColumnCVar.getFullName().cstr());
  202. // Invalidate cache entries for what we already allocated
  203. for(U32 j = 0; j < i; ++j)
  204. {
  205. m_tileAlloc.invalidateCache(encodeTileHash(lightUuid, componentIndex, j));
  206. }
  207. return TileAllocatorResult2::kAllocationFailed;
  208. }
  209. if(!(result & TileAllocatorResult2::kTileCached))
  210. {
  211. g_tilesAllocatedStatVar.increment(1);
  212. }
  213. goodResult &= result;
  214. // Set viewport
  215. const UVec4 viewport = UVec4(tileViewport) * m_tileResolution;
  216. atlasTileViewports[i] = viewport;
  217. }
  218. return goodResult;
  219. }
  220. void ShadowMapping::processLights(RenderingContext& ctx)
  221. {
  222. // First allocate tiles for the dir light and then build passes for points and spot lights. Then passes for the dir light. The dir light has many
  223. // passes and it will push the other types of lights further into the future. So do those first.
  224. // Vars
  225. const Vec3 cameraOrigin = ctx.m_matrices.m_cameraTransform.getTranslationPart().xyz();
  226. RenderGraphDescription& rgraph = ctx.m_renderGraphDescr;
  227. const CameraComponent& mainCam = SceneGraph::getSingleton().getActiveCameraNode().getFirstComponentOfType<CameraComponent>();
  228. // Allocate tiles for the dir light first but don't build any passes
  229. const LightComponent* dirLight = SceneGraph::getSingleton().getDirectionalLight();
  230. if(dirLight && (!dirLight->getShadowEnabled() || !g_shadowCascadeCountCVar.get()))
  231. {
  232. dirLight = nullptr; // Skip dir light
  233. }
  234. Array<UVec4, kMaxShadowCascades> dirLightAtlasViewports;
  235. if(dirLight)
  236. {
  237. const U32 cascadeCount = g_shadowCascadeCountCVar.get();
  238. Array<U32, kMaxShadowCascades> hierarchies;
  239. for(U32 cascade = 0; cascade < cascadeCount; ++cascade)
  240. {
  241. // Change the quality per cascade
  242. hierarchies[cascade] = kTileAllocHierarchyCount - 1 - chooseDirectionalLightShadowCascadeDetail(cascade);
  243. }
  244. [[maybe_unused]] const TileAllocatorResult2 res = allocateAtlasTiles(kMaxU32, 0, cascadeCount, &hierarchies[0], &dirLightAtlasViewports[0]);
  245. ANKI_ASSERT(!!(res & TileAllocatorResult2::kAllocationSucceded) && "Dir light should never fail");
  246. }
  247. // Process the point lights first
  248. U32 lightIdx = 0;
  249. WeakArray<LightComponent*> lights = getRenderer().getPrimaryNonRenderableVisibility().getInterestingVisibleComponents().m_shadowLights;
  250. for(LightComponent* lightc : lights)
  251. {
  252. if(lightc->getLightComponentType() != LightComponentType::kPoint || !lightc->getShadowEnabled())
  253. {
  254. continue;
  255. }
  256. // Prepare data to allocate tiles and allocate
  257. U32 hierarchy;
  258. chooseDetail(cameraOrigin, *lightc, {g_lod0MaxDistanceCVar.get(), g_lod1MaxDistanceCVar.get()}, hierarchy);
  259. Array<U32, 6> hierarchies;
  260. hierarchies.fill(hierarchy);
  261. Array<UVec4, 6> atlasViewports;
  262. const TileAllocatorResult2 result = allocateAtlasTiles(lightc->getUuid(), lightc->getArrayIndex(), 6, &hierarchies[0], &atlasViewports[0]);
  263. if(!!(result & TileAllocatorResult2::kAllocationSucceded))
  264. {
  265. // All good, update the light
  266. // Remove a few texels to avoid bilinear filtering bleeding
  267. F32 texelsBorder;
  268. if(g_shadowMappingPcfCVar.get())
  269. {
  270. texelsBorder = 2.0f; // 2 texels
  271. }
  272. else
  273. {
  274. texelsBorder = 0.5f; // Half texel
  275. }
  276. const F32 atlasResolution = F32(m_tileResolution * m_tileCountBothAxis);
  277. F32 superTileSize = F32(atlasViewports[0][2]); // Should be the same for all tiles and faces
  278. superTileSize -= texelsBorder * 2.0f; // Remove from both sides
  279. Array<Vec4, 6> uvViewports;
  280. for(U face = 0; face < 6; ++face)
  281. {
  282. // Add a half texel to the viewport's start to avoid bilinear filtering bleeding
  283. const Vec2 uvViewportXY = (Vec2(atlasViewports[face].xy()) + texelsBorder) / atlasResolution;
  284. uvViewports[face] = Vec4(uvViewportXY, Vec2(superTileSize / atlasResolution));
  285. }
  286. if(!(result & TileAllocatorResult2::kTileCached))
  287. {
  288. lightc->setShadowAtlasUvViewports(uvViewports);
  289. }
  290. // Vis testing
  291. const Array<F32, kMaxLodCount - 1> lodDistances = {g_lod0MaxDistanceCVar.get(), g_lod1MaxDistanceCVar.get()};
  292. DistanceGpuVisibilityInput visIn;
  293. visIn.m_passesName = generateTempPassName("Shadows point light", lightIdx);
  294. visIn.m_technique = RenderingTechnique::kDepth;
  295. visIn.m_lodReferencePoint = ctx.m_matrices.m_cameraTransform.getTranslationPart().xyz();
  296. visIn.m_lodDistances = lodDistances;
  297. visIn.m_rgraph = &rgraph;
  298. visIn.m_pointOfTest = lightc->getWorldPosition();
  299. visIn.m_testRadius = lightc->getRadius();
  300. visIn.m_hashVisibles = true;
  301. GpuVisibilityOutput visOut;
  302. getRenderer().getGpuVisibility().populateRenderGraph(visIn, visOut);
  303. // Vet visibility
  304. const Bool renderAllways = !(result & TileAllocatorResult2::kTileCached);
  305. BufferView clearTileIndirectArgs;
  306. if(!renderAllways)
  307. {
  308. clearTileIndirectArgs = createVetVisibilityPass(generateTempPassName("Shadows: Vet point light", lightIdx), *lightc, visOut, rgraph);
  309. }
  310. // Additional visibility
  311. GpuMeshletVisibilityOutput meshletVisOut;
  312. if(getRenderer().runSoftwareMeshletRendering())
  313. {
  314. PassthroughGpuMeshletVisibilityInput meshIn;
  315. meshIn.m_passesName = generateTempPassName("Shadows point light", lightIdx);
  316. meshIn.m_technique = RenderingTechnique::kDepth;
  317. meshIn.m_rgraph = &rgraph;
  318. meshIn.fillBuffers(visOut);
  319. getRenderer().getGpuVisibility().populateRenderGraph(meshIn, meshletVisOut);
  320. }
  321. // Draw
  322. Array<ShadowSubpassInfo, 6> subpasses;
  323. for(U32 face = 0; face < 6; ++face)
  324. {
  325. Frustum frustum;
  326. frustum.init(FrustumType::kPerspective);
  327. frustum.setPerspective(kClusterObjectFrustumNearPlane, lightc->getRadius(), kPi / 2.0f, kPi / 2.0f);
  328. frustum.setWorldTransform(
  329. Transform(lightc->getWorldPosition().xyz0(), Frustum::getOmnidirectionalFrustumRotations()[face], Vec4(1.0f, 1.0f, 1.0f, 0.0f)));
  330. frustum.update();
  331. subpasses[face].m_clearTileIndirectArgs = clearTileIndirectArgs;
  332. subpasses[face].m_viewMat = frustum.getViewMatrix();
  333. subpasses[face].m_viewport = atlasViewports[face];
  334. subpasses[face].m_viewProjMat = frustum.getViewProjectionMatrix();
  335. }
  336. createDrawShadowsPass(subpasses, visOut, meshletVisOut, generateTempPassName("Shadows: Point light", lightIdx), rgraph);
  337. }
  338. else
  339. {
  340. // Can't be a caster from now on
  341. lightc->setShadowAtlasUvViewports({});
  342. }
  343. ++lightIdx;
  344. }
  345. // Process the spot lights 2nd
  346. lightIdx = 0;
  347. for(LightComponent* lightc : lights)
  348. {
  349. if(lightc->getLightComponentType() != LightComponentType::kSpot || !lightc->getShadowEnabled())
  350. {
  351. continue;
  352. }
  353. // Allocate tile
  354. U32 hierarchy;
  355. chooseDetail(cameraOrigin, *lightc, {g_lod0MaxDistanceCVar.get(), g_lod1MaxDistanceCVar.get()}, hierarchy);
  356. UVec4 atlasViewport;
  357. const TileAllocatorResult2 result = allocateAtlasTiles(lightc->getUuid(), lightc->getArrayIndex(), 1, &hierarchy, &atlasViewport);
  358. if(!!(result & TileAllocatorResult2::kAllocationSucceded))
  359. {
  360. // All good, update the light
  361. if(!(result & TileAllocatorResult2::kTileCached))
  362. {
  363. const F32 atlasResolution = F32(m_tileResolution * m_tileCountBothAxis);
  364. const Vec4 uvViewport = Vec4(atlasViewport) / atlasResolution;
  365. lightc->setShadowAtlasUvViewports({&uvViewport, 1});
  366. }
  367. // Vis testing
  368. const Array<F32, kMaxLodCount - 1> lodDistances = {g_lod0MaxDistanceCVar.get(), g_lod1MaxDistanceCVar.get()};
  369. FrustumGpuVisibilityInput visIn;
  370. visIn.m_passesName = generateTempPassName("Shadows spot light", lightIdx);
  371. visIn.m_technique = RenderingTechnique::kDepth;
  372. visIn.m_lodReferencePoint = cameraOrigin;
  373. visIn.m_lodDistances = lodDistances;
  374. visIn.m_rgraph = &rgraph;
  375. visIn.m_viewProjectionMatrix = lightc->getSpotLightViewProjectionMatrix();
  376. visIn.m_hashVisibles = true;
  377. visIn.m_viewportSize = atlasViewport.zw();
  378. GpuVisibilityOutput visOut;
  379. getRenderer().getGpuVisibility().populateRenderGraph(visIn, visOut);
  380. // Vet visibility
  381. const Bool renderAllways = !(result & TileAllocatorResult2::kTileCached);
  382. BufferView clearTileIndirectArgs;
  383. if(!renderAllways)
  384. {
  385. clearTileIndirectArgs = createVetVisibilityPass(generateTempPassName("Shadows: Vet spot light", lightIdx), *lightc, visOut, rgraph);
  386. }
  387. // Additional visibility
  388. GpuMeshletVisibilityOutput meshletVisOut;
  389. if(getRenderer().runSoftwareMeshletRendering())
  390. {
  391. GpuMeshletVisibilityInput meshIn;
  392. meshIn.m_passesName = generateTempPassName("Shadows spot light", lightIdx);
  393. meshIn.m_technique = RenderingTechnique::kDepth;
  394. meshIn.m_viewProjectionMatrix = lightc->getSpotLightViewProjectionMatrix();
  395. meshIn.m_cameraTransform = lightc->getSpotLightViewMatrix().getInverseTransformation();
  396. meshIn.m_viewportSize = atlasViewport.zw();
  397. meshIn.m_rgraph = &rgraph;
  398. meshIn.fillBuffers(visOut);
  399. getRenderer().getGpuVisibility().populateRenderGraph(meshIn, meshletVisOut);
  400. }
  401. // Add draw pass
  402. createDrawShadowsPass(atlasViewport, lightc->getSpotLightViewProjectionMatrix(), lightc->getSpotLightViewMatrix(), visOut, meshletVisOut,
  403. clearTileIndirectArgs, {}, generateTempPassName("Shadows: Spot light", lightIdx), rgraph);
  404. }
  405. else
  406. {
  407. // Doesn't have renderables or the allocation failed, won't be a shadow caster
  408. lightc->setShadowAtlasUvViewports({});
  409. }
  410. }
  411. // Process the directional light last
  412. if(dirLight)
  413. {
  414. const U32 cascadeCount = g_shadowCascadeCountCVar.get();
  415. // Compute the view projection matrices
  416. Array<F32, kMaxShadowCascades> cascadeDistances;
  417. static_assert(kMaxShadowCascades == 4);
  418. cascadeDistances[0] = g_shadowCascade0DistanceCVar.get();
  419. cascadeDistances[1] = g_shadowCascade1DistanceCVar.get();
  420. cascadeDistances[2] = g_shadowCascade2DistanceCVar.get();
  421. cascadeDistances[3] = g_shadowCascade3DistanceCVar.get();
  422. Array<Mat4, kMaxShadowCascades> cascadeViewProjMats;
  423. Array<Mat3x4, kMaxShadowCascades> cascadeViewMats;
  424. Array<Mat4, kMaxShadowCascades> cascadeProjMats;
  425. dirLight->computeCascadeFrustums(mainCam.getFrustum(), {&cascadeDistances[0], cascadeCount}, {&cascadeProjMats[0], cascadeCount},
  426. {&cascadeViewMats[0], cascadeCount});
  427. for(U cascade = 0; cascade < cascadeCount; ++cascade)
  428. {
  429. cascadeViewProjMats[cascade] = cascadeProjMats[cascade] * Mat4(cascadeViewMats[cascade], Vec4(0.0f, 0.0f, 0.0f, 1.0f));
  430. }
  431. // HZB generation
  432. HzbDirectionalLightInput hzbGenIn;
  433. hzbGenIn.m_cascadeCount = cascadeCount;
  434. hzbGenIn.m_depthBufferRt = getRenderer().getGBuffer().getDepthRt();
  435. hzbGenIn.m_depthBufferRtSize = getRenderer().getInternalResolution();
  436. hzbGenIn.m_cameraProjectionMatrix = ctx.m_matrices.m_projection;
  437. hzbGenIn.m_cameraInverseViewProjectionMatrix = ctx.m_matrices.m_invertedViewProjection;
  438. for(U cascade = 0; cascade < cascadeCount; ++cascade)
  439. {
  440. hzbGenIn.m_cascades[cascade].m_hzbRt = rgraph.newRenderTarget(m_cascadeHzbRtDescrs[cascade]);
  441. hzbGenIn.m_cascades[cascade].m_hzbRtSize = UVec2(m_cascadeHzbRtDescrs[cascade].m_width, m_cascadeHzbRtDescrs[cascade].m_height);
  442. hzbGenIn.m_cascades[cascade].m_viewMatrix = cascadeViewMats[cascade];
  443. hzbGenIn.m_cascades[cascade].m_projectionMatrix = cascadeProjMats[cascade];
  444. hzbGenIn.m_cascades[cascade].m_cascadeMaxDistance = cascadeDistances[cascade];
  445. }
  446. getRenderer().getHzbGenerator().populateRenderGraphDirectionalLight(hzbGenIn, rgraph);
  447. // Create passes per cascade
  448. for(U32 cascade = 0; cascade < cascadeCount; ++cascade)
  449. {
  450. // Vis testing
  451. const Array<F32, kMaxLodCount - 1> lodDistances = {g_lod0MaxDistanceCVar.get(), g_lod1MaxDistanceCVar.get()};
  452. FrustumGpuVisibilityInput visIn;
  453. visIn.m_passesName = generateTempPassName("Shadows: Dir light cascade", cascade);
  454. visIn.m_technique = RenderingTechnique::kDepth;
  455. visIn.m_viewProjectionMatrix = cascadeViewProjMats[cascade];
  456. visIn.m_lodReferencePoint = ctx.m_matrices.m_cameraTransform.getTranslationPart().xyz();
  457. visIn.m_lodDistances = lodDistances;
  458. visIn.m_hzbRt = &hzbGenIn.m_cascades[cascade].m_hzbRt;
  459. visIn.m_rgraph = &rgraph;
  460. visIn.m_viewportSize = dirLightAtlasViewports[cascade].zw();
  461. GpuVisibilityOutput visOut;
  462. getRenderer().getGpuVisibility().populateRenderGraph(visIn, visOut);
  463. // Additional visibility
  464. GpuMeshletVisibilityOutput meshletVisOut;
  465. if(getRenderer().runSoftwareMeshletRendering())
  466. {
  467. GpuMeshletVisibilityInput meshIn;
  468. meshIn.m_passesName = generateTempPassName("Shadows: Dir light cascade", lightIdx);
  469. meshIn.m_technique = RenderingTechnique::kDepth;
  470. meshIn.m_viewProjectionMatrix = cascadeViewProjMats[cascade];
  471. meshIn.m_cameraTransform = cascadeViewMats[cascade].getInverseTransformation();
  472. meshIn.m_viewportSize = dirLightAtlasViewports[cascade].zw();
  473. meshIn.m_rgraph = &rgraph;
  474. meshIn.fillBuffers(visOut);
  475. getRenderer().getGpuVisibility().populateRenderGraph(meshIn, meshletVisOut);
  476. }
  477. // Draw
  478. createDrawShadowsPass(dirLightAtlasViewports[cascade], cascadeViewProjMats[cascade], cascadeViewMats[cascade], visOut, meshletVisOut, {},
  479. hzbGenIn.m_cascades[cascade].m_hzbRt, generateTempPassName("Shadows: Dir light cascade", cascade), rgraph);
  480. // Update the texture matrix to point to the correct region in the atlas
  481. ctx.m_dirLightTextureMatrices[cascade] = createSpotLightTextureMatrix(dirLightAtlasViewports[cascade]) * cascadeViewProjMats[cascade];
  482. }
  483. }
  484. }
  485. BufferView ShadowMapping::createVetVisibilityPass(CString passName, const LightComponent& lightc, const GpuVisibilityOutput& visOut,
  486. RenderGraphDescription& rgraph) const
  487. {
  488. BufferView clearTileIndirectArgs;
  489. clearTileIndirectArgs = GpuVisibleTransientMemoryPool::getSingleton().allocate(sizeof(DrawIndirectArgs));
  490. ComputeRenderPassDescription& pass = rgraph.newComputeRenderPass(passName);
  491. // The shader doesn't actually write to the handle but have it as a write dependency for the drawer to correctly wait for this pass
  492. pass.newBufferDependency(visOut.m_dependency, BufferUsageBit::kStorageComputeWrite);
  493. pass.setWork([this, &lightc, hashBuff = visOut.m_visiblesHashBuffer, mdiBuff = visOut.m_legacy.m_mdiDrawCountsBuffer, clearTileIndirectArgs,
  494. taskShadersIndirectArgs = visOut.m_mesh.m_taskShaderIndirectArgsBuffer](RenderPassWorkContext& rpass) {
  495. CommandBuffer& cmdb = *rpass.m_commandBuffer;
  496. cmdb.bindShaderProgram(m_vetVisibilityGrProg.get());
  497. const UVec4 lightIndex(lightc.getGpuSceneLightAllocation().getIndex());
  498. cmdb.setPushConstants(&lightIndex, sizeof(lightIndex));
  499. cmdb.bindStorageBuffer(0, 0, hashBuff);
  500. cmdb.bindStorageBuffer(0, 1, mdiBuff);
  501. cmdb.bindStorageBuffer(0, 2, GpuSceneArrays::Light::getSingleton().getBufferView());
  502. cmdb.bindStorageBuffer(0, 3, GpuSceneArrays::LightVisibleRenderablesHash::getSingleton().getBufferView());
  503. cmdb.bindStorageBuffer(0, 4, clearTileIndirectArgs);
  504. cmdb.bindStorageBuffer(0, 5, taskShadersIndirectArgs);
  505. ANKI_ASSERT(RenderStateBucketContainer::getSingleton().getBucketCount(RenderingTechnique::kDepth) <= 64 && "TODO");
  506. cmdb.dispatchCompute(1, 1, 1);
  507. });
  508. return clearTileIndirectArgs;
  509. }
  510. void ShadowMapping::createDrawShadowsPass(const UVec4& viewport, const Mat4& viewProjMat, const Mat3x4& viewMat, const GpuVisibilityOutput& visOut,
  511. const GpuMeshletVisibilityOutput& meshletVisOut, const BufferView& clearTileIndirectArgs,
  512. const RenderTargetHandle hzbRt, CString passName, RenderGraphDescription& rgraph)
  513. {
  514. ShadowSubpassInfo spass;
  515. spass.m_clearTileIndirectArgs = clearTileIndirectArgs;
  516. spass.m_hzbRt = hzbRt;
  517. spass.m_viewMat = viewMat;
  518. spass.m_viewport = viewport;
  519. spass.m_viewProjMat = viewProjMat;
  520. createDrawShadowsPass({&spass, 1}, visOut, meshletVisOut, passName, rgraph);
  521. }
  522. void ShadowMapping::createDrawShadowsPass(ConstWeakArray<ShadowSubpassInfo> subpasses_, const GpuVisibilityOutput& visOut,
  523. const GpuMeshletVisibilityOutput& meshletVisOut, CString passName, RenderGraphDescription& rgraph)
  524. {
  525. WeakArray<ShadowSubpassInfo> subpasses;
  526. newArray<ShadowSubpassInfo>(getRenderer().getFrameMemoryPool(), subpasses_.getSize(), subpasses);
  527. memcpy(subpasses.getBegin(), subpasses_.getBegin(), subpasses.getSizeInBytes());
  528. // Compute the whole viewport
  529. UVec4 viewport;
  530. if(subpasses.getSize() == 1)
  531. {
  532. viewport = subpasses[0].m_viewport;
  533. }
  534. else
  535. {
  536. viewport = UVec4(kMaxU32, kMaxU32, 0, 0);
  537. for(const ShadowSubpassInfo& s : subpasses)
  538. {
  539. viewport.x() = min(viewport.x(), s.m_viewport.x());
  540. viewport.y() = min(viewport.y(), s.m_viewport.y());
  541. viewport.z() = max(viewport.z(), s.m_viewport.x() + s.m_viewport.z());
  542. viewport.w() = max(viewport.w(), s.m_viewport.y() + s.m_viewport.w());
  543. }
  544. viewport.z() -= viewport.x();
  545. viewport.w() -= viewport.y();
  546. }
  547. // Create the pass
  548. GraphicsRenderPassDescription& pass = rgraph.newGraphicsRenderPass(passName);
  549. const Bool loadFb = !(subpasses.getSize() == 1 && subpasses[0].m_clearTileIndirectArgs.isValid());
  550. RenderTargetInfo smRti(m_runCtx.m_rt);
  551. smRti.m_loadOperation = (loadFb) ? RenderTargetLoadOperation::kLoad : RenderTargetLoadOperation::kClear;
  552. smRti.m_clearValue.m_depthStencil.m_depth = 1.0f;
  553. smRti.m_aspect = DepthStencilAspectBit::kDepth;
  554. pass.setRenderpassInfo({}, &smRti, viewport[0], viewport[1], viewport[2], viewport[3]);
  555. pass.newBufferDependency((meshletVisOut.isFilled()) ? meshletVisOut.m_dependency : visOut.m_dependency, BufferUsageBit::kIndirectDraw);
  556. pass.newTextureDependency(m_runCtx.m_rt, TextureUsageBit::kFramebufferWrite, TextureSubresourceInfo(DepthStencilAspectBit::kDepth));
  557. pass.setWork([this, visOut, meshletVisOut, subpasses, loadFb](RenderPassWorkContext& rgraphCtx) {
  558. ANKI_TRACE_SCOPED_EVENT(ShadowMapping);
  559. CommandBuffer& cmdb = *rgraphCtx.m_commandBuffer;
  560. for(U32 i = 0; i < subpasses.getSize(); ++i)
  561. {
  562. const ShadowSubpassInfo& spass = subpasses[i];
  563. cmdb.setViewport(spass.m_viewport[0], spass.m_viewport[1], spass.m_viewport[2], spass.m_viewport[3]);
  564. if(loadFb)
  565. {
  566. cmdb.bindShaderProgram(m_clearDepthGrProg.get());
  567. cmdb.setDepthCompareOperation(CompareOperation::kAlways);
  568. if(spass.m_clearTileIndirectArgs.isValid())
  569. {
  570. cmdb.drawIndirect(PrimitiveTopology::kTriangles, spass.m_clearTileIndirectArgs);
  571. }
  572. else
  573. {
  574. cmdb.draw(PrimitiveTopology::kTriangles, 3);
  575. }
  576. cmdb.setDepthCompareOperation(CompareOperation::kLess);
  577. }
  578. // Set state
  579. cmdb.setPolygonOffset(kShadowsPolygonOffsetFactor, kShadowsPolygonOffsetUnits);
  580. RenderableDrawerArguments args;
  581. args.m_renderingTechinuqe = RenderingTechnique::kDepth;
  582. args.m_viewMatrix = spass.m_viewMat;
  583. args.m_cameraTransform = spass.m_viewMat.getInverseTransformation();
  584. args.m_viewProjectionMatrix = spass.m_viewProjMat;
  585. args.m_previousViewProjectionMatrix = Mat4::getIdentity(); // Don't care
  586. args.m_sampler = getRenderer().getSamplers().m_trilinearRepeat.get();
  587. args.m_viewport = UVec4(spass.m_viewport[0], spass.m_viewport[1], spass.m_viewport[2], spass.m_viewport[3]);
  588. args.fill(visOut);
  589. TextureViewPtr hzbView;
  590. if(spass.m_hzbRt.isValid())
  591. {
  592. hzbView = rgraphCtx.createTextureView(spass.m_hzbRt);
  593. args.m_hzbTexture = hzbView.get();
  594. }
  595. if(meshletVisOut.isFilled())
  596. {
  597. args.fill(meshletVisOut);
  598. }
  599. getRenderer().getSceneDrawer().drawMdi(args, cmdb);
  600. }
  601. });
  602. }
  603. } // end namespace anki