BsShadowRendering.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889
  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, UINT32 numCascades)
  308. :ShadowMapBase(size), mNumCascades(numCascades), mTargets(numCascades), mShadowInfos(numCascades)
  309. {
  310. mShadowMap = GpuResourcePool::instance().get(POOLED_RENDER_TEXTURE_DESC::create2D(SHADOW_MAP_FORMAT, size, size,
  311. TU_DEPTHSTENCIL, 0, false, numCascades));
  312. RENDER_TEXTURE_DESC rtDesc;
  313. rtDesc.depthStencilSurface.texture = mShadowMap->texture;
  314. rtDesc.depthStencilSurface.numFaces = 1;
  315. for (UINT32 i = 0; i < mNumCascades; ++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 = 4096;
  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, const RendererLight& rendererLight,
  748. GBufferTextures gbuffer) const
  749. {
  750. UINT32 shadowQuality = view.getRenderSettings().shadowSettings.shadowFilteringQuality;
  751. const Light* light = rendererLight.internal;
  752. UINT32 lightIdx = light->getRendererId();
  753. auto viewProps = view.getProperties();
  754. const Matrix4& viewP = viewProps.projTransform;
  755. Matrix4 viewInvVP = viewProps.viewProjTransform.inverse();
  756. SPtr<GpuParamBlockBuffer> perViewBuffer = view.getPerViewBuffer();
  757. RenderAPI& rapi = RenderAPI::instance();
  758. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  759. // TODO - Calculate and set a scissor rectangle for the light
  760. SPtr<GpuParamBlockBuffer> shadowParamBuffer = gShadowProjectParamsDef.createBuffer();
  761. SPtr<GpuParamBlockBuffer> shadowOmniParamBuffer = gShadowProjectOmniParamsDef.createBuffer();
  762. UINT32 viewIdx = view.getViewIdx();
  763. Vector<const ShadowInfo*> shadowInfos;
  764. if(light->getType() == LightType::Radial)
  765. {
  766. const LightShadows& shadows = mRadialLightShadows[lightIdx];
  767. for(UINT32 i = 0; i < shadows.numShadows; ++i)
  768. {
  769. UINT32 shadowIdx = shadows.startIdx + i;
  770. const ShadowInfo& shadowInfo = mShadowInfos[shadowIdx];
  771. if (shadowInfo.fadePerView[viewIdx] < 0.005f)
  772. continue;
  773. for(UINT32 j = 0; j < 6; j++)
  774. gShadowProjectOmniParamsDef.gFaceVPMatrices.set(shadowOmniParamBuffer, shadowInfo.shadowVPTransforms[j], j);
  775. gShadowProjectOmniParamsDef.gDepthBias.set(shadowOmniParamBuffer, shadowInfo.depthBias);
  776. gShadowProjectOmniParamsDef.gFadePercent.set(shadowOmniParamBuffer, shadowInfo.fadePerView[viewIdx]);
  777. gShadowProjectOmniParamsDef.gInvResolution.set(shadowOmniParamBuffer, 1.0f / shadowInfo.area.width);
  778. const Transform& tfrm = light->getTransform();
  779. Vector4 lightPosAndRadius(tfrm.getPosition(), light->getAttenuationRadius());
  780. gShadowProjectOmniParamsDef.gLightPosAndRadius.set(shadowOmniParamBuffer, lightPosAndRadius);
  781. // Reduce shadow quality based on shadow map resolution for spot lights
  782. UINT32 effectiveShadowQuality = getShadowQuality(shadowQuality, shadowInfo.area.width, 2);
  783. // Check if viewer is inside the light bounds
  784. //// Expand the light bounds slightly to handle the case when the near plane is intersecting the light volume
  785. float lightRadius = light->getAttenuationRadius() + viewProps.nearPlane * 3.0f;
  786. bool viewerInsideVolume = (tfrm.getPosition() - viewProps.viewOrigin).length() < lightRadius;
  787. SPtr<Texture> shadowMap = mShadowCubemaps[shadowInfo.textureIdx].getTexture();
  788. ShadowProjectParams shadowParams(*light, shadowMap, shadowOmniParamBuffer, perViewBuffer, gbuffer);
  789. ShadowProjectOmniMat* mat = ShadowProjectOmniMat::getVariation(effectiveShadowQuality, viewerInsideVolume,
  790. viewProps.numSamples > 1);
  791. mat->bind(shadowParams);
  792. gRendererUtility().draw(gRendererUtility().getSphereStencil());
  793. }
  794. }
  795. else // Directional & spot
  796. {
  797. shadowInfos.clear();
  798. bool isCSM = light->getType() == LightType::Directional;
  799. if(!isCSM)
  800. {
  801. const LightShadows& shadows = mSpotLightShadows[lightIdx];
  802. for (UINT32 i = 0; i < shadows.numShadows; ++i)
  803. {
  804. UINT32 shadowIdx = shadows.startIdx + i;
  805. const ShadowInfo& shadowInfo = mShadowInfos[shadowIdx];
  806. if (shadowInfo.fadePerView[viewIdx] < 0.005f)
  807. continue;
  808. shadowInfos.push_back(&shadowInfo);
  809. }
  810. }
  811. else // Directional
  812. {
  813. const LightShadows& shadows = mDirectionalLightShadows[lightIdx].viewShadows[viewIdx];
  814. if (shadows.numShadows > 0)
  815. {
  816. UINT32 mapIdx = shadows.startIdx;
  817. const ShadowCascadedMap& cascadedMap = mCascadedShadowMaps[mapIdx];
  818. // Render cascades in far to near order.
  819. // Note: If rendering other non-cascade maps they should be rendered after cascades.
  820. for (INT32 i = cascadedMap.getNumCascades() - 1; i >= 0; i--)
  821. shadowInfos.push_back(&cascadedMap.getShadowInfo(i));
  822. }
  823. }
  824. for(auto& shadowInfo : shadowInfos)
  825. {
  826. float depthScale, depthOffset;
  827. // Depth range scale is already baked into the ortho projection matrix, so avoid doing it here
  828. if (isCSM)
  829. {
  830. // Need to map from API-specific clip space depth to [0, 1] range
  831. depthScale = 1.0f / (rapiInfo.getMaximumDepthInputValue() - rapiInfo.getMinimumDepthInputValue());
  832. depthOffset = -rapiInfo.getMinimumDepthInputValue() * depthScale;
  833. }
  834. else
  835. {
  836. depthScale = 1.0f / shadowInfo->depthRange;
  837. depthOffset = 0.0f;
  838. }
  839. SPtr<Texture> shadowMap;
  840. UINT32 shadowMapFace = 0;
  841. if(!isCSM)
  842. shadowMap = mDynamicShadowMaps[shadowInfo->textureIdx].getTexture();
  843. else
  844. {
  845. shadowMap = mCascadedShadowMaps[shadowInfo->textureIdx].getTexture();
  846. shadowMapFace = shadowInfo->cascadeIdx;
  847. }
  848. Matrix4 mixedToShadowUV = createMixedToShadowUVMatrix(viewP, viewInvVP, shadowInfo->normArea,
  849. depthScale, depthOffset, shadowInfo->shadowVPTransform);
  850. auto shadowMapProps = shadowMap->getProperties();
  851. Vector2 shadowMapSize((float)shadowMapProps.getWidth(), (float)shadowMapProps.getHeight());
  852. float transitionScale = getFadeTransition(*light, shadowInfo->subjectBounds.getRadius(),
  853. shadowInfo->depthRange, shadowInfo->area.width);
  854. gShadowProjectParamsDef.gFadePlaneDepth.set(shadowParamBuffer, shadowInfo->depthFade);
  855. gShadowProjectParamsDef.gMixedToShadowSpace.set(shadowParamBuffer, mixedToShadowUV);
  856. gShadowProjectParamsDef.gShadowMapSize.set(shadowParamBuffer, shadowMapSize);
  857. gShadowProjectParamsDef.gShadowMapSizeInv.set(shadowParamBuffer, 1.0f / shadowMapSize);
  858. gShadowProjectParamsDef.gSoftTransitionScale.set(shadowParamBuffer, transitionScale);
  859. if(isCSM)
  860. gShadowProjectParamsDef.gFadePercent.set(shadowParamBuffer, 1.0f);
  861. else
  862. gShadowProjectParamsDef.gFadePercent.set(shadowParamBuffer, shadowInfo->fadePerView[viewIdx]);
  863. if(shadowInfo->fadeRange == 0.0f)
  864. gShadowProjectParamsDef.gInvFadePlaneRange.set(shadowParamBuffer, 0.0f);
  865. else
  866. gShadowProjectParamsDef.gInvFadePlaneRange.set(shadowParamBuffer, 1.0f / shadowInfo->fadeRange);
  867. // Generate a stencil buffer to avoid evaluating pixels without any receiver geometry in the shadow area
  868. std::array<Vector3, 8> frustumVertices;
  869. UINT32 effectiveShadowQuality = shadowQuality;
  870. if(!isCSM)
  871. {
  872. ConvexVolume shadowFrustum;
  873. frustumVertices = getFrustum(shadowInfo->shadowVPTransform.inverse(), shadowFrustum);
  874. // Check if viewer is inside the frustum. Frustum is slightly expanded so that if the near plane is
  875. // intersecting the shadow frustum, it is counted as inside. This needs to be conservative as the code
  876. // for handling viewer outside the frustum will not properly render intersections with the near plane.
  877. bool viewerInsideFrustum = shadowFrustum.contains(viewProps.viewOrigin, viewProps.nearPlane * 3.0f);
  878. ShadowProjectStencilMat* mat = ShadowProjectStencilMat::getVariation(false, viewerInsideFrustum);
  879. mat->bind(perViewBuffer);
  880. drawFrustum(frustumVertices);
  881. // Reduce shadow quality based on shadow map resolution for spot lights
  882. effectiveShadowQuality = getShadowQuality(shadowQuality, shadowInfo->area.width, 2);
  883. }
  884. else
  885. {
  886. // Need to generate near and far planes to clip the geometry within the current CSM slice.
  887. // Note: If the render API supports built-in depth bound tests that could be used instead.
  888. Vector3 near = viewProps.projTransform.multiply(Vector3(0, 0, -shadowInfo->depthNear));
  889. Vector3 far = viewProps.projTransform.multiply(Vector3(0, 0, -shadowInfo->depthFar));
  890. ShadowProjectStencilMat* mat = ShadowProjectStencilMat::getVariation(true, true);
  891. mat->bind(perViewBuffer);
  892. drawNearFarPlanes(near.z, far.z, shadowInfo->cascadeIdx != 0);
  893. }
  894. gShadowProjectParamsDef.gFace.set(shadowParamBuffer, (float)shadowMapFace);
  895. ShadowProjectParams shadowParams(*light, shadowMap, shadowParamBuffer, perViewBuffer, gbuffer);
  896. ShadowProjectMat* mat = ShadowProjectMat::getVariation(effectiveShadowQuality, isCSM, viewProps.numSamples > 1);
  897. mat->bind(shadowParams);
  898. if (!isCSM)
  899. drawFrustum(frustumVertices);
  900. else
  901. gRendererUtility().drawScreenQuad();
  902. }
  903. }
  904. }
  905. void ShadowRendering::renderCascadedShadowMaps(const RendererView& view, UINT32 lightIdx, RendererScene& scene,
  906. const FrameInfo& frameInfo)
  907. {
  908. UINT32 viewIdx = view.getViewIdx();
  909. LightShadows& lightShadows = mDirectionalLightShadows[lightIdx].viewShadows[viewIdx];
  910. if (!view.getRenderSettings().enableShadows)
  911. {
  912. lightShadows.startIdx = -1;
  913. lightShadows.numShadows = 0;
  914. return;
  915. }
  916. // Note: Currently I'm using spherical bounds for the cascaded frustum which might result in non-optimal usage
  917. // of the shadow map. A different approach would be to generate a bounding box and then both adjust the aspect
  918. // ratio (and therefore dimensions) of the shadow map, as well as rotate the camera so the visible area best fits
  919. // in the map. It remains to be seen if this is viable.
  920. // - Note2: Actually both of these will likely have serious negative impact on shadow stability.
  921. const SceneInfo& sceneInfo = scene.getSceneInfo();
  922. const RendererLight& rendererLight = sceneInfo.directionalLights[lightIdx];
  923. Light* light = rendererLight.internal;
  924. RenderAPI& rapi = RenderAPI::instance();
  925. const Transform& tfrm = light->getTransform();
  926. Vector3 lightDir = -tfrm.getRotation().zAxis();
  927. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  928. ShadowInfo shadowInfo;
  929. shadowInfo.lightIdx = lightIdx;
  930. shadowInfo.textureIdx = -1;
  931. UINT32 mapSize = std::min(mShadowMapSize, MAX_ATLAS_SIZE);
  932. shadowInfo.area = Rect2I(0, 0, mapSize, mapSize);
  933. shadowInfo.updateNormArea(mapSize);
  934. UINT32 numCascades = view.getRenderSettings().shadowSettings.numCascades;
  935. for (UINT32 i = 0; i < (UINT32)mCascadedShadowMaps.size(); i++)
  936. {
  937. ShadowCascadedMap& shadowMap = mCascadedShadowMaps[i];
  938. if (!shadowMap.isUsed() && shadowMap.getSize() == mapSize && shadowMap.getNumCascades() == numCascades)
  939. {
  940. shadowInfo.textureIdx = i;
  941. shadowMap.markAsUsed();
  942. break;
  943. }
  944. }
  945. if (shadowInfo.textureIdx == (UINT32)-1)
  946. {
  947. shadowInfo.textureIdx = (UINT32)mCascadedShadowMaps.size();
  948. mCascadedShadowMaps.push_back(ShadowCascadedMap(mapSize, numCascades));
  949. ShadowCascadedMap& shadowMap = mCascadedShadowMaps.back();
  950. shadowMap.markAsUsed();
  951. }
  952. ShadowCascadedMap& shadowMap = mCascadedShadowMaps[shadowInfo.textureIdx];
  953. Quaternion lightRotation(BsIdentity);
  954. lightRotation.lookRotation(lightDir, Vector3::UNIT_Y);
  955. for (UINT32 i = 0; i < numCascades; ++i)
  956. {
  957. Sphere frustumBounds;
  958. ConvexVolume cascadeCullVolume = getCSMSplitFrustum(view, lightDir, i, numCascades, frustumBounds);
  959. // Make sure the size of the projected area is in multiples of shadow map pixel size (for stability)
  960. float worldUnitsPerTexel = frustumBounds.getRadius() * 2.0f / shadowMap.getSize();
  961. float orthoSize = floor(frustumBounds.getRadius() * 2.0f / worldUnitsPerTexel) * worldUnitsPerTexel * 0.5f;
  962. worldUnitsPerTexel = orthoSize * 2.0f / shadowMap.getSize();
  963. // Snap caster origin to the shadow map pixel grid, to ensure shadow map stability
  964. Vector3 casterOrigin = frustumBounds.getCenter();
  965. Matrix4 shadowView = Matrix4::view(Vector3::ZERO, lightRotation);
  966. Vector3 shadowSpaceOrigin = shadowView.multiplyAffine(casterOrigin);
  967. Vector2 snapOffset(fmod(shadowSpaceOrigin.x, worldUnitsPerTexel), fmod(shadowSpaceOrigin.y, worldUnitsPerTexel));
  968. shadowSpaceOrigin.x -= snapOffset.x;
  969. shadowSpaceOrigin.y -= snapOffset.y;
  970. Matrix4 shadowViewInv = shadowView.inverseAffine();
  971. casterOrigin = shadowViewInv.multiplyAffine(shadowSpaceOrigin);
  972. // Move the light so it is centered at the subject frustum, with depth range covering the frustum bounds
  973. shadowInfo.depthRange = frustumBounds.getRadius() * 2.0f;
  974. Vector3 offsetLightPos = casterOrigin - lightDir * frustumBounds.getRadius();
  975. Matrix4 offsetViewMat = Matrix4::view(offsetLightPos, lightRotation);
  976. Matrix4 proj = Matrix4::projectionOrthographic(-orthoSize, orthoSize, orthoSize, -orthoSize, 0.0f,
  977. shadowInfo.depthRange);
  978. RenderAPI::instance().convertProjectionMatrix(proj, proj);
  979. shadowInfo.cascadeIdx = i;
  980. shadowInfo.shadowVPTransform = proj * offsetViewMat;
  981. // Determine split range
  982. float splitNear = getCSMSplitDistance(view, i, numCascades);
  983. float splitFar = getCSMSplitDistance(view, i + 1, numCascades);
  984. shadowInfo.depthNear = splitNear;
  985. shadowInfo.depthFade = splitFar;
  986. shadowInfo.subjectBounds = frustumBounds;
  987. if ((UINT32)(i + 1) < numCascades)
  988. shadowInfo.fadeRange = CASCADE_FRACTION_FADE * (shadowInfo.depthFade - shadowInfo.depthNear);
  989. else
  990. shadowInfo.fadeRange = 0.0f;
  991. shadowInfo.depthFar = shadowInfo.depthFade + shadowInfo.fadeRange;
  992. shadowInfo.depthBias = getDepthBias(*light, frustumBounds.getRadius(), shadowInfo.depthRange, mapSize);
  993. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, shadowInfo.depthBias);
  994. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / shadowInfo.depthRange);
  995. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, shadowInfo.shadowVPTransform);
  996. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  997. rapi.setRenderTarget(shadowMap.getTarget(i));
  998. rapi.clearRenderTarget(FBT_DEPTH);
  999. ShadowDepthDirectionalMat* depthDirMat = ShadowDepthDirectionalMat::get();
  1000. depthDirMat->bind(shadowParamsBuffer);
  1001. // Render all renderables into the shadow map
  1002. ShadowRenderQueueDirOptions dirOptions(
  1003. cascadeCullVolume,
  1004. shadowParamsBuffer);
  1005. ShadowRenderQueue::execute(scene, frameInfo, dirOptions);
  1006. shadowMap.setShadowInfo(i, shadowInfo);
  1007. }
  1008. lightShadows.startIdx = shadowInfo.textureIdx;
  1009. lightShadows.numShadows = 1;
  1010. }
  1011. void ShadowRendering::renderSpotShadowMap(const RendererLight& rendererLight, const ShadowMapOptions& options,
  1012. RendererScene& scene, const FrameInfo& frameInfo)
  1013. {
  1014. Light* light = rendererLight.internal;
  1015. const SceneInfo& sceneInfo = scene.getSceneInfo();
  1016. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  1017. ShadowInfo mapInfo;
  1018. mapInfo.fadePerView = options.fadePercents;
  1019. mapInfo.lightIdx = options.lightIdx;
  1020. mapInfo.cascadeIdx = -1;
  1021. bool foundSpace = false;
  1022. for (UINT32 i = 0; i < (UINT32)mDynamicShadowMaps.size(); i++)
  1023. {
  1024. ShadowMapAtlas& atlas = mDynamicShadowMaps[i];
  1025. if (atlas.addMap(options.mapSize, mapInfo.area, SHADOW_MAP_BORDER))
  1026. {
  1027. mapInfo.textureIdx = i;
  1028. foundSpace = true;
  1029. break;
  1030. }
  1031. }
  1032. if (!foundSpace)
  1033. {
  1034. mapInfo.textureIdx = (UINT32)mDynamicShadowMaps.size();
  1035. mDynamicShadowMaps.push_back(ShadowMapAtlas(MAX_ATLAS_SIZE));
  1036. ShadowMapAtlas& atlas = mDynamicShadowMaps.back();
  1037. atlas.addMap(options.mapSize, mapInfo.area, SHADOW_MAP_BORDER);
  1038. }
  1039. mapInfo.updateNormArea(MAX_ATLAS_SIZE);
  1040. ShadowMapAtlas& atlas = mDynamicShadowMaps[mapInfo.textureIdx];
  1041. RenderAPI& rapi = RenderAPI::instance();
  1042. rapi.setRenderTarget(atlas.getTarget());
  1043. rapi.setViewport(mapInfo.normArea);
  1044. rapi.clearViewport(FBT_DEPTH);
  1045. mapInfo.depthNear = 0.05f;
  1046. mapInfo.depthFar = light->getAttenuationRadius();
  1047. mapInfo.depthFade = mapInfo.depthFar;
  1048. mapInfo.fadeRange = 0.0f;
  1049. mapInfo.depthRange = mapInfo.depthFar - mapInfo.depthNear;
  1050. mapInfo.depthBias = getDepthBias(*light, light->getBounds().getRadius(), mapInfo.depthRange, options.mapSize);
  1051. mapInfo.subjectBounds = light->getBounds();
  1052. Quaternion lightRotation(BsIdentity);
  1053. lightRotation.lookRotation(-light->getTransform().getRotation().zAxis());
  1054. Matrix4 view = Matrix4::view(rendererLight.getShiftedLightPosition(), lightRotation);
  1055. Matrix4 proj = Matrix4::projectionPerspective(light->getSpotAngle(), 1.0f, 0.05f, light->getAttenuationRadius());
  1056. ConvexVolume localFrustum = ConvexVolume(proj);
  1057. RenderAPI::instance().convertProjectionMatrix(proj, proj);
  1058. mapInfo.shadowVPTransform = proj * view;
  1059. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, mapInfo.depthBias);
  1060. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / mapInfo.depthRange);
  1061. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, mapInfo.shadowVPTransform);
  1062. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  1063. const Vector<Plane>& frustumPlanes = localFrustum.getPlanes();
  1064. Matrix4 worldMatrix = view.transpose();
  1065. Vector<Plane> worldPlanes(frustumPlanes.size());
  1066. UINT32 j = 0;
  1067. for (auto& plane : frustumPlanes)
  1068. {
  1069. worldPlanes[j] = worldMatrix.multiplyAffine(plane);
  1070. j++;
  1071. }
  1072. ConvexVolume worldFrustum(worldPlanes);
  1073. // Render all renderables into the shadow map
  1074. ShadowRenderQueueSpotOptions spotOptions(
  1075. worldFrustum,
  1076. shadowParamsBuffer);
  1077. ShadowRenderQueue::execute(scene, frameInfo, spotOptions);
  1078. // Restore viewport
  1079. rapi.setViewport(Rect2(0.0f, 0.0f, 1.0f, 1.0f));
  1080. LightShadows& lightShadows = mSpotLightShadows[options.lightIdx];
  1081. mShadowInfos[lightShadows.startIdx + lightShadows.numShadows] = mapInfo;
  1082. lightShadows.numShadows++;
  1083. }
  1084. void ShadowRendering::renderRadialShadowMap(const RendererLight& rendererLight,
  1085. const ShadowMapOptions& options, RendererScene& scene, const FrameInfo& frameInfo)
  1086. {
  1087. Light* light = rendererLight.internal;
  1088. const SceneInfo& sceneInfo = scene.getSceneInfo();
  1089. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  1090. SPtr<GpuParamBlockBuffer> shadowCubeMatricesBuffer = gShadowCubeMatricesDef.createBuffer();
  1091. SPtr<GpuParamBlockBuffer> shadowCubeMasksBuffer = gShadowCubeMasksDef.createBuffer();
  1092. ShadowInfo mapInfo;
  1093. mapInfo.lightIdx = options.lightIdx;
  1094. mapInfo.textureIdx = -1;
  1095. mapInfo.fadePerView = options.fadePercents;
  1096. mapInfo.cascadeIdx = -1;
  1097. mapInfo.area = Rect2I(0, 0, options.mapSize, options.mapSize);
  1098. mapInfo.updateNormArea(options.mapSize);
  1099. for (UINT32 i = 0; i < (UINT32)mShadowCubemaps.size(); i++)
  1100. {
  1101. ShadowCubemap& cubemap = mShadowCubemaps[i];
  1102. if (!cubemap.isUsed() && cubemap.getSize() == options.mapSize)
  1103. {
  1104. mapInfo.textureIdx = i;
  1105. cubemap.markAsUsed();
  1106. break;
  1107. }
  1108. }
  1109. if (mapInfo.textureIdx == (UINT32)-1)
  1110. {
  1111. mapInfo.textureIdx = (UINT32)mShadowCubemaps.size();
  1112. mShadowCubemaps.push_back(ShadowCubemap(options.mapSize));
  1113. ShadowCubemap& cubemap = mShadowCubemaps.back();
  1114. cubemap.markAsUsed();
  1115. }
  1116. ShadowCubemap& cubemap = mShadowCubemaps[mapInfo.textureIdx];
  1117. mapInfo.depthNear = 0.05f;
  1118. mapInfo.depthFar = light->getAttenuationRadius();
  1119. mapInfo.depthFade = mapInfo.depthFar;
  1120. mapInfo.fadeRange = 0.0f;
  1121. mapInfo.depthRange = mapInfo.depthFar - mapInfo.depthNear;
  1122. mapInfo.depthBias = getDepthBias(*light, light->getBounds().getRadius(), mapInfo.depthRange, options.mapSize);
  1123. mapInfo.subjectBounds = light->getBounds();
  1124. // Note: Projecting on positive Z axis, because cubemaps use a left-handed coordinate system
  1125. Matrix4 proj = Matrix4::projectionPerspective(Degree(90.0f), 1.0f, 0.05f, light->getAttenuationRadius(), true);
  1126. ConvexVolume localFrustum(proj);
  1127. RenderAPI& rapi = RenderAPI::instance();
  1128. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  1129. rapi.convertProjectionMatrix(proj, proj);
  1130. // Render cubemaps upside down if necessary
  1131. Matrix4 adjustedProj = proj;
  1132. if(rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp))
  1133. {
  1134. // All big APIs use the same cubemap sampling coordinates, as well as the same face order. But APIs that
  1135. // use bottom-up UV coordinates require the cubemap faces to be stored upside down in order to get the same
  1136. // behaviour. APIs that use an upside-down NDC Y axis have the same problem as the rendered image will be
  1137. // upside down, but this is handled by the projection matrix. If both of those are enabled, then the effect
  1138. // cancels out.
  1139. adjustedProj[1][1] = -proj[1][1];
  1140. }
  1141. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, mapInfo.depthBias);
  1142. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / mapInfo.depthRange);
  1143. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, Matrix4::IDENTITY);
  1144. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  1145. ConvexVolume frustums[6];
  1146. Vector<Plane> boundingPlanes;
  1147. for (UINT32 i = 0; i < 6; i++)
  1148. {
  1149. // Calculate view matrix
  1150. Vector3 forward;
  1151. Vector3 up = Vector3::UNIT_Y;
  1152. switch (i)
  1153. {
  1154. case CF_PositiveX:
  1155. forward = Vector3::UNIT_X;
  1156. break;
  1157. case CF_NegativeX:
  1158. forward = -Vector3::UNIT_X;
  1159. break;
  1160. case CF_PositiveY:
  1161. forward = Vector3::UNIT_Y;
  1162. up = -Vector3::UNIT_Z;
  1163. break;
  1164. case CF_NegativeY:
  1165. forward = -Vector3::UNIT_Y;
  1166. up = Vector3::UNIT_Z;
  1167. break;
  1168. case CF_PositiveZ:
  1169. forward = Vector3::UNIT_Z;
  1170. break;
  1171. case CF_NegativeZ:
  1172. forward = -Vector3::UNIT_Z;
  1173. break;
  1174. }
  1175. Vector3 right = Vector3::cross(up, forward);
  1176. Matrix3 viewRotationMat = Matrix3(right, up, forward);
  1177. Vector3 lightPos = light->getTransform().getPosition();
  1178. Matrix4 viewOffsetMat = Matrix4::translation(-lightPos);
  1179. Matrix4 view = Matrix4(viewRotationMat.transpose()) * viewOffsetMat;
  1180. mapInfo.shadowVPTransforms[i] = proj * view;
  1181. Matrix4 shadowViewProj = adjustedProj * view;
  1182. gShadowCubeMatricesDef.gFaceVPMatrices.set(shadowCubeMatricesBuffer, shadowViewProj, i);
  1183. // Calculate world frustum for culling
  1184. const Vector<Plane>& frustumPlanes = localFrustum.getPlanes();
  1185. Matrix4 worldMatrix = Matrix4::translation(lightPos) * Matrix4(viewRotationMat);
  1186. Vector<Plane> worldPlanes(frustumPlanes.size());
  1187. UINT32 j = 0;
  1188. for (auto& plane : frustumPlanes)
  1189. {
  1190. worldPlanes[j] = worldMatrix.multiplyAffine(plane);
  1191. j++;
  1192. }
  1193. frustums[i] = ConvexVolume(worldPlanes);
  1194. // Register far plane of all frustums
  1195. boundingPlanes.push_back(worldPlanes.back());
  1196. }
  1197. rapi.setRenderTarget(cubemap.getTarget());
  1198. rapi.clearRenderTarget(FBT_DEPTH);
  1199. // Render all renderables into the shadow map
  1200. ConvexVolume boundingVolume(boundingPlanes);
  1201. ShadowRenderQueueCubeOptions cubeOptions(
  1202. frustums,
  1203. boundingVolume,
  1204. shadowParamsBuffer,
  1205. shadowCubeMatricesBuffer,
  1206. shadowCubeMasksBuffer);
  1207. ShadowRenderQueue::execute(scene, frameInfo, cubeOptions);
  1208. LightShadows& lightShadows = mRadialLightShadows[options.lightIdx];
  1209. mShadowInfos[lightShadows.startIdx + lightShadows.numShadows] = mapInfo;
  1210. lightShadows.numShadows++;
  1211. }
  1212. void ShadowRendering::calcShadowMapProperties(const RendererLight& light, const RendererViewGroup& viewGroup,
  1213. UINT32 border, UINT32& size, SmallVector<float, 6>& fadePercents, float& maxFadePercent) const
  1214. {
  1215. const static float SHADOW_TEXELS_PER_PIXEL = 1.0f;
  1216. // Find a view in which the light has the largest radius
  1217. float maxMapSize = 0.0f;
  1218. maxFadePercent = 0.0f;
  1219. for (int i = 0; i < (int)viewGroup.getNumViews(); ++i)
  1220. {
  1221. const RendererView& view = *viewGroup.getView(i);
  1222. const RendererViewProperties& viewProps = view.getProperties();
  1223. const RenderSettings& viewSettings = view.getRenderSettings();
  1224. if(!viewSettings.enableShadows)
  1225. fadePercents.push_back(0.0f);
  1226. {
  1227. // Approximation for screen space sphere radius: screenSize * 0.5 * cot(fov) * radius / Z, where FOV is the
  1228. // largest one
  1229. //// First get sphere depth
  1230. const Matrix4& viewVP = viewProps.viewProjTransform;
  1231. float depth = viewVP.multiply(Vector4(light.internal->getTransform().getPosition(), 1.0f)).w;
  1232. // This is just 1/tan(fov), for both horz. and vert. FOV
  1233. float viewScaleX = viewProps.projTransform[0][0];
  1234. float viewScaleY = viewProps.projTransform[1][1];
  1235. float screenScaleX = viewScaleX * viewProps.viewRect.width * 0.5f;
  1236. float screenScaleY = viewScaleY * viewProps.viewRect.height * 0.5f;
  1237. float screenScale = std::max(screenScaleX, screenScaleY);
  1238. //// Calc radius (clamp if too close to avoid massive numbers)
  1239. float radiusNDC = light.internal->getBounds().getRadius() / std::max(depth, 1.0f);
  1240. //// Radius of light bounds in percent of the view surface, multiplied by screen size in pixels
  1241. float radiusScreen = radiusNDC * screenScale;
  1242. float optimalMapSize = SHADOW_TEXELS_PER_PIXEL * radiusScreen;
  1243. maxMapSize = std::max(maxMapSize, optimalMapSize);
  1244. // Determine if the shadow should fade out
  1245. float fadePercent = Math::lerp01(optimalMapSize, (float)MIN_SHADOW_MAP_SIZE, (float)SHADOW_MAP_FADE_SIZE);
  1246. fadePercents.push_back(fadePercent);
  1247. maxFadePercent = std::max(maxFadePercent, fadePercent);
  1248. }
  1249. }
  1250. // If light fully (or nearly fully) covers the screen, use full shadow map resolution, otherwise
  1251. // scale it down to smaller power of two, while clamping to minimal allowed resolution
  1252. UINT32 effectiveMapSize = Bitwise::nextPow2((UINT32)maxMapSize);
  1253. effectiveMapSize = Math::clamp(effectiveMapSize, MIN_SHADOW_MAP_SIZE, mShadowMapSize);
  1254. // Leave room for border
  1255. size = std::max(effectiveMapSize - 2 * border, 1u);
  1256. }
  1257. void ShadowRendering::drawNearFarPlanes(float near, float far, bool drawNear) const
  1258. {
  1259. RenderAPI& rapi = RenderAPI::instance();
  1260. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  1261. float flipY = rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown) ? -1.0f : 1.0f;
  1262. // Update VB with new vertices
  1263. Vector3 vertices[8] =
  1264. {
  1265. // Near plane
  1266. { -1.0f, -1.0f * flipY, near },
  1267. { 1.0f, -1.0f * flipY, near },
  1268. { 1.0f, 1.0f * flipY, near },
  1269. { -1.0f, 1.0f * flipY, near },
  1270. // Far plane
  1271. { -1.0f, -1.0f * flipY, far },
  1272. { 1.0f, -1.0f * flipY, far },
  1273. { 1.0f, 1.0f * flipY, far },
  1274. { -1.0f, 1.0f * flipY, far },
  1275. };
  1276. mPlaneVB->writeData(0, sizeof(vertices), vertices, BWT_DISCARD);
  1277. // Draw the mesh
  1278. rapi.setVertexDeclaration(mPositionOnlyVD);
  1279. rapi.setVertexBuffers(0, &mPlaneVB, 1);
  1280. rapi.setIndexBuffer(mPlaneIB);
  1281. rapi.setDrawOperation(DOT_TRIANGLE_LIST);
  1282. rapi.drawIndexed(0, drawNear ? 12 : 6, 0, drawNear ? 8 : 4);
  1283. }
  1284. void ShadowRendering::drawFrustum(const std::array<Vector3, 8>& corners) const
  1285. {
  1286. RenderAPI& rapi = RenderAPI::instance();
  1287. // Update VB with new vertices
  1288. mFrustumVB->writeData(0, sizeof(Vector3) * 8, corners.data(), BWT_DISCARD);
  1289. // Draw the mesh
  1290. rapi.setVertexDeclaration(mPositionOnlyVD);
  1291. rapi.setVertexBuffers(0, &mFrustumVB, 1);
  1292. rapi.setIndexBuffer(mFrustumIB);
  1293. rapi.setDrawOperation(DOT_TRIANGLE_LIST);
  1294. rapi.drawIndexed(0, 36, 0, 8);
  1295. }
  1296. UINT32 ShadowRendering::getShadowQuality(UINT32 requestedQuality, UINT32 shadowMapResolution, UINT32 minAllowedQuality)
  1297. {
  1298. static const UINT32 TARGET_RESOLUTION = 512;
  1299. // If shadow map resolution is smaller than some target resolution drop the number of PCF samples (shadow quality)
  1300. // so that the penumbra better matches with larger sized shadow maps.
  1301. while(requestedQuality > minAllowedQuality && shadowMapResolution < TARGET_RESOLUTION)
  1302. {
  1303. shadowMapResolution *= 2;
  1304. requestedQuality = std::max(requestedQuality - 1, 1U);
  1305. }
  1306. return requestedQuality;
  1307. }
  1308. ConvexVolume ShadowRendering::getCSMSplitFrustum(const RendererView& view, const Vector3& lightDir, UINT32 cascade,
  1309. UINT32 numCascades, Sphere& outBounds)
  1310. {
  1311. // Determine split range
  1312. float splitNear = getCSMSplitDistance(view, cascade, numCascades);
  1313. float splitFar = getCSMSplitDistance(view, cascade + 1, numCascades);
  1314. // Calculate the eight vertices of the split frustum
  1315. auto& viewProps = view.getProperties();
  1316. const Matrix4& projMat = viewProps.projTransform;
  1317. float aspect;
  1318. float nearHalfWidth, nearHalfHeight;
  1319. float farHalfWidth, farHalfHeight;
  1320. if(viewProps.projType == PT_PERSPECTIVE)
  1321. {
  1322. aspect = fabs(projMat[0][0] / projMat[1][1]);
  1323. float tanHalfFOV = 1.0f / projMat[0][0];
  1324. nearHalfWidth = splitNear * tanHalfFOV;
  1325. nearHalfHeight = nearHalfWidth * aspect;
  1326. farHalfWidth = splitFar * tanHalfFOV;
  1327. farHalfHeight = farHalfWidth * aspect;
  1328. }
  1329. else
  1330. {
  1331. aspect = projMat[0][0] / projMat[1][1];
  1332. nearHalfWidth = farHalfWidth = projMat[0][0] / 4.0f;
  1333. nearHalfHeight = farHalfHeight = projMat[1][1] / 4.0f;
  1334. }
  1335. const Matrix4& viewMat = viewProps.viewTransform;
  1336. Vector3 cameraRight = Vector3(viewMat[0]);
  1337. Vector3 cameraUp = Vector3(viewMat[1]);
  1338. const Vector3& viewOrigin = viewProps.viewOrigin;
  1339. const Vector3& viewDir = viewProps.viewDirection;
  1340. Vector3 frustumVerts[] =
  1341. {
  1342. viewOrigin + viewDir * splitNear - cameraRight * nearHalfWidth + cameraUp * nearHalfHeight, // Near, left, top
  1343. viewOrigin + viewDir * splitNear + cameraRight * nearHalfWidth + cameraUp * nearHalfHeight, // Near, right, top
  1344. viewOrigin + viewDir * splitNear + cameraRight * nearHalfWidth - cameraUp * nearHalfHeight, // Near, right, bottom
  1345. viewOrigin + viewDir * splitNear - cameraRight * nearHalfWidth - cameraUp * nearHalfHeight, // Near, left, bottom
  1346. viewOrigin + viewDir * splitFar - cameraRight * farHalfWidth + cameraUp * farHalfHeight, // Far, left, top
  1347. viewOrigin + viewDir * splitFar + cameraRight * farHalfWidth + cameraUp * farHalfHeight, // Far, right, top
  1348. viewOrigin + viewDir * splitFar + cameraRight * farHalfWidth - cameraUp * farHalfHeight, // Far, right, bottom
  1349. viewOrigin + viewDir * splitFar - cameraRight * farHalfWidth - cameraUp * farHalfHeight, // Far, left, bottom
  1350. };
  1351. // Calculate the bounding sphere of the frustum
  1352. float diagonalNearSq = nearHalfWidth * nearHalfWidth + nearHalfHeight * nearHalfHeight;
  1353. float diagonalFarSq = farHalfWidth * farHalfWidth + farHalfHeight * farHalfHeight;
  1354. float length = splitFar - splitNear;
  1355. float offset = (diagonalNearSq - diagonalFarSq) / (2 * length) + length * 0.5f;
  1356. float distToCenter = Math::clamp(splitFar - offset, splitNear, splitFar);
  1357. Vector3 center = viewOrigin + viewDir * distToCenter;
  1358. float radius = 0.0f;
  1359. for (auto& entry : frustumVerts)
  1360. radius = std::max(radius, center.squaredDistance(entry));
  1361. radius = std::max((float)sqrt(radius), 1.0f);
  1362. outBounds = Sphere(center, radius);
  1363. // Generate light frustum planes
  1364. Plane viewPlanes[6];
  1365. viewPlanes[FRUSTUM_PLANE_NEAR] = Plane(frustumVerts[0], frustumVerts[1], frustumVerts[2]);
  1366. viewPlanes[FRUSTUM_PLANE_FAR] = Plane(frustumVerts[5], frustumVerts[4], frustumVerts[7]);
  1367. viewPlanes[FRUSTUM_PLANE_LEFT] = Plane(frustumVerts[4], frustumVerts[0], frustumVerts[3]);
  1368. viewPlanes[FRUSTUM_PLANE_RIGHT] = Plane(frustumVerts[1], frustumVerts[5], frustumVerts[6]);
  1369. viewPlanes[FRUSTUM_PLANE_TOP] = Plane(frustumVerts[4], frustumVerts[5], frustumVerts[1]);
  1370. viewPlanes[FRUSTUM_PLANE_BOTTOM] = Plane(frustumVerts[3], frustumVerts[2], frustumVerts[6]);
  1371. //// Add camera's planes facing towards the lights (forming the back of the volume)
  1372. Vector<Plane> lightVolume;
  1373. for(auto& entry : viewPlanes)
  1374. {
  1375. if (entry.normal.dot(lightDir) < 0.0f)
  1376. lightVolume.push_back(entry);
  1377. }
  1378. //// Determine edge planes by testing adjacent planes with different facing
  1379. ////// Pairs of frustum planes that share an edge
  1380. UINT32 adjacentPlanes[][2] =
  1381. {
  1382. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_LEFT },
  1383. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_RIGHT },
  1384. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_TOP },
  1385. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_BOTTOM },
  1386. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_LEFT },
  1387. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_RIGHT },
  1388. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_TOP },
  1389. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_BOTTOM },
  1390. { FRUSTUM_PLANE_LEFT, FRUSTUM_PLANE_TOP },
  1391. { FRUSTUM_PLANE_TOP, FRUSTUM_PLANE_RIGHT },
  1392. { FRUSTUM_PLANE_RIGHT, FRUSTUM_PLANE_BOTTOM },
  1393. { FRUSTUM_PLANE_BOTTOM, FRUSTUM_PLANE_LEFT },
  1394. };
  1395. ////// Vertex indices of edges on the boundary between two planes
  1396. UINT32 sharedEdges[][2] =
  1397. {
  1398. { 3, 0 },{ 1, 2 },{ 0, 1 },{ 2, 3 },
  1399. { 4, 7 },{ 6, 5 },{ 5, 4 },{ 7, 6 },
  1400. { 4, 0 },{ 5, 1 },{ 6, 2 },{ 7, 3 }
  1401. };
  1402. for(UINT32 i = 0; i < 12; i++)
  1403. {
  1404. const Plane& planeA = viewPlanes[adjacentPlanes[i][0]];
  1405. const Plane& planeB = viewPlanes[adjacentPlanes[i][1]];
  1406. float dotA = planeA.normal.dot(lightDir);
  1407. float dotB = planeB.normal.dot(lightDir);
  1408. if((dotA * dotB) < 0.0f)
  1409. {
  1410. const Vector3& vertA = frustumVerts[sharedEdges[i][0]];
  1411. const Vector3& vertB = frustumVerts[sharedEdges[i][1]];
  1412. Vector3 vertC = vertA + lightDir;
  1413. if (dotA < 0.0f)
  1414. lightVolume.push_back(Plane(vertA, vertB, vertC));
  1415. else
  1416. lightVolume.push_back(Plane(vertB, vertA, vertC));
  1417. }
  1418. }
  1419. return ConvexVolume(lightVolume);
  1420. }
  1421. float ShadowRendering::getCSMSplitDistance(const RendererView& view, UINT32 index, UINT32 numCascades)
  1422. {
  1423. auto& shadowSettings = view.getRenderSettings().shadowSettings;
  1424. float distributionExponent = shadowSettings.cascadeDistributionExponent;
  1425. // First determine the scale of the split, relative to the entire range
  1426. float scaleModifier = 1.0f;
  1427. float scale = 0.0f;
  1428. float totalScale = 0.0f;
  1429. //// Split 0 corresponds to near plane
  1430. if (index > 0)
  1431. {
  1432. for (UINT32 i = 0; i < numCascades; i++)
  1433. {
  1434. if (i < index)
  1435. scale += scaleModifier;
  1436. totalScale += scaleModifier;
  1437. scaleModifier *= distributionExponent;
  1438. }
  1439. scale = scale / totalScale;
  1440. }
  1441. // Calculate split distance in Z
  1442. auto& viewProps = view.getProperties();
  1443. float near = viewProps.nearPlane;
  1444. float far = Math::clamp(shadowSettings.directionalShadowDistance, viewProps.nearPlane, viewProps.farPlane);
  1445. return near + (far - near) * scale;
  1446. }
  1447. float ShadowRendering::getDepthBias(const Light& light, float radius, float depthRange, UINT32 mapSize)
  1448. {
  1449. const static float RADIAL_LIGHT_BIAS = 0.0005f;
  1450. const static float SPOT_DEPTH_BIAS = 0.01f;
  1451. const static float DIR_DEPTH_BIAS = 0.001f; // In clip space units
  1452. const static float DEFAULT_RESOLUTION = 512.0f;
  1453. // Increase bias if map size smaller than some resolution
  1454. float resolutionScale = 1.0f;
  1455. if (light.getType() != LightType::Directional)
  1456. resolutionScale = DEFAULT_RESOLUTION / (float)mapSize;
  1457. // Adjust range because in shader we compare vs. clip space depth
  1458. float rangeScale = 1.0f;
  1459. if (light.getType() == LightType::Spot)
  1460. rangeScale = 1.0f / depthRange;
  1461. auto& apiInfo = RenderAPI::instance().getAPIInfo();
  1462. float deviceDepthRange = apiInfo.getMaximumDepthInputValue() - apiInfo.getMinimumDepthInputValue();
  1463. float defaultBias = 1.0f;
  1464. switch(light.getType())
  1465. {
  1466. case LightType::Directional:
  1467. defaultBias = DIR_DEPTH_BIAS * deviceDepthRange;
  1468. break;
  1469. case LightType::Radial:
  1470. defaultBias = RADIAL_LIGHT_BIAS;
  1471. break;
  1472. case LightType::Spot:
  1473. defaultBias = SPOT_DEPTH_BIAS;
  1474. break;
  1475. default:
  1476. break;
  1477. }
  1478. return defaultBias * light.getShadowBias() * resolutionScale * rangeScale;
  1479. }
  1480. float ShadowRendering::getFadeTransition(const Light& light, float radius, float depthRange, UINT32 mapSize)
  1481. {
  1482. const static float SPOT_LIGHT_SCALE = 1000.0f;
  1483. const static float DIR_LIGHT_SCALE = 50000000.0f;
  1484. // Note: Currently fade transitions are only used in spot & directional (non omni-directional) lights, so no need
  1485. // to account for radial light type.
  1486. if (light.getType() == LightType::Directional)
  1487. {
  1488. // Reduce the size of the transition region when shadow map resolution is higher
  1489. float resolutionScale = 1.0f / (float)mapSize;
  1490. // Reduce the size of the transition region when the depth range is larger
  1491. float rangeScale = 1.0f / depthRange;
  1492. // Increase the size of the transition region for larger lights
  1493. float radiusScale = radius;
  1494. return DIR_LIGHT_SCALE * rangeScale * resolutionScale * radiusScale;
  1495. }
  1496. else
  1497. return fabs(light.getShadowBias()) * SPOT_LIGHT_SCALE;
  1498. }
  1499. }}