BsShadowRendering.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsShadowRendering.h"
  4. #include "BsRendererView.h"
  5. #include "BsRendererScene.h"
  6. #include "Renderer/BsLight.h"
  7. #include "Renderer/BsRendererUtility.h"
  8. #include "Material/BsGpuParamsSet.h"
  9. #include "Mesh/BsMesh.h"
  10. #include "Renderer/BsCamera.h"
  11. #include "Utility/BsBitwise.h"
  12. #include "RenderAPI/BsVertexDataDesc.h"
  13. #include "Renderer/BsRenderer.h"
  14. namespace bs { namespace ct
  15. {
  16. ShadowParamsDef gShadowParamsDef;
  17. ShadowDepthNormalMat::ShadowDepthNormalMat()
  18. { }
  19. void ShadowDepthNormalMat::bind(const SPtr<GpuParamBlockBuffer>& shadowParams)
  20. {
  21. mParams->setParamBlockBuffer("ShadowParams", shadowParams);
  22. RenderAPI::instance().setGraphicsPipeline(mGfxPipeline);
  23. RenderAPI::instance().setStencilRef(mStencilRef);
  24. }
  25. void ShadowDepthNormalMat::setPerObjectBuffer(const SPtr<GpuParamBlockBuffer>& perObjectParams)
  26. {
  27. mParams->setParamBlockBuffer("PerObject", perObjectParams);
  28. RenderAPI::instance().setGpuParams(mParams);
  29. }
  30. ShadowDepthNormalMat* ShadowDepthNormalMat::getVariation(bool skinned, bool morph)
  31. {
  32. if(skinned)
  33. {
  34. if(morph)
  35. return get(getVariation<true, true>());
  36. return get(getVariation<true, false>());
  37. }
  38. else
  39. {
  40. if(morph)
  41. return get(getVariation<false, true>());
  42. return get(getVariation<false, false>());
  43. }
  44. }
  45. ShadowDepthDirectionalMat::ShadowDepthDirectionalMat()
  46. { }
  47. void ShadowDepthDirectionalMat::bind(const SPtr<GpuParamBlockBuffer>& shadowParams)
  48. {
  49. mParams->setParamBlockBuffer("ShadowParams", shadowParams);
  50. RenderAPI::instance().setGraphicsPipeline(mGfxPipeline);
  51. RenderAPI::instance().setStencilRef(mStencilRef);
  52. }
  53. void ShadowDepthDirectionalMat::setPerObjectBuffer(const SPtr<GpuParamBlockBuffer>& perObjectParams)
  54. {
  55. mParams->setParamBlockBuffer("PerObject", perObjectParams);
  56. RenderAPI::instance().setGpuParams(mParams);
  57. }
  58. ShadowDepthDirectionalMat* ShadowDepthDirectionalMat::getVariation(bool skinned, bool morph)
  59. {
  60. if(skinned)
  61. {
  62. if(morph)
  63. return get(getVariation<true, true>());
  64. return get(getVariation<true, false>());
  65. }
  66. else
  67. {
  68. if(morph)
  69. return get(getVariation<false, true>());
  70. return get(getVariation<false, false>());
  71. }
  72. }
  73. ShadowCubeMatricesDef gShadowCubeMatricesDef;
  74. ShadowCubeMasksDef gShadowCubeMasksDef;
  75. ShadowDepthCubeMat::ShadowDepthCubeMat()
  76. { }
  77. void ShadowDepthCubeMat::bind(const SPtr<GpuParamBlockBuffer>& shadowParams,
  78. const SPtr<GpuParamBlockBuffer>& shadowCubeMatrices)
  79. {
  80. mParams->setParamBlockBuffer("ShadowParams", shadowParams);
  81. mParams->setParamBlockBuffer("ShadowCubeMatrices", shadowCubeMatrices);
  82. RenderAPI::instance().setGraphicsPipeline(mGfxPipeline);
  83. RenderAPI::instance().setStencilRef(mStencilRef);
  84. }
  85. void ShadowDepthCubeMat::setPerObjectBuffer(const SPtr<GpuParamBlockBuffer>& perObjectParams,
  86. const SPtr<GpuParamBlockBuffer>& shadowCubeMasks)
  87. {
  88. mParams->setParamBlockBuffer("PerObject", perObjectParams);
  89. mParams->setParamBlockBuffer("ShadowCubeMasks", shadowCubeMasks);
  90. RenderAPI::instance().setGpuParams(mParams);
  91. }
  92. ShadowDepthCubeMat* ShadowDepthCubeMat::getVariation(bool skinned, bool morph)
  93. {
  94. if(skinned)
  95. {
  96. if(morph)
  97. return get(getVariation<true, true>());
  98. return get(getVariation<true, false>());
  99. }
  100. else
  101. {
  102. if(morph)
  103. return get(getVariation<false, true>());
  104. return get(getVariation<false, false>());
  105. }
  106. }
  107. ShadowProjectParamsDef gShadowProjectParamsDef;
  108. ShadowProjectVertParamsDef gShadowProjectVertParamsDef;
  109. ShadowProjectStencilMat::ShadowProjectStencilMat()
  110. {
  111. mVertParams = gShadowProjectVertParamsDef.createBuffer();
  112. if(mParams->hasParamBlock(GPT_VERTEX_PROGRAM, "VertParams"))
  113. mParams->setParamBlockBuffer(GPT_VERTEX_PROGRAM, "VertParams", mVertParams);
  114. }
  115. void ShadowProjectStencilMat::bind(const SPtr<GpuParamBlockBuffer>& perCamera)
  116. {
  117. Vector4 lightPosAndScale(0, 0, 0, 1);
  118. gShadowProjectVertParamsDef.gPositionAndScale.set(mVertParams, lightPosAndScale);
  119. mParams->setParamBlockBuffer("PerCamera", perCamera);
  120. RendererMaterial::bind();
  121. }
  122. ShadowProjectStencilMat* ShadowProjectStencilMat::getVariation(bool directional, bool useZFailStencil)
  123. {
  124. if(directional)
  125. return get(getVariation<true, true>());
  126. else
  127. {
  128. if (useZFailStencil)
  129. return get(getVariation<false, true>());
  130. else
  131. return get(getVariation<false, false>());
  132. }
  133. }
  134. ShadowProjectMat::ShadowProjectMat()
  135. : mGBufferParams(GPT_FRAGMENT_PROGRAM, mParams)
  136. {
  137. mParams->getTextureParam(GPT_FRAGMENT_PROGRAM, "gShadowTex", mShadowMapParam);
  138. if(mParams->hasSamplerState(GPT_FRAGMENT_PROGRAM, "gShadowSampler"))
  139. mParams->getSamplerStateParam(GPT_FRAGMENT_PROGRAM, "gShadowSampler", mShadowSamplerParam);
  140. else
  141. mParams->getSamplerStateParam(GPT_FRAGMENT_PROGRAM, "gShadowTex", mShadowSamplerParam);
  142. SAMPLER_STATE_DESC desc;
  143. desc.minFilter = FO_POINT;
  144. desc.magFilter = FO_POINT;
  145. desc.mipFilter = FO_POINT;
  146. desc.addressMode.u = TAM_CLAMP;
  147. desc.addressMode.v = TAM_CLAMP;
  148. desc.addressMode.w = TAM_CLAMP;
  149. mSamplerState = SamplerState::create(desc);
  150. mVertParams = gShadowProjectVertParamsDef.createBuffer();
  151. if(mParams->hasParamBlock(GPT_VERTEX_PROGRAM, "VertParams"))
  152. mParams->setParamBlockBuffer(GPT_VERTEX_PROGRAM, "VertParams", mVertParams);
  153. }
  154. void ShadowProjectMat::bind(const ShadowProjectParams& params)
  155. {
  156. Vector4 lightPosAndScale(Vector3(0.0f, 0.0f, 0.0f), 1.0f);
  157. gShadowProjectVertParamsDef.gPositionAndScale.set(mVertParams, lightPosAndScale);
  158. mGBufferParams.bind(params.gbuffer);
  159. mShadowMapParam.set(params.shadowMap);
  160. mShadowSamplerParam.set(mSamplerState);
  161. mParams->setParamBlockBuffer("Params", params.shadowParams);
  162. mParams->setParamBlockBuffer("PerCamera", params.perCamera);
  163. RendererMaterial::bind();
  164. }
  165. ShadowProjectMat* ShadowProjectMat::getVariation(UINT32 quality, bool directional, bool MSAA)
  166. {
  167. #define BIND_MAT(QUALITY) \
  168. { \
  169. if(directional) \
  170. if (MSAA) \
  171. return get(getVariation<QUALITY, true, true>()); \
  172. else \
  173. return get(getVariation<QUALITY, true, false>()); \
  174. else \
  175. if (MSAA) \
  176. return get(getVariation<QUALITY, false, true>()); \
  177. else \
  178. return get(getVariation<QUALITY, false, false>()); \
  179. }
  180. if(quality <= 1)
  181. BIND_MAT(1)
  182. else if(quality == 2)
  183. BIND_MAT(2)
  184. else if(quality == 3)
  185. BIND_MAT(3)
  186. else // 4 or higher
  187. BIND_MAT(4)
  188. #undef BIND_MAT
  189. }
  190. ShadowProjectOmniParamsDef gShadowProjectOmniParamsDef;
  191. ShadowProjectOmniMat::ShadowProjectOmniMat()
  192. : mGBufferParams(GPT_FRAGMENT_PROGRAM, mParams)
  193. {
  194. mParams->getTextureParam(GPT_FRAGMENT_PROGRAM, "gShadowCubeTex", mShadowMapParam);
  195. if(mParams->hasSamplerState(GPT_FRAGMENT_PROGRAM, "gShadowCubeSampler"))
  196. mParams->getSamplerStateParam(GPT_FRAGMENT_PROGRAM, "gShadowCubeSampler", mShadowSamplerParam);
  197. else
  198. mParams->getSamplerStateParam(GPT_FRAGMENT_PROGRAM, "gShadowCubeTex", mShadowSamplerParam);
  199. SAMPLER_STATE_DESC desc;
  200. desc.minFilter = FO_LINEAR;
  201. desc.magFilter = FO_LINEAR;
  202. desc.mipFilter = FO_POINT;
  203. desc.addressMode.u = TAM_CLAMP;
  204. desc.addressMode.v = TAM_CLAMP;
  205. desc.addressMode.w = TAM_CLAMP;
  206. desc.comparisonFunc = CMPF_GREATER_EQUAL;
  207. mSamplerState = SamplerState::create(desc);
  208. mVertParams = gShadowProjectVertParamsDef.createBuffer();
  209. if(mParams->hasParamBlock(GPT_VERTEX_PROGRAM, "VertParams"))
  210. mParams->setParamBlockBuffer(GPT_VERTEX_PROGRAM, "VertParams", mVertParams);
  211. }
  212. void ShadowProjectOmniMat::bind(const ShadowProjectParams& params)
  213. {
  214. Vector4 lightPosAndScale(params.light.getTransform().getPosition(), params.light.getAttenuationRadius());
  215. gShadowProjectVertParamsDef.gPositionAndScale.set(mVertParams, lightPosAndScale);
  216. mGBufferParams.bind(params.gbuffer);
  217. mShadowMapParam.set(params.shadowMap);
  218. mShadowSamplerParam.set(mSamplerState);
  219. mParams->setParamBlockBuffer("Params", params.shadowParams);
  220. mParams->setParamBlockBuffer("PerCamera", params.perCamera);
  221. RendererMaterial::bind();
  222. }
  223. ShadowProjectOmniMat* ShadowProjectOmniMat::getVariation(UINT32 quality, bool inside, bool MSAA)
  224. {
  225. #define BIND_MAT(QUALITY) \
  226. { \
  227. if(inside) \
  228. if (MSAA) \
  229. return get(getVariation<QUALITY, true, true>()); \
  230. else \
  231. return get(getVariation<QUALITY, true, false>()); \
  232. else \
  233. if (MSAA) \
  234. return get(getVariation<QUALITY, false, true>()); \
  235. else \
  236. return get(getVariation<QUALITY, false, false>()); \
  237. }
  238. if(quality <= 1)
  239. BIND_MAT(1)
  240. else if(quality == 2)
  241. BIND_MAT(2)
  242. else if(quality == 3)
  243. BIND_MAT(3)
  244. else // 4 or higher
  245. BIND_MAT(4)
  246. #undef BIND_MAT
  247. }
  248. void ShadowInfo::updateNormArea(UINT32 atlasSize)
  249. {
  250. normArea.x = area.x / (float)atlasSize;
  251. normArea.y = area.y / (float)atlasSize;
  252. normArea.width = area.width / (float)atlasSize;
  253. normArea.height = area.height / (float)atlasSize;
  254. }
  255. ShadowMapAtlas::ShadowMapAtlas(UINT32 size)
  256. : mLayout(0, 0, size, size, true), mLastUsedCounter(0)
  257. {
  258. mAtlas = GpuResourcePool::instance().get(
  259. POOLED_RENDER_TEXTURE_DESC::create2D(SHADOW_MAP_FORMAT, size, size, TU_DEPTHSTENCIL));
  260. }
  261. bool ShadowMapAtlas::addMap(UINT32 size, Rect2I& area, UINT32 border)
  262. {
  263. UINT32 sizeWithBorder = size + border * 2;
  264. UINT32 x, y;
  265. if (!mLayout.addElement(sizeWithBorder, sizeWithBorder, x, y))
  266. return false;
  267. area.width = area.height = size;
  268. area.x = x + border;
  269. area.y = y + border;
  270. mLastUsedCounter = 0;
  271. return true;
  272. }
  273. void ShadowMapAtlas::clear()
  274. {
  275. mLayout.clear();
  276. mLastUsedCounter++;
  277. }
  278. bool ShadowMapAtlas::isEmpty() const
  279. {
  280. return mLayout.isEmpty();
  281. }
  282. SPtr<Texture> ShadowMapAtlas::getTexture() const
  283. {
  284. return mAtlas->texture;
  285. }
  286. SPtr<RenderTexture> ShadowMapAtlas::getTarget() const
  287. {
  288. return mAtlas->renderTexture;
  289. }
  290. ShadowMapBase::ShadowMapBase(UINT32 size)
  291. : mSize(size), mIsUsed(false), mLastUsedCounter (0)
  292. { }
  293. SPtr<Texture> ShadowMapBase::getTexture() const
  294. {
  295. return mShadowMap->texture;
  296. }
  297. ShadowCubemap::ShadowCubemap(UINT32 size)
  298. :ShadowMapBase(size)
  299. {
  300. mShadowMap = GpuResourcePool::instance().get(
  301. POOLED_RENDER_TEXTURE_DESC::createCube(SHADOW_MAP_FORMAT, size, size, TU_DEPTHSTENCIL));
  302. }
  303. SPtr<RenderTexture> ShadowCubemap::getTarget() const
  304. {
  305. return mShadowMap->renderTexture;
  306. }
  307. ShadowCascadedMap::ShadowCascadedMap(UINT32 size)
  308. :ShadowMapBase(size)
  309. {
  310. mShadowMap = GpuResourcePool::instance().get(POOLED_RENDER_TEXTURE_DESC::create2D(SHADOW_MAP_FORMAT, size, size,
  311. TU_DEPTHSTENCIL, 0, false, NUM_CASCADE_SPLITS));
  312. RENDER_TEXTURE_DESC rtDesc;
  313. rtDesc.depthStencilSurface.texture = mShadowMap->texture;
  314. rtDesc.depthStencilSurface.numFaces = 1;
  315. for (UINT32 i = 0; i < NUM_CASCADE_SPLITS; ++i)
  316. {
  317. rtDesc.depthStencilSurface.face = i;
  318. mTargets[i] = RenderTexture::create(rtDesc);
  319. }
  320. }
  321. SPtr<RenderTexture> ShadowCascadedMap::getTarget(UINT32 cascadeIdx) const
  322. {
  323. return mTargets[cascadeIdx];
  324. }
  325. /**
  326. * Provides a common way for all types of shadow depth rendering to render the relevant objects into the depth map.
  327. * Iterates over all relevant objects in the scene, binds the relevant materials and renders the objects into the depth
  328. * map.
  329. */
  330. class ShadowRenderQueue
  331. {
  332. public:
  333. struct Command
  334. {
  335. Command()
  336. { }
  337. Command(BeastRenderableElement* element)
  338. :element(element), isElement(true)
  339. { }
  340. union
  341. {
  342. BeastRenderableElement* element;
  343. RendererObject* renderable;
  344. };
  345. bool isElement : 1;
  346. UINT32 mask : 6;
  347. };
  348. template<class Options>
  349. static void execute(RendererScene& scene, const FrameInfo& frameInfo, const Options& opt)
  350. {
  351. static_assert((UINT32)RenderableAnimType::Count == 4, "RenderableAnimType is expected to have four sequential entries.");
  352. const SceneInfo& sceneInfo = scene.getSceneInfo();
  353. bs_frame_mark();
  354. {
  355. FrameVector<Command> commands[4];
  356. // Make a list of relevant renderables and prepare them for rendering
  357. for (UINT32 i = 0; i < sceneInfo.renderables.size(); i++)
  358. {
  359. const Sphere& bounds = sceneInfo.renderableCullInfos[i].bounds.getSphere();
  360. if (!opt.intersects(bounds))
  361. continue;
  362. scene.prepareRenderable(i, frameInfo);
  363. Command renderableCommand;
  364. renderableCommand.mask = 0;
  365. RendererObject* renderable = sceneInfo.renderables[i];
  366. renderableCommand.isElement = false;
  367. renderableCommand.renderable = renderable;
  368. opt.prepare(renderableCommand, bounds);
  369. bool renderableBound[4];
  370. bs_zero_out(renderableBound);
  371. for (auto& element : renderable->elements)
  372. {
  373. UINT32 arrayIdx = (int)element.animType;
  374. if (!renderableBound[arrayIdx])
  375. {
  376. commands[arrayIdx].push_back(renderableCommand);
  377. renderableBound[arrayIdx] = true;
  378. }
  379. commands[arrayIdx].push_back(Command(&element));
  380. }
  381. }
  382. static const ShaderVariation* VAR_LOOKUP[4] =
  383. {
  384. &SVar_Static, &SVar_Skinned, &SVar_Morph, &SVar_SkinnedMorph
  385. };
  386. for (UINT32 i = 0; i < (UINT32)RenderableAnimType::Count; i++)
  387. {
  388. opt.bindMaterial(*VAR_LOOKUP[i]);
  389. for (auto& command : commands[i])
  390. {
  391. if (command.isElement)
  392. {
  393. const BeastRenderableElement& element = *command.element;
  394. if (element.morphVertexDeclaration == nullptr)
  395. gRendererUtility().draw(element.mesh, element.subMesh);
  396. else
  397. gRendererUtility().drawMorph(element.mesh, element.subMesh, element.morphShapeBuffer,
  398. element.morphVertexDeclaration);
  399. }
  400. else
  401. opt.bindRenderable(command);
  402. }
  403. }
  404. }
  405. bs_frame_clear();
  406. }
  407. };
  408. /** Specialization used for ShadowRenderQueue when rendering cube (omnidirectional) shadow maps. */
  409. struct ShadowRenderQueueCubeOptions
  410. {
  411. ShadowRenderQueueCubeOptions(
  412. const ConvexVolume (&frustums)[6],
  413. const ConvexVolume& boundingVolume,
  414. const SPtr<GpuParamBlockBuffer>& shadowParamsBuffer,
  415. const SPtr<GpuParamBlockBuffer>& shadowCubeMatricesBuffer,
  416. const SPtr<GpuParamBlockBuffer>& shadowCubeMasksBuffer)
  417. : frustums(frustums), boundingVolume(boundingVolume), shadowParamsBuffer(shadowParamsBuffer)
  418. , shadowCubeMatricesBuffer(shadowCubeMatricesBuffer), shadowCubeMasksBuffer(shadowCubeMasksBuffer)
  419. { }
  420. bool intersects(const Sphere& bounds) const
  421. {
  422. return boundingVolume.intersects(bounds);
  423. }
  424. void prepare(ShadowRenderQueue::Command& command, const Sphere& bounds) const
  425. {
  426. for (UINT32 j = 0; j < 6; j++)
  427. command.mask |= (frustums[j].intersects(bounds) ? 1 : 0) << j;
  428. }
  429. void bindMaterial(const ShaderVariation& variation) const
  430. {
  431. material = ShadowDepthCubeMat::get(variation);
  432. material->bind(shadowParamsBuffer, shadowCubeMatricesBuffer);
  433. }
  434. void bindRenderable(ShadowRenderQueue::Command& command) const
  435. {
  436. RendererObject* renderable = command.renderable;
  437. for (UINT32 j = 0; j < 6; j++)
  438. gShadowCubeMasksDef.gFaceMasks.set(shadowCubeMasksBuffer, (command.mask & (1 << j)), j);
  439. material->setPerObjectBuffer(renderable->perObjectParamBuffer, shadowCubeMasksBuffer);
  440. }
  441. const ConvexVolume (&frustums)[6];
  442. const ConvexVolume& boundingVolume;
  443. const SPtr<GpuParamBlockBuffer>& shadowParamsBuffer;
  444. const SPtr<GpuParamBlockBuffer>& shadowCubeMatricesBuffer;
  445. const SPtr<GpuParamBlockBuffer>& shadowCubeMasksBuffer;
  446. mutable ShadowDepthCubeMat* material = nullptr;
  447. };
  448. /** Specialization used for ShadowRenderQueue when rendering spot light shadow maps. */
  449. struct ShadowRenderQueueSpotOptions
  450. {
  451. ShadowRenderQueueSpotOptions(
  452. const ConvexVolume& boundingVolume,
  453. const SPtr<GpuParamBlockBuffer>& shadowParamsBuffer)
  454. : boundingVolume(boundingVolume), shadowParamsBuffer(shadowParamsBuffer)
  455. { }
  456. bool intersects(const Sphere& bounds) const
  457. {
  458. return boundingVolume.intersects(bounds);
  459. }
  460. void prepare(ShadowRenderQueue::Command& command, const Sphere& bounds) const
  461. {
  462. }
  463. void bindMaterial(const ShaderVariation& variation) const
  464. {
  465. material = ShadowDepthNormalMat::get(variation);
  466. material->bind(shadowParamsBuffer);
  467. }
  468. void bindRenderable(ShadowRenderQueue::Command& command) const
  469. {
  470. RendererObject* renderable = command.renderable;
  471. material->setPerObjectBuffer(renderable->perObjectParamBuffer);
  472. }
  473. const ConvexVolume& boundingVolume;
  474. const SPtr<GpuParamBlockBuffer>& shadowParamsBuffer;
  475. mutable ShadowDepthNormalMat* material = nullptr;
  476. };
  477. /** Specialization used for ShadowRenderQueue when rendering directional light shadow maps. */
  478. struct ShadowRenderQueueDirOptions
  479. {
  480. ShadowRenderQueueDirOptions(
  481. const ConvexVolume& boundingVolume,
  482. const SPtr<GpuParamBlockBuffer>& shadowParamsBuffer)
  483. : boundingVolume(boundingVolume), shadowParamsBuffer(shadowParamsBuffer)
  484. { }
  485. bool intersects(const Sphere& bounds) const
  486. {
  487. return boundingVolume.intersects(bounds);
  488. }
  489. void prepare(ShadowRenderQueue::Command& command, const Sphere& bounds) const
  490. {
  491. }
  492. void bindMaterial(const ShaderVariation& variation) const
  493. {
  494. material = ShadowDepthDirectionalMat::get(variation);
  495. material->bind(shadowParamsBuffer);
  496. }
  497. void bindRenderable(ShadowRenderQueue::Command& command) const
  498. {
  499. RendererObject* renderable = command.renderable;
  500. material->setPerObjectBuffer(renderable->perObjectParamBuffer);
  501. }
  502. const ConvexVolume& boundingVolume;
  503. const SPtr<GpuParamBlockBuffer>& shadowParamsBuffer;
  504. mutable ShadowDepthDirectionalMat* material = nullptr;
  505. };
  506. const UINT32 ShadowRendering::MAX_ATLAS_SIZE = 8192;
  507. const UINT32 ShadowRendering::MAX_UNUSED_FRAMES = 60;
  508. const UINT32 ShadowRendering::MIN_SHADOW_MAP_SIZE = 32;
  509. const UINT32 ShadowRendering::SHADOW_MAP_FADE_SIZE = 64;
  510. const UINT32 ShadowRendering::SHADOW_MAP_BORDER = 4;
  511. const float ShadowRendering::CASCADE_FRACTION_FADE = 0.1f;
  512. ShadowRendering::ShadowRendering(UINT32 shadowMapSize)
  513. : mShadowMapSize(shadowMapSize)
  514. {
  515. SPtr<VertexDataDesc> vertexDesc = VertexDataDesc::create();
  516. vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION);
  517. mPositionOnlyVD = VertexDeclaration::create(vertexDesc);
  518. // Create plane index and vertex buffers
  519. {
  520. VERTEX_BUFFER_DESC vbDesc;
  521. vbDesc.numVerts = 8;
  522. vbDesc.usage = GBU_DYNAMIC;
  523. vbDesc.vertexSize = mPositionOnlyVD->getProperties().getVertexSize(0);
  524. mPlaneVB = VertexBuffer::create(vbDesc);
  525. INDEX_BUFFER_DESC ibDesc;
  526. ibDesc.indexType = IT_32BIT;
  527. ibDesc.numIndices = 12;
  528. mPlaneIB = IndexBuffer::create(ibDesc);
  529. UINT32 indices[] =
  530. {
  531. // Far plane, back facing
  532. 4, 7, 6,
  533. 4, 6, 5,
  534. // Near plane, front facing
  535. 0, 1, 2,
  536. 0, 2, 3
  537. };
  538. mPlaneIB->writeData(0, sizeof(indices), indices);
  539. }
  540. // Create frustum index and vertex buffers
  541. {
  542. VERTEX_BUFFER_DESC vbDesc;
  543. vbDesc.numVerts = 8;
  544. vbDesc.usage = GBU_DYNAMIC;
  545. vbDesc.vertexSize = mPositionOnlyVD->getProperties().getVertexSize(0);
  546. mFrustumVB = VertexBuffer::create(vbDesc);
  547. INDEX_BUFFER_DESC ibDesc;
  548. ibDesc.indexType = IT_32BIT;
  549. ibDesc.numIndices = 36;
  550. mFrustumIB = IndexBuffer::create(ibDesc);
  551. mFrustumIB->writeData(0, sizeof(AABox::CUBE_INDICES), AABox::CUBE_INDICES);
  552. }
  553. }
  554. void ShadowRendering::setShadowMapSize(UINT32 size)
  555. {
  556. if (mShadowMapSize == size)
  557. return;
  558. mCascadedShadowMaps.clear();
  559. mDynamicShadowMaps.clear();
  560. mShadowCubemaps.clear();
  561. }
  562. void ShadowRendering::renderShadowMaps(RendererScene& scene, const RendererViewGroup& viewGroup,
  563. const FrameInfo& frameInfo)
  564. {
  565. // Note: Currently all shadows are dynamic and are rebuilt every frame. I should later added support for static
  566. // shadow maps which can be used for immovable lights. Such a light can then maintain a set of shadow maps,
  567. // one of which is static and only effects the static geometry, while the rest are per-object shadow maps used
  568. // for dynamic objects. Then only a small subset of geometry needs to be redrawn, instead of everything.
  569. // Note: Add support for per-object shadows and a way to force a renderable to use per-object shadows. This can be
  570. // used for adding high quality shadows on specific objects (e.g. important characters during cinematics).
  571. const SceneInfo& sceneInfo = scene.getSceneInfo();
  572. const VisibilityInfo& visibility = viewGroup.getVisibilityInfo();
  573. // Clear all transient data from last frame
  574. mShadowInfos.clear();
  575. mSpotLightShadows.resize(sceneInfo.spotLights.size());
  576. mRadialLightShadows.resize(sceneInfo.radialLights.size());
  577. mDirectionalLightShadows.resize(sceneInfo.directionalLights.size());
  578. mSpotLightShadowOptions.clear();
  579. mRadialLightShadowOptions.clear();
  580. // Clear all dynamic light atlases
  581. for (auto& entry : mCascadedShadowMaps)
  582. entry.clear();
  583. for (auto& entry : mDynamicShadowMaps)
  584. entry.clear();
  585. for (auto& entry : mShadowCubemaps)
  586. entry.clear();
  587. // Determine shadow map sizes and sort them
  588. UINT32 shadowInfoCount = 0;
  589. for (UINT32 i = 0; i < (UINT32)sceneInfo.spotLights.size(); ++i)
  590. {
  591. const RendererLight& light = sceneInfo.spotLights[i];
  592. mSpotLightShadows[i].startIdx = shadowInfoCount;
  593. mSpotLightShadows[i].numShadows = 0;
  594. // Note: I'm using visibility across all views, while I could be using visibility for every view individually,
  595. // if I kept that information somewhere
  596. if (!light.internal->getCastsShadow() || !visibility.spotLights[i])
  597. continue;
  598. ShadowMapOptions options;
  599. options.lightIdx = i;
  600. float maxFadePercent;
  601. calcShadowMapProperties(light, viewGroup, SHADOW_MAP_BORDER, options.mapSize, options.fadePercents, maxFadePercent);
  602. // Don't render shadow maps that will end up nearly completely faded out
  603. if (maxFadePercent < 0.005f)
  604. continue;
  605. mSpotLightShadowOptions.push_back(options);
  606. shadowInfoCount++; // For now, always a single fully dynamic shadow for a single light, but that may change
  607. }
  608. for (UINT32 i = 0; i < (UINT32)sceneInfo.radialLights.size(); ++i)
  609. {
  610. const RendererLight& light = sceneInfo.radialLights[i];
  611. mRadialLightShadows[i].startIdx = shadowInfoCount;
  612. mRadialLightShadows[i].numShadows = 0;
  613. // Note: I'm using visibility across all views, while I could be using visibility for every view individually,
  614. // if I kept that information somewhere
  615. if (!light.internal->getCastsShadow() || !visibility.radialLights[i])
  616. continue;
  617. ShadowMapOptions options;
  618. options.lightIdx = i;
  619. float maxFadePercent;
  620. calcShadowMapProperties(light, viewGroup, 0, options.mapSize, options.fadePercents, maxFadePercent);
  621. // Don't render shadow maps that will end up nearly completely faded out
  622. if (maxFadePercent < 0.005f)
  623. continue;
  624. mRadialLightShadowOptions.push_back(options);
  625. shadowInfoCount++; // For now, always a single fully dynamic shadow for a single light, but that may change
  626. }
  627. // Sort spot lights by size so they fit neatly in the texture atlas
  628. std::sort(mSpotLightShadowOptions.begin(), mSpotLightShadowOptions.end(),
  629. [](const ShadowMapOptions& a, const ShadowMapOptions& b) { return a.mapSize > b.mapSize; } );
  630. // Reserve space for shadow infos
  631. mShadowInfos.resize(shadowInfoCount);
  632. // Deallocate unused textures (must be done before rendering shadows, in order to ensure indices don't change)
  633. for(auto iter = mDynamicShadowMaps.begin(); iter != mDynamicShadowMaps.end(); ++iter)
  634. {
  635. if(iter->getLastUsedCounter() >= MAX_UNUSED_FRAMES)
  636. {
  637. // These are always populated in order, so we can assume all following atlases are also empty
  638. mDynamicShadowMaps.erase(iter, mDynamicShadowMaps.end());
  639. break;
  640. }
  641. }
  642. for(auto iter = mCascadedShadowMaps.begin(); iter != mCascadedShadowMaps.end();)
  643. {
  644. if (iter->getLastUsedCounter() >= MAX_UNUSED_FRAMES)
  645. iter = mCascadedShadowMaps.erase(iter);
  646. else
  647. ++iter;
  648. }
  649. for(auto iter = mShadowCubemaps.begin(); iter != mShadowCubemaps.end();)
  650. {
  651. if (iter->getLastUsedCounter() >= MAX_UNUSED_FRAMES)
  652. iter = mShadowCubemaps.erase(iter);
  653. else
  654. ++iter;
  655. }
  656. // Render shadow maps
  657. for (UINT32 i = 0; i < (UINT32)sceneInfo.directionalLights.size(); ++i)
  658. {
  659. const RendererLight& light = sceneInfo.directionalLights[i];
  660. if (!light.internal->getCastsShadow())
  661. return;
  662. UINT32 numViews = viewGroup.getNumViews();
  663. mDirectionalLightShadows[i].viewShadows.resize(numViews);
  664. for (UINT32 j = 0; j < numViews; ++j)
  665. renderCascadedShadowMaps(*viewGroup.getView(j), i, scene, frameInfo);
  666. }
  667. for(auto& entry : mSpotLightShadowOptions)
  668. {
  669. UINT32 lightIdx = entry.lightIdx;
  670. renderSpotShadowMap(sceneInfo.spotLights[lightIdx], entry, scene, frameInfo);
  671. }
  672. for (auto& entry : mRadialLightShadowOptions)
  673. {
  674. UINT32 lightIdx = entry.lightIdx;
  675. renderRadialShadowMap(sceneInfo.radialLights[lightIdx], entry, scene, frameInfo);
  676. }
  677. }
  678. /**
  679. * Generates a frustum from the provided view-projection matrix.
  680. *
  681. * @param[in] invVP Inverse of the view-projection matrix to use for generating the frustum.
  682. * @param[out] worldFrustum Generated frustum planes, in world space.
  683. * @return Individual vertices of the frustum corners, in world space. Ordered using the
  684. * AABox::CornerEnum.
  685. */
  686. std::array<Vector3, 8> getFrustum(const Matrix4& invVP, ConvexVolume& worldFrustum)
  687. {
  688. std::array<Vector3, 8> output;
  689. RenderAPI& rapi = RenderAPI::instance();
  690. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  691. float flipY = 1.0f;
  692. if (rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown))
  693. flipY = -1.0f;
  694. AABox frustumCube(
  695. Vector3(-1, -1 * flipY, rapiInfo.getMinimumDepthInputValue()),
  696. Vector3(1, 1 * flipY, rapiInfo.getMaximumDepthInputValue())
  697. );
  698. for(size_t i = 0; i < output.size(); i++)
  699. {
  700. Vector3 corner = frustumCube.getCorner((AABox::Corner)i);
  701. output[i] = invVP.multiply(corner);
  702. }
  703. Vector<Plane> planes(6);
  704. planes[FRUSTUM_PLANE_NEAR] = Plane(output[AABox::NEAR_LEFT_BOTTOM], output[AABox::NEAR_RIGHT_BOTTOM], output[AABox::NEAR_RIGHT_TOP]);
  705. planes[FRUSTUM_PLANE_FAR] = Plane(output[AABox::FAR_LEFT_BOTTOM], output[AABox::FAR_LEFT_TOP], output[AABox::FAR_RIGHT_TOP]);
  706. planes[FRUSTUM_PLANE_LEFT] = Plane(output[AABox::NEAR_LEFT_BOTTOM], output[AABox::NEAR_LEFT_TOP], output[AABox::FAR_LEFT_TOP]);
  707. planes[FRUSTUM_PLANE_RIGHT] = Plane(output[AABox::FAR_RIGHT_TOP], output[AABox::NEAR_RIGHT_TOP], output[AABox::NEAR_RIGHT_BOTTOM]);
  708. planes[FRUSTUM_PLANE_TOP] = Plane(output[AABox::NEAR_LEFT_TOP], output[AABox::NEAR_RIGHT_TOP], output[AABox::FAR_RIGHT_TOP]);
  709. planes[FRUSTUM_PLANE_BOTTOM] = Plane(output[AABox::NEAR_LEFT_BOTTOM], output[AABox::FAR_LEFT_BOTTOM], output[AABox::FAR_RIGHT_BOTTOM]);
  710. worldFrustum = ConvexVolume(planes);
  711. return output;
  712. }
  713. /**
  714. * Converts a point in mixed space (clip_x, clip_y, view_z, view_w) to UV coordinates on a shadow map (x, y),
  715. * and normalized linear depth from the shadow caster's perspective (z).
  716. */
  717. Matrix4 createMixedToShadowUVMatrix(const Matrix4& viewP, const Matrix4& viewInvVP, const Rect2& shadowMapArea,
  718. float depthScale, float depthOffset, const Matrix4& shadowViewProj)
  719. {
  720. // Projects a point from (clip_x, clip_y, view_z, view_w) into clip space
  721. Matrix4 mixedToShadow = Matrix4::IDENTITY;
  722. mixedToShadow[2][2] = viewP[2][2];
  723. mixedToShadow[2][3] = viewP[2][3];
  724. mixedToShadow[3][2] = viewP[3][2];
  725. mixedToShadow[3][3] = 0.0f;
  726. // Projects a point in clip space back to homogeneus world space
  727. mixedToShadow = viewInvVP * mixedToShadow;
  728. // Projects a point in world space to shadow clip space
  729. mixedToShadow = shadowViewProj * mixedToShadow;
  730. // Convert shadow clip space coordinates to UV coordinates relative to the shadow map rectangle, and normalize
  731. // depth
  732. RenderAPI& rapi = RenderAPI::instance();
  733. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  734. float flipY = -1.0f;
  735. // Either of these flips the Y axis, but if they're both true they cancel out
  736. if (rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp) ^ rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown))
  737. flipY = -flipY;
  738. Matrix4 shadowMapTfrm
  739. (
  740. shadowMapArea.width * 0.5f, 0, 0, shadowMapArea.x + 0.5f * shadowMapArea.width,
  741. 0, flipY * shadowMapArea.height * 0.5f, 0, shadowMapArea.y + 0.5f * shadowMapArea.height,
  742. 0, 0, depthScale, depthOffset,
  743. 0, 0, 0, 1
  744. );
  745. return shadowMapTfrm * mixedToShadow;
  746. }
  747. void ShadowRendering::renderShadowOcclusion(const RendererView& view, UINT32 shadowQuality,
  748. const RendererLight& rendererLight, GBufferTextures gbuffer) const
  749. {
  750. const Light* light = rendererLight.internal;
  751. UINT32 lightIdx = light->getRendererId();
  752. auto viewProps = view.getProperties();
  753. const Matrix4& viewP = viewProps.projTransform;
  754. Matrix4 viewInvVP = viewProps.viewProjTransform.inverse();
  755. SPtr<GpuParamBlockBuffer> perViewBuffer = view.getPerViewBuffer();
  756. RenderAPI& rapi = RenderAPI::instance();
  757. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  758. // TODO - Calculate and set a scissor rectangle for the light
  759. SPtr<GpuParamBlockBuffer> shadowParamBuffer = gShadowProjectParamsDef.createBuffer();
  760. SPtr<GpuParamBlockBuffer> shadowOmniParamBuffer = gShadowProjectOmniParamsDef.createBuffer();
  761. UINT32 viewIdx = view.getViewIdx();
  762. Vector<const ShadowInfo*> shadowInfos;
  763. if(light->getType() == LightType::Radial)
  764. {
  765. const LightShadows& shadows = mRadialLightShadows[lightIdx];
  766. for(UINT32 i = 0; i < shadows.numShadows; ++i)
  767. {
  768. UINT32 shadowIdx = shadows.startIdx + i;
  769. const ShadowInfo& shadowInfo = mShadowInfos[shadowIdx];
  770. if (shadowInfo.fadePerView[viewIdx] < 0.005f)
  771. continue;
  772. for(UINT32 j = 0; j < 6; j++)
  773. gShadowProjectOmniParamsDef.gFaceVPMatrices.set(shadowOmniParamBuffer, shadowInfo.shadowVPTransforms[j], j);
  774. gShadowProjectOmniParamsDef.gDepthBias.set(shadowOmniParamBuffer, shadowInfo.depthBias);
  775. gShadowProjectOmniParamsDef.gFadePercent.set(shadowOmniParamBuffer, shadowInfo.fadePerView[viewIdx]);
  776. gShadowProjectOmniParamsDef.gInvResolution.set(shadowOmniParamBuffer, 1.0f / shadowInfo.area.width);
  777. const Transform& tfrm = light->getTransform();
  778. Vector4 lightPosAndRadius(tfrm.getPosition(), light->getAttenuationRadius());
  779. gShadowProjectOmniParamsDef.gLightPosAndRadius.set(shadowOmniParamBuffer, lightPosAndRadius);
  780. // Reduce shadow quality based on shadow map resolution for spot lights
  781. UINT32 effectiveShadowQuality = getShadowQuality(shadowQuality, shadowInfo.area.width, 2);
  782. // Check if viewer is inside the light bounds
  783. //// Expand the light bounds slightly to handle the case when the near plane is intersecting the light volume
  784. float lightRadius = light->getAttenuationRadius() + viewProps.nearPlane * 3.0f;
  785. bool viewerInsideVolume = (tfrm.getPosition() - viewProps.viewOrigin).length() < lightRadius;
  786. SPtr<Texture> shadowMap = mShadowCubemaps[shadowInfo.textureIdx].getTexture();
  787. ShadowProjectParams shadowParams(*light, shadowMap, shadowOmniParamBuffer, perViewBuffer, gbuffer);
  788. ShadowProjectOmniMat* mat = ShadowProjectOmniMat::getVariation(effectiveShadowQuality, viewerInsideVolume,
  789. viewProps.numSamples > 1);
  790. mat->bind(shadowParams);
  791. gRendererUtility().draw(gRendererUtility().getSphereStencil());
  792. }
  793. }
  794. else // Directional & spot
  795. {
  796. shadowInfos.clear();
  797. bool isCSM = light->getType() == LightType::Directional;
  798. if(!isCSM)
  799. {
  800. const LightShadows& shadows = mSpotLightShadows[lightIdx];
  801. for (UINT32 i = 0; i < shadows.numShadows; ++i)
  802. {
  803. UINT32 shadowIdx = shadows.startIdx + i;
  804. const ShadowInfo& shadowInfo = mShadowInfos[shadowIdx];
  805. if (shadowInfo.fadePerView[viewIdx] < 0.005f)
  806. continue;
  807. shadowInfos.push_back(&shadowInfo);
  808. }
  809. }
  810. else // Directional
  811. {
  812. const LightShadows& shadows = mDirectionalLightShadows[lightIdx].viewShadows[viewIdx];
  813. if (shadows.numShadows > 0)
  814. {
  815. UINT32 mapIdx = shadows.startIdx;
  816. const ShadowCascadedMap& cascadedMap = mCascadedShadowMaps[mapIdx];
  817. // Render cascades in far to near order.
  818. // Note: If rendering other non-cascade maps they should be rendered after cascades.
  819. for (INT32 i = NUM_CASCADE_SPLITS - 1; i >= 0; i--)
  820. shadowInfos.push_back(&cascadedMap.getShadowInfo(i));
  821. }
  822. }
  823. for(auto& shadowInfo : shadowInfos)
  824. {
  825. float depthScale, depthOffset;
  826. // Depth range scale is already baked into the ortho projection matrix, so avoid doing it here
  827. if (isCSM)
  828. {
  829. // Need to map from NDC depth to [0, 1]
  830. depthScale = 1.0f / (rapiInfo.getMaximumDepthInputValue() - rapiInfo.getMinimumDepthInputValue());
  831. depthOffset = -rapiInfo.getMinimumDepthInputValue() * depthScale;
  832. }
  833. else
  834. {
  835. depthScale = 1.0f / shadowInfo->depthRange;
  836. depthOffset = 0.0f;
  837. }
  838. Matrix4 mixedToShadowUV = createMixedToShadowUVMatrix(viewP, viewInvVP, shadowInfo->normArea,
  839. depthScale, depthOffset, shadowInfo->shadowVPTransform);
  840. Vector2 shadowMapSize((float)shadowInfo->area.width, (float)shadowInfo->area.height);
  841. float transitionScale = getFadeTransition(*light, shadowInfo->subjectBounds.getRadius(),
  842. shadowInfo->depthRange, shadowInfo->area.width);
  843. gShadowProjectParamsDef.gFadePlaneDepth.set(shadowParamBuffer, shadowInfo->depthFade);
  844. gShadowProjectParamsDef.gMixedToShadowSpace.set(shadowParamBuffer, mixedToShadowUV);
  845. gShadowProjectParamsDef.gShadowMapSize.set(shadowParamBuffer, shadowMapSize);
  846. gShadowProjectParamsDef.gShadowMapSizeInv.set(shadowParamBuffer, 1.0f / shadowMapSize);
  847. gShadowProjectParamsDef.gSoftTransitionScale.set(shadowParamBuffer, transitionScale);
  848. if(isCSM)
  849. gShadowProjectParamsDef.gFadePercent.set(shadowParamBuffer, 1.0f);
  850. else
  851. gShadowProjectParamsDef.gFadePercent.set(shadowParamBuffer, shadowInfo->fadePerView[viewIdx]);
  852. if(shadowInfo->fadeRange == 0.0f)
  853. gShadowProjectParamsDef.gInvFadePlaneRange.set(shadowParamBuffer, 0.0f);
  854. else
  855. gShadowProjectParamsDef.gInvFadePlaneRange.set(shadowParamBuffer, 1.0f / shadowInfo->fadeRange);
  856. // Generate a stencil buffer to avoid evaluating pixels without any receiver geometry in the shadow area
  857. std::array<Vector3, 8> frustumVertices;
  858. UINT32 effectiveShadowQuality = shadowQuality;
  859. if(!isCSM)
  860. {
  861. ConvexVolume shadowFrustum;
  862. frustumVertices = getFrustum(shadowInfo->shadowVPTransform.inverse(), shadowFrustum);
  863. // Check if viewer is inside the frustum. Frustum is slightly expanded so that if the near plane is
  864. // intersecting the shadow frustum, it is counted as inside. This needs to be conservative as the code
  865. // for handling viewer outside the frustum will not properly render intersections with the near plane.
  866. bool viewerInsideFrustum = shadowFrustum.contains(viewProps.viewOrigin, viewProps.nearPlane * 3.0f);
  867. ShadowProjectStencilMat* mat = ShadowProjectStencilMat::getVariation(false, viewerInsideFrustum);
  868. mat->bind(perViewBuffer);
  869. drawFrustum(frustumVertices);
  870. // Reduce shadow quality based on shadow map resolution for spot lights
  871. effectiveShadowQuality = getShadowQuality(shadowQuality, shadowInfo->area.width, 2);
  872. }
  873. else
  874. {
  875. // Need to generate near and far planes to clip the geometry within the current CSM slice.
  876. // Note: If the render API supports built-in depth bound tests that could be used instead.
  877. Vector3 near = viewProps.projTransform.multiply(Vector3(0, 0, -shadowInfo->depthNear));
  878. Vector3 far = viewProps.projTransform.multiply(Vector3(0, 0, -shadowInfo->depthFar));
  879. ShadowProjectStencilMat* mat = ShadowProjectStencilMat::getVariation(true, true);
  880. mat->bind(perViewBuffer);
  881. drawNearFarPlanes(near.z, far.z, shadowInfo->cascadeIdx != 0);
  882. }
  883. SPtr<Texture> shadowMap;
  884. UINT32 shadowMapFace = 0;
  885. if(!isCSM)
  886. shadowMap = mDynamicShadowMaps[shadowInfo->textureIdx].getTexture();
  887. else
  888. {
  889. shadowMap = mCascadedShadowMaps[shadowInfo->textureIdx].getTexture();
  890. shadowMapFace = shadowInfo->cascadeIdx;
  891. }
  892. gShadowProjectParamsDef.gFace.set(shadowParamBuffer, (float)shadowMapFace);
  893. ShadowProjectParams shadowParams(*light, shadowMap, shadowParamBuffer, perViewBuffer, gbuffer);
  894. ShadowProjectMat* mat = ShadowProjectMat::getVariation(effectiveShadowQuality, isCSM, viewProps.numSamples > 1);
  895. mat->bind(shadowParams);
  896. if (!isCSM)
  897. drawFrustum(frustumVertices);
  898. else
  899. gRendererUtility().drawScreenQuad();
  900. }
  901. }
  902. }
  903. void ShadowRendering::renderCascadedShadowMaps(const RendererView& view, UINT32 lightIdx, RendererScene& scene,
  904. const FrameInfo& frameInfo)
  905. {
  906. UINT32 viewIdx = view.getViewIdx();
  907. LightShadows& lightShadows = mDirectionalLightShadows[lightIdx].viewShadows[viewIdx];
  908. if (!view.getRenderSettings().enableShadows)
  909. {
  910. lightShadows.startIdx = -1;
  911. lightShadows.numShadows = 0;
  912. return;
  913. }
  914. // Note: Currently I'm using spherical bounds for the cascaded frustum which might result in non-optimal usage
  915. // of the shadow map. A different approach would be to generate a bounding box and then both adjust the aspect
  916. // ratio (and therefore dimensions) of the shadow map, as well as rotate the camera so the visible area best fits
  917. // in the map. It remains to be seen if this is viable.
  918. const SceneInfo& sceneInfo = scene.getSceneInfo();
  919. const RendererLight& rendererLight = sceneInfo.directionalLights[lightIdx];
  920. Light* light = rendererLight.internal;
  921. RenderAPI& rapi = RenderAPI::instance();
  922. const Transform& tfrm = light->getTransform();
  923. Vector3 lightDir = -tfrm.getRotation().zAxis();
  924. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  925. ShadowInfo shadowInfo;
  926. shadowInfo.lightIdx = lightIdx;
  927. shadowInfo.textureIdx = -1;
  928. UINT32 mapSize = std::min(mShadowMapSize, MAX_ATLAS_SIZE);
  929. shadowInfo.area = Rect2I(0, 0, mapSize, mapSize);
  930. shadowInfo.updateNormArea(mapSize);
  931. for (UINT32 i = 0; i < (UINT32)mCascadedShadowMaps.size(); i++)
  932. {
  933. ShadowCascadedMap& shadowMap = mCascadedShadowMaps[i];
  934. if (!shadowMap.isUsed() && shadowMap.getSize() == mapSize)
  935. {
  936. shadowInfo.textureIdx = i;
  937. shadowMap.markAsUsed();
  938. break;
  939. }
  940. }
  941. if (shadowInfo.textureIdx == (UINT32)-1)
  942. {
  943. shadowInfo.textureIdx = (UINT32)mCascadedShadowMaps.size();
  944. mCascadedShadowMaps.push_back(ShadowCascadedMap(mapSize));
  945. ShadowCascadedMap& shadowMap = mCascadedShadowMaps.back();
  946. shadowMap.markAsUsed();
  947. }
  948. ShadowCascadedMap& shadowMap = mCascadedShadowMaps[shadowInfo.textureIdx];
  949. Quaternion lightRotation(BsIdentity);
  950. lightRotation.lookRotation(-tfrm.getRotation().zAxis());
  951. Matrix4 viewMat = Matrix4::view(tfrm.getPosition(), lightRotation);
  952. for (UINT32 i = 0; i < NUM_CASCADE_SPLITS; ++i)
  953. {
  954. Sphere frustumBounds;
  955. ConvexVolume cascadeCullVolume = getCSMSplitFrustum(view, -lightDir, i, NUM_CASCADE_SPLITS, frustumBounds);
  956. // Move the light at the boundary of the subject frustum, so we don't waste depth range
  957. Vector3 frustumCenterViewSpace = viewMat.multiply(frustumBounds.getCenter());
  958. float minSubjectDepth = -frustumCenterViewSpace.z - frustumBounds.getRadius();
  959. float maxSubjectDepth = minSubjectDepth + frustumBounds.getRadius() * 2.0f;
  960. shadowInfo.depthRange = maxSubjectDepth - minSubjectDepth;
  961. Vector3 offsetLightPos = tfrm.getPosition() + lightDir * minSubjectDepth;
  962. Matrix4 offsetViewMat = Matrix4::view(offsetLightPos, lightRotation);
  963. float orthoSize = frustumBounds.getRadius() * 0.5f;
  964. Matrix4 proj = Matrix4::projectionOrthographic(-orthoSize, orthoSize, orthoSize, -orthoSize, 0.0f,
  965. shadowInfo.depthRange);
  966. RenderAPI::instance().convertProjectionMatrix(proj, proj);
  967. shadowInfo.cascadeIdx = i;
  968. shadowInfo.shadowVPTransform = proj * offsetViewMat;
  969. // Determine split range
  970. float splitNear = getCSMSplitDistance(view, i, NUM_CASCADE_SPLITS);
  971. float splitFar = getCSMSplitDistance(view, i + 1, NUM_CASCADE_SPLITS);
  972. shadowInfo.depthNear = splitNear;
  973. shadowInfo.depthFade = splitFar;
  974. shadowInfo.subjectBounds = frustumBounds;
  975. if ((UINT32)(i + 1) < NUM_CASCADE_SPLITS)
  976. shadowInfo.fadeRange = CASCADE_FRACTION_FADE * (shadowInfo.depthFade - shadowInfo.depthNear);
  977. else
  978. shadowInfo.fadeRange = 0.0f;
  979. shadowInfo.depthFar = shadowInfo.depthFade + shadowInfo.fadeRange;
  980. shadowInfo.depthBias = getDepthBias(*light, frustumBounds.getRadius(), shadowInfo.depthRange, mapSize);
  981. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, shadowInfo.depthBias);
  982. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / shadowInfo.depthRange);
  983. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, shadowInfo.shadowVPTransform);
  984. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  985. rapi.setRenderTarget(shadowMap.getTarget(i));
  986. rapi.clearRenderTarget(FBT_DEPTH);
  987. ShadowDepthDirectionalMat* depthDirMat = ShadowDepthDirectionalMat::get();
  988. depthDirMat->bind(shadowParamsBuffer);
  989. // Render all renderables into the shadow map
  990. ShadowRenderQueueDirOptions spotOptions(
  991. cascadeCullVolume,
  992. shadowParamsBuffer);
  993. ShadowRenderQueue::execute(scene, frameInfo, spotOptions);
  994. shadowMap.setShadowInfo(i, shadowInfo);
  995. }
  996. lightShadows.startIdx = shadowInfo.textureIdx;
  997. lightShadows.numShadows = 1;
  998. }
  999. void ShadowRendering::renderSpotShadowMap(const RendererLight& rendererLight, const ShadowMapOptions& options,
  1000. RendererScene& scene, const FrameInfo& frameInfo)
  1001. {
  1002. Light* light = rendererLight.internal;
  1003. const SceneInfo& sceneInfo = scene.getSceneInfo();
  1004. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  1005. ShadowInfo mapInfo;
  1006. mapInfo.fadePerView = options.fadePercents;
  1007. mapInfo.lightIdx = options.lightIdx;
  1008. mapInfo.cascadeIdx = -1;
  1009. bool foundSpace = false;
  1010. for (UINT32 i = 0; i < (UINT32)mDynamicShadowMaps.size(); i++)
  1011. {
  1012. ShadowMapAtlas& atlas = mDynamicShadowMaps[i];
  1013. if (atlas.addMap(options.mapSize, mapInfo.area, SHADOW_MAP_BORDER))
  1014. {
  1015. mapInfo.textureIdx = i;
  1016. foundSpace = true;
  1017. break;
  1018. }
  1019. }
  1020. if (!foundSpace)
  1021. {
  1022. mapInfo.textureIdx = (UINT32)mDynamicShadowMaps.size();
  1023. mDynamicShadowMaps.push_back(ShadowMapAtlas(MAX_ATLAS_SIZE));
  1024. ShadowMapAtlas& atlas = mDynamicShadowMaps.back();
  1025. atlas.addMap(options.mapSize, mapInfo.area, SHADOW_MAP_BORDER);
  1026. }
  1027. mapInfo.updateNormArea(MAX_ATLAS_SIZE);
  1028. ShadowMapAtlas& atlas = mDynamicShadowMaps[mapInfo.textureIdx];
  1029. RenderAPI& rapi = RenderAPI::instance();
  1030. rapi.setRenderTarget(atlas.getTarget());
  1031. rapi.setViewport(mapInfo.normArea);
  1032. rapi.clearViewport(FBT_DEPTH);
  1033. mapInfo.depthNear = 0.05f;
  1034. mapInfo.depthFar = light->getAttenuationRadius();
  1035. mapInfo.depthFade = mapInfo.depthFar;
  1036. mapInfo.fadeRange = 0.0f;
  1037. mapInfo.depthRange = mapInfo.depthFar - mapInfo.depthNear;
  1038. mapInfo.depthBias = getDepthBias(*light, light->getBounds().getRadius(), mapInfo.depthRange, options.mapSize);
  1039. mapInfo.subjectBounds = light->getBounds();
  1040. Quaternion lightRotation(BsIdentity);
  1041. lightRotation.lookRotation(-light->getTransform().getRotation().zAxis());
  1042. Matrix4 view = Matrix4::view(rendererLight.getShiftedLightPosition(), lightRotation);
  1043. Matrix4 proj = Matrix4::projectionPerspective(light->getSpotAngle(), 1.0f, 0.05f, light->getAttenuationRadius());
  1044. ConvexVolume localFrustum = ConvexVolume(proj);
  1045. RenderAPI::instance().convertProjectionMatrix(proj, proj);
  1046. mapInfo.shadowVPTransform = proj * view;
  1047. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, mapInfo.depthBias);
  1048. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / mapInfo.depthRange);
  1049. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, mapInfo.shadowVPTransform);
  1050. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  1051. const Vector<Plane>& frustumPlanes = localFrustum.getPlanes();
  1052. Matrix4 worldMatrix = view.transpose();
  1053. Vector<Plane> worldPlanes(frustumPlanes.size());
  1054. UINT32 j = 0;
  1055. for (auto& plane : frustumPlanes)
  1056. {
  1057. worldPlanes[j] = worldMatrix.multiplyAffine(plane);
  1058. j++;
  1059. }
  1060. ConvexVolume worldFrustum(worldPlanes);
  1061. // Render all renderables into the shadow map
  1062. ShadowRenderQueueSpotOptions spotOptions(
  1063. worldFrustum,
  1064. shadowParamsBuffer);
  1065. ShadowRenderQueue::execute(scene, frameInfo, spotOptions);
  1066. // Restore viewport
  1067. rapi.setViewport(Rect2(0.0f, 0.0f, 1.0f, 1.0f));
  1068. LightShadows& lightShadows = mSpotLightShadows[options.lightIdx];
  1069. mShadowInfos[lightShadows.startIdx + lightShadows.numShadows] = mapInfo;
  1070. lightShadows.numShadows++;
  1071. }
  1072. void ShadowRendering::renderRadialShadowMap(const RendererLight& rendererLight,
  1073. const ShadowMapOptions& options, RendererScene& scene, const FrameInfo& frameInfo)
  1074. {
  1075. Light* light = rendererLight.internal;
  1076. const SceneInfo& sceneInfo = scene.getSceneInfo();
  1077. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  1078. SPtr<GpuParamBlockBuffer> shadowCubeMatricesBuffer = gShadowCubeMatricesDef.createBuffer();
  1079. SPtr<GpuParamBlockBuffer> shadowCubeMasksBuffer = gShadowCubeMasksDef.createBuffer();
  1080. ShadowInfo mapInfo;
  1081. mapInfo.lightIdx = options.lightIdx;
  1082. mapInfo.textureIdx = -1;
  1083. mapInfo.fadePerView = options.fadePercents;
  1084. mapInfo.cascadeIdx = -1;
  1085. mapInfo.area = Rect2I(0, 0, options.mapSize, options.mapSize);
  1086. mapInfo.updateNormArea(options.mapSize);
  1087. for (UINT32 i = 0; i < (UINT32)mShadowCubemaps.size(); i++)
  1088. {
  1089. ShadowCubemap& cubemap = mShadowCubemaps[i];
  1090. if (!cubemap.isUsed() && cubemap.getSize() == options.mapSize)
  1091. {
  1092. mapInfo.textureIdx = i;
  1093. cubemap.markAsUsed();
  1094. break;
  1095. }
  1096. }
  1097. if (mapInfo.textureIdx == (UINT32)-1)
  1098. {
  1099. mapInfo.textureIdx = (UINT32)mShadowCubemaps.size();
  1100. mShadowCubemaps.push_back(ShadowCubemap(options.mapSize));
  1101. ShadowCubemap& cubemap = mShadowCubemaps.back();
  1102. cubemap.markAsUsed();
  1103. }
  1104. ShadowCubemap& cubemap = mShadowCubemaps[mapInfo.textureIdx];
  1105. mapInfo.depthNear = 0.05f;
  1106. mapInfo.depthFar = light->getAttenuationRadius();
  1107. mapInfo.depthFade = mapInfo.depthFar;
  1108. mapInfo.fadeRange = 0.0f;
  1109. mapInfo.depthRange = mapInfo.depthFar - mapInfo.depthNear;
  1110. mapInfo.depthBias = getDepthBias(*light, light->getBounds().getRadius(), mapInfo.depthRange, options.mapSize);
  1111. mapInfo.subjectBounds = light->getBounds();
  1112. // Note: Projecting on positive Z axis, because cubemaps use a left-handed coordinate system
  1113. Matrix4 proj = Matrix4::projectionPerspective(Degree(90.0f), 1.0f, 0.05f, light->getAttenuationRadius(), true);
  1114. ConvexVolume localFrustum(proj);
  1115. RenderAPI& rapi = RenderAPI::instance();
  1116. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  1117. rapi.convertProjectionMatrix(proj, proj);
  1118. // Render cubemaps upside down if necessary
  1119. Matrix4 adjustedProj = proj;
  1120. if(rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp))
  1121. {
  1122. // All big APIs use the same cubemap sampling coordinates, as well as the same face order. But APIs that
  1123. // use bottom-up UV coordinates require the cubemap faces to be stored upside down in order to get the same
  1124. // behaviour. APIs that use an upside-down NDC Y axis have the same problem as the rendered image will be
  1125. // upside down, but this is handled by the projection matrix. If both of those are enabled, then the effect
  1126. // cancels out.
  1127. adjustedProj[1][1] = -proj[1][1];
  1128. }
  1129. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, mapInfo.depthBias);
  1130. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / mapInfo.depthRange);
  1131. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, Matrix4::IDENTITY);
  1132. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  1133. ConvexVolume frustums[6];
  1134. Vector<Plane> boundingPlanes;
  1135. for (UINT32 i = 0; i < 6; i++)
  1136. {
  1137. // Calculate view matrix
  1138. Vector3 forward;
  1139. Vector3 up = Vector3::UNIT_Y;
  1140. switch (i)
  1141. {
  1142. case CF_PositiveX:
  1143. forward = Vector3::UNIT_X;
  1144. break;
  1145. case CF_NegativeX:
  1146. forward = -Vector3::UNIT_X;
  1147. break;
  1148. case CF_PositiveY:
  1149. forward = Vector3::UNIT_Y;
  1150. up = -Vector3::UNIT_Z;
  1151. break;
  1152. case CF_NegativeY:
  1153. forward = -Vector3::UNIT_Y;
  1154. up = Vector3::UNIT_Z;
  1155. break;
  1156. case CF_PositiveZ:
  1157. forward = Vector3::UNIT_Z;
  1158. break;
  1159. case CF_NegativeZ:
  1160. forward = -Vector3::UNIT_Z;
  1161. break;
  1162. }
  1163. Vector3 right = Vector3::cross(up, forward);
  1164. Matrix3 viewRotationMat = Matrix3(right, up, forward);
  1165. Vector3 lightPos = light->getTransform().getPosition();
  1166. Matrix4 viewOffsetMat = Matrix4::translation(-lightPos);
  1167. Matrix4 view = Matrix4(viewRotationMat.transpose()) * viewOffsetMat;
  1168. mapInfo.shadowVPTransforms[i] = proj * view;
  1169. Matrix4 shadowViewProj = adjustedProj * view;
  1170. gShadowCubeMatricesDef.gFaceVPMatrices.set(shadowCubeMatricesBuffer, shadowViewProj, i);
  1171. // Calculate world frustum for culling
  1172. const Vector<Plane>& frustumPlanes = localFrustum.getPlanes();
  1173. Matrix4 worldMatrix = Matrix4::translation(lightPos) * Matrix4(viewRotationMat);
  1174. Vector<Plane> worldPlanes(frustumPlanes.size());
  1175. UINT32 j = 0;
  1176. for (auto& plane : frustumPlanes)
  1177. {
  1178. worldPlanes[j] = worldMatrix.multiplyAffine(plane);
  1179. j++;
  1180. }
  1181. frustums[i] = ConvexVolume(worldPlanes);
  1182. // Register far plane of all frustums
  1183. boundingPlanes.push_back(worldPlanes.back());
  1184. }
  1185. rapi.setRenderTarget(cubemap.getTarget());
  1186. rapi.clearRenderTarget(FBT_DEPTH);
  1187. // Render all renderables into the shadow map
  1188. ConvexVolume boundingVolume(boundingPlanes);
  1189. ShadowRenderQueueCubeOptions cubeOptions(
  1190. frustums,
  1191. boundingVolume,
  1192. shadowParamsBuffer,
  1193. shadowCubeMatricesBuffer,
  1194. shadowCubeMasksBuffer);
  1195. ShadowRenderQueue::execute(scene, frameInfo, cubeOptions);
  1196. LightShadows& lightShadows = mRadialLightShadows[options.lightIdx];
  1197. mShadowInfos[lightShadows.startIdx + lightShadows.numShadows] = mapInfo;
  1198. lightShadows.numShadows++;
  1199. }
  1200. void ShadowRendering::calcShadowMapProperties(const RendererLight& light, const RendererViewGroup& viewGroup,
  1201. UINT32 border, UINT32& size, SmallVector<float, 6>& fadePercents, float& maxFadePercent) const
  1202. {
  1203. const static float SHADOW_TEXELS_PER_PIXEL = 1.0f;
  1204. // Find a view in which the light has the largest radius
  1205. float maxMapSize = 0.0f;
  1206. maxFadePercent = 0.0f;
  1207. for (int i = 0; i < (int)viewGroup.getNumViews(); ++i)
  1208. {
  1209. const RendererView& view = *viewGroup.getView(i);
  1210. const RendererViewProperties& viewProps = view.getProperties();
  1211. const RenderSettings& viewSettings = view.getRenderSettings();
  1212. if(!viewSettings.enableShadows)
  1213. fadePercents.push_back(0.0f);
  1214. {
  1215. // Approximation for screen space sphere radius: screenSize * 0.5 * cot(fov) * radius / Z, where FOV is the
  1216. // largest one
  1217. //// First get sphere depth
  1218. const Matrix4& viewVP = viewProps.viewProjTransform;
  1219. float depth = viewVP.multiply(Vector4(light.internal->getTransform().getPosition(), 1.0f)).w;
  1220. // This is just 1/tan(fov), for both horz. and vert. FOV
  1221. float viewScaleX = viewProps.projTransform[0][0];
  1222. float viewScaleY = viewProps.projTransform[1][1];
  1223. float screenScaleX = viewScaleX * viewProps.viewRect.width * 0.5f;
  1224. float screenScaleY = viewScaleY * viewProps.viewRect.height * 0.5f;
  1225. float screenScale = std::max(screenScaleX, screenScaleY);
  1226. //// Calc radius (clamp if too close to avoid massive numbers)
  1227. float radiusNDC = light.internal->getBounds().getRadius() / std::max(depth, 1.0f);
  1228. //// Radius of light bounds in percent of the view surface, multiplied by screen size in pixels
  1229. float radiusScreen = radiusNDC * screenScale;
  1230. float optimalMapSize = SHADOW_TEXELS_PER_PIXEL * radiusScreen;
  1231. maxMapSize = std::max(maxMapSize, optimalMapSize);
  1232. // Determine if the shadow should fade out
  1233. float fadePercent = Math::lerp01(optimalMapSize, (float)MIN_SHADOW_MAP_SIZE, (float)SHADOW_MAP_FADE_SIZE);
  1234. fadePercents.push_back(fadePercent);
  1235. maxFadePercent = std::max(maxFadePercent, fadePercent);
  1236. }
  1237. }
  1238. // If light fully (or nearly fully) covers the screen, use full shadow map resolution, otherwise
  1239. // scale it down to smaller power of two, while clamping to minimal allowed resolution
  1240. UINT32 effectiveMapSize = Bitwise::nextPow2((UINT32)maxMapSize);
  1241. effectiveMapSize = Math::clamp(effectiveMapSize, MIN_SHADOW_MAP_SIZE, mShadowMapSize);
  1242. // Leave room for border
  1243. size = std::max(effectiveMapSize - 2 * border, 1u);
  1244. }
  1245. void ShadowRendering::drawNearFarPlanes(float near, float far, bool drawNear) const
  1246. {
  1247. RenderAPI& rapi = RenderAPI::instance();
  1248. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  1249. float flipY = rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown) ? -1.0f : 1.0f;
  1250. // Update VB with new vertices
  1251. Vector3 vertices[8] =
  1252. {
  1253. // Near plane
  1254. { -1.0f, -1.0f * flipY, near },
  1255. { 1.0f, -1.0f * flipY, near },
  1256. { 1.0f, 1.0f * flipY, near },
  1257. { -1.0f, 1.0f * flipY, near },
  1258. // Far plane
  1259. { -1.0f, -1.0f * flipY, far },
  1260. { 1.0f, -1.0f * flipY, far },
  1261. { 1.0f, 1.0f * flipY, far },
  1262. { -1.0f, 1.0f * flipY, far },
  1263. };
  1264. mPlaneVB->writeData(0, sizeof(vertices), vertices, BWT_DISCARD);
  1265. // Draw the mesh
  1266. rapi.setVertexDeclaration(mPositionOnlyVD);
  1267. rapi.setVertexBuffers(0, &mPlaneVB, 1);
  1268. rapi.setIndexBuffer(mPlaneIB);
  1269. rapi.setDrawOperation(DOT_TRIANGLE_LIST);
  1270. rapi.drawIndexed(0, drawNear ? 12 : 6, 0, drawNear ? 8 : 4);
  1271. }
  1272. void ShadowRendering::drawFrustum(const std::array<Vector3, 8>& corners) const
  1273. {
  1274. RenderAPI& rapi = RenderAPI::instance();
  1275. // Update VB with new vertices
  1276. mFrustumVB->writeData(0, sizeof(Vector3) * 8, corners.data(), BWT_DISCARD);
  1277. // Draw the mesh
  1278. rapi.setVertexDeclaration(mPositionOnlyVD);
  1279. rapi.setVertexBuffers(0, &mFrustumVB, 1);
  1280. rapi.setIndexBuffer(mFrustumIB);
  1281. rapi.setDrawOperation(DOT_TRIANGLE_LIST);
  1282. rapi.drawIndexed(0, 36, 0, 8);
  1283. }
  1284. UINT32 ShadowRendering::getShadowQuality(UINT32 requestedQuality, UINT32 shadowMapResolution, UINT32 minAllowedQuality)
  1285. {
  1286. static const UINT32 TARGET_RESOLUTION = 512;
  1287. // If shadow map resolution is smaller than some target resolution drop the number of PCF samples (shadow quality)
  1288. // so that the penumbra better matches with larger sized shadow maps.
  1289. while(requestedQuality > minAllowedQuality && shadowMapResolution < TARGET_RESOLUTION)
  1290. {
  1291. shadowMapResolution *= 2;
  1292. requestedQuality = std::max(requestedQuality - 1, 1U);
  1293. }
  1294. return requestedQuality;
  1295. }
  1296. ConvexVolume ShadowRendering::getCSMSplitFrustum(const RendererView& view, const Vector3& lightDir, UINT32 cascade,
  1297. UINT32 numCascades, Sphere& outBounds)
  1298. {
  1299. // Determine split range
  1300. float splitNear = getCSMSplitDistance(view, cascade, numCascades);
  1301. float splitFar = getCSMSplitDistance(view, cascade + 1, numCascades);
  1302. // Calculate the eight vertices of the split frustum
  1303. auto& viewProps = view.getProperties();
  1304. const Matrix4& projMat = viewProps.projTransform;
  1305. float aspect;
  1306. float nearHalfWidth, nearHalfHeight;
  1307. float farHalfWidth, farHalfHeight;
  1308. if(viewProps.projType == PT_PERSPECTIVE)
  1309. {
  1310. aspect = fabs(projMat[0][0] / projMat[1][1]);
  1311. float tanHalfFOV = 1.0f / projMat[0][0];
  1312. nearHalfWidth = splitNear * tanHalfFOV;
  1313. nearHalfHeight = nearHalfWidth * aspect;
  1314. farHalfWidth = splitFar * tanHalfFOV;
  1315. farHalfHeight = farHalfWidth * aspect;
  1316. }
  1317. else
  1318. {
  1319. aspect = projMat[0][0] / projMat[1][1];
  1320. nearHalfWidth = farHalfWidth = projMat[0][0] / 4.0f;
  1321. nearHalfHeight = farHalfHeight = projMat[1][1] / 4.0f;
  1322. }
  1323. const Matrix4& viewMat = viewProps.viewTransform;
  1324. Vector3 cameraRight = Vector3(viewMat[0]);
  1325. Vector3 cameraUp = Vector3(viewMat[1]);
  1326. const Vector3& viewOrigin = viewProps.viewOrigin;
  1327. const Vector3& viewDir = viewProps.viewDirection;
  1328. Vector3 frustumVerts[] =
  1329. {
  1330. viewOrigin + viewDir * splitNear - cameraRight * nearHalfWidth + cameraUp * nearHalfHeight, // Near, left, top
  1331. viewOrigin + viewDir * splitNear + cameraRight * nearHalfWidth + cameraUp * nearHalfHeight, // Near, right, top
  1332. viewOrigin + viewDir * splitNear + cameraRight * nearHalfWidth - cameraUp * nearHalfHeight, // Near, right, bottom
  1333. viewOrigin + viewDir * splitNear - cameraRight * nearHalfWidth - cameraUp * nearHalfHeight, // Near, left, bottom
  1334. viewOrigin + viewDir * splitFar - cameraRight * farHalfWidth + cameraUp * farHalfHeight, // Far, left, top
  1335. viewOrigin + viewDir * splitFar + cameraRight * farHalfWidth + cameraUp * farHalfHeight, // Far, right, top
  1336. viewOrigin + viewDir * splitFar + cameraRight * farHalfWidth - cameraUp * farHalfHeight, // Far, right, bottom
  1337. viewOrigin + viewDir * splitFar - cameraRight * farHalfWidth - cameraUp * farHalfHeight, // Far, left, bottom
  1338. };
  1339. // Calculate the bounding sphere of the frustum
  1340. float diagonalNearSq = nearHalfWidth * nearHalfWidth + nearHalfHeight * nearHalfHeight;
  1341. float diagonalFarSq = farHalfWidth * farHalfWidth + farHalfHeight * farHalfHeight;
  1342. float length = splitFar - splitNear;
  1343. float offset = (diagonalNearSq - diagonalFarSq) / (2 * length) + length * 0.5f;
  1344. float distToCenter = Math::clamp(splitFar - offset, splitNear, splitFar);
  1345. Vector3 center = viewOrigin + viewDir * distToCenter;
  1346. float radius = 0.0f;
  1347. for (auto& entry : frustumVerts)
  1348. radius = std::max(radius, center.squaredDistance(entry));
  1349. radius = std::max((float)sqrt(radius), 1.0f);
  1350. outBounds = Sphere(center, radius);
  1351. // Generate light frustum planes
  1352. Plane viewPlanes[6];
  1353. viewPlanes[FRUSTUM_PLANE_NEAR] = Plane(frustumVerts[0], frustumVerts[1], frustumVerts[2]);
  1354. viewPlanes[FRUSTUM_PLANE_FAR] = Plane(frustumVerts[5], frustumVerts[4], frustumVerts[7]);
  1355. viewPlanes[FRUSTUM_PLANE_LEFT] = Plane(frustumVerts[4], frustumVerts[0], frustumVerts[3]);
  1356. viewPlanes[FRUSTUM_PLANE_RIGHT] = Plane(frustumVerts[1], frustumVerts[5], frustumVerts[6]);
  1357. viewPlanes[FRUSTUM_PLANE_TOP] = Plane(frustumVerts[4], frustumVerts[5], frustumVerts[1]);
  1358. viewPlanes[FRUSTUM_PLANE_BOTTOM] = Plane(frustumVerts[3], frustumVerts[2], frustumVerts[6]);
  1359. Vector<Plane> lightVolume;
  1360. //// Add camera's planes facing towards the lights (forming the back of the volume)
  1361. for(auto& entry : viewPlanes)
  1362. {
  1363. if (entry.normal.dot(lightDir) < 0.0f)
  1364. lightVolume.push_back(entry);
  1365. }
  1366. //// Determine edge planes by testing adjacent planes with different facing
  1367. ////// Pairs of frustum planes that share an edge
  1368. UINT32 adjacentPlanes[][2] =
  1369. {
  1370. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_LEFT },
  1371. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_RIGHT },
  1372. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_TOP },
  1373. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_BOTTOM },
  1374. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_LEFT },
  1375. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_RIGHT },
  1376. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_TOP },
  1377. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_BOTTOM },
  1378. { FRUSTUM_PLANE_LEFT, FRUSTUM_PLANE_TOP },
  1379. { FRUSTUM_PLANE_TOP, FRUSTUM_PLANE_RIGHT },
  1380. { FRUSTUM_PLANE_RIGHT, FRUSTUM_PLANE_BOTTOM },
  1381. { FRUSTUM_PLANE_BOTTOM, FRUSTUM_PLANE_LEFT },
  1382. };
  1383. ////// Vertex indices of edges on the boundary between two planes
  1384. UINT32 sharedEdges[][2] =
  1385. {
  1386. { 3, 0 },{ 1, 2 },{ 0, 1 },{ 2, 3 },
  1387. { 4, 7 },{ 6, 5 },{ 5, 4 },{ 7, 6 },
  1388. { 4, 0 },{ 5, 1 },{ 6, 2 },{ 7, 3 }
  1389. };
  1390. for(UINT32 i = 0; i < 12; i++)
  1391. {
  1392. const Plane& planeA = viewPlanes[adjacentPlanes[i][0]];
  1393. const Plane& planeB = viewPlanes[adjacentPlanes[i][1]];
  1394. float dotA = planeA.normal.dot(lightDir);
  1395. float dotB = planeB.normal.dot(lightDir);
  1396. if((dotA * dotB) < 0.0f)
  1397. {
  1398. const Vector3& vertA = frustumVerts[sharedEdges[i][0]];
  1399. const Vector3& vertB = frustumVerts[sharedEdges[i][1]];
  1400. Vector3 vertC = vertA + lightDir;
  1401. if (dotA < 0.0f)
  1402. lightVolume.push_back(Plane(vertA, vertB, vertC));
  1403. else
  1404. lightVolume.push_back(Plane(vertB, vertA, vertC));
  1405. }
  1406. }
  1407. return ConvexVolume(lightVolume);
  1408. }
  1409. float ShadowRendering::getCSMSplitDistance(const RendererView& view, UINT32 index, UINT32 numCascades)
  1410. {
  1411. // Determines the size of each subsequent cascade split. Value of 1 means the cascades will be linearly split.
  1412. // Value of 2 means each subsequent split will be twice the size of the previous one. Valid range is roughly
  1413. // [1, 4].
  1414. // Note: Make this an adjustable property?
  1415. const static float DISTRIBUTON_EXPONENT = 3.0f;
  1416. // First determine the scale of the split, relative to the entire range
  1417. float scaleModifier = 1.0f;
  1418. float scale = 0.0f;
  1419. float totalScale = 0.0f;
  1420. //// Split 0 corresponds to near plane
  1421. if (index > 0)
  1422. {
  1423. for (UINT32 i = 0; i < numCascades; i++)
  1424. {
  1425. if (i < index)
  1426. scale += scaleModifier;
  1427. totalScale += scaleModifier;
  1428. scaleModifier *= DISTRIBUTON_EXPONENT;
  1429. }
  1430. scale = scale / totalScale;
  1431. }
  1432. // Calculate split distance in Z
  1433. auto& viewProps = view.getProperties();
  1434. float near = viewProps.nearPlane;
  1435. float far = viewProps.farPlane;
  1436. return near + (far - near) * scale;
  1437. }
  1438. float ShadowRendering::getDepthBias(const Light& light, float radius, float depthRange, UINT32 mapSize)
  1439. {
  1440. const static float RADIAL_LIGHT_BIAS = 0.0005f;
  1441. const static float SPOT_DEPTH_BIAS = 0.01f;
  1442. const static float DIR_DEPTH_BIAS = 0.5f;
  1443. const static float DEFAULT_RESOLUTION = 512.0f;
  1444. // Increase bias if map size smaller than some resolution
  1445. float resolutionScale;
  1446. if (light.getType() == LightType::Directional)
  1447. resolutionScale = radius / (float)mapSize;
  1448. else
  1449. resolutionScale = DEFAULT_RESOLUTION / (float)mapSize;
  1450. // Adjust range because in shader we compare vs. clip space depth
  1451. float rangeScale;
  1452. if (light.getType() == LightType::Radial)
  1453. rangeScale = 1.0f;
  1454. else
  1455. rangeScale = 1.0f / depthRange;
  1456. float defaultBias = 1.0f;
  1457. switch(light.getType())
  1458. {
  1459. case LightType::Directional:
  1460. defaultBias = DIR_DEPTH_BIAS;
  1461. break;
  1462. case LightType::Radial:
  1463. defaultBias = RADIAL_LIGHT_BIAS;
  1464. break;
  1465. case LightType::Spot:
  1466. defaultBias = SPOT_DEPTH_BIAS;
  1467. break;
  1468. default:
  1469. break;
  1470. }
  1471. return defaultBias * light.getShadowBias() * resolutionScale * rangeScale;
  1472. }
  1473. float ShadowRendering::getFadeTransition(const Light& light, float radius, float depthRange, UINT32 mapSize)
  1474. {
  1475. const static float SPOT_LIGHT_SCALE = 1000.0f;
  1476. const static float DIR_LIGHT_SCALE = 5000000.0f;
  1477. // Note: Currently fade transitions are only used in spot & directional (non omni-directional) lights, so no need
  1478. // to account for radial light type.
  1479. if (light.getType() == LightType::Directional)
  1480. {
  1481. // Reduce the size of the transition region when shadow map resolution is higher
  1482. float resolutionScale = 1.0f / (float)mapSize;
  1483. // Reduce the size of the transition region when the depth range is larger
  1484. float rangeScale = 1.0f / depthRange;
  1485. // Increase the size of the transition region for larger lights
  1486. float radiusScale = radius;
  1487. return light.getShadowBias() * DIR_LIGHT_SCALE * rangeScale * resolutionScale * radiusScale;
  1488. }
  1489. else
  1490. return light.getShadowBias() * SPOT_LIGHT_SCALE;
  1491. }
  1492. }}