BsRenderCompositor.cpp 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsRenderCompositor.h"
  4. #include "BsGpuResourcePool.h"
  5. #include "BsRendererView.h"
  6. #include "Renderer/BsRendererUtility.h"
  7. #include "Mesh/BsMesh.h"
  8. #include "RenderAPI/BsGpuBuffer.h"
  9. #include "BsStandardDeferredLighting.h"
  10. #include "BsRenderBeastOptions.h"
  11. #include "Renderer/BsCamera.h"
  12. #include "BsRendererScene.h"
  13. #include "BsRenderBeast.h"
  14. #include "Utility/BsBitwise.h"
  15. #include "BsRendererTextures.h"
  16. #include "BsObjectRendering.h"
  17. #include "Material/BsGpuParamsSet.h"
  18. #include "Renderer/BsRendererExtension.h"
  19. #include "Renderer/BsSkybox.h"
  20. #include "BsLightProbes.h"
  21. namespace bs { namespace ct
  22. {
  23. UnorderedMap<StringID, RenderCompositor::NodeType*> RenderCompositor::mNodeTypes;
  24. RenderCompositor::~RenderCompositor()
  25. {
  26. clear();
  27. }
  28. void RenderCompositor::build(const RendererView& view, const StringID& finalNode)
  29. {
  30. clear();
  31. bs_frame_mark();
  32. {
  33. FrameUnorderedMap<StringID, UINT32> processedNodes;
  34. mIsValid = true;
  35. std::function<bool(const StringID&)> registerNode = [&](const StringID& nodeId)
  36. {
  37. // Find node type
  38. auto iterFind = mNodeTypes.find(nodeId);
  39. if (iterFind == mNodeTypes.end())
  40. {
  41. LOGERR("Cannot find render compositor node of type \"" + String(nodeId.cstr()) + "\".");
  42. return false;
  43. }
  44. NodeType* nodeType = iterFind->second;
  45. // Register current node
  46. auto iterFind2 = processedNodes.find(nodeId);
  47. // New node
  48. if (iterFind2 == processedNodes.end())
  49. {
  50. // Mark it as invalid for now
  51. processedNodes[nodeId] = -1;
  52. }
  53. // Register node dependencies
  54. SmallVector<StringID, 4> depIds = nodeType->getDependencies(view);
  55. for (auto& dep : depIds)
  56. {
  57. if (!registerNode(dep))
  58. return false;
  59. }
  60. // Register current node
  61. UINT32 curIdx;
  62. // New node, properly populate its index
  63. if (iterFind2 == processedNodes.end())
  64. {
  65. iterFind2 = processedNodes.find(nodeId);
  66. curIdx = (UINT32)mNodeInfos.size();
  67. mNodeInfos.push_back(NodeInfo());
  68. processedNodes[nodeId] = curIdx;
  69. NodeInfo& nodeInfo = mNodeInfos.back();
  70. nodeInfo.node = nodeType->create();
  71. nodeInfo.lastUseIdx = -1;
  72. for (auto& depId : depIds)
  73. {
  74. iterFind2 = processedNodes.find(depId);
  75. NodeInfo& depNodeInfo = mNodeInfos[iterFind2->second];
  76. nodeInfo.inputs.push_back(depNodeInfo.node);
  77. }
  78. }
  79. else // Existing node
  80. {
  81. curIdx = iterFind2->second;
  82. // Check if invalid
  83. if (curIdx == -1)
  84. {
  85. LOGERR("Render compositor nodes recursion detected. Node \"" + String(nodeId.cstr()) + "\" " +
  86. "depends on node \"" + String(iterFind->first.cstr()) + "\" which is not available at " +
  87. "this stage.");
  88. return false;
  89. }
  90. }
  91. // Update dependency last use counters
  92. for (auto& dep : depIds)
  93. {
  94. iterFind2 = processedNodes.find(dep);
  95. NodeInfo& depNodeInfo = mNodeInfos[iterFind2->second];
  96. if (depNodeInfo.lastUseIdx == -1)
  97. depNodeInfo.lastUseIdx = curIdx;
  98. else
  99. depNodeInfo.lastUseIdx = std::max(depNodeInfo.lastUseIdx, curIdx);
  100. }
  101. return true;
  102. };
  103. mIsValid = registerNode(finalNode);
  104. if (!mIsValid)
  105. clear();
  106. }
  107. bs_frame_clear();
  108. }
  109. void RenderCompositor::execute(RenderCompositorNodeInputs& inputs) const
  110. {
  111. if (!mIsValid)
  112. return;
  113. bs_frame_mark();
  114. {
  115. FrameVector<const NodeInfo*> activeNodes;
  116. UINT32 idx = 0;
  117. for (auto& entry : mNodeInfos)
  118. {
  119. inputs.inputNodes = entry.inputs;
  120. entry.node->render(inputs);
  121. activeNodes.push_back(&entry);
  122. for (UINT32 i = 0; i < (UINT32)activeNodes.size(); ++i)
  123. {
  124. if (activeNodes[i] == nullptr)
  125. continue;
  126. if (activeNodes[i]->lastUseIdx <= idx)
  127. {
  128. activeNodes[i]->node->clear();
  129. activeNodes[i] = nullptr;
  130. }
  131. }
  132. idx++;
  133. }
  134. }
  135. bs_frame_clear();
  136. if (!mNodeInfos.empty())
  137. mNodeInfos.back().node->clear();
  138. }
  139. void RenderCompositor::clear()
  140. {
  141. for (auto& entry : mNodeInfos)
  142. bs_delete(entry.node);
  143. mNodeInfos.clear();
  144. mIsValid = false;
  145. }
  146. void RCNodeSceneDepth::render(const RenderCompositorNodeInputs& inputs)
  147. {
  148. GpuResourcePool& resPool = GpuResourcePool::instance();
  149. const RendererViewProperties& viewProps = inputs.view.getProperties();
  150. UINT32 width = viewProps.viewRect.width;
  151. UINT32 height = viewProps.viewRect.height;
  152. UINT32 numSamples = viewProps.numSamples;
  153. depthTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_D32_S8X24, width, height, TU_DEPTHSTENCIL,
  154. numSamples, false));
  155. }
  156. void RCNodeSceneDepth::clear()
  157. {
  158. GpuResourcePool& resPool = GpuResourcePool::instance();
  159. resPool.release(depthTex);
  160. }
  161. SmallVector<StringID, 4> RCNodeSceneDepth::getDependencies(const RendererView& view)
  162. {
  163. return {};
  164. }
  165. void RCNodeGBuffer::render(const RenderCompositorNodeInputs& inputs)
  166. {
  167. // Allocate necessary textures & targets
  168. GpuResourcePool& resPool = GpuResourcePool::instance();
  169. const RendererViewProperties& viewProps = inputs.view.getProperties();
  170. UINT32 width = viewProps.viewRect.width;
  171. UINT32 height = viewProps.viewRect.height;
  172. UINT32 numSamples = viewProps.numSamples;
  173. // Note: Consider customizable formats. e.g. for testing if quality can be improved with higher precision normals.
  174. albedoTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA8, width, height, TU_RENDERTARGET,
  175. numSamples, true));
  176. normalTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGB10A2, width, height, TU_RENDERTARGET,
  177. numSamples, false));
  178. roughMetalTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RG16F, width, height, TU_RENDERTARGET,
  179. numSamples, false)); // Note: Metal doesn't need 16-bit float
  180. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[0]);
  181. SPtr<PooledRenderTexture> sceneDepthTex = sceneDepthNode->depthTex;
  182. bool rebuildRT = false;
  183. if (renderTarget != nullptr)
  184. {
  185. rebuildRT |= renderTarget->getColorTexture(0) != albedoTex->texture;
  186. rebuildRT |= renderTarget->getColorTexture(1) != normalTex->texture;
  187. rebuildRT |= renderTarget->getColorTexture(2) != roughMetalTex->texture;
  188. rebuildRT |= renderTarget->getDepthStencilTexture() != sceneDepthTex->texture;
  189. }
  190. else
  191. rebuildRT = true;
  192. if (renderTarget == nullptr || rebuildRT)
  193. {
  194. RENDER_TEXTURE_DESC gbufferDesc;
  195. gbufferDesc.colorSurfaces[0].texture = albedoTex->texture;
  196. gbufferDesc.colorSurfaces[0].face = 0;
  197. gbufferDesc.colorSurfaces[0].numFaces = 1;
  198. gbufferDesc.colorSurfaces[0].mipLevel = 0;
  199. gbufferDesc.colorSurfaces[1].texture = normalTex->texture;
  200. gbufferDesc.colorSurfaces[1].face = 0;
  201. gbufferDesc.colorSurfaces[1].numFaces = 1;
  202. gbufferDesc.colorSurfaces[1].mipLevel = 0;
  203. gbufferDesc.colorSurfaces[2].texture = roughMetalTex->texture;
  204. gbufferDesc.colorSurfaces[2].face = 0;
  205. gbufferDesc.colorSurfaces[2].numFaces = 1;
  206. gbufferDesc.colorSurfaces[2].mipLevel = 0;
  207. gbufferDesc.depthStencilSurface.texture = sceneDepthTex->texture;
  208. gbufferDesc.depthStencilSurface.face = 0;
  209. gbufferDesc.depthStencilSurface.mipLevel = 0;
  210. renderTarget = RenderTexture::create(gbufferDesc);
  211. }
  212. // Prepare all visible objects. Note that this also prepares non-opaque objects.
  213. const VisibilityInfo& visibility = inputs.view.getVisibilityMasks();
  214. UINT32 numRenderables = (UINT32)inputs.scene.renderables.size();
  215. for (UINT32 i = 0; i < numRenderables; i++)
  216. {
  217. if (!visibility.renderables[i])
  218. continue;
  219. RendererObject* rendererObject = inputs.scene.renderables[i];
  220. rendererObject->updatePerCallBuffer(viewProps.viewProjTransform);
  221. for (auto& element : inputs.scene.renderables[i]->elements)
  222. {
  223. if (element.perCameraBindingIdx != -1)
  224. element.params->setParamBlockBuffer(element.perCameraBindingIdx, inputs.view.getPerViewBuffer(), true);
  225. }
  226. }
  227. Camera* sceneCamera = inputs.view.getSceneCamera();
  228. // Trigger pre-base-pass callbacks
  229. if (sceneCamera != nullptr)
  230. {
  231. for(auto& extension : inputs.extPreBasePass)
  232. {
  233. if (extension->check(*sceneCamera))
  234. extension->render(*sceneCamera);
  235. }
  236. }
  237. // Render base pass
  238. RenderAPI& rapi = RenderAPI::instance();
  239. rapi.setRenderTarget(renderTarget);
  240. Rect2 area(0.0f, 0.0f, 1.0f, 1.0f);
  241. rapi.setViewport(area);
  242. // Clear all targets
  243. rapi.clearViewport(FBT_COLOR | FBT_DEPTH | FBT_STENCIL, Color::ZERO, 1.0f, 0);
  244. // Render all visible opaque elements
  245. const Vector<RenderQueueElement>& opaqueElements = inputs.view.getOpaqueQueue()->getSortedElements();
  246. for (auto iter = opaqueElements.begin(); iter != opaqueElements.end(); ++iter)
  247. {
  248. BeastRenderableElement* renderElem = static_cast<BeastRenderableElement*>(iter->renderElem);
  249. SPtr<Material> material = renderElem->material;
  250. if (iter->applyPass)
  251. gRendererUtility().setPass(material, iter->passIdx, renderElem->techniqueIdx);
  252. gRendererUtility().setPassParams(renderElem->params, iter->passIdx);
  253. if(renderElem->morphVertexDeclaration == nullptr)
  254. gRendererUtility().draw(renderElem->mesh, renderElem->subMesh);
  255. else
  256. gRendererUtility().drawMorph(renderElem->mesh, renderElem->subMesh, renderElem->morphShapeBuffer,
  257. renderElem->morphVertexDeclaration);
  258. }
  259. // Trigger post-base-pass callbacks
  260. if (sceneCamera != nullptr)
  261. {
  262. for(auto& extension : inputs.extPostBasePass)
  263. {
  264. if (extension->check(*sceneCamera))
  265. extension->render(*sceneCamera);
  266. }
  267. }
  268. }
  269. void RCNodeGBuffer::clear()
  270. {
  271. GpuResourcePool& resPool = GpuResourcePool::instance();
  272. resPool.release(albedoTex);
  273. resPool.release(normalTex);
  274. resPool.release(roughMetalTex);
  275. }
  276. SmallVector<StringID, 4> RCNodeGBuffer::getDependencies(const RendererView& view)
  277. {
  278. return { RCNodeSceneDepth::getNodeId() };
  279. }
  280. void RCNodeSceneColor::render(const RenderCompositorNodeInputs& inputs)
  281. {
  282. GpuResourcePool& resPool = GpuResourcePool::instance();
  283. const RendererViewProperties& viewProps = inputs.view.getProperties();
  284. UINT32 width = viewProps.viewRect.width;
  285. UINT32 height = viewProps.viewRect.height;
  286. UINT32 numSamples = viewProps.numSamples;
  287. // Note: Consider customizable HDR format via options? e.g. smaller PF_FLOAT_R11G11B10 or larger 32-bit format
  288. sceneColorTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width, height, TU_RENDERTARGET |
  289. TU_LOADSTORE, numSamples, false));
  290. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[0]);
  291. SPtr<PooledRenderTexture> sceneDepthTex = sceneDepthNode->depthTex;
  292. if (viewProps.numSamples > 1)
  293. {
  294. UINT32 bufferNumElements = width * height * viewProps.numSamples;
  295. flattenedSceneColorBuffer = resPool.get(POOLED_STORAGE_BUFFER_DESC::createStandard(BF_16X4F, bufferNumElements));
  296. }
  297. else
  298. flattenedSceneColorBuffer = nullptr;
  299. bool rebuildRT = false;
  300. if (renderTarget != nullptr)
  301. {
  302. rebuildRT |= renderTarget->getColorTexture(0) != sceneColorTex->texture;
  303. rebuildRT |= renderTarget->getDepthStencilTexture() != sceneDepthTex->texture;
  304. }
  305. else
  306. rebuildRT = true;
  307. if (rebuildRT)
  308. {
  309. RENDER_TEXTURE_DESC sceneColorDesc;
  310. sceneColorDesc.colorSurfaces[0].texture = sceneColorTex->texture;
  311. sceneColorDesc.colorSurfaces[0].face = 0;
  312. sceneColorDesc.colorSurfaces[0].numFaces = 1;
  313. sceneColorDesc.colorSurfaces[0].mipLevel = 0;
  314. sceneColorDesc.depthStencilSurface.texture = sceneDepthTex->texture;
  315. sceneColorDesc.depthStencilSurface.face = 0;
  316. sceneColorDesc.depthStencilSurface.numFaces = 1;
  317. sceneColorDesc.depthStencilSurface.mipLevel = 0;
  318. renderTarget = RenderTexture::create(sceneColorDesc);
  319. }
  320. }
  321. void RCNodeSceneColor::clear()
  322. {
  323. GpuResourcePool& resPool = GpuResourcePool::instance();
  324. resPool.release(sceneColorTex);
  325. if (flattenedSceneColorBuffer != nullptr)
  326. resPool.release(flattenedSceneColorBuffer);
  327. }
  328. SmallVector<StringID, 4> RCNodeSceneColor::getDependencies(const RendererView& view)
  329. {
  330. return { RCNodeSceneDepth::getNodeId() };
  331. }
  332. void RCNodeMSAACoverage::render(const RenderCompositorNodeInputs& inputs)
  333. {
  334. GpuResourcePool& resPool = GpuResourcePool::instance();
  335. const RendererViewProperties& viewProps = inputs.view.getProperties();
  336. UINT32 width = viewProps.viewRect.width;
  337. UINT32 height = viewProps.viewRect.height;
  338. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, width, height, TU_RENDERTARGET));
  339. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[0]);
  340. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[1]);
  341. GBufferTextures gbuffer;
  342. gbuffer.albedo = gbufferNode->albedoTex->texture;
  343. gbuffer.normals = gbufferNode->normalTex->texture;
  344. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  345. gbuffer.depth = sceneDepthNode->depthTex->texture;
  346. MSAACoverageMat* mat = MSAACoverageMat::getVariation(viewProps.numSamples);
  347. RenderAPI& rapi = RenderAPI::instance();
  348. rapi.setRenderTarget(output->renderTexture);
  349. mat->execute(inputs.view, gbuffer);
  350. MSAACoverageStencilMat* stencilMat = MSAACoverageStencilMat::get();
  351. rapi.setRenderTarget(sceneDepthNode->depthTex->renderTexture);
  352. stencilMat->execute(inputs.view, output->texture);
  353. }
  354. void RCNodeMSAACoverage::clear()
  355. {
  356. GpuResourcePool& resPool = GpuResourcePool::instance();
  357. resPool.release(output);
  358. }
  359. SmallVector<StringID, 4> RCNodeMSAACoverage::getDependencies(const RendererView& view)
  360. {
  361. return { RCNodeGBuffer::getNodeId(), RCNodeSceneDepth::getNodeId() };
  362. }
  363. void RCNodeLightAccumulation::render(const RenderCompositorNodeInputs& inputs)
  364. {
  365. GpuResourcePool& resPool = GpuResourcePool::instance();
  366. const RendererViewProperties& viewProps = inputs.view.getProperties();
  367. RCNodeSceneDepth* depthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[0]);
  368. UINT32 width = viewProps.viewRect.width;
  369. UINT32 height = viewProps.viewRect.height;
  370. UINT32 numSamples = viewProps.numSamples;
  371. if (numSamples > 1)
  372. {
  373. UINT32 bufferNumElements = width * height * numSamples;
  374. flattenedLightAccumBuffer =
  375. resPool.get(POOLED_STORAGE_BUFFER_DESC::createStandard(BF_16X4F, bufferNumElements));
  376. SPtr<GpuBuffer> buffer = flattenedLightAccumBuffer->buffer;
  377. auto& bufferProps = buffer->getProperties();
  378. UINT32 bufferSize = bufferProps.getElementSize() * bufferProps.getElementCount();
  379. UINT16* data = (UINT16*)buffer->lock(0, bufferSize, GBL_WRITE_ONLY_DISCARD);
  380. {
  381. memset(data, 0, bufferSize);
  382. }
  383. buffer->unlock();
  384. }
  385. else
  386. flattenedLightAccumBuffer = nullptr;
  387. lightAccumulationTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width,
  388. height, TU_LOADSTORE | TU_RENDERTARGET, numSamples, false));
  389. bool rebuildRT;
  390. if (renderTarget != nullptr)
  391. {
  392. rebuildRT = renderTarget->getColorTexture(0) != lightAccumulationTex->texture;
  393. rebuildRT |= renderTarget->getDepthStencilTexture() != depthNode->depthTex->texture;
  394. }
  395. else
  396. rebuildRT = true;
  397. if (rebuildRT)
  398. {
  399. RENDER_TEXTURE_DESC lightAccumulationRTDesc;
  400. lightAccumulationRTDesc.colorSurfaces[0].texture = lightAccumulationTex->texture;
  401. lightAccumulationRTDesc.colorSurfaces[0].face = 0;
  402. lightAccumulationRTDesc.colorSurfaces[0].numFaces = 1;
  403. lightAccumulationRTDesc.colorSurfaces[0].mipLevel = 0;
  404. lightAccumulationRTDesc.depthStencilSurface.texture = depthNode->depthTex->texture;
  405. lightAccumulationRTDesc.depthStencilSurface.face = 0;
  406. lightAccumulationRTDesc.depthStencilSurface.numFaces = 1;
  407. lightAccumulationRTDesc.depthStencilSurface.mipLevel = 0;
  408. renderTarget = RenderTexture::create(lightAccumulationRTDesc);
  409. }
  410. }
  411. void RCNodeLightAccumulation::clear()
  412. {
  413. GpuResourcePool& resPool = GpuResourcePool::instance();
  414. resPool.release(lightAccumulationTex);
  415. if (flattenedLightAccumBuffer)
  416. resPool.release(flattenedLightAccumBuffer);
  417. }
  418. SmallVector<StringID, 4> RCNodeLightAccumulation::getDependencies(const RendererView& view)
  419. {
  420. return { RCNodeSceneDepth::getNodeId() };
  421. }
  422. void RCNodeTiledDeferredLighting::render(const RenderCompositorNodeInputs& inputs)
  423. {
  424. output = static_cast<RCNodeLightAccumulation*>(inputs.inputNodes[0]);
  425. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[1]);
  426. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[2]);
  427. const RendererViewProperties& viewProps = inputs.view.getProperties();
  428. SPtr<Texture> msaaCoverage;
  429. if(viewProps.numSamples > 1)
  430. {
  431. RCNodeMSAACoverage* coverageNode = static_cast<RCNodeMSAACoverage*>(inputs.inputNodes[3]);
  432. msaaCoverage = coverageNode->output->texture;
  433. }
  434. TiledDeferredLightingMat* tiledDeferredMat = TiledDeferredLightingMat::getVariation(viewProps.numSamples);
  435. GBufferTextures gbuffer;
  436. gbuffer.albedo = gbufferNode->albedoTex->texture;
  437. gbuffer.normals = gbufferNode->normalTex->texture;
  438. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  439. gbuffer.depth = sceneDepthNode->depthTex->texture;
  440. RenderAPI& rapi = RenderAPI::instance();
  441. rapi.setRenderTarget(output->renderTarget, FBT_DEPTH | FBT_STENCIL, RT_COLOR0 | RT_DEPTH_STENCIL);
  442. const VisibleLightData& lightData = inputs.viewGroup.getVisibleLightData();
  443. SPtr<GpuBuffer> flattenedLightAccumBuffer;
  444. if (output->flattenedLightAccumBuffer)
  445. flattenedLightAccumBuffer = output->flattenedLightAccumBuffer->buffer;
  446. tiledDeferredMat->execute(inputs.view, lightData, gbuffer, output->lightAccumulationTex->texture,
  447. flattenedLightAccumBuffer, msaaCoverage);
  448. }
  449. void RCNodeTiledDeferredLighting::clear()
  450. {
  451. output = nullptr;
  452. }
  453. SmallVector<StringID, 4> RCNodeTiledDeferredLighting::getDependencies(const RendererView& view)
  454. {
  455. SmallVector<StringID, 4> deps;
  456. deps.push_back(RCNodeLightAccumulation::getNodeId());
  457. deps.push_back(RCNodeGBuffer::getNodeId());
  458. deps.push_back(RCNodeSceneDepth::getNodeId());
  459. if(view.getProperties().numSamples > 1)
  460. deps.push_back(RCNodeMSAACoverage::getNodeId());
  461. return deps;
  462. }
  463. void RCNodeStandardDeferredLighting::render(const RenderCompositorNodeInputs& inputs)
  464. {
  465. RCNodeTiledDeferredLighting* tileDeferredNode = static_cast<RCNodeTiledDeferredLighting*>(inputs.inputNodes[0]);
  466. output = tileDeferredNode->output;
  467. // If shadows are disabled we handle all lights through tiled deferred
  468. if (!inputs.view.getRenderSettings().enableShadows)
  469. {
  470. mLightOcclusionRT = nullptr;
  471. return;
  472. }
  473. GpuResourcePool& resPool = GpuResourcePool::instance();
  474. const RendererViewProperties& viewProps = inputs.view.getProperties();
  475. UINT32 width = viewProps.viewRect.width;
  476. UINT32 height = viewProps.viewRect.height;
  477. UINT32 numSamples = viewProps.numSamples;
  478. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[1]);
  479. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[2]);
  480. // Allocate light occlusion
  481. SPtr<PooledRenderTexture> lightOcclusionTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, width,
  482. height, TU_RENDERTARGET, numSamples, false));
  483. bool rebuildRT = false;
  484. if (mLightOcclusionRT != nullptr)
  485. {
  486. rebuildRT |= mLightOcclusionRT->getColorTexture(0) != lightOcclusionTex->texture;
  487. rebuildRT |= mLightOcclusionRT->getDepthStencilTexture() != sceneDepthNode->depthTex->texture;
  488. }
  489. else
  490. rebuildRT = true;
  491. if (rebuildRT)
  492. {
  493. RENDER_TEXTURE_DESC lightOcclusionRTDesc;
  494. lightOcclusionRTDesc.colorSurfaces[0].texture = lightOcclusionTex->texture;
  495. lightOcclusionRTDesc.colorSurfaces[0].face = 0;
  496. lightOcclusionRTDesc.colorSurfaces[0].numFaces = 1;
  497. lightOcclusionRTDesc.colorSurfaces[0].mipLevel = 0;
  498. lightOcclusionRTDesc.depthStencilSurface.texture = sceneDepthNode->depthTex->texture;
  499. lightOcclusionRTDesc.depthStencilSurface.face = 0;
  500. lightOcclusionRTDesc.depthStencilSurface.numFaces = 1;
  501. lightOcclusionRTDesc.depthStencilSurface.mipLevel = 0;
  502. mLightOcclusionRT = RenderTexture::create(lightOcclusionRTDesc);
  503. }
  504. GBufferTextures gbuffer;
  505. gbuffer.albedo = gbufferNode->albedoTex->texture;
  506. gbuffer.normals = gbufferNode->normalTex->texture;
  507. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  508. gbuffer.depth = sceneDepthNode->depthTex->texture;
  509. const VisibleLightData& lightData = inputs.viewGroup.getVisibleLightData();
  510. const ShadowRendering& shadowRenderer = inputs.viewGroup.getShadowRenderer();
  511. RenderAPI& rapi = RenderAPI::instance();
  512. for (UINT32 i = 0; i < (UINT32)LightType::Count; i++)
  513. {
  514. LightType lightType = (LightType)i;
  515. auto& lights = lightData.getLights(lightType);
  516. UINT32 count = lightData.getNumShadowedLights(lightType);
  517. UINT32 offset = lightData.getNumUnshadowedLights(lightType);
  518. for (UINT32 j = 0; j < count; j++)
  519. {
  520. rapi.setRenderTarget(mLightOcclusionRT, FBT_DEPTH, RT_DEPTH_STENCIL);
  521. Rect2 area(0.0f, 0.0f, 1.0f, 1.0f);
  522. rapi.setViewport(area);
  523. rapi.clearViewport(FBT_COLOR, Color::ZERO);
  524. UINT32 lightIdx = offset + j;
  525. const RendererLight& light = *lights[lightIdx];
  526. shadowRenderer.renderShadowOcclusion(inputs.view, inputs.options.shadowFilteringQuality, light, gbuffer);
  527. rapi.setRenderTarget(output->renderTarget, FBT_DEPTH | FBT_STENCIL, RT_COLOR0 | RT_DEPTH_STENCIL);
  528. StandardDeferred::instance().renderLight(lightType, light, inputs.view, gbuffer,
  529. lightOcclusionTex->texture);
  530. }
  531. }
  532. // Makes sure light accumulation can be read by following passes
  533. rapi.setRenderTarget(nullptr);
  534. resPool.release(lightOcclusionTex);
  535. }
  536. void RCNodeStandardDeferredLighting::clear()
  537. {
  538. output = nullptr;
  539. }
  540. SmallVector<StringID, 4> RCNodeStandardDeferredLighting::getDependencies(const RendererView& view)
  541. {
  542. SmallVector<StringID, 4> deps;
  543. deps.push_back(RCNodeTiledDeferredLighting::getNodeId());
  544. deps.push_back(RCNodeGBuffer::getNodeId());
  545. deps.push_back(RCNodeSceneDepth::getNodeId());
  546. if (view.getProperties().numSamples > 1)
  547. deps.push_back(RCNodeUnflattenLightAccum::getNodeId());
  548. return deps;
  549. }
  550. void RCNodeUnflattenLightAccum::render(const RenderCompositorNodeInputs& inputs)
  551. {
  552. RCNodeLightAccumulation* lightAccumNode = static_cast<RCNodeLightAccumulation*>(inputs.inputNodes[0]);
  553. FlatFramebufferToTextureMat* material = FlatFramebufferToTextureMat::get();
  554. RenderAPI& rapi = RenderAPI::instance();
  555. rapi.setRenderTarget(lightAccumNode->renderTarget, FBT_DEPTH | FBT_STENCIL, RT_COLOR0 | RT_DEPTH_STENCIL);
  556. material->execute(lightAccumNode->flattenedLightAccumBuffer->buffer, lightAccumNode->lightAccumulationTex->texture);
  557. }
  558. void RCNodeUnflattenLightAccum::clear()
  559. {
  560. output = nullptr;
  561. }
  562. SmallVector<StringID, 4> RCNodeUnflattenLightAccum::getDependencies(const RendererView& view)
  563. {
  564. return { RCNodeLightAccumulation::getNodeId() };
  565. }
  566. void RCNodeIndirectLighting::render(const RenderCompositorNodeInputs& inputs)
  567. {
  568. if (!inputs.view.getRenderSettings().enableIndirectLighting)
  569. return;
  570. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[0]);
  571. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[1]);
  572. RCNodeLightAccumulation* lightAccumNode = static_cast <RCNodeLightAccumulation*>(inputs.inputNodes[2]);
  573. SPtr<Texture> ssao;
  574. if (inputs.view.getRenderSettings().ambientOcclusion.enabled)
  575. {
  576. RCNodeSSAO* ssaoNode = static_cast<RCNodeSSAO*>(inputs.inputNodes[4]);
  577. ssao = ssaoNode->output->texture;
  578. }
  579. else
  580. ssao = Texture::WHITE;
  581. GpuResourcePool& resPool = GpuResourcePool::instance();
  582. const RendererViewProperties& viewProps = inputs.view.getProperties();
  583. const LightProbes& lightProbes = inputs.scene.lightProbes;
  584. LightProbesInfo lpInfo = lightProbes.getInfo();
  585. IrradianceEvaluateMat* evaluateMat;
  586. SPtr<PooledRenderTexture> volumeIndices;
  587. if(lightProbes.hasAnyProbes())
  588. {
  589. POOLED_RENDER_TEXTURE_DESC volumeIndicesDesc;
  590. POOLED_RENDER_TEXTURE_DESC depthDesc;
  591. TetrahedraRenderMat::getOutputDesc(inputs.view, volumeIndicesDesc, depthDesc);
  592. volumeIndices = resPool.get(volumeIndicesDesc);
  593. SPtr<PooledRenderTexture> depthTex = resPool.get(depthDesc);
  594. RENDER_TEXTURE_DESC rtDesc;
  595. rtDesc.colorSurfaces[0].texture = volumeIndices->texture;
  596. rtDesc.depthStencilSurface.texture = depthTex->texture;
  597. SPtr<RenderTexture> rt = RenderTexture::create(rtDesc);
  598. RenderAPI& rapi = RenderAPI::instance();
  599. rapi.setRenderTarget(rt);
  600. rapi.clearRenderTarget(FBT_DEPTH);
  601. gRendererUtility().clear(-1);
  602. TetrahedraRenderMat* renderTetrahedra = TetrahedraRenderMat::getVariation(viewProps.numSamples > 1, true);
  603. renderTetrahedra->execute(inputs.view, sceneDepthNode->depthTex->texture, lpInfo.tetrahedraVolume, rt);
  604. rt = nullptr;
  605. resPool.release(depthTex);
  606. evaluateMat = IrradianceEvaluateMat::getVariation(viewProps.numSamples > 1, true, false);
  607. }
  608. else // Sky only
  609. {
  610. evaluateMat = IrradianceEvaluateMat::getVariation(viewProps.numSamples > 1, true, true);
  611. }
  612. GBufferTextures gbuffer;
  613. gbuffer.albedo = gbufferNode->albedoTex->texture;
  614. gbuffer.normals = gbufferNode->normalTex->texture;
  615. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  616. gbuffer.depth = sceneDepthNode->depthTex->texture;
  617. SPtr<Texture> volumeIndicesTex;
  618. if (volumeIndices)
  619. volumeIndicesTex = volumeIndices->texture;
  620. evaluateMat->execute(inputs.view, gbuffer, volumeIndicesTex, lpInfo, inputs.scene.skybox, ssao,
  621. lightAccumNode->renderTarget);
  622. if(volumeIndices)
  623. resPool.release(volumeIndices);
  624. }
  625. void RCNodeIndirectLighting::clear()
  626. {
  627. // Do nothing
  628. }
  629. SmallVector<StringID, 4> RCNodeIndirectLighting::getDependencies(const RendererView& view)
  630. {
  631. SmallVector<StringID, 4> deps;
  632. deps.push_back(RCNodeGBuffer::getNodeId());
  633. deps.push_back(RCNodeSceneDepth::getNodeId());
  634. deps.push_back(RCNodeLightAccumulation::getNodeId());
  635. deps.push_back(RCNodeStandardDeferredLighting::getNodeId());
  636. if(view.getRenderSettings().ambientOcclusion.enabled)
  637. deps.push_back(RCNodeSSAO::getNodeId());
  638. if (view.getProperties().numSamples > 1)
  639. deps.push_back(RCNodeUnflattenLightAccum::getNodeId());
  640. return deps;
  641. }
  642. void RCNodeTiledDeferredIBL::render(const RenderCompositorNodeInputs& inputs)
  643. {
  644. const RenderSettings& rs = inputs.view.getRenderSettings();
  645. RCNodeSceneColor* sceneColorNode = static_cast<RCNodeSceneColor*>(inputs.inputNodes[0]);
  646. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[1]);
  647. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[2]);
  648. RCNodeLightAccumulation* lightAccumNode = static_cast <RCNodeLightAccumulation*>(inputs.inputNodes[3]);
  649. SPtr<Texture> ssr;
  650. if (rs.screenSpaceReflections.enabled)
  651. {
  652. RCNodeSSR* ssrNode = static_cast<RCNodeSSR*>(inputs.inputNodes[5]);
  653. ssr = ssrNode->output->texture;
  654. }
  655. else
  656. ssr = Texture::BLACK;
  657. UINT32 nodeIdx = 6;
  658. SPtr<Texture> ssao;
  659. if (rs.ambientOcclusion.enabled)
  660. {
  661. RCNodeSSAO* ssaoNode = static_cast<RCNodeSSAO*>(inputs.inputNodes[nodeIdx++]);
  662. ssao = ssaoNode->output->texture;
  663. }
  664. else
  665. ssao = Texture::WHITE;
  666. const RendererViewProperties& viewProps = inputs.view.getProperties();
  667. SPtr<Texture> msaaCoverage;
  668. if(viewProps.numSamples > 1)
  669. {
  670. RCNodeMSAACoverage* coverageNode = static_cast<RCNodeMSAACoverage*>(inputs.inputNodes[nodeIdx++]);
  671. msaaCoverage = coverageNode->output->texture;
  672. }
  673. TiledDeferredImageBasedLightingMat* material = TiledDeferredImageBasedLightingMat::getVariation(viewProps.numSamples);
  674. TiledDeferredImageBasedLightingMat::Inputs iblInputs;
  675. iblInputs.gbuffer.albedo = gbufferNode->albedoTex->texture;
  676. iblInputs.gbuffer.normals = gbufferNode->normalTex->texture;
  677. iblInputs.gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  678. iblInputs.gbuffer.depth = sceneDepthNode->depthTex->texture;
  679. iblInputs.sceneColorTex = sceneColorNode->sceneColorTex->texture;
  680. iblInputs.lightAccumulation = lightAccumNode->lightAccumulationTex->texture;
  681. iblInputs.preIntegratedGF = RendererTextures::preintegratedEnvGF;
  682. iblInputs.ambientOcclusion = ssao;
  683. iblInputs.ssr = ssr;
  684. iblInputs.msaaCoverage = msaaCoverage;
  685. if(sceneColorNode->flattenedSceneColorBuffer)
  686. iblInputs.sceneColorBuffer = sceneColorNode->flattenedSceneColorBuffer->buffer;
  687. material->execute(inputs.view, inputs.scene, inputs.viewGroup.getVisibleReflProbeData(), iblInputs);
  688. }
  689. void RCNodeTiledDeferredIBL::clear()
  690. {
  691. output = nullptr;
  692. }
  693. SmallVector<StringID, 4> RCNodeTiledDeferredIBL::getDependencies(const RendererView& view)
  694. {
  695. SmallVector<StringID, 4> deps;
  696. deps.push_back(RCNodeSceneColor::getNodeId());
  697. deps.push_back(RCNodeGBuffer::getNodeId());
  698. deps.push_back(RCNodeSceneDepth::getNodeId());
  699. deps.push_back(RCNodeLightAccumulation::getNodeId());
  700. deps.push_back(RCNodeIndirectLighting::getNodeId());
  701. deps.push_back(RCNodeSSR::getNodeId());
  702. if(view.getRenderSettings().ambientOcclusion.enabled)
  703. deps.push_back(RCNodeSSAO::getNodeId());
  704. if(view.getProperties().numSamples > 1)
  705. deps.push_back(RCNodeMSAACoverage::getNodeId());
  706. return deps;
  707. }
  708. void RCNodeUnflattenSceneColor::render(const RenderCompositorNodeInputs& inputs)
  709. {
  710. RCNodeSceneColor* sceneColorNode = static_cast<RCNodeSceneColor*>(inputs.inputNodes[0]);
  711. FlatFramebufferToTextureMat* material = FlatFramebufferToTextureMat::get();
  712. int readOnlyFlags = FBT_DEPTH | FBT_STENCIL;
  713. RenderAPI& rapi = RenderAPI::instance();
  714. rapi.setRenderTarget(sceneColorNode->renderTarget, readOnlyFlags, RT_COLOR0 | RT_DEPTH_STENCIL);
  715. Rect2 area(0.0f, 0.0f, 1.0f, 1.0f);
  716. rapi.setViewport(area);
  717. material->execute(sceneColorNode->flattenedSceneColorBuffer->buffer, sceneColorNode->sceneColorTex->texture);
  718. }
  719. void RCNodeUnflattenSceneColor::clear()
  720. {
  721. output = nullptr;
  722. }
  723. SmallVector<StringID, 4> RCNodeUnflattenSceneColor::getDependencies(const RendererView& view)
  724. {
  725. return { RCNodeSceneColor::getNodeId() };
  726. }
  727. RCNodeClusteredForward::RCNodeClusteredForward()
  728. {
  729. SAMPLER_STATE_DESC desc;
  730. desc.minFilter = FO_POINT;
  731. desc.magFilter = FO_POINT;
  732. desc.mipFilter = FO_POINT;
  733. desc.addressMode.u = TAM_CLAMP;
  734. desc.addressMode.v = TAM_CLAMP;
  735. desc.addressMode.w = TAM_CLAMP;
  736. mSSRAOSamplerState = SamplerState::create(desc);
  737. }
  738. void RCNodeClusteredForward::render(const RenderCompositorNodeInputs& inputs)
  739. {
  740. const SceneInfo& sceneInfo = inputs.scene;
  741. const RendererViewProperties& viewProps = inputs.view.getProperties();
  742. const VisibleLightData& visibleLightData = inputs.viewGroup.getVisibleLightData();
  743. const VisibleReflProbeData& visibleReflProbeData = inputs.viewGroup.getVisibleReflProbeData();
  744. const LightGrid& lightGrid = inputs.view.getLightGrid();
  745. SPtr<GpuParamBlockBuffer> gridParams;
  746. SPtr<GpuBuffer> gridLightOffsetsAndSize, gridLightIndices;
  747. SPtr<GpuBuffer> gridProbeOffsetsAndSize, gridProbeIndices;
  748. lightGrid.getOutputs(gridLightOffsetsAndSize, gridLightIndices, gridProbeOffsetsAndSize, gridProbeIndices,
  749. gridParams);
  750. // Prepare refl. probe param buffer
  751. ReflProbeParamBuffer reflProbeParamBuffer;
  752. reflProbeParamBuffer.populate(sceneInfo.skybox, visibleReflProbeData, sceneInfo.reflProbeCubemapsTex,
  753. viewProps.renderingReflections);
  754. SPtr<Texture> skyFilteredRadiance;
  755. if(sceneInfo.skybox)
  756. skyFilteredRadiance = sceneInfo.skybox->getFilteredRadiance();
  757. // Prepare objects for rendering
  758. const VisibilityInfo& visibility = inputs.view.getVisibilityMasks();
  759. UINT32 numRenderables = (UINT32)sceneInfo.renderables.size();
  760. for (UINT32 i = 0; i < numRenderables; i++)
  761. {
  762. if (!visibility.renderables[i])
  763. continue;
  764. for (auto& element : sceneInfo.renderables[i]->elements)
  765. {
  766. bool isTransparent = (element.material->getShader()->getFlags() & (UINT32)ShaderFlags::Transparent) != 0;
  767. if (!isTransparent)
  768. continue;
  769. // Note: It would be nice to be able to set this once and keep it, only updating if the buffers actually
  770. // change (e.g. when growing). Although technically the internal systems should be smart enough to
  771. // avoid updates unless objects actually changed.
  772. if (element.gridParamsBindingIdx != -1)
  773. element.params->setParamBlockBuffer(element.gridParamsBindingIdx, gridParams, true);
  774. element.gridLightOffsetsAndSizeParam.set(gridLightOffsetsAndSize);
  775. element.gridLightIndicesParam.set(gridLightIndices);
  776. element.lightsBufferParam.set(visibleLightData.getLightBuffer());
  777. // Image based lighting params
  778. ImageBasedLightingParams& iblParams = element.imageBasedParams;
  779. if (iblParams.reflProbeParamsBindingIdx != -1)
  780. element.params->setParamBlockBuffer(iblParams.reflProbeParamsBindingIdx, reflProbeParamBuffer.buffer);
  781. element.gridProbeOffsetsAndSizeParam.set(gridProbeOffsetsAndSize);
  782. iblParams.reflectionProbeIndicesParam.set(gridProbeIndices);
  783. iblParams.reflectionProbesParam.set(visibleReflProbeData.getProbeBuffer());
  784. iblParams.skyReflectionsTexParam.set(skyFilteredRadiance);
  785. iblParams.ambientOcclusionTexParam.set(Texture::WHITE); // Note: Add SSAO here?
  786. iblParams.ssrTexParam.set(Texture::BLACK); // Note: Add SSR here?
  787. iblParams.reflectionProbeCubemapsTexParam.set(sceneInfo.reflProbeCubemapsTex);
  788. iblParams.preintegratedEnvBRDFParam.set(RendererTextures::preintegratedEnvGF);
  789. iblParams.ssrSampParam.set(mSSRAOSamplerState);
  790. iblParams.ambientOcclusionSampParam.set(mSSRAOSamplerState);
  791. }
  792. }
  793. // TODO: Transparent objects cannot receive shadows. In order to support this I'd have to render the light occlusion
  794. // for all lights affecting this object into a single (or a few) textures. I can likely use texture arrays for this,
  795. // or to avoid sampling many textures, perhaps just jam it all in one or few texture channels.
  796. const Vector<RenderQueueElement>& transparentElements = inputs.view.getTransparentQueue()->getSortedElements();
  797. for (auto iter = transparentElements.begin(); iter != transparentElements.end(); ++iter)
  798. {
  799. BeastRenderableElement* renderElem = static_cast<BeastRenderableElement*>(iter->renderElem);
  800. SPtr<Material> material = renderElem->material;
  801. if (iter->applyPass)
  802. gRendererUtility().setPass(material, iter->passIdx, renderElem->techniqueIdx);
  803. gRendererUtility().setPassParams(renderElem->params, iter->passIdx);
  804. if(renderElem->morphVertexDeclaration == nullptr)
  805. gRendererUtility().draw(renderElem->mesh, renderElem->subMesh);
  806. else
  807. gRendererUtility().drawMorph(renderElem->mesh, renderElem->subMesh, renderElem->morphShapeBuffer,
  808. renderElem->morphVertexDeclaration);
  809. }
  810. // Trigger post-lighting callbacks
  811. Camera* sceneCamera = inputs.view.getSceneCamera();
  812. if (sceneCamera != nullptr)
  813. {
  814. for(auto& extension : inputs.extPostLighting)
  815. {
  816. if (extension->check(*sceneCamera))
  817. extension->render(*sceneCamera);
  818. }
  819. }
  820. }
  821. void RCNodeClusteredForward::clear()
  822. {
  823. // Do nothing
  824. }
  825. SmallVector<StringID, 4> RCNodeClusteredForward::getDependencies(const RendererView& view)
  826. {
  827. return { RCNodeSceneColor::getNodeId(), RCNodeSkybox::getNodeId() };
  828. }
  829. void RCNodeSkybox::render(const RenderCompositorNodeInputs& inputs)
  830. {
  831. Skybox* skybox = inputs.scene.skybox;
  832. SPtr<Texture> radiance = skybox ? skybox->getTexture() : nullptr;
  833. if (radiance != nullptr)
  834. {
  835. SkyboxMat* material = SkyboxMat::getVariation(false);
  836. material->bind(inputs.view.getPerViewBuffer());
  837. material->setParams(radiance, Color::White);
  838. }
  839. else
  840. {
  841. Color clearColor = inputs.view.getProperties().clearColor;
  842. SkyboxMat* material = SkyboxMat::getVariation(true);
  843. material->bind(inputs.view.getPerViewBuffer());
  844. material->setParams(nullptr, clearColor);
  845. }
  846. RCNodeSceneColor* sceneColorNode = static_cast<RCNodeSceneColor*>(inputs.inputNodes[1]);
  847. int readOnlyFlags = FBT_DEPTH | FBT_STENCIL;
  848. RenderAPI& rapi = RenderAPI::instance();
  849. rapi.setRenderTarget(sceneColorNode->renderTarget, readOnlyFlags, RT_COLOR0 | RT_DEPTH_STENCIL);
  850. Rect2 area(0.0f, 0.0f, 1.0f, 1.0f);
  851. rapi.setViewport(area);
  852. SPtr<Mesh> mesh = gRendererUtility().getSkyBoxMesh();
  853. gRendererUtility().draw(mesh, mesh->getProperties().getSubMesh(0));
  854. }
  855. void RCNodeSkybox::clear()
  856. { }
  857. SmallVector<StringID, 4> RCNodeSkybox::getDependencies(const RendererView& view)
  858. {
  859. SmallVector<StringID, 4> deps;
  860. deps.push_back(RCNodeTiledDeferredIBL::getNodeId());
  861. deps.push_back(RCNodeSceneColor::getNodeId());
  862. if (view.getProperties().numSamples > 1)
  863. deps.push_back(RCNodeUnflattenSceneColor::getNodeId());
  864. return deps;
  865. }
  866. void RCNodeFinalResolve::render(const RenderCompositorNodeInputs& inputs)
  867. {
  868. const RendererViewProperties& viewProps = inputs.view.getProperties();
  869. SPtr<Texture> input;
  870. if(viewProps.runPostProcessing)
  871. {
  872. RCNodePostProcess* postProcessNode = static_cast<RCNodePostProcess*>(inputs.inputNodes[0]);
  873. // Note: Ideally the last PP effect could write directly to the final target and we could avoid this copy
  874. input = postProcessNode->getLastOutput();
  875. }
  876. else
  877. {
  878. RCNodeSceneColor* sceneColorNode = static_cast<RCNodeSceneColor*>(inputs.inputNodes[0]);
  879. input = sceneColorNode->sceneColorTex->texture;
  880. }
  881. SPtr<RenderTarget> target = viewProps.target;
  882. RenderAPI& rapi = RenderAPI::instance();
  883. rapi.setRenderTarget(target);
  884. rapi.setViewport(viewProps.nrmViewRect);
  885. gRendererUtility().blit(input, Rect2I::EMPTY, viewProps.flipView);
  886. if(viewProps.encodeDepth)
  887. {
  888. RCNodeResolvedSceneDepth* resolvedSceneDepthNode = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[0]);
  889. EncodeDepthMat* encodeDepthMat = EncodeDepthMat::get();
  890. encodeDepthMat->execute(resolvedSceneDepthNode->output->texture, viewProps.depthEncodeNear,
  891. viewProps.depthEncodeFar, target);
  892. }
  893. // Trigger overlay callbacks
  894. Camera* sceneCamera = inputs.view.getSceneCamera();
  895. if (sceneCamera != nullptr)
  896. {
  897. for(auto& extension : inputs.extOverlay)
  898. {
  899. if (extension->check(*sceneCamera))
  900. extension->render(*sceneCamera);
  901. }
  902. }
  903. }
  904. void RCNodeFinalResolve::clear()
  905. { }
  906. SmallVector<StringID, 4> RCNodeFinalResolve::getDependencies(const RendererView& view)
  907. {
  908. const RendererViewProperties& viewProps = view.getProperties();
  909. SmallVector<StringID, 4> deps;
  910. if(viewProps.runPostProcessing)
  911. {
  912. deps.push_back(RCNodePostProcess::getNodeId());
  913. deps.push_back(RCNodeFXAA::getNodeId());
  914. }
  915. else
  916. {
  917. deps.push_back(RCNodeSceneColor::getNodeId());
  918. deps.push_back(RCNodeClusteredForward::getNodeId());
  919. }
  920. if(viewProps.encodeDepth)
  921. deps.push_back(RCNodeResolvedSceneDepth::getNodeId());
  922. return deps;
  923. }
  924. RCNodePostProcess::RCNodePostProcess()
  925. :mOutput(), mAllocated()
  926. { }
  927. void RCNodePostProcess::getAndSwitch(const RendererView& view, SPtr<RenderTexture>& output, SPtr<Texture>& lastFrame) const
  928. {
  929. GpuResourcePool& resPool = GpuResourcePool::instance();
  930. const RendererViewProperties& viewProps = view.getProperties();
  931. UINT32 width = viewProps.viewRect.width;
  932. UINT32 height = viewProps.viewRect.height;
  933. if(!mAllocated[mCurrentIdx])
  934. {
  935. mOutput[mCurrentIdx] = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA8, width, height,
  936. TU_RENDERTARGET, 1, false));
  937. mAllocated[mCurrentIdx] = true;
  938. }
  939. output = mOutput[mCurrentIdx]->renderTexture;
  940. UINT32 otherIdx = (mCurrentIdx + 1) % 2;
  941. if (mAllocated[otherIdx])
  942. lastFrame = mOutput[otherIdx]->texture;
  943. mCurrentIdx = otherIdx;
  944. }
  945. SPtr<Texture> RCNodePostProcess::getLastOutput() const
  946. {
  947. UINT32 otherIdx = (mCurrentIdx + 1) % 2;
  948. if (mAllocated[otherIdx])
  949. return mOutput[otherIdx]->texture;
  950. return nullptr;
  951. }
  952. void RCNodePostProcess::render(const RenderCompositorNodeInputs& inputs)
  953. {
  954. // Do nothing, this is just a helper node
  955. }
  956. void RCNodePostProcess::clear()
  957. {
  958. GpuResourcePool& resPool = GpuResourcePool::instance();
  959. if (mAllocated[0])
  960. resPool.release(mOutput[0]);
  961. if (mAllocated[1])
  962. resPool.release(mOutput[1]);
  963. mAllocated[0] = false;
  964. mAllocated[1] = false;
  965. mCurrentIdx = 0;
  966. }
  967. SmallVector<StringID, 4> RCNodePostProcess::getDependencies(const RendererView& view)
  968. {
  969. return {};
  970. }
  971. RCNodeTonemapping::~RCNodeTonemapping()
  972. {
  973. GpuResourcePool& resPool = GpuResourcePool::instance();
  974. if (mTonemapLUT)
  975. resPool.release(mTonemapLUT);
  976. if (prevEyeAdaptation)
  977. resPool.release(prevEyeAdaptation);
  978. }
  979. void RCNodeTonemapping::render(const RenderCompositorNodeInputs& inputs)
  980. {
  981. GpuResourcePool& resPool = GpuResourcePool::instance();
  982. const RendererViewProperties& viewProps = inputs.view.getProperties();
  983. const RenderSettings& settings = inputs.view.getRenderSettings();
  984. RCNodeSceneColor* sceneColorNode = static_cast<RCNodeSceneColor*>(inputs.inputNodes[0]);
  985. RCNodePostProcess* postProcessNode = static_cast<RCNodePostProcess*>(inputs.inputNodes[2]);
  986. SPtr<Texture> sceneColor = sceneColorNode->sceneColorTex->texture;
  987. bool hdr = settings.enableHDR;
  988. bool msaa = viewProps.numSamples > 1;
  989. if(hdr && settings.enableAutoExposure)
  990. {
  991. // Downsample scene
  992. DownsampleMat* downsampleMat = DownsampleMat::getVariation(1, msaa);
  993. SPtr<PooledRenderTexture> downsampledScene = resPool.get(DownsampleMat::getOutputDesc(sceneColor));
  994. downsampleMat->execute(sceneColor, downsampledScene->renderTexture);
  995. // Generate histogram
  996. SPtr<PooledRenderTexture> eyeAdaptHistogram = resPool.get(
  997. EyeAdaptHistogramMat::getOutputDesc(downsampledScene->texture));
  998. EyeAdaptHistogramMat* eyeAdaptHistogramMat = EyeAdaptHistogramMat::get();
  999. eyeAdaptHistogramMat->execute(downsampledScene->texture, eyeAdaptHistogram->texture, settings.autoExposure);
  1000. // Reduce histogram
  1001. SPtr<PooledRenderTexture> reducedHistogram = resPool.get(EyeAdaptHistogramReduceMat::getOutputDesc());
  1002. SPtr<Texture> prevFrameEyeAdaptation;
  1003. if (prevEyeAdaptation != nullptr)
  1004. prevFrameEyeAdaptation = prevEyeAdaptation->texture;
  1005. EyeAdaptHistogramReduceMat* eyeAdaptHistogramReduce = EyeAdaptHistogramReduceMat::get();
  1006. eyeAdaptHistogramReduce->execute(downsampledScene->texture, eyeAdaptHistogram->texture,
  1007. prevFrameEyeAdaptation, reducedHistogram->renderTexture);
  1008. resPool.release(downsampledScene);
  1009. downsampledScene = nullptr;
  1010. resPool.release(eyeAdaptHistogram);
  1011. eyeAdaptHistogram = nullptr;
  1012. // Generate eye adaptation value
  1013. eyeAdaptation = resPool.get(EyeAdaptationMat::getOutputDesc());
  1014. EyeAdaptationMat* eyeAdaptationMat = EyeAdaptationMat::get();
  1015. eyeAdaptationMat->execute(reducedHistogram->texture, eyeAdaptation->renderTexture, inputs.frameInfo.timeDelta,
  1016. settings.autoExposure, settings.exposureScale);
  1017. resPool.release(reducedHistogram);
  1018. reducedHistogram = nullptr;
  1019. }
  1020. else
  1021. {
  1022. if(prevEyeAdaptation)
  1023. resPool.release(prevEyeAdaptation);
  1024. prevEyeAdaptation = nullptr;
  1025. eyeAdaptation = nullptr;
  1026. }
  1027. bool gammaOnly;
  1028. bool autoExposure;
  1029. if (hdr)
  1030. {
  1031. if (settings.enableTonemapping)
  1032. {
  1033. UINT64 latestHash = inputs.view.getRenderSettingsHash();
  1034. bool tonemapLUTDirty = mTonemapLastUpdateHash != latestHash;
  1035. if (tonemapLUTDirty) // Rebuild LUT if PP settings changed
  1036. {
  1037. if(mTonemapLUT == nullptr)
  1038. mTonemapLUT = resPool.get(CreateTonemapLUTMat::getOutputDesc());
  1039. CreateTonemapLUTMat* createLUT = CreateTonemapLUTMat::get();
  1040. createLUT->execute(mTonemapLUT->texture, settings);
  1041. mTonemapLastUpdateHash = latestHash;
  1042. }
  1043. gammaOnly = false;
  1044. }
  1045. else
  1046. gammaOnly = true;
  1047. autoExposure = settings.enableAutoExposure;
  1048. }
  1049. else
  1050. {
  1051. gammaOnly = true;
  1052. autoExposure = false;
  1053. }
  1054. if(gammaOnly)
  1055. {
  1056. if(mTonemapLUT)
  1057. {
  1058. resPool.release(mTonemapLUT);
  1059. mTonemapLUT = nullptr;
  1060. }
  1061. }
  1062. TonemappingMat* tonemapping = TonemappingMat::getVariation(gammaOnly, autoExposure, msaa);
  1063. SPtr<RenderTexture> ppOutput;
  1064. SPtr<Texture> ppLastFrame;
  1065. postProcessNode->getAndSwitch(inputs.view, ppOutput, ppLastFrame);
  1066. SPtr<Texture> eyeAdaptationTex;
  1067. if (eyeAdaptation)
  1068. eyeAdaptationTex = eyeAdaptation->texture;
  1069. SPtr<Texture> tonemapLUTTex;
  1070. if (mTonemapLUT)
  1071. tonemapLUTTex = mTonemapLUT->texture;
  1072. tonemapping->execute(sceneColor, eyeAdaptationTex, tonemapLUTTex, ppOutput, settings);
  1073. }
  1074. void RCNodeTonemapping::clear()
  1075. {
  1076. GpuResourcePool& resPool = GpuResourcePool::instance();
  1077. // Save eye adaptation for next frame
  1078. if(prevEyeAdaptation)
  1079. resPool.release(prevEyeAdaptation);
  1080. std::swap(eyeAdaptation, prevEyeAdaptation);
  1081. }
  1082. SmallVector<StringID, 4> RCNodeTonemapping::getDependencies(const RendererView& view)
  1083. {
  1084. return{ RCNodeSceneColor::getNodeId(), RCNodeClusteredForward::getNodeId(), RCNodePostProcess::getNodeId() };
  1085. }
  1086. void RCNodeGaussianDOF::render(const RenderCompositorNodeInputs& inputs)
  1087. {
  1088. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[1]);
  1089. RCNodePostProcess* postProcessNode = static_cast<RCNodePostProcess*>(inputs.inputNodes[2]);
  1090. const DepthOfFieldSettings& settings = inputs.view.getRenderSettings().depthOfField;
  1091. bool near = settings.nearBlurAmount > 0.0f;
  1092. bool far = settings.farBlurAmount > 0.0f;
  1093. bool enabled = settings.enabled && (near || far);
  1094. if(!enabled)
  1095. return;
  1096. GaussianDOFSeparateMat* separateMat = GaussianDOFSeparateMat::getVariation(near, far);
  1097. GaussianDOFCombineMat* combineMat = GaussianDOFCombineMat::getVariation(near, far);
  1098. GaussianBlurMat* blurMat = GaussianBlurMat::get();
  1099. SPtr<RenderTexture> ppOutput;
  1100. SPtr<Texture> ppLastFrame;
  1101. postProcessNode->getAndSwitch(inputs.view, ppOutput, ppLastFrame);
  1102. separateMat->execute(ppLastFrame, sceneDepthNode->depthTex->texture, inputs.view, settings);
  1103. SPtr<PooledRenderTexture> nearTex, farTex;
  1104. if(near && far)
  1105. {
  1106. nearTex = separateMat->getOutput(0);
  1107. farTex = separateMat->getOutput(1);
  1108. }
  1109. else
  1110. {
  1111. if (near)
  1112. nearTex = separateMat->getOutput(0);
  1113. else
  1114. farTex = separateMat->getOutput(0);
  1115. }
  1116. // Blur the out of focus pixels
  1117. // Note: Perhaps set up stencil so I can avoid performing blur on unused parts of the textures?
  1118. const TextureProperties& texProps = nearTex ? nearTex->texture->getProperties() : farTex->texture->getProperties();
  1119. POOLED_RENDER_TEXTURE_DESC tempTexDesc = POOLED_RENDER_TEXTURE_DESC::create2D(texProps.getFormat(),
  1120. texProps.getWidth(), texProps.getHeight(), TU_RENDERTARGET);
  1121. SPtr<PooledRenderTexture> tempTexture = GpuResourcePool::instance().get(tempTexDesc);
  1122. SPtr<Texture> blurredNearTex;
  1123. if(nearTex)
  1124. {
  1125. blurMat->execute(nearTex->texture, settings.nearBlurAmount, tempTexture->renderTexture);
  1126. blurredNearTex = tempTexture->texture;
  1127. }
  1128. SPtr<Texture> blurredFarTex;
  1129. if(farTex)
  1130. {
  1131. // If temporary texture is used up, re-use the original near texture for the blurred result
  1132. if(blurredNearTex)
  1133. {
  1134. blurMat->execute(farTex->texture, settings.farBlurAmount, nearTex->renderTexture);
  1135. blurredFarTex = nearTex->texture;
  1136. }
  1137. else // Otherwise just use the temporary
  1138. {
  1139. blurMat->execute(farTex->texture, settings.farBlurAmount, tempTexture->renderTexture);
  1140. blurredFarTex = tempTexture->texture;
  1141. }
  1142. }
  1143. combineMat->execute(ppLastFrame, blurredNearTex, blurredFarTex,
  1144. sceneDepthNode->depthTex->texture, ppOutput, inputs.view, settings);
  1145. separateMat->release();
  1146. GpuResourcePool::instance().release(tempTexture);
  1147. }
  1148. void RCNodeGaussianDOF::clear()
  1149. {
  1150. // Do nothing
  1151. }
  1152. SmallVector<StringID, 4> RCNodeGaussianDOF::getDependencies(const RendererView& view)
  1153. {
  1154. return { RCNodeTonemapping::getNodeId(), RCNodeSceneDepth::getNodeId(), RCNodePostProcess::getNodeId() };
  1155. }
  1156. void RCNodeFXAA::render(const RenderCompositorNodeInputs& inputs)
  1157. {
  1158. const RenderSettings& settings = inputs.view.getRenderSettings();
  1159. if (!settings.enableFXAA)
  1160. return;
  1161. RCNodePostProcess* postProcessNode = static_cast<RCNodePostProcess*>(inputs.inputNodes[1]);
  1162. SPtr<RenderTexture> ppOutput;
  1163. SPtr<Texture> ppLastFrame;
  1164. postProcessNode->getAndSwitch(inputs.view, ppOutput, ppLastFrame);
  1165. // Note: I could skip executing FXAA over DOF and motion blurred pixels
  1166. FXAAMat* fxaa = FXAAMat::get();
  1167. fxaa->execute(ppLastFrame, ppOutput);
  1168. }
  1169. void RCNodeFXAA::clear()
  1170. {
  1171. // Do nothing
  1172. }
  1173. SmallVector<StringID, 4> RCNodeFXAA::getDependencies(const RendererView& view)
  1174. {
  1175. return { RCNodeGaussianDOF::getNodeId(), RCNodePostProcess::getNodeId() };
  1176. }
  1177. void RCNodeResolvedSceneDepth::render(const RenderCompositorNodeInputs& inputs)
  1178. {
  1179. GpuResourcePool& resPool = GpuResourcePool::instance();
  1180. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1181. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[0]);
  1182. if (viewProps.numSamples > 1)
  1183. {
  1184. UINT32 width = viewProps.viewRect.width;
  1185. UINT32 height = viewProps.viewRect.height;
  1186. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_D32_S8X24, width, height,
  1187. TU_DEPTHSTENCIL, 1, false));
  1188. RenderAPI& rapi = RenderAPI::instance();
  1189. rapi.setRenderTarget(output->renderTexture);
  1190. rapi.clearRenderTarget(FBT_STENCIL);
  1191. gRendererUtility().blit(sceneDepthNode->depthTex->texture, Rect2I::EMPTY, false, true);
  1192. mPassThrough = false;
  1193. }
  1194. else
  1195. {
  1196. output = sceneDepthNode->depthTex;
  1197. mPassThrough = true;
  1198. }
  1199. }
  1200. void RCNodeResolvedSceneDepth::clear()
  1201. {
  1202. GpuResourcePool& resPool = GpuResourcePool::instance();
  1203. if (!mPassThrough)
  1204. resPool.release(output);
  1205. else
  1206. output = nullptr;
  1207. mPassThrough = false;
  1208. }
  1209. SmallVector<StringID, 4> RCNodeResolvedSceneDepth::getDependencies(const RendererView& view)
  1210. {
  1211. // GBuffer require because it renders the base pass (populates the depth buffer)
  1212. return { RCNodeSceneDepth::getNodeId(), RCNodeGBuffer::getNodeId() };
  1213. }
  1214. void RCNodeHiZ::render(const RenderCompositorNodeInputs& inputs)
  1215. {
  1216. GpuResourcePool& resPool = GpuResourcePool::instance();
  1217. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1218. RCNodeResolvedSceneDepth* resolvedSceneDepth = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[0]);
  1219. UINT32 width = viewProps.viewRect.width;
  1220. UINT32 height = viewProps.viewRect.height;
  1221. UINT32 size = Bitwise::nextPow2(std::max(width, height));
  1222. UINT32 numMips = PixelUtil::getMaxMipmaps(size, size, 1, PF_R32F);
  1223. size = 1 << numMips;
  1224. // Note: Use the 32-bit buffer here as 16-bit causes too much banding (most of the scene gets assigned 4-5 different
  1225. // depth values).
  1226. // - When I add UNORM 16-bit format I should be able to switch to that
  1227. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_R32F, size, size, TU_RENDERTARGET, 1, false, 1,
  1228. numMips));
  1229. Rect2 srcRect = viewProps.nrmViewRect;
  1230. // If viewport size is odd, adjust UV
  1231. srcRect.width += (viewProps.viewRect.width % 2) * (1.0f / viewProps.viewRect.width);
  1232. srcRect.height += (viewProps.viewRect.height % 2) * (1.0f / viewProps.viewRect.height);
  1233. // Generate first mip
  1234. RENDER_TEXTURE_DESC rtDesc;
  1235. rtDesc.colorSurfaces[0].texture = output->texture;
  1236. rtDesc.colorSurfaces[0].mipLevel = 0;
  1237. SPtr<RenderTexture> rt = RenderTexture::create(rtDesc);
  1238. Rect2 destRect;
  1239. bool downsampledFirstMip = false; // Not used currently
  1240. if (downsampledFirstMip)
  1241. {
  1242. // Make sure that 1 pixel in HiZ maps to a 2x2 block in source
  1243. destRect = Rect2(0, 0,
  1244. Math::ceilToInt(viewProps.viewRect.width / 2.0f) / (float)size,
  1245. Math::ceilToInt(viewProps.viewRect.height / 2.0f) / (float)size);
  1246. BuildHiZMat* material = BuildHiZMat::get();
  1247. material->execute(resolvedSceneDepth->output->texture, 0, srcRect, destRect, rt);
  1248. }
  1249. else // First level is just a copy of the depth buffer
  1250. {
  1251. destRect = Rect2(0, 0,
  1252. viewProps.viewRect.width / (float)size,
  1253. viewProps.viewRect.height / (float)size);
  1254. RenderAPI& rapi = RenderAPI::instance();
  1255. rapi.setRenderTarget(rt);
  1256. rapi.setViewport(destRect);
  1257. Rect2I srcAreaInt;
  1258. srcAreaInt.x = (INT32)(srcRect.x * viewProps.viewRect.width);
  1259. srcAreaInt.y = (INT32)(srcRect.y * viewProps.viewRect.height);
  1260. srcAreaInt.width = (UINT32)(srcRect.width * viewProps.viewRect.width);
  1261. srcAreaInt.height = (UINT32)(srcRect.height * viewProps.viewRect.height);
  1262. gRendererUtility().blit(resolvedSceneDepth->output->texture, srcAreaInt);
  1263. rapi.setViewport(Rect2(0, 0, 1, 1));
  1264. }
  1265. // Generate remaining mip levels
  1266. for(UINT32 i = 1; i <= numMips; i++)
  1267. {
  1268. rtDesc.colorSurfaces[0].mipLevel = i;
  1269. rt = RenderTexture::create(rtDesc);
  1270. BuildHiZMat* material = BuildHiZMat::get();
  1271. material->execute(output->texture, i - 1, destRect, destRect, rt);
  1272. }
  1273. }
  1274. void RCNodeHiZ::clear()
  1275. {
  1276. GpuResourcePool& resPool = GpuResourcePool::instance();
  1277. resPool.release(output);
  1278. }
  1279. SmallVector<StringID, 4> RCNodeHiZ::getDependencies(const RendererView& view)
  1280. {
  1281. // Note: This doesn't actually use any gbuffer textures, but node is a dependency because it renders to the depth
  1282. // buffer. In order to avoid keeping gbuffer textures alive I could separate out the base pass into its own node
  1283. // perhaps. But at the moment it doesn't matter, as anything using HiZ also needs gbuffer.
  1284. return { RCNodeResolvedSceneDepth::getNodeId(), RCNodeGBuffer::getNodeId() };
  1285. }
  1286. void RCNodeSSAO::render(const RenderCompositorNodeInputs& inputs)
  1287. {
  1288. /** Maximum valid depth range within samples in a sample set. In meters. */
  1289. static const float DEPTH_RANGE = 1.0f;
  1290. GpuResourcePool& resPool = GpuResourcePool::instance();
  1291. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1292. const AmbientOcclusionSettings& settings = inputs.view.getRenderSettings().ambientOcclusion;
  1293. RCNodeResolvedSceneDepth* resolvedDepthNode = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[0]);
  1294. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[1]);
  1295. SPtr<Texture> sceneDepth = resolvedDepthNode->output->texture;
  1296. SPtr<Texture> sceneNormals = gbufferNode->normalTex->texture;
  1297. const TextureProperties& normalsProps = sceneNormals->getProperties();
  1298. SPtr<PooledRenderTexture> resolvedNormals;
  1299. RenderAPI& rapi = RenderAPI::instance();
  1300. if(sceneNormals->getProperties().getNumSamples() > 1)
  1301. {
  1302. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(normalsProps.getFormat(),
  1303. normalsProps.getWidth(), normalsProps.getHeight(), TU_RENDERTARGET);
  1304. resolvedNormals = resPool.get(desc);
  1305. rapi.setRenderTarget(resolvedNormals->renderTexture);
  1306. gRendererUtility().blit(sceneNormals);
  1307. sceneNormals = resolvedNormals->texture;
  1308. }
  1309. // Multiple downsampled AO levels are used to minimize cache trashing. Downsampled AO targets use larger radius,
  1310. // whose contents are then blended with the higher level.
  1311. UINT32 quality = settings.quality;
  1312. UINT32 numDownsampleLevels = 0;
  1313. if (quality > 1)
  1314. numDownsampleLevels = 1;
  1315. else if (quality > 2)
  1316. numDownsampleLevels = 2;
  1317. SSAODownsampleMat* downsample = SSAODownsampleMat::get();
  1318. SPtr<PooledRenderTexture> setupTex0;
  1319. if(numDownsampleLevels > 0)
  1320. {
  1321. Vector2I downsampledSize(
  1322. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 2)),
  1323. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 2))
  1324. );
  1325. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, downsampledSize.x,
  1326. downsampledSize.y, TU_RENDERTARGET);
  1327. setupTex0 = GpuResourcePool::instance().get(desc);
  1328. downsample->execute(inputs.view, sceneDepth, sceneNormals, setupTex0->renderTexture, DEPTH_RANGE);
  1329. }
  1330. SPtr<PooledRenderTexture> setupTex1;
  1331. if(numDownsampleLevels > 1)
  1332. {
  1333. Vector2I downsampledSize(
  1334. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 4)),
  1335. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 4))
  1336. );
  1337. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, downsampledSize.x,
  1338. downsampledSize.y, TU_RENDERTARGET);
  1339. setupTex1 = GpuResourcePool::instance().get(desc);
  1340. downsample->execute(inputs.view, sceneDepth, sceneNormals, setupTex1->renderTexture, DEPTH_RANGE);
  1341. }
  1342. SSAOTextureInputs textures;
  1343. textures.sceneDepth = sceneDepth;
  1344. textures.sceneNormals = sceneNormals;
  1345. textures.randomRotations = RendererTextures::ssaoRandomization4x4;
  1346. SPtr<PooledRenderTexture> downAOTex1;
  1347. if(numDownsampleLevels > 1)
  1348. {
  1349. textures.aoSetup = setupTex1->texture;
  1350. Vector2I downsampledSize(
  1351. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 4)),
  1352. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 4))
  1353. );
  1354. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, downsampledSize.x,
  1355. downsampledSize.y, TU_RENDERTARGET);
  1356. downAOTex1 = GpuResourcePool::instance().get(desc);
  1357. SSAOMat* ssaoMat = SSAOMat::getVariation(false, false, quality);
  1358. ssaoMat->execute(inputs.view, textures, downAOTex1->renderTexture, settings);
  1359. GpuResourcePool::instance().release(setupTex1);
  1360. setupTex1 = nullptr;
  1361. }
  1362. SPtr<PooledRenderTexture> downAOTex0;
  1363. if(numDownsampleLevels > 0)
  1364. {
  1365. textures.aoSetup = setupTex0->texture;
  1366. if(downAOTex1)
  1367. textures.aoDownsampled = downAOTex1->texture;
  1368. Vector2I downsampledSize(
  1369. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 2)),
  1370. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 2))
  1371. );
  1372. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, downsampledSize.x,
  1373. downsampledSize.y, TU_RENDERTARGET);
  1374. downAOTex0 = GpuResourcePool::instance().get(desc);
  1375. bool upsample = numDownsampleLevels > 1;
  1376. SSAOMat* ssaoMat = SSAOMat::getVariation(upsample, false, quality);
  1377. ssaoMat->execute(inputs.view, textures, downAOTex0->renderTexture, settings);
  1378. if(upsample)
  1379. {
  1380. GpuResourcePool::instance().release(downAOTex1);
  1381. downAOTex1 = nullptr;
  1382. }
  1383. }
  1384. UINT32 width = viewProps.viewRect.width;
  1385. UINT32 height = viewProps.viewRect.height;
  1386. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, width, height, TU_RENDERTARGET));
  1387. {
  1388. if(setupTex0)
  1389. textures.aoSetup = setupTex0->texture;
  1390. if(downAOTex0)
  1391. textures.aoDownsampled = downAOTex0->texture;
  1392. bool upsample = numDownsampleLevels > 0;
  1393. SSAOMat* ssaoMat = SSAOMat::getVariation(upsample, true, quality);
  1394. ssaoMat->execute(inputs.view, textures, output->renderTexture, settings);
  1395. }
  1396. if(resolvedNormals)
  1397. {
  1398. GpuResourcePool::instance().release(resolvedNormals);
  1399. resolvedNormals = nullptr;
  1400. }
  1401. if(numDownsampleLevels > 0)
  1402. {
  1403. GpuResourcePool::instance().release(setupTex0);
  1404. GpuResourcePool::instance().release(downAOTex0);
  1405. }
  1406. // Blur the output
  1407. // Note: If I implement temporal AA then this can probably be avoided. I can instead jitter the sample offsets
  1408. // each frame, and averaging them out should yield blurred AO.
  1409. if(quality > 1) // On level 0 we don't blur at all, on level 1 we use the ad-hoc blur in shader
  1410. {
  1411. const RenderTargetProperties& rtProps = output->renderTexture->getProperties();
  1412. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, rtProps.getWidth(),
  1413. rtProps.getHeight(), TU_RENDERTARGET);
  1414. SPtr<PooledRenderTexture> blurIntermediateTex = GpuResourcePool::instance().get(desc);
  1415. SSAOBlurMat* blurHorz = SSAOBlurMat::getVariation(true);
  1416. SSAOBlurMat* blurVert = SSAOBlurMat::getVariation(false);
  1417. blurHorz->execute(inputs.view, output->texture, sceneDepth, blurIntermediateTex->renderTexture, DEPTH_RANGE);
  1418. blurVert->execute(inputs.view, blurIntermediateTex->texture, sceneDepth, output->renderTexture, DEPTH_RANGE);
  1419. GpuResourcePool::instance().release(blurIntermediateTex);
  1420. }
  1421. }
  1422. void RCNodeSSAO::clear()
  1423. {
  1424. GpuResourcePool& resPool = GpuResourcePool::instance();
  1425. resPool.release(output);
  1426. }
  1427. SmallVector<StringID, 4> RCNodeSSAO::getDependencies(const RendererView& view)
  1428. {
  1429. return { RCNodeResolvedSceneDepth::getNodeId(), RCNodeGBuffer::getNodeId() };
  1430. }
  1431. RCNodeSSR::~RCNodeSSR()
  1432. {
  1433. deallocOutputs();
  1434. }
  1435. void RCNodeSSR::render(const RenderCompositorNodeInputs& inputs)
  1436. {
  1437. const ScreenSpaceReflectionsSettings& settings = inputs.view.getRenderSettings().screenSpaceReflections;
  1438. if (settings.enabled)
  1439. {
  1440. RenderAPI& rapi = RenderAPI::instance();
  1441. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[0]);
  1442. RCNodeLightAccumulation* lightAccumNode = static_cast<RCNodeLightAccumulation*>(inputs.inputNodes[1]);
  1443. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[2]);
  1444. RCNodeHiZ* hiZNode = static_cast<RCNodeHiZ*>(inputs.inputNodes[3]);
  1445. RCNodeResolvedSceneDepth* resolvedSceneDepthNode = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[4]);
  1446. GpuResourcePool& resPool = GpuResourcePool::instance();
  1447. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1448. UINT32 width = viewProps.viewRect.width;
  1449. UINT32 height = viewProps.viewRect.height;
  1450. SPtr<Texture> hiZ = hiZNode->output->texture;
  1451. // This will be executing before scene color is resolved, so get the light accum buffer instead
  1452. SPtr<Texture> sceneColor = lightAccumNode->lightAccumulationTex->texture;
  1453. // Resolve multiple samples if MSAA is used
  1454. SPtr<PooledRenderTexture> resolvedSceneColor;
  1455. if(viewProps.numSamples > 1)
  1456. {
  1457. resolvedSceneColor = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width, height,
  1458. TU_RENDERTARGET));
  1459. rapi.setRenderTarget(resolvedSceneColor->renderTexture);
  1460. gRendererUtility().blit(sceneColor);
  1461. sceneColor = resolvedSceneColor->texture;
  1462. }
  1463. GBufferTextures gbuffer;
  1464. gbuffer.albedo = gbufferNode->albedoTex->texture;
  1465. gbuffer.normals = gbufferNode->normalTex->texture;
  1466. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  1467. gbuffer.depth = sceneDepthNode->depthTex->texture;
  1468. SSRStencilMat* stencilMat = SSRStencilMat::getVariation(viewProps.numSamples > 1, true);
  1469. // Note: Making the assumption that the stencil buffer is clear at this point
  1470. rapi.setRenderTarget(resolvedSceneDepthNode->output->renderTexture);
  1471. stencilMat->execute(inputs.view, gbuffer, settings);
  1472. SPtr<PooledRenderTexture> traceOutput = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width,
  1473. height, TU_RENDERTARGET));
  1474. RENDER_TEXTURE_DESC traceRtDesc;
  1475. traceRtDesc.colorSurfaces[0].texture = traceOutput->texture;
  1476. traceRtDesc.depthStencilSurface.texture = resolvedSceneDepthNode->output->texture;
  1477. SPtr<RenderTexture> traceRt = RenderTexture::create(traceRtDesc);
  1478. rapi.setRenderTarget(traceRt, FBT_DEPTH | FBT_STENCIL, RT_DEPTH_STENCIL);
  1479. rapi.clearRenderTarget(FBT_COLOR);
  1480. SSRTraceMat* traceMat = SSRTraceMat::getVariation(settings.quality, viewProps.numSamples > 1, true);
  1481. traceMat->execute(inputs.view, gbuffer, sceneColor, hiZ, settings, traceRt);
  1482. if (resolvedSceneColor)
  1483. {
  1484. resPool.release(resolvedSceneColor);
  1485. resolvedSceneColor = nullptr;
  1486. }
  1487. if (mPrevFrame)
  1488. {
  1489. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width, height, TU_RENDERTARGET));
  1490. rapi.setRenderTarget(output->renderTexture);
  1491. rapi.clearRenderTarget(FBT_COLOR);
  1492. SSRResolveMat* resolveMat = SSRResolveMat::getVariation(viewProps.numSamples > 1);
  1493. resolveMat->execute(inputs.view, mPrevFrame->texture, traceOutput->texture, sceneDepthNode->depthTex->texture,
  1494. output->renderTexture);
  1495. resPool.release(traceOutput);
  1496. }
  1497. else
  1498. output = traceOutput;
  1499. RenderAPI::instance().setRenderTarget(nullptr);
  1500. }
  1501. else
  1502. deallocOutputs();
  1503. }
  1504. void RCNodeSSR::clear()
  1505. {
  1506. GpuResourcePool& resPool = GpuResourcePool::instance();
  1507. if(mPrevFrame)
  1508. resPool.release(mPrevFrame);
  1509. mPrevFrame = output;
  1510. output = nullptr;
  1511. }
  1512. void RCNodeSSR::deallocOutputs()
  1513. {
  1514. GpuResourcePool& resPool = GpuResourcePool::instance();
  1515. if(mPrevFrame)
  1516. {
  1517. resPool.release(mPrevFrame);
  1518. mPrevFrame = nullptr;
  1519. }
  1520. }
  1521. SmallVector<StringID, 4> RCNodeSSR::getDependencies(const RendererView& view)
  1522. {
  1523. SmallVector<StringID, 4> deps;
  1524. if (view.getRenderSettings().screenSpaceReflections.enabled)
  1525. {
  1526. deps.push_back(RCNodeSceneDepth::getNodeId());
  1527. deps.push_back(RCNodeLightAccumulation::getNodeId());
  1528. deps.push_back(RCNodeGBuffer::getNodeId());
  1529. deps.push_back(RCNodeHiZ::getNodeId());
  1530. deps.push_back(RCNodeResolvedSceneDepth::getNodeId());
  1531. if (view.getProperties().numSamples > 1)
  1532. deps.push_back(RCNodeUnflattenLightAccum::getNodeId());
  1533. }
  1534. return deps;
  1535. }
  1536. }}