BsShadowRendering.cpp 56 KB

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