BsShadowRendering.cpp 57 KB

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