BsShadowRendering.cpp 62 KB

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