ShadowMapping.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. // Copyright (C) 2009-2022, 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/RenderQueue.h>
  8. #include <AnKi/Core/ConfigSet.h>
  9. #include <AnKi/Util/ThreadHive.h>
  10. #include <AnKi/Util/Tracer.h>
  11. namespace anki {
  12. class ShadowMapping::Scratch::WorkItem
  13. {
  14. public:
  15. UVec4 m_viewport;
  16. RenderQueue* m_renderQueue;
  17. U32 m_firstRenderableElement;
  18. U32 m_renderableElementCount;
  19. U32 m_threadPoolTaskIdx;
  20. U32 m_renderQueueElementsLod;
  21. };
  22. class ShadowMapping::Scratch::LightToRenderToScratchInfo
  23. {
  24. public:
  25. UVec4 m_viewport;
  26. RenderQueue* m_renderQueue;
  27. U32 m_drawcallCount;
  28. U32 m_renderQueueElementsLod;
  29. };
  30. class ShadowMapping::Atlas::ResolveWorkItem
  31. {
  32. public:
  33. Vec4 m_uvInBounds; ///< Bounds used to avoid blurring neighbour tiles.
  34. Vec4 m_uvIn; ///< UV + size that point to the scratch buffer.
  35. UVec4 m_viewportOut; ///< Viewport in the atlas RT.
  36. Bool m_blur;
  37. };
  38. ShadowMapping::~ShadowMapping()
  39. {
  40. }
  41. Error ShadowMapping::init()
  42. {
  43. ANKI_R_LOGV("Initializing shadowmapping")
  44. const Error err = initInternal();
  45. if(err)
  46. {
  47. ANKI_R_LOGE("Failed to initialize shadowmapping");
  48. }
  49. else
  50. {
  51. ANKI_R_LOGV("Shadowmapping initialized. Scratch size %ux%u, atlas size %ux%u",
  52. m_scratch.m_tileCountX * m_scratch.m_tileResolution,
  53. m_scratch.m_tileCountY * m_scratch.m_tileResolution,
  54. m_atlas.m_tileCountBothAxis * m_atlas.m_tileResolution,
  55. m_atlas.m_tileCountBothAxis * m_atlas.m_tileResolution);
  56. }
  57. return err;
  58. }
  59. Error ShadowMapping::initScratch()
  60. {
  61. // Init the shadowmaps and FBs
  62. {
  63. m_scratch.m_tileCountX = getConfig().getRShadowMappingScratchTileCountX();
  64. m_scratch.m_tileCountY = getConfig().getRShadowMappingScratchTileCountY();
  65. m_scratch.m_tileResolution = getConfig().getRShadowMappingTileResolution();
  66. // RT
  67. m_scratch.m_rtDescr = m_r->create2DRenderTargetDescription(m_scratch.m_tileResolution * m_scratch.m_tileCountX,
  68. m_scratch.m_tileResolution * m_scratch.m_tileCountY,
  69. m_r->getDepthNoStencilFormat(), "SM scratch");
  70. m_scratch.m_rtDescr.bake();
  71. // FB
  72. m_scratch.m_fbDescr.m_depthStencilAttachment.m_loadOperation = AttachmentLoadOperation::CLEAR;
  73. m_scratch.m_fbDescr.m_depthStencilAttachment.m_clearValue.m_depthStencil.m_depth = 1.0f;
  74. m_scratch.m_fbDescr.m_depthStencilAttachment.m_aspect = DepthStencilAspectBit::DEPTH;
  75. m_scratch.m_fbDescr.bake();
  76. }
  77. m_scratch.m_tileAlloc.init(getAllocator(), m_scratch.m_tileCountX, m_scratch.m_tileCountY, MAX_LOD_COUNT, false);
  78. return Error::NONE;
  79. }
  80. Error ShadowMapping::initAtlas()
  81. {
  82. const Bool preferCompute = getConfig().getRPreferCompute();
  83. // Init RT
  84. {
  85. m_atlas.m_tileResolution = getConfig().getRShadowMappingTileResolution();
  86. m_atlas.m_tileCountBothAxis = getConfig().getRShadowMappingTileCountPerRowOrColumn();
  87. // RT
  88. const Format texFormat = (ANKI_EVSM4) ? Format::R32G32B32A32_SFLOAT : Format::R32G32_SFLOAT;
  89. TextureUsageBit usage = TextureUsageBit::SAMPLED_FRAGMENT | TextureUsageBit::SAMPLED_COMPUTE;
  90. usage |= (preferCompute) ? TextureUsageBit::IMAGE_COMPUTE_WRITE : TextureUsageBit::ALL_FRAMEBUFFER_ATTACHMENT;
  91. TextureInitInfo texinit = m_r->create2DRenderTargetInitInfo(
  92. m_atlas.m_tileResolution * m_atlas.m_tileCountBothAxis,
  93. m_atlas.m_tileResolution * m_atlas.m_tileCountBothAxis, texFormat, usage, "SM atlas");
  94. ClearValue clearVal;
  95. clearVal.m_colorf[0] = 1.0f;
  96. m_atlas.m_tex = m_r->createAndClearRenderTarget(texinit, TextureUsageBit::SAMPLED_FRAGMENT, clearVal);
  97. }
  98. // Tiles
  99. m_atlas.m_tileAlloc.init(getAllocator(), m_atlas.m_tileCountBothAxis, m_atlas.m_tileCountBothAxis, MAX_LOD_COUNT,
  100. true);
  101. // Programs and shaders
  102. {
  103. ANKI_CHECK(getResourceManager().loadResource((preferCompute) ? "ShaderBinaries/EvsmCompute.ankiprogbin"
  104. : "ShaderBinaries/EvsmRaster.ankiprogbin",
  105. m_atlas.m_resolveProg));
  106. ShaderProgramResourceVariantInitInfo variantInitInfo(m_atlas.m_resolveProg);
  107. variantInitInfo.addConstant("INPUT_TEXTURE_SIZE", UVec2(m_scratch.m_tileCountX * m_scratch.m_tileResolution,
  108. m_scratch.m_tileCountY * m_scratch.m_tileResolution));
  109. if(!preferCompute)
  110. {
  111. variantInitInfo.addConstant("FB_SIZE", UVec2(m_atlas.m_tileCountBothAxis * m_atlas.m_tileResolution));
  112. }
  113. const ShaderProgramResourceVariant* variant;
  114. m_atlas.m_resolveProg->getOrCreateVariant(variantInitInfo, variant);
  115. m_atlas.m_resolveGrProg = variant->getProgram();
  116. }
  117. m_atlas.m_fbDescr.m_colorAttachmentCount = 1;
  118. m_atlas.m_fbDescr.m_colorAttachments[0].m_loadOperation = AttachmentLoadOperation::LOAD;
  119. m_atlas.m_fbDescr.bake();
  120. return Error::NONE;
  121. }
  122. Error ShadowMapping::initInternal()
  123. {
  124. ANKI_CHECK(initScratch());
  125. ANKI_CHECK(initAtlas());
  126. return Error::NONE;
  127. }
  128. void ShadowMapping::runAtlas(RenderPassWorkContext& rgraphCtx)
  129. {
  130. ANKI_ASSERT(m_atlas.m_resolveWorkItems.getSize());
  131. ANKI_TRACE_SCOPED_EVENT(R_SM);
  132. CommandBufferPtr& cmdb = rgraphCtx.m_commandBuffer;
  133. // Allocate and populate uniforms
  134. EvsmResolveUniforms* uniforms = allocateAndBindStorage<EvsmResolveUniforms*>(
  135. m_atlas.m_resolveWorkItems.getSize() * sizeof(EvsmResolveUniforms), cmdb, 0, 0);
  136. for(U32 i = 0; i < m_atlas.m_resolveWorkItems.getSize(); ++i)
  137. {
  138. EvsmResolveUniforms& uni = uniforms[i];
  139. const Atlas::ResolveWorkItem& workItem = m_atlas.m_resolveWorkItems[i];
  140. uni.m_viewportXY = IVec2(workItem.m_viewportOut.xy());
  141. uni.m_viewportZW = Vec2(workItem.m_viewportOut.zw());
  142. uni.m_uvScale = workItem.m_uvIn.zw();
  143. uni.m_uvTranslation = workItem.m_uvIn.xy();
  144. uni.m_uvMin = workItem.m_uvInBounds.xy();
  145. uni.m_uvMax = workItem.m_uvInBounds.xy() + workItem.m_uvInBounds.zw();
  146. uni.m_blur = workItem.m_blur;
  147. }
  148. cmdb->bindShaderProgram(m_atlas.m_resolveGrProg);
  149. // Continue
  150. cmdb->bindSampler(0, 1, m_r->getSamplers().m_trilinearClamp);
  151. rgraphCtx.bindTexture(0, 2, m_scratch.m_rt, TextureSubresourceInfo(DepthStencilAspectBit::DEPTH));
  152. if(getConfig().getRPreferCompute())
  153. {
  154. rgraphCtx.bindImage(0, 3, m_atlas.m_rt);
  155. constexpr U32 workgroupSize = 8;
  156. ANKI_ASSERT(m_atlas.m_tileResolution >= workgroupSize && (m_atlas.m_tileResolution % workgroupSize) == 0);
  157. cmdb->dispatchCompute(m_atlas.m_tileResolution / workgroupSize, m_atlas.m_tileResolution / workgroupSize,
  158. m_atlas.m_resolveWorkItems.getSize());
  159. }
  160. else
  161. {
  162. cmdb->setViewport(0, 0, m_atlas.m_tex->getWidth(), m_atlas.m_tex->getHeight());
  163. cmdb->drawArrays(PrimitiveTopology::TRIANGLES, 6, m_atlas.m_resolveWorkItems.getSize());
  164. }
  165. }
  166. void ShadowMapping::runShadowMapping(RenderPassWorkContext& rgraphCtx)
  167. {
  168. ANKI_ASSERT(m_scratch.m_workItems.getSize());
  169. ANKI_TRACE_SCOPED_EVENT(R_SM);
  170. CommandBufferPtr& cmdb = rgraphCtx.m_commandBuffer;
  171. const U threadIdx = rgraphCtx.m_currentSecondLevelCommandBufferIndex;
  172. for(Scratch::WorkItem& work : m_scratch.m_workItems)
  173. {
  174. if(work.m_threadPoolTaskIdx != threadIdx)
  175. {
  176. continue;
  177. }
  178. // Set state
  179. cmdb->setViewport(work.m_viewport[0], work.m_viewport[1], work.m_viewport[2], work.m_viewport[3]);
  180. cmdb->setScissor(work.m_viewport[0], work.m_viewport[1], work.m_viewport[2], work.m_viewport[3]);
  181. m_r->getSceneDrawer().drawRange(RenderingTechnique::SHADOW, work.m_renderQueue->m_viewMatrix,
  182. work.m_renderQueue->m_viewProjectionMatrix,
  183. Mat4::getIdentity(), // Don't care about prev matrices here
  184. cmdb, m_r->getSamplers().m_trilinearRepeatAniso,
  185. work.m_renderQueue->m_renderables.getBegin() + work.m_firstRenderableElement,
  186. work.m_renderQueue->m_renderables.getBegin() + work.m_firstRenderableElement
  187. + work.m_renderableElementCount,
  188. work.m_renderQueueElementsLod, work.m_renderQueueElementsLod);
  189. }
  190. }
  191. void ShadowMapping::populateRenderGraph(RenderingContext& ctx)
  192. {
  193. ANKI_TRACE_SCOPED_EVENT(R_SM);
  194. // First process the lights
  195. U32 threadCountForScratchPass = 0;
  196. processLights(ctx, threadCountForScratchPass);
  197. // Build the render graph
  198. RenderGraphDescription& rgraph = ctx.m_renderGraphDescr;
  199. if(m_scratch.m_workItems.getSize())
  200. {
  201. // Will have to create render passes
  202. // Scratch pass
  203. {
  204. // Compute render area
  205. const U32 minx = 0, miny = 0;
  206. const U32 height = m_scratch.m_maxViewportHeight;
  207. const U32 width = m_scratch.m_maxViewportWidth;
  208. GraphicsRenderPassDescription& pass = rgraph.newGraphicsRenderPass("SM scratch");
  209. m_scratch.m_rt = rgraph.newRenderTarget(m_scratch.m_rtDescr);
  210. pass.setFramebufferInfo(m_scratch.m_fbDescr, {}, m_scratch.m_rt, {}, minx, miny, width, height);
  211. ANKI_ASSERT(threadCountForScratchPass
  212. && threadCountForScratchPass <= m_r->getThreadHive().getThreadCount());
  213. pass.setWork(threadCountForScratchPass, [this](RenderPassWorkContext& rgraphCtx) {
  214. runShadowMapping(rgraphCtx);
  215. });
  216. TextureSubresourceInfo subresource = TextureSubresourceInfo(DepthStencilAspectBit::DEPTH);
  217. pass.newDependency({m_scratch.m_rt, TextureUsageBit::ALL_FRAMEBUFFER_ATTACHMENT, subresource});
  218. }
  219. // Atlas pass
  220. {
  221. if(ANKI_LIKELY(m_atlas.m_rtImportedOnce))
  222. {
  223. m_atlas.m_rt = rgraph.importRenderTarget(m_atlas.m_tex);
  224. }
  225. else
  226. {
  227. m_atlas.m_rt = rgraph.importRenderTarget(m_atlas.m_tex, TextureUsageBit::SAMPLED_FRAGMENT);
  228. m_atlas.m_rtImportedOnce = true;
  229. }
  230. if(getConfig().getRPreferCompute())
  231. {
  232. ComputeRenderPassDescription& pass = rgraph.newComputeRenderPass("EVSM resolve");
  233. pass.setWork([this](RenderPassWorkContext& rgraphCtx) {
  234. runAtlas(rgraphCtx);
  235. });
  236. pass.newDependency(RenderPassDependency(m_scratch.m_rt, TextureUsageBit::SAMPLED_COMPUTE,
  237. TextureSubresourceInfo(DepthStencilAspectBit::DEPTH)));
  238. pass.newDependency(RenderPassDependency(m_atlas.m_rt, TextureUsageBit::IMAGE_COMPUTE_WRITE));
  239. }
  240. else
  241. {
  242. GraphicsRenderPassDescription& pass = rgraph.newGraphicsRenderPass("EVSM resolve");
  243. pass.setFramebufferInfo(m_atlas.m_fbDescr, {m_atlas.m_rt});
  244. pass.setWork([this](RenderPassWorkContext& rgraphCtx) {
  245. runAtlas(rgraphCtx);
  246. });
  247. pass.newDependency(RenderPassDependency(m_scratch.m_rt, TextureUsageBit::SAMPLED_FRAGMENT,
  248. TextureSubresourceInfo(DepthStencilAspectBit::DEPTH)));
  249. pass.newDependency(
  250. RenderPassDependency(m_atlas.m_rt, TextureUsageBit::FRAMEBUFFER_ATTACHMENT_READ
  251. | TextureUsageBit::FRAMEBUFFER_ATTACHMENT_WRITE));
  252. }
  253. }
  254. }
  255. else
  256. {
  257. // No need for shadowmapping passes, just import the atlas
  258. if(ANKI_LIKELY(m_atlas.m_rtImportedOnce))
  259. {
  260. m_atlas.m_rt = rgraph.importRenderTarget(m_atlas.m_tex);
  261. }
  262. else
  263. {
  264. m_atlas.m_rt = rgraph.importRenderTarget(m_atlas.m_tex, TextureUsageBit::SAMPLED_FRAGMENT);
  265. m_atlas.m_rtImportedOnce = true;
  266. }
  267. }
  268. }
  269. Mat4 ShadowMapping::createSpotLightTextureMatrix(const UVec4& viewport) const
  270. {
  271. const F32 atlasSize = F32(m_atlas.m_tileResolution * m_atlas.m_tileCountBothAxis);
  272. #if ANKI_COMPILER_GCC_COMPATIBLE
  273. # pragma GCC diagnostic push
  274. # pragma GCC diagnostic ignored "-Wpedantic" // Because GCC and clang throw an incorrect warning
  275. #endif
  276. const Vec2 uv(F32(viewport[0]) / atlasSize, F32(viewport[1]) / atlasSize);
  277. #if ANKI_COMPILER_GCC_COMPATIBLE
  278. # pragma GCC diagnostic pop
  279. #endif
  280. ANKI_ASSERT(uv >= Vec2(0.0f) && uv <= Vec2(1.0f));
  281. ANKI_ASSERT(viewport[2] == viewport[3]);
  282. const F32 sizeTextureSpace = F32(viewport[2]) / atlasSize;
  283. return Mat4(sizeTextureSpace, 0.0f, 0.0f, uv.x(), 0.0f, sizeTextureSpace, 0.0f, uv.y(), 0.0f, 0.0f, 1.0f, 0.0f,
  284. 0.0f, 0.0f, 0.0f, 1.0f);
  285. }
  286. void ShadowMapping::chooseLod(const Vec4& cameraOrigin, const PointLightQueueElement& light, Bool& blurAtlas,
  287. U32& tileBufferLod, U32& renderQueueElementsLod) const
  288. {
  289. const F32 distFromTheCamera = (cameraOrigin - light.m_worldPosition.xyz0()).getLength() - light.m_radius;
  290. if(distFromTheCamera < getConfig().getLod0MaxDistance())
  291. {
  292. ANKI_ASSERT(m_pointLightsMaxLod == 1);
  293. blurAtlas = true;
  294. tileBufferLod = 1;
  295. renderQueueElementsLod = 0;
  296. }
  297. else
  298. {
  299. blurAtlas = false;
  300. tileBufferLod = 0;
  301. renderQueueElementsLod = MAX_LOD_COUNT - 1;
  302. }
  303. }
  304. void ShadowMapping::chooseLod(const Vec4& cameraOrigin, const SpotLightQueueElement& light, Bool& blurAtlas,
  305. U32& tileBufferLod, U32& renderQueueElementsLod) const
  306. {
  307. // Get some data
  308. const Vec4 coneOrigin = light.m_worldTransform.getTranslationPart().xyz0();
  309. const Vec4 coneDir = -light.m_worldTransform.getZAxis().xyz0();
  310. const F32 coneAngle = light.m_outerAngle;
  311. // Compute the distance from the camera to the light cone
  312. const Vec4 V = cameraOrigin - coneOrigin;
  313. const F32 VlenSq = V.dot(V);
  314. const F32 V1len = V.dot(coneDir);
  315. const F32 distFromTheCamera = cos(coneAngle) * sqrt(VlenSq - V1len * V1len) - V1len * sin(coneAngle);
  316. if(distFromTheCamera < getConfig().getLod0MaxDistance())
  317. {
  318. blurAtlas = true;
  319. tileBufferLod = 2;
  320. renderQueueElementsLod = 0;
  321. }
  322. else if(distFromTheCamera < getConfig().getLod1MaxDistance())
  323. {
  324. blurAtlas = false;
  325. tileBufferLod = 1;
  326. renderQueueElementsLod = MAX_LOD_COUNT - 1;
  327. }
  328. else
  329. {
  330. blurAtlas = false;
  331. tileBufferLod = 0;
  332. renderQueueElementsLod = MAX_LOD_COUNT - 1;
  333. }
  334. }
  335. TileAllocatorResult ShadowMapping::allocateTilesAndScratchTiles(U64 lightUuid, U32 faceCount, const U64* faceTimestamps,
  336. const U32* faceIndices, const U32* drawcallsCount,
  337. const U32* lods, UVec4* atlasTileViewports,
  338. UVec4* scratchTileViewports,
  339. TileAllocatorResult* subResults)
  340. {
  341. ANKI_ASSERT(lightUuid > 0);
  342. ANKI_ASSERT(faceCount > 0);
  343. ANKI_ASSERT(faceTimestamps);
  344. ANKI_ASSERT(faceIndices);
  345. ANKI_ASSERT(drawcallsCount);
  346. ANKI_ASSERT(lods);
  347. TileAllocatorResult res = TileAllocatorResult::ALLOCATION_FAILED;
  348. // Allocate atlas tiles first. They may be cached and that will affect how many scratch tiles we'll need
  349. for(U i = 0; i < faceCount; ++i)
  350. {
  351. Array<U32, 4> tileRanges;
  352. res = m_atlas.m_tileAlloc.allocate(m_r->getGlobalTimestamp(), faceTimestamps[i], lightUuid, faceIndices[i],
  353. drawcallsCount[i], lods[i], tileRanges);
  354. if(res == TileAllocatorResult::ALLOCATION_FAILED)
  355. {
  356. ANKI_R_LOGW("There is not enough space in the shadow atlas for more shadow maps. "
  357. "Increase the r_shadowMappingTileCountPerRowOrColumn or decrease the scene's shadow casters");
  358. // Invalidate cache entries for what we already allocated
  359. for(U j = 0; j < i; ++j)
  360. {
  361. m_atlas.m_tileAlloc.invalidateCache(lightUuid, faceIndices[j]);
  362. }
  363. return res;
  364. }
  365. subResults[i] = res;
  366. // Set viewport
  367. atlasTileViewports[i] = UVec4(tileRanges) * m_atlas.m_tileResolution;
  368. }
  369. // Allocate scratch tiles
  370. for(U i = 0; i < faceCount; ++i)
  371. {
  372. if(subResults[i] == TileAllocatorResult::CACHED)
  373. {
  374. continue;
  375. }
  376. ANKI_ASSERT(subResults[i] == TileAllocatorResult::ALLOCATION_SUCCEEDED);
  377. Array<U32, 4> tileRanges;
  378. res = m_scratch.m_tileAlloc.allocate(m_r->getGlobalTimestamp(), faceTimestamps[i], lightUuid, faceIndices[i],
  379. drawcallsCount[i], lods[i], tileRanges);
  380. if(res == TileAllocatorResult::ALLOCATION_FAILED)
  381. {
  382. ANKI_R_LOGW("Don't have enough space in the scratch shadow mapping buffer. "
  383. "If you see this message too often increase r_shadowMappingScratchTileCountX/Y");
  384. // Invalidate atlas tiles
  385. for(U j = 0; j < faceCount; ++j)
  386. {
  387. m_atlas.m_tileAlloc.invalidateCache(lightUuid, faceIndices[j]);
  388. }
  389. return res;
  390. }
  391. // Fix viewport
  392. scratchTileViewports[i] = UVec4(tileRanges) * m_scratch.m_tileResolution;
  393. // Update the max view width
  394. m_scratch.m_maxViewportWidth =
  395. max(m_scratch.m_maxViewportWidth, scratchTileViewports[i][0] + scratchTileViewports[i][2]);
  396. m_scratch.m_maxViewportHeight =
  397. max(m_scratch.m_maxViewportHeight, scratchTileViewports[i][1] + scratchTileViewports[i][3]);
  398. }
  399. return res;
  400. }
  401. void ShadowMapping::processLights(RenderingContext& ctx, U32& threadCountForScratchPass)
  402. {
  403. // Reset the scratch viewport width
  404. m_scratch.m_maxViewportWidth = 0;
  405. m_scratch.m_maxViewportHeight = 0;
  406. // Vars
  407. const Vec4 cameraOrigin = ctx.m_renderQueue->m_cameraTransform.getTranslationPart().xyz0();
  408. DynamicArrayAuto<Scratch::LightToRenderToScratchInfo> lightsToRender(ctx.m_tempAllocator);
  409. U32 drawcallCount = 0;
  410. DynamicArrayAuto<Atlas::ResolveWorkItem> atlasWorkItems(ctx.m_tempAllocator);
  411. // First thing, allocate an empty tile for empty faces of point lights
  412. UVec4 emptyTileViewport;
  413. {
  414. Array<U32, 4> tileRange;
  415. const TileAllocatorResult res =
  416. m_atlas.m_tileAlloc.allocate(m_r->getGlobalTimestamp(), 1, MAX_U64, 0, 1, m_pointLightsMaxLod, tileRange);
  417. emptyTileViewport = UVec4(tileRange);
  418. (void)res;
  419. #if ANKI_ENABLE_ASSERTIONS
  420. static Bool firstRun = true;
  421. if(firstRun)
  422. {
  423. ANKI_ASSERT(res == TileAllocatorResult::ALLOCATION_SUCCEEDED);
  424. firstRun = false;
  425. }
  426. else
  427. {
  428. ANKI_ASSERT(res == TileAllocatorResult::CACHED);
  429. }
  430. #endif
  431. }
  432. // Process the directional light first.
  433. if(ctx.m_renderQueue->m_directionalLight.m_shadowCascadeCount > 0)
  434. {
  435. DirectionalLightQueueElement& light = ctx.m_renderQueue->m_directionalLight;
  436. Array<U64, MAX_SHADOW_CASCADES2> timestamps;
  437. Array<U32, MAX_SHADOW_CASCADES2> cascadeIndices;
  438. Array<U32, MAX_SHADOW_CASCADES2> drawcallCounts;
  439. Array<UVec4, MAX_SHADOW_CASCADES2> atlasViewports;
  440. Array<UVec4, MAX_SHADOW_CASCADES2> scratchViewports;
  441. Array<TileAllocatorResult, MAX_SHADOW_CASCADES2> subResults;
  442. Array<U32, MAX_SHADOW_CASCADES2> lods;
  443. Array<U32, MAX_SHADOW_CASCADES2> renderQueueElementsLods;
  444. Array<Bool, MAX_SHADOW_CASCADES2> blurAtlass;
  445. U32 activeCascades = 0;
  446. for(U32 cascade = 0; cascade < light.m_shadowCascadeCount; ++cascade)
  447. {
  448. ANKI_ASSERT(light.m_shadowRenderQueues[cascade]);
  449. if(light.m_shadowRenderQueues[cascade]->m_renderables.getSize() > 0)
  450. {
  451. // Cascade with drawcalls, will need tiles
  452. timestamps[activeCascades] = m_r->getGlobalTimestamp(); // This light is always updated
  453. cascadeIndices[activeCascades] = cascade;
  454. drawcallCounts[activeCascades] = 1; // Doesn't matter
  455. // Change the quality per cascade
  456. blurAtlass[activeCascades] = (cascade <= 1);
  457. lods[activeCascades] = (cascade <= 1) ? (MAX_LOD_COUNT - 1) : (lods[0] - 1);
  458. renderQueueElementsLods[activeCascades] = (cascade == 0) ? 0 : (MAX_LOD_COUNT - 1);
  459. ++activeCascades;
  460. }
  461. }
  462. const Bool allocationFailed =
  463. activeCascades == 0
  464. || allocateTilesAndScratchTiles(light.m_uuid, activeCascades, &timestamps[0], &cascadeIndices[0],
  465. &drawcallCounts[0], &lods[0], &atlasViewports[0], &scratchViewports[0],
  466. &subResults[0])
  467. == TileAllocatorResult::ALLOCATION_FAILED;
  468. if(!allocationFailed)
  469. {
  470. activeCascades = 0;
  471. for(U cascade = 0; cascade < light.m_shadowCascadeCount; ++cascade)
  472. {
  473. if(light.m_shadowRenderQueues[cascade]->m_renderables.getSize() > 0)
  474. {
  475. // Cascade with drawcalls, push some work for it
  476. // Update the texture matrix to point to the correct region in the atlas
  477. light.m_textureMatrices[cascade] =
  478. createSpotLightTextureMatrix(atlasViewports[activeCascades]) * light.m_textureMatrices[cascade];
  479. // Push work
  480. newScratchAndAtlasResloveRenderWorkItems(
  481. atlasViewports[activeCascades], scratchViewports[activeCascades], blurAtlass[activeCascades],
  482. light.m_shadowRenderQueues[cascade], renderQueueElementsLods[activeCascades], lightsToRender,
  483. atlasWorkItems, drawcallCount);
  484. ++activeCascades;
  485. }
  486. else
  487. {
  488. // Empty cascade, point it to the empty tile
  489. light.m_textureMatrices[cascade] =
  490. createSpotLightTextureMatrix(emptyTileViewport) * light.m_textureMatrices[cascade];
  491. }
  492. }
  493. }
  494. else
  495. {
  496. // Light can't be a caster this frame
  497. light.m_shadowCascadeCount = 0;
  498. zeroMemory(light.m_shadowRenderQueues);
  499. }
  500. }
  501. // Process the point lights.
  502. for(PointLightQueueElement& light : ctx.m_renderQueue->m_pointLights)
  503. {
  504. if(!light.hasShadow())
  505. {
  506. continue;
  507. }
  508. // Prepare data to allocate tiles and allocate
  509. Array<U64, 6> timestamps;
  510. Array<U32, 6> faceIndices;
  511. Array<U32, 6> drawcallCounts;
  512. Array<UVec4, 6> atlasViewports;
  513. Array<UVec4, 6> scratchViewports;
  514. Array<TileAllocatorResult, 6> subResults;
  515. Array<U32, 6> lods;
  516. U32 numOfFacesThatHaveDrawcalls = 0;
  517. Bool blurAtlas;
  518. U32 lod, renderQueueElementsLod;
  519. chooseLod(cameraOrigin, light, blurAtlas, lod, renderQueueElementsLod);
  520. for(U32 face = 0; face < 6; ++face)
  521. {
  522. ANKI_ASSERT(light.m_shadowRenderQueues[face]);
  523. if(light.m_shadowRenderQueues[face]->m_renderables.getSize())
  524. {
  525. // Has renderables, need to allocate tiles for it so add it to the arrays
  526. faceIndices[numOfFacesThatHaveDrawcalls] = face;
  527. timestamps[numOfFacesThatHaveDrawcalls] =
  528. light.m_shadowRenderQueues[face]->m_shadowRenderablesLastUpdateTimestamp;
  529. drawcallCounts[numOfFacesThatHaveDrawcalls] = light.m_shadowRenderQueues[face]->m_renderables.getSize();
  530. lods[numOfFacesThatHaveDrawcalls] = lod;
  531. ++numOfFacesThatHaveDrawcalls;
  532. }
  533. }
  534. const Bool allocationFailed =
  535. numOfFacesThatHaveDrawcalls == 0
  536. || allocateTilesAndScratchTiles(light.m_uuid, numOfFacesThatHaveDrawcalls, &timestamps[0], &faceIndices[0],
  537. &drawcallCounts[0], &lods[0], &atlasViewports[0], &scratchViewports[0],
  538. &subResults[0])
  539. == TileAllocatorResult::ALLOCATION_FAILED;
  540. if(!allocationFailed)
  541. {
  542. // All good, update the lights
  543. const F32 atlasResolution = F32(m_atlas.m_tileResolution * m_atlas.m_tileCountBothAxis);
  544. F32 superTileSize = F32(atlasViewports[0][2]); // Should be the same for all tiles and faces
  545. superTileSize -= 1.0f; // Remove 2 half texels to avoid bilinear filtering bleeding
  546. light.m_shadowAtlasTileSize = superTileSize / atlasResolution;
  547. numOfFacesThatHaveDrawcalls = 0;
  548. for(U face = 0; face < 6; ++face)
  549. {
  550. if(light.m_shadowRenderQueues[face]->m_renderables.getSize())
  551. {
  552. // Has drawcalls, asigned it to a tile
  553. const UVec4& atlasViewport = atlasViewports[numOfFacesThatHaveDrawcalls];
  554. const UVec4& scratchViewport = scratchViewports[numOfFacesThatHaveDrawcalls];
  555. // Add a half texel to the viewport's start to avoid bilinear filtering bleeding
  556. light.m_shadowAtlasTileOffsets[face].x() = (F32(atlasViewport[0]) + 0.5f) / atlasResolution;
  557. light.m_shadowAtlasTileOffsets[face].y() = (F32(atlasViewport[1]) + 0.5f) / atlasResolution;
  558. if(subResults[numOfFacesThatHaveDrawcalls] != TileAllocatorResult::CACHED)
  559. {
  560. newScratchAndAtlasResloveRenderWorkItems(
  561. atlasViewport, scratchViewport, blurAtlas, light.m_shadowRenderQueues[face],
  562. renderQueueElementsLod, lightsToRender, atlasWorkItems, drawcallCount);
  563. }
  564. ++numOfFacesThatHaveDrawcalls;
  565. }
  566. else
  567. {
  568. // Doesn't have renderables, point the face to the empty tile
  569. UVec4 atlasViewport = emptyTileViewport;
  570. ANKI_ASSERT(F32(atlasViewport[2]) <= superTileSize && F32(atlasViewport[3]) <= superTileSize);
  571. atlasViewport[2] = U32(superTileSize);
  572. atlasViewport[3] = U32(superTileSize);
  573. light.m_shadowAtlasTileOffsets[face].x() = (F32(atlasViewport[0]) + 0.5f) / atlasResolution;
  574. light.m_shadowAtlasTileOffsets[face].y() = (F32(atlasViewport[1]) + 0.5f) / atlasResolution;
  575. }
  576. }
  577. }
  578. else
  579. {
  580. // Light can't be a caster this frame
  581. zeroMemory(light.m_shadowRenderQueues);
  582. }
  583. }
  584. // Process the spot lights
  585. for(SpotLightQueueElement& light : ctx.m_renderQueue->m_spotLights)
  586. {
  587. if(!light.hasShadow())
  588. {
  589. continue;
  590. }
  591. // Allocate tiles
  592. U32 faceIdx = 0;
  593. TileAllocatorResult subResult;
  594. UVec4 atlasViewport;
  595. UVec4 scratchViewport;
  596. const U32 localDrawcallCount = light.m_shadowRenderQueue->m_renderables.getSize();
  597. Bool blurAtlas;
  598. U32 lod, renderQueueElementsLod;
  599. chooseLod(cameraOrigin, light, blurAtlas, lod, renderQueueElementsLod);
  600. const Bool allocationFailed =
  601. localDrawcallCount == 0
  602. || allocateTilesAndScratchTiles(
  603. light.m_uuid, 1, &light.m_shadowRenderQueue->m_shadowRenderablesLastUpdateTimestamp, &faceIdx,
  604. &localDrawcallCount, &lod, &atlasViewport, &scratchViewport, &subResult)
  605. == TileAllocatorResult::ALLOCATION_FAILED;
  606. if(!allocationFailed)
  607. {
  608. // All good, update the light
  609. // Update the texture matrix to point to the correct region in the atlas
  610. light.m_textureMatrix = createSpotLightTextureMatrix(atlasViewport) * light.m_textureMatrix;
  611. if(subResult != TileAllocatorResult::CACHED)
  612. {
  613. newScratchAndAtlasResloveRenderWorkItems(atlasViewport, scratchViewport, blurAtlas,
  614. light.m_shadowRenderQueue, renderQueueElementsLod,
  615. lightsToRender, atlasWorkItems, drawcallCount);
  616. }
  617. }
  618. else
  619. {
  620. // Doesn't have renderables or the allocation failed, won't be a shadow caster
  621. light.m_shadowRenderQueue = nullptr;
  622. }
  623. }
  624. // Split the work that will happen in the scratch buffer
  625. if(lightsToRender.getSize())
  626. {
  627. DynamicArrayAuto<Scratch::WorkItem> workItems(ctx.m_tempAllocator);
  628. Scratch::LightToRenderToScratchInfo* lightToRender = lightsToRender.getBegin();
  629. U32 lightToRenderDrawcallCount = lightToRender->m_drawcallCount;
  630. const Scratch::LightToRenderToScratchInfo* lightToRenderEnd = lightsToRender.getEnd();
  631. const U32 threadCount = computeNumberOfSecondLevelCommandBuffers(drawcallCount);
  632. threadCountForScratchPass = threadCount;
  633. for(U32 taskId = 0; taskId < threadCount; ++taskId)
  634. {
  635. U32 start, end;
  636. splitThreadedProblem(taskId, threadCount, drawcallCount, start, end);
  637. // While there are drawcalls in this task emit new work items
  638. U32 taskDrawcallCount = end - start;
  639. ANKI_ASSERT(taskDrawcallCount > 0 && "Because we used computeNumberOfSecondLevelCommandBuffers()");
  640. while(taskDrawcallCount)
  641. {
  642. ANKI_ASSERT(lightToRender != lightToRenderEnd);
  643. const U32 workItemDrawcallCount = min(lightToRenderDrawcallCount, taskDrawcallCount);
  644. Scratch::WorkItem workItem;
  645. workItem.m_viewport = lightToRender->m_viewport;
  646. workItem.m_renderQueue = lightToRender->m_renderQueue;
  647. workItem.m_firstRenderableElement = lightToRender->m_drawcallCount - lightToRenderDrawcallCount;
  648. workItem.m_renderableElementCount = workItemDrawcallCount;
  649. workItem.m_threadPoolTaskIdx = taskId;
  650. workItem.m_renderQueueElementsLod = lightToRender->m_renderQueueElementsLod;
  651. workItems.emplaceBack(workItem);
  652. // Decrease the drawcall counts for the task and the light
  653. ANKI_ASSERT(taskDrawcallCount >= workItemDrawcallCount);
  654. taskDrawcallCount -= workItemDrawcallCount;
  655. ANKI_ASSERT(lightToRenderDrawcallCount >= workItemDrawcallCount);
  656. lightToRenderDrawcallCount -= workItemDrawcallCount;
  657. // Move to the next light
  658. if(lightToRenderDrawcallCount == 0)
  659. {
  660. ++lightToRender;
  661. lightToRenderDrawcallCount =
  662. (lightToRender != lightToRenderEnd) ? lightToRender->m_drawcallCount : 0;
  663. }
  664. }
  665. }
  666. ANKI_ASSERT(lightToRender == lightToRenderEnd);
  667. ANKI_ASSERT(lightsToRender.getSize() <= workItems.getSize());
  668. // All good, store the work items for the threads to pick up
  669. {
  670. Scratch::WorkItem* items;
  671. U32 itemSize;
  672. U32 itemStorageSize;
  673. workItems.moveAndReset(items, itemSize, itemStorageSize);
  674. ANKI_ASSERT(items && itemSize && itemStorageSize);
  675. m_scratch.m_workItems = WeakArray<Scratch::WorkItem>(items, itemSize);
  676. Atlas::ResolveWorkItem* atlasItems;
  677. atlasWorkItems.moveAndReset(atlasItems, itemSize, itemStorageSize);
  678. ANKI_ASSERT(atlasItems && itemSize && itemStorageSize);
  679. m_atlas.m_resolveWorkItems = WeakArray<Atlas::ResolveWorkItem>(atlasItems, itemSize);
  680. }
  681. }
  682. else
  683. {
  684. m_scratch.m_workItems = WeakArray<Scratch::WorkItem>();
  685. m_atlas.m_resolveWorkItems = WeakArray<Atlas::ResolveWorkItem>();
  686. }
  687. }
  688. void ShadowMapping::newScratchAndAtlasResloveRenderWorkItems(
  689. const UVec4& atlasViewport, const UVec4& scratchVewport, Bool blurAtlas, RenderQueue* lightRenderQueue,
  690. U32 renderQueueElementsLod, DynamicArrayAuto<Scratch::LightToRenderToScratchInfo>& scratchWorkItem,
  691. DynamicArrayAuto<Atlas::ResolveWorkItem>& atlasResolveWorkItem, U32& drawcallCount) const
  692. {
  693. // Scratch work item
  694. {
  695. Scratch::LightToRenderToScratchInfo toRender;
  696. toRender.m_renderQueue = lightRenderQueue;
  697. toRender.m_viewport = scratchVewport;
  698. toRender.m_drawcallCount = lightRenderQueue->m_renderables.getSize();
  699. toRender.m_renderQueueElementsLod = renderQueueElementsLod;
  700. scratchWorkItem.emplaceBack(toRender);
  701. drawcallCount += lightRenderQueue->m_renderables.getSize();
  702. }
  703. // Atlas resolve work items
  704. const U32 tilesX = scratchVewport[2] / m_scratch.m_tileResolution;
  705. const U32 tilesY = scratchVewport[3] / m_scratch.m_tileResolution;
  706. for(U32 x = 0; x < tilesX; ++x)
  707. {
  708. for(U32 y = 0; y < tilesY; ++y)
  709. {
  710. const F32 scratchAtlasWidth = F32(m_scratch.m_tileCountX * m_scratch.m_tileResolution);
  711. const F32 scratchAtlasHeight = F32(m_scratch.m_tileCountY * m_scratch.m_tileResolution);
  712. Atlas::ResolveWorkItem atlasItem;
  713. atlasItem.m_uvInBounds[0] = F32(scratchVewport[0]) / scratchAtlasWidth;
  714. atlasItem.m_uvInBounds[1] = F32(scratchVewport[1]) / scratchAtlasHeight;
  715. atlasItem.m_uvInBounds[2] = F32(scratchVewport[2]) / scratchAtlasWidth;
  716. atlasItem.m_uvInBounds[3] = F32(scratchVewport[3]) / scratchAtlasHeight;
  717. atlasItem.m_uvIn[0] = F32(scratchVewport[0] + scratchVewport[2] / tilesX * x) / scratchAtlasWidth;
  718. atlasItem.m_uvIn[1] = F32(scratchVewport[1] + scratchVewport[3] / tilesY * y) / scratchAtlasHeight;
  719. atlasItem.m_uvIn[2] = F32(scratchVewport[2] / tilesX) / scratchAtlasWidth;
  720. atlasItem.m_uvIn[3] = F32(scratchVewport[3] / tilesY) / scratchAtlasHeight;
  721. atlasItem.m_viewportOut[0] = atlasViewport[0] + atlasViewport[2] / tilesX * x;
  722. atlasItem.m_viewportOut[1] = atlasViewport[1] + atlasViewport[3] / tilesY * y;
  723. atlasItem.m_viewportOut[2] = atlasViewport[2] / tilesX;
  724. atlasItem.m_viewportOut[3] = atlasViewport[3] / tilesY;
  725. atlasItem.m_blur = blurAtlas;
  726. atlasResolveWorkItem.emplaceBack(atlasItem);
  727. }
  728. }
  729. }
  730. } // end namespace anki