renderProbeMgr.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "renderProbeMgr.h"
  23. #include "console/consoleTypes.h"
  24. #include "scene/sceneObject.h"
  25. #include "materials/materialManager.h"
  26. #include "scene/sceneRenderState.h"
  27. #include "math/util/sphereMesh.h"
  28. #include "math/util/matrixSet.h"
  29. #include "materials/processedMaterial.h"
  30. #include "renderInstance/renderDeferredMgr.h"
  31. #include "math/mPolyhedron.impl.h"
  32. #include "gfx/gfxTransformSaver.h"
  33. #include "lighting/advanced/advancedLightBinManager.h" //for ssao
  34. #include "gfx/gfxDebugEvent.h"
  35. #include "shaderGen/shaderGenVars.h"
  36. #include "materials/shaderData.h"
  37. #include "gfx/gfxTextureManager.h"
  38. #include "scene/reflectionManager.h"
  39. #include "postFx/postEffect.h"
  40. #include "T3D/lighting/reflectionProbe.h"
  41. #include "T3D/lighting/IBLUtilities.h"
  42. //For our cameraQuery setup
  43. #include "T3D/gameTSCtrl.h"
  44. #include "T3D/Scene.h"
  45. #define TORQUE_GFX_VISUAL_DEBUG //renderdoc debugging
  46. IMPLEMENT_CONOBJECT(RenderProbeMgr);
  47. ConsoleDocClass( RenderProbeMgr,
  48. "@brief A render bin which uses object callbacks for rendering.\n\n"
  49. "This render bin gathers object render instances and calls its delegate "
  50. "method to perform rendering. It is used infrequently for specialized "
  51. "scene objects which perform custom rendering.\n\n"
  52. "@ingroup RenderBin\n" );
  53. RenderProbeMgr *RenderProbeMgr::smProbeManager = NULL;
  54. bool RenderProbeMgr::smRenderReflectionProbes = true;
  55. F32 RenderProbeMgr::smMaxProbeDrawDistance = 100;
  56. S32 RenderProbeMgr::smMaxProbesPerFrame = 8;
  57. S32 QSORT_CALLBACK AscendingReflectProbeInfluence(const void* a, const void* b)
  58. {
  59. // Debug Profiling.
  60. PROFILE_SCOPE(AdvancedLightBinManager_AscendingReflectProbeInfluence);
  61. // Fetch asset definitions.
  62. const ProbeRenderInst* pReflectProbeA = (*(ProbeRenderInst**)a);
  63. const ProbeRenderInst* pReflectProbeB = (*(ProbeRenderInst**)b);
  64. //sort by score
  65. return pReflectProbeA->mScore - pReflectProbeB->mScore;
  66. }
  67. //
  68. //
  69. ProbeRenderInst::ProbeRenderInst() :
  70. mIsEnabled(true),
  71. mTransform(true),
  72. mDirty(false),
  73. mPriority(1.0f),
  74. mScore(0.0f),
  75. mPrefilterCubemap(NULL),
  76. mIrradianceCubemap(NULL),
  77. mRadius(1.0f),
  78. mProbeRefOffset(0, 0, 0),
  79. mProbeRefScale(1,1,1),
  80. mAtten(0.0),
  81. mCubemapIndex(0),
  82. mProbeIdx(0),
  83. mProbeShapeType(Box)
  84. {
  85. }
  86. ProbeRenderInst::~ProbeRenderInst()
  87. {
  88. if (mPrefilterCubemap && mPrefilterCubemap.isValid())
  89. {
  90. mPrefilterCubemap.free();
  91. }
  92. if (mIrradianceCubemap && mIrradianceCubemap.isValid())
  93. {
  94. mIrradianceCubemap.free();
  95. }
  96. }
  97. void ProbeRenderInst::set(const ProbeRenderInst *probeInfo)
  98. {
  99. mTransform = probeInfo->mTransform;
  100. mPrefilterCubemap = probeInfo->mPrefilterCubemap;
  101. mIrradianceCubemap = probeInfo->mIrradianceCubemap;
  102. mRadius = probeInfo->mRadius;
  103. mProbeShapeType = probeInfo->mProbeShapeType;
  104. mBounds = probeInfo->mBounds;
  105. mScore = probeInfo->mScore;
  106. mAtten = probeInfo->mAtten;
  107. }
  108. //
  109. //
  110. ProbeShaderConstants::ProbeShaderConstants()
  111. : mInit(false),
  112. mShader(NULL),
  113. mProbePositionSC(NULL),
  114. mProbeRefPosSC(NULL),
  115. mRefScaleSC(NULL),
  116. mProbeConfigDataSC(NULL),
  117. mProbeSpecularCubemapSC(NULL),
  118. mProbeIrradianceCubemapSC(NULL),
  119. mProbeCountSC(NULL),
  120. mBRDFTextureMap(NULL),
  121. mSkylightCubemapIdxSC(NULL),
  122. mWorldToObjArraySC(NULL)
  123. {
  124. }
  125. ProbeShaderConstants::~ProbeShaderConstants()
  126. {
  127. if (mShader.isValid())
  128. {
  129. mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
  130. mShader = NULL;
  131. }
  132. }
  133. void ProbeShaderConstants::init(GFXShader* shader)
  134. {
  135. if (mShader.getPointer() != shader)
  136. {
  137. if (mShader.isValid())
  138. mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
  139. mShader = shader;
  140. mShader->getReloadSignal().notify(this, &ProbeShaderConstants::_onShaderReload);
  141. }
  142. //Reflection Probes
  143. mProbePositionSC = shader->getShaderConstHandle(ShaderGenVars::probePosition);
  144. mProbeRefPosSC = shader->getShaderConstHandle(ShaderGenVars::probeRefPos);
  145. mRefScaleSC = shader->getShaderConstHandle(ShaderGenVars::refScale);
  146. mWorldToObjArraySC = shader->getShaderConstHandle(ShaderGenVars::worldToObjArray);
  147. mProbeConfigDataSC = shader->getShaderConstHandle(ShaderGenVars::probeConfigData);
  148. mProbeSpecularCubemapSC = shader->getShaderConstHandle(ShaderGenVars::specularCubemapAR);
  149. mProbeIrradianceCubemapSC = shader->getShaderConstHandle(ShaderGenVars::irradianceCubemapAR);
  150. mProbeCountSC = shader->getShaderConstHandle(ShaderGenVars::probeCount);
  151. mBRDFTextureMap = shader->getShaderConstHandle(ShaderGenVars::BRDFTextureMap);
  152. mSkylightCubemapIdxSC = shader->getShaderConstHandle(ShaderGenVars::skylightCubemapIdx);
  153. mInit = true;
  154. }
  155. bool ProbeShaderConstants::isValid()
  156. {
  157. if (mProbePositionSC->isValid() ||
  158. mProbeConfigDataSC->isValid() ||
  159. mRefScaleSC->isValid() ||
  160. mProbeSpecularCubemapSC->isValid() ||
  161. mProbeIrradianceCubemapSC->isValid())
  162. return true;
  163. return false;
  164. }
  165. void ProbeShaderConstants::_onShaderReload()
  166. {
  167. if (mShader.isValid())
  168. init(mShader);
  169. }
  170. //
  171. //
  172. RenderProbeMgr::RenderProbeMgr()
  173. : RenderBinManager(RenderPassManager::RIT_Probes, 1.0f, 1.0f),
  174. mLastShader(nullptr),
  175. mLastConstants(nullptr),
  176. mProbesDirty(false),
  177. mHasSkylight(false),
  178. mSkylightCubemapIdx(-1),
  179. mCubeMapCount(0),
  180. mDefaultSkyLight(nullptr)
  181. {
  182. mEffectiveProbeCount = 0;
  183. mMipCount = 0;
  184. mProbeArrayEffect = nullptr;
  185. smProbeManager = this;
  186. mCubeMapCount = 0;
  187. mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
  188. for (U32 i = 0; i < PROBE_MAX_COUNT; i++)
  189. {
  190. mCubeMapSlots[i] = false;
  191. }
  192. mPrefilterSize = 64;
  193. mPrefilterMipLevels = mLog2(F32(mPrefilterSize)) + 1;
  194. }
  195. RenderProbeMgr::RenderProbeMgr(RenderInstType riType, F32 renderOrder, F32 processAddOrder)
  196. : RenderBinManager(riType, renderOrder, processAddOrder)
  197. {
  198. mCubeMapCount = 0;
  199. dMemset(mCubeMapSlots, false, sizeof(mCubeMapSlots));
  200. mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
  201. mDefaultSkyLight = nullptr;
  202. mEffectiveProbeCount = 0;
  203. mHasSkylight = false;
  204. mSkylightCubemapIdx = -1;
  205. mLastConstants = nullptr;
  206. mMipCount = 0;
  207. mProbesDirty = false;
  208. mUseHDRCaptures = true;
  209. mPrefilterSize = 64;
  210. mPrefilterMipLevels = mLog2(F32(mPrefilterSize)) + 1;
  211. }
  212. RenderProbeMgr::~RenderProbeMgr()
  213. {
  214. mLastShader = NULL;
  215. mLastConstants = NULL;
  216. for (ProbeConstantMap::Iterator i = mConstantLookup.begin(); i != mConstantLookup.end(); i++)
  217. {
  218. if (i->value)
  219. SAFE_DELETE(i->value);
  220. }
  221. mConstantLookup.clear();
  222. }
  223. bool RenderProbeMgr::onAdd()
  224. {
  225. if (!Parent::onAdd())
  226. return false;
  227. mIrradianceArray = GFXCubemapArrayHandle(GFX->createCubemapArray());
  228. mPrefilterArray = GFXCubemapArrayHandle(GFX->createCubemapArray());
  229. //pre-allocate a few slots
  230. mIrradianceArray->init(PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_IRRAD_SIZE, PROBE_FORMAT);
  231. mPrefilterArray->init(PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_PREFILTER_SIZE, PROBE_FORMAT);
  232. mCubeSlotCount = PROBE_ARRAY_SLOT_BUFFER_SIZE;
  233. //create our own default default skylight
  234. mDefaultSkyLight = new ProbeRenderInst;
  235. mDefaultSkyLight->mProbeShapeType = ProbeRenderInst::Skylight;
  236. mDefaultSkyLight->mIsEnabled = false;
  237. String defaultIrradMapPath = GFXTextureManager::getDefaultIrradianceCubemapPath();
  238. if (!mDefaultSkyLight->mIrradianceCubemap.set(defaultIrradMapPath))
  239. {
  240. Con::errorf("RenderProbeMgr::onAdd: Failed to load default irradiance cubemap");
  241. return false;
  242. }
  243. String defaultPrefilterPath = GFXTextureManager::getDefaultPrefilterCubemapPath();
  244. if (!mDefaultSkyLight->mPrefilterCubemap.set(defaultPrefilterPath))
  245. {
  246. Con::errorf("RenderProbeMgr::onAdd: Failed to load default prefilter cubemap");
  247. return false;
  248. }
  249. String brdfTexturePath = GFXTextureManager::getBRDFTexturePath();
  250. if (!mBRDFTexture.set(brdfTexturePath, &GFXTexturePersistentSRGBProfile, "BRDFTexture"))
  251. {
  252. Con::errorf("RenderProbeMgr::onAdd: Failed to load BRDF Texture");
  253. return false;
  254. }
  255. return true;
  256. }
  257. void RenderProbeMgr::onRemove()
  258. {
  259. Parent::onRemove();
  260. }
  261. void RenderProbeMgr::initPersistFields()
  262. {
  263. Parent::initPersistFields();
  264. }
  265. void RenderProbeMgr::consoleInit()
  266. {
  267. Parent::consoleInit();
  268. // Vars for debug rendering while the RoadEditor is open, only used if smEditorOpen is true.
  269. Con::addVariable("$pref::maxProbeDrawDistance", TypeF32, &RenderProbeMgr::smMaxProbeDrawDistance, "Max distance for reflection probes to render.\n");
  270. Con::addVariable("$pref::MaxProbesPerFrame", TypeS32, &RenderProbeMgr::smMaxProbesPerFrame, "Max number of Environment Probes that can be rendered per-frame.\n");
  271. }
  272. void RenderProbeMgr::registerProbe(ProbeRenderInst* newProbe)
  273. {
  274. //Can't have over the probe limit
  275. if (mRegisteredProbes.size() + 1 >= PROBE_MAX_COUNT)
  276. return;
  277. mRegisteredProbes.push_back(newProbe);
  278. newProbe->mProbeIdx = mRegisteredProbes.size() - 1;
  279. const U32 cubeIndex = _findNextEmptyCubeSlot();
  280. if (cubeIndex == INVALID_CUBE_SLOT)
  281. {
  282. Con::warnf("RenderProbeMgr::addProbe: Invalid cubemap slot.");
  283. return;
  284. }
  285. //check if we need to resize the cubemap array
  286. if (cubeIndex >= mCubeSlotCount)
  287. {
  288. //alloc temp array handles
  289. GFXCubemapArrayHandle irr = GFXCubemapArrayHandle(GFX->createCubemapArray());
  290. GFXCubemapArrayHandle prefilter = GFXCubemapArrayHandle(GFX->createCubemapArray());
  291. irr->init(mCubeSlotCount + PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_IRRAD_SIZE, PROBE_FORMAT);
  292. prefilter->init(mCubeSlotCount + PROBE_ARRAY_SLOT_BUFFER_SIZE, PROBE_PREFILTER_SIZE, PROBE_FORMAT);
  293. mIrradianceArray->copyTo(irr);
  294. mPrefilterArray->copyTo(prefilter);
  295. //assign the temp handles to the new ones, this will destroy the old ones as well
  296. mIrradianceArray = irr;
  297. mPrefilterArray = prefilter;
  298. mCubeSlotCount += PROBE_ARRAY_SLOT_BUFFER_SIZE;
  299. }
  300. newProbe->mCubemapIndex = cubeIndex;
  301. //mark cubemap slot as taken
  302. mCubeMapSlots[cubeIndex] = true;
  303. mCubeMapCount++;
  304. #ifdef TORQUE_DEBUG
  305. Con::warnf("RenderProbeMgr::registerProbe: Registered probe %u to cubeIndex %u", newProbe->mProbeIdx, cubeIndex);
  306. #endif
  307. mProbesDirty = true;
  308. }
  309. void RenderProbeMgr::unregisterProbe(U32 probeIdx)
  310. {
  311. //Mostly for consolidation, but also lets us sanity check or prep any other data we need for rendering this in one place at time of flagging for render
  312. if (probeIdx >= mRegisteredProbes.size())
  313. return;
  314. if (mRegisteredProbes[probeIdx]->mCubemapIndex == INVALID_CUBE_SLOT)
  315. return;
  316. //mark cubemap slot as available now
  317. mCubeMapSlots[mRegisteredProbes[probeIdx]->mCubemapIndex] = false;
  318. mCubeMapCount--;
  319. mRegisteredProbes.erase(probeIdx);
  320. //recalculate all the probe's indicies just to be sure
  321. for (U32 i = 0; i < mRegisteredProbes.size(); i++)
  322. {
  323. mRegisteredProbes[i]->mProbeIdx = i;
  324. }
  325. //rebuild our probe data
  326. mProbesDirty = true;
  327. }
  328. void RenderProbeMgr::submitProbe(const ProbeRenderInst& newProbe)
  329. {
  330. mActiveProbes.push_back(newProbe);
  331. }
  332. //
  333. //
  334. PostEffect* RenderProbeMgr::getProbeArrayEffect()
  335. {
  336. if (!mProbeArrayEffect)
  337. {
  338. mProbeArrayEffect = dynamic_cast<PostEffect*>(Sim::findObject("reflectionProbeArrayPostFX"));
  339. if (!mProbeArrayEffect)
  340. return nullptr;
  341. }
  342. return mProbeArrayEffect;
  343. }
  344. //remove
  345. //Con::setIntVariable("lightMetrics::activeReflectionProbes", mReflectProbeBin.size());
  346. //Con::setIntVariable("lightMetrics::culledReflectProbes", 0/*mNumLightsCulled*/);
  347. //
  348. void RenderProbeMgr::updateProbes()
  349. {
  350. mProbesDirty = true;
  351. }
  352. void RenderProbeMgr::updateProbeTexture(ProbeRenderInst* probeInfo)
  353. {
  354. if (probeInfo->mIrradianceCubemap.isNull() || !probeInfo->mIrradianceCubemap->isInitialized())
  355. {
  356. Con::errorf("RenderProbeMgr::updateProbeTexture() - tried to update a probe's texture with an invalid or uninitialized irradiance map!");
  357. return;
  358. }
  359. if (probeInfo->mPrefilterCubemap.isNull() || !probeInfo->mPrefilterCubemap->isInitialized())
  360. {
  361. Con::errorf("RenderProbeMgr::updateProbeTexture() - tried to update a probe's texture with an invalid or uninitialized specular map!");
  362. return;
  363. }
  364. const U32 cubeIndex = probeInfo->mCubemapIndex;
  365. mIrradianceArray->updateTexture(probeInfo->mIrradianceCubemap, cubeIndex);
  366. mPrefilterArray->updateTexture(probeInfo->mPrefilterCubemap, cubeIndex);
  367. #ifdef TORQUE_DEBUG
  368. Con::warnf("UpdatedProbeTexture - probeIdx: %u on cubeIndex %u, Irrad validity: %d, Prefilter validity: %d", probeInfo->mProbeIdx, cubeIndex,
  369. probeInfo->mIrradianceCubemap->isInitialized(), probeInfo->mPrefilterCubemap->isInitialized());
  370. #endif
  371. }
  372. void RenderProbeMgr::reloadTextures()
  373. {
  374. U32 probeCount = mRegisteredProbes.size();
  375. for (U32 i = 0; i < probeCount; i++)
  376. {
  377. updateProbeTexture(mRegisteredProbes[i]);
  378. }
  379. mProbesDirty = true;
  380. }
  381. void RenderProbeMgr::_setupPerFrameParameters(const SceneRenderState *state)
  382. {
  383. PROFILE_SCOPE(RenderProbeMgr_SetupPerFrameParameters);
  384. mProbeData = ProbeDataSet(smMaxProbesPerFrame);
  385. getBestProbes(state->getCameraPosition(), &mProbeData);
  386. }
  387. ProbeShaderConstants* RenderProbeMgr::getProbeShaderConstants(GFXShaderConstBuffer* buffer)
  388. {
  389. if (!buffer)
  390. return NULL;
  391. PROFILE_SCOPE(ProbeManager_GetProbeShaderConstants);
  392. GFXShader* shader = buffer->getShader();
  393. // Check to see if this is the same shader, we'll get hit repeatedly by
  394. // the same one due to the render bin loops.
  395. if (mLastShader.getPointer() != shader)
  396. {
  397. ProbeConstantMap::Iterator iter = mConstantLookup.find(shader);
  398. if (iter != mConstantLookup.end())
  399. {
  400. mLastConstants = iter->value;
  401. }
  402. else
  403. {
  404. ProbeShaderConstants* psc = new ProbeShaderConstants();
  405. mConstantLookup[shader] = psc;
  406. mLastConstants = psc;
  407. }
  408. // Set our new shader
  409. mLastShader = shader;
  410. }
  411. /*if (mLastConstants == nullptr)
  412. {
  413. ProbeShaderConstants* psc = new ProbeShaderConstants();
  414. mConstantLookup[shader] = psc;
  415. mLastConstants = psc;
  416. }*/
  417. // Make sure that our current lighting constants are initialized
  418. if (mLastConstants && !mLastConstants->mInit)
  419. mLastConstants->init(shader);
  420. return mLastConstants;
  421. }
  422. void RenderProbeMgr::setupSGData(SceneData& data, const SceneRenderState* state, LightInfo* light)
  423. {
  424. //ensure they're sorted for forward rendering
  425. mActiveProbes.sort(_probeScoreCmp);
  426. }
  427. void RenderProbeMgr::_update4ProbeConsts(const SceneData &sgData,
  428. MatrixSet &matSet,
  429. ProbeShaderConstants *probeShaderConsts,
  430. GFXShaderConstBuffer *shaderConsts)
  431. {
  432. PROFILE_SCOPE(ProbeManager_Update4ProbeConsts);
  433. // Skip over gathering lights if we don't have to!
  434. if (probeShaderConsts->isValid())
  435. {
  436. PROFILE_SCOPE(ProbeManager_Update4ProbeConsts_setProbes);
  437. const U32 MAX_FORWARD_PROBES = 4;
  438. ProbeDataSet probeSet(MAX_FORWARD_PROBES);
  439. matSet.restoreSceneViewProjection();
  440. getBestProbes(sgData.objTrans->getPosition(), &probeSet);
  441. static AlignedArray<Point4F> probePositionAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  442. static AlignedArray<Point4F> refScaleAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  443. static AlignedArray<Point4F> probeRefPositionAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  444. static AlignedArray<Point4F> probeConfigAlignedArray(probeSet.maxProbeCount, sizeof(Point4F));
  445. for (U32 i = 0; i < probeSet.maxProbeCount; i++)
  446. {
  447. probePositionAlignedArray[i] = probeSet.probePositionArray[i];
  448. probeRefPositionAlignedArray[i] = probeSet.probeRefPositionArray[i];
  449. refScaleAlignedArray[i] = probeSet.refScaleArray[i];
  450. probeConfigAlignedArray[i] = probeSet.probeConfigArray[i];
  451. }
  452. shaderConsts->setSafe(probeShaderConsts->mProbeCountSC, (S32)probeSet.effectiveProbeCount);
  453. shaderConsts->setSafe(probeShaderConsts->mProbePositionSC, probePositionAlignedArray);
  454. shaderConsts->setSafe(probeShaderConsts->mProbeRefPosSC, probeRefPositionAlignedArray);
  455. if(probeShaderConsts->isValid())
  456. shaderConsts->set(probeShaderConsts->mWorldToObjArraySC, probeSet.probeWorldToObjArray.address(), probeSet.effectiveProbeCount, GFXSCT_Float4x4);
  457. shaderConsts->setSafe(probeShaderConsts->mRefScaleSC, refScaleAlignedArray);
  458. shaderConsts->setSafe(probeShaderConsts->mProbeConfigDataSC, probeConfigAlignedArray);
  459. shaderConsts->setSafe(probeShaderConsts->mSkylightCubemapIdxSC, (float)probeSet.skyLightIdx);
  460. if(probeShaderConsts->mBRDFTextureMap->getSamplerRegister() != -1 && mBRDFTexture.isValid())
  461. GFX->setTexture(probeShaderConsts->mBRDFTextureMap->getSamplerRegister(), mBRDFTexture);
  462. if(probeShaderConsts->mProbeSpecularCubemapSC->getSamplerRegister() != -1)
  463. GFX->setCubeArrayTexture(probeShaderConsts->mProbeSpecularCubemapSC->getSamplerRegister(), mPrefilterArray);
  464. if(probeShaderConsts->mProbeIrradianceCubemapSC->getSamplerRegister() != -1)
  465. GFX->setCubeArrayTexture(probeShaderConsts->mProbeIrradianceCubemapSC->getSamplerRegister(), mIrradianceArray);
  466. }
  467. }
  468. S32 QSORT_CALLBACK RenderProbeMgr::_probeScoreCmp(const ProbeRenderInst* a, const ProbeRenderInst* b)
  469. {
  470. F32 diff = a->getScore() - b->getScore();
  471. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  472. }
  473. void RenderProbeMgr::getBestProbes(const Point3F& objPosition, ProbeDataSet* probeDataSet)
  474. {
  475. PROFILE_SCOPE(ProbeManager_getBestProbes);
  476. //Array rendering
  477. U32 probeCount = mActiveProbes.size();
  478. Vector<S8> bestPickProbes;
  479. bestPickProbes.setSize(probeDataSet->maxProbeCount);
  480. bestPickProbes.fill(-1);
  481. probeDataSet->effectiveProbeCount = 0;
  482. for (U32 i = 0; i < probeCount; i++)
  483. {
  484. if (probeDataSet->skyLightIdx != -1 && probeDataSet->effectiveProbeCount >= probeDataSet->maxProbeCount)
  485. break;
  486. const ProbeRenderInst& curEntry = mActiveProbes[i];
  487. if (!curEntry.mIsEnabled)
  488. continue;
  489. if (curEntry.mProbeShapeType != ProbeRenderInst::Skylight)
  490. {
  491. if (probeDataSet->effectiveProbeCount < probeDataSet->maxProbeCount)
  492. {
  493. bestPickProbes[probeDataSet->effectiveProbeCount] = i;
  494. probeDataSet->effectiveProbeCount++;
  495. }
  496. }
  497. else
  498. {
  499. probeDataSet->skyLightIdx = curEntry.mCubemapIndex;
  500. }
  501. }
  502. //Grab our best probe picks
  503. for (U32 i = 0; i < bestPickProbes.size(); i++)
  504. {
  505. if (bestPickProbes[i] == -1)
  506. continue;
  507. const ProbeRenderInst& curEntry = mActiveProbes[bestPickProbes[i]];
  508. MatrixF p2A = curEntry.getTransform();
  509. p2A.inverse();
  510. probeDataSet->refScaleArray[i] = curEntry.mProbeRefScale / p2A.getScale();
  511. Point3F probePos = curEntry.getPosition();
  512. Point3F refPos = probePos + curEntry.mProbeRefOffset * probeDataSet->refScaleArray[i].asPoint3F();
  513. probeDataSet->probeWorldToObjArray[i] = curEntry.getTransform();
  514. probeDataSet->probePositionArray[i] = Point4F(probePos.x, probePos.y, probePos.z, 0);
  515. probeDataSet->probeRefPositionArray[i] = Point4F(refPos.x, refPos.y, refPos.z, 0);
  516. probeDataSet->probeConfigArray[i] = Point4F(curEntry.mProbeShapeType,
  517. curEntry.mRadius,
  518. curEntry.mAtten,
  519. curEntry.mCubemapIndex);
  520. }
  521. }
  522. void RenderProbeMgr::getProbeTextureData(ProbeTextureArrayData* probeTextureSet)
  523. {
  524. probeTextureSet->BRDFTexture = mBRDFTexture;
  525. probeTextureSet->prefilterArray = mPrefilterArray;
  526. probeTextureSet->irradianceArray = mIrradianceArray;
  527. }
  528. void RenderProbeMgr::setProbeInfo(ProcessedMaterial *pmat,
  529. const Material *mat,
  530. const SceneData &sgData,
  531. const SceneRenderState *state,
  532. U32 pass,
  533. GFXShaderConstBuffer *shaderConsts)
  534. {
  535. // Skip this if we're rendering from the deferred bin.
  536. if (sgData.binType == SceneData::DeferredBin)
  537. return;
  538. PROFILE_SCOPE(ProbeManager_setProbeInfo);
  539. ProbeShaderConstants *psc = getProbeShaderConstants(shaderConsts);
  540. // NOTE: If you encounter a crash from this point forward
  541. // while setting a shader constant its probably because the
  542. // mConstantLookup has bad shaders/constants in it.
  543. //
  544. // This is a known crash bug that can occur if materials/shaders
  545. // are reloaded and the light manager is not reset.
  546. //
  547. // We should look to fix this by clearing the table.
  548. MatrixSet matSet = state->getRenderPass()->getMatrixSet();
  549. // Update the forward shading light constants.
  550. _update4ProbeConsts(sgData, matSet, psc, shaderConsts);
  551. }
  552. //-----------------------------------------------------------------------------
  553. // render objects
  554. //-----------------------------------------------------------------------------
  555. void RenderProbeMgr::render( SceneRenderState *state )
  556. {
  557. if (getProbeArrayEffect() == nullptr)
  558. {
  559. mActiveProbes.clear();
  560. return;
  561. }
  562. GFXDEBUGEVENT_SCOPE(RenderProbeMgr_render, ColorI::WHITE);
  563. //Sort the active probes
  564. mActiveProbes.sort(_probeScoreCmp);
  565. // Initialize and set the per-frame data
  566. _setupPerFrameParameters(state);
  567. // Early out if nothing to draw.
  568. if (!RenderProbeMgr::smRenderReflectionProbes || (!state->isDiffusePass() && !state->isReflectPass()) || (mProbeData.effectiveProbeCount == 0 && mProbeData.skyLightIdx == -1))
  569. {
  570. getProbeArrayEffect()->setSkip(true);
  571. mActiveProbes.clear();
  572. return;
  573. }
  574. GFXTransformSaver saver;
  575. //Visualization
  576. String useDebugAtten = Con::getVariable("$Probes::showAttenuation", "0");
  577. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_ATTENUATION", useDebugAtten);
  578. String useDebugSpecCubemap = Con::getVariable("$Probes::showSpecularCubemaps", "0");
  579. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_SPECCUBEMAP", useDebugSpecCubemap);
  580. String useDebugDiffuseCubemap = Con::getVariable("$Probes::showDiffuseCubemaps", "0");
  581. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_DIFFCUBEMAP", useDebugDiffuseCubemap);
  582. String useDebugContrib = Con::getVariable("$Probes::showProbeContrib", "0");
  583. mProbeArrayEffect->setShaderMacro("DEBUGVIZ_CONTRIB", useDebugContrib);
  584. if(mProbeData.skyLightIdx != -1 && mProbeData.effectiveProbeCount == 0)
  585. mProbeArrayEffect->setShaderMacro("SKYLIGHT_ONLY", "1");
  586. else
  587. mProbeArrayEffect->setShaderMacro("SKYLIGHT_ONLY", "0");
  588. String probePerFrame = Con::getVariable("$pref::MaxProbesPerFrame", "8");
  589. mProbeArrayEffect->setShaderMacro("MAX_PROBES", probePerFrame);
  590. //ssao mask
  591. if (AdvancedLightBinManager::smUseSSAOMask)
  592. {
  593. //find ssaoMask
  594. NamedTexTargetRef ssaoTarget = NamedTexTarget::find("ssaoMask");
  595. GFXTextureObject* pTexObj = ssaoTarget->getTexture();
  596. if (pTexObj)
  597. {
  598. mProbeArrayEffect->setShaderMacro("USE_SSAO_MASK");
  599. mProbeArrayEffect->setTexture(6, pTexObj);
  600. }
  601. }
  602. else
  603. {
  604. mProbeArrayEffect->setTexture(6, GFXTexHandle(NULL));
  605. }
  606. mProbeArrayEffect->setTexture(3, mBRDFTexture);
  607. mProbeArrayEffect->setCubemapArrayTexture(4, mPrefilterArray);
  608. mProbeArrayEffect->setCubemapArrayTexture(5, mIrradianceArray);
  609. mProbeArrayEffect->setShaderConst("$numProbes", (S32)mProbeData.effectiveProbeCount);
  610. mProbeArrayEffect->setShaderConst("$skylightCubemapIdx", (S32)mProbeData.skyLightIdx);
  611. mProbeArrayEffect->setShaderConst("$cubeMips", (float)mMipCount);
  612. //also set up some colors
  613. Vector<Point4F> contribColors;
  614. contribColors.setSize(mProbeData.effectiveProbeCount);
  615. if (mProbeData.effectiveProbeCount != 0)
  616. {
  617. if (useDebugContrib == String("1"))
  618. {
  619. MRandomLCG RandomGen;
  620. RandomGen.setSeed(mProbeData.effectiveProbeCount);
  621. for (U32 i = 0; i < mProbeData.effectiveProbeCount; i++)
  622. {
  623. //we're going to cheat here a little for consistent debugging behavior. The first 3 probes will always have R G and then B for their colors, every other will be random
  624. if (i == 0)
  625. contribColors[i] = Point4F(1, 0, 0, 1);
  626. else if (i == 1)
  627. contribColors[i] = Point4F(0, 1, 0, 1);
  628. else if (i == 2)
  629. contribColors[i] = Point4F(0, 0, 1, 1);
  630. else
  631. contribColors[i] = Point4F(RandomGen.randF(0, 1), RandomGen.randF(0, 1), RandomGen.randF(0, 1), 1);
  632. }
  633. }
  634. }
  635. mProbeArrayEffect->setShaderConst("$probeContribColors", contribColors);
  636. mProbeArrayEffect->setShaderConst("$inProbePosArray", mProbeData.probePositionArray);
  637. mProbeArrayEffect->setShaderConst("$inRefPosArray", mProbeData.probeRefPositionArray);
  638. mProbeArrayEffect->setShaderConst("$worldToObjArray", mProbeData.probeWorldToObjArray);
  639. mProbeArrayEffect->setShaderConst("$refScaleArray", mProbeData.refScaleArray);
  640. mProbeArrayEffect->setShaderConst("$probeConfigData", mProbeData.probeConfigArray);
  641. // Make sure the effect is gonna render.
  642. getProbeArrayEffect()->setSkip(false);
  643. mActiveProbes.clear();
  644. }
  645. void RenderProbeMgr::bakeProbe(ReflectionProbe *probe)
  646. {
  647. GFXDEBUGEVENT_SCOPE(RenderProbeMgr_Bake, ColorI::WHITE);
  648. Con::warnf("RenderProbeMgr::bakeProbe() - Beginning bake!");
  649. U32 startMSTime = Platform::getRealMilliseconds();
  650. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  651. U32 resolution = Con::getIntVariable("$pref::ReflectionProbes::BakeResolution", 64);
  652. U32 prefilterMipLevels = mLog2(F32(resolution)) + 1;
  653. bool renderWithProbes = Con::getIntVariable("$pref::ReflectionProbes::RenderWithProbes", false);
  654. ReflectionProbe* clientProbe = nullptr;
  655. if (probe->isServerObject())
  656. clientProbe = static_cast<ReflectionProbe*>(probe->getClientObject());
  657. else
  658. return;
  659. if (clientProbe == nullptr)
  660. return;
  661. String probePrefilterPath = clientProbe->getPrefilterMapPath();
  662. String probeIrradPath = clientProbe->getIrradianceMapPath();
  663. if (clientProbe->mReflectionModeType != ReflectionProbe::DynamicCubemap)
  664. {
  665. //Prep our bake path
  666. if (probePrefilterPath.isEmpty() || probeIrradPath.isEmpty())
  667. {
  668. Con::errorf("RenderProbeMgr::bake() - Unable to bake our captures because probe doesn't have a path set");
  669. return;
  670. }
  671. }
  672. // Save the current transforms so we can restore
  673. // it for child control rendering below.
  674. GFXTransformSaver saver;
  675. bool probeRenderState = RenderProbeMgr::smRenderReflectionProbes;
  676. F32 farPlane = 1000.0f;
  677. ReflectorDesc reflDesc;
  678. reflDesc.texSize = resolution;
  679. reflDesc.farDist = farPlane;
  680. reflDesc.detailAdjust = 1;
  681. reflDesc.objectTypeMask = probe->mProbeShapeType == ProbeRenderInst::ProbeShapeType::Skylight ? SKYLIGHT_CAPTURE_TYPEMASK : REFLECTION_PROBE_CAPTURE_TYPEMASK;
  682. CubeReflector cubeRefl;
  683. cubeRefl.registerReflector(probe, &reflDesc);
  684. ReflectParams reflParams;
  685. //need to get the query somehow. Likely do some sort of get function to fetch from the guiTSControl that's active
  686. CameraQuery query; //need to get the last cameraQuery
  687. query.fov = 90; //90 degree slices for each of the 6 sides
  688. query.nearPlane = 0.1f;
  689. query.farPlane = farPlane;
  690. query.headMatrix = MatrixF();
  691. query.cameraMatrix = clientProbe->getTransform();
  692. Frustum culler;
  693. culler.set(false,
  694. query.fov,
  695. 1.0f,
  696. query.nearPlane,
  697. query.farPlane,
  698. query.cameraMatrix);
  699. S32 stereoTarget = GFX->getCurrentStereoTarget();
  700. Point2I maxRes(2048, 2048); //basically a boundary so we don't go over this and break stuff
  701. reflParams.culler = culler;
  702. reflParams.eyeId = stereoTarget;
  703. reflParams.query = &query;
  704. reflParams.startOfUpdateMs = startMSTime;
  705. reflParams.viewportExtent = maxRes;
  706. if (!renderWithProbes)
  707. RenderProbeMgr::smRenderReflectionProbes = false;
  708. GFXFormat reflectFormat;
  709. if (mUseHDRCaptures)
  710. reflectFormat = GFXFormatR16G16B16A16F;
  711. else
  712. reflectFormat = GFXFormatR8G8B8A8;
  713. const GFXFormat oldRefFmt = REFLECTMGR->getReflectFormat();
  714. REFLECTMGR->setReflectFormat(reflectFormat);
  715. mProbeArrayEffect->setShaderConst("$CAPTURING", true);
  716. cubeRefl.updateReflection(reflParams, clientProbe->getTransform().getPosition()+clientProbe->mProbeRefOffset);
  717. mProbeArrayEffect->setShaderConst("$CAPTURING", false);
  718. //Now, save out the maps
  719. //create irridiance cubemap
  720. if (cubeRefl.getCubemap())
  721. {
  722. //Just to ensure we're prepped for the generation
  723. clientProbe->createClientResources();
  724. //Prep it with whatever resolution we've dictated for our bake
  725. clientProbe->mIrridianceMap->mCubemap->initDynamic(resolution, reflectFormat);
  726. clientProbe->mPrefilterMap->mCubemap->initDynamic(resolution, reflectFormat);
  727. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  728. IBLUtilities::GenerateIrradianceMap(renderTarget, cubeRefl.getCubemap(), clientProbe->mIrridianceMap->mCubemap);
  729. IBLUtilities::GeneratePrefilterMap(renderTarget, cubeRefl.getCubemap(), prefilterMipLevels, clientProbe->mPrefilterMap->mCubemap);
  730. U32 endMSTime = Platform::getRealMilliseconds();
  731. F32 diffTime = F32(endMSTime - startMSTime);
  732. Con::warnf("RenderProbeMgr::bake() - Finished Capture! Took %g milliseconds", diffTime);
  733. Con::warnf("RenderProbeMgr::bake() - Beginning save now!");
  734. IBLUtilities::SaveCubeMap(clientProbe->getIrradianceMapPath(), clientProbe->mIrridianceMap->mCubemap);
  735. IBLUtilities::SaveCubeMap(clientProbe->getPrefilterMapPath(), clientProbe->mPrefilterMap->mCubemap);
  736. }
  737. else
  738. {
  739. Con::errorf("RenderProbeMgr::bake() - Didn't generate a valid scene capture cubemap, unable to generate prefilter and irradiance maps!");
  740. }
  741. if (!renderWithProbes)
  742. RenderProbeMgr::smRenderReflectionProbes = probeRenderState;
  743. cubeRefl.unregisterReflector();
  744. U32 endMSTime = Platform::getRealMilliseconds();
  745. F32 diffTime = F32(endMSTime - startMSTime);
  746. probe->setMaskBits(-1);
  747. Con::warnf("RenderProbeMgr::bake() - Finished bake! Took %g milliseconds", diffTime);
  748. REFLECTMGR->setReflectFormat(oldRefFmt);
  749. }
  750. void RenderProbeMgr::bakeProbes()
  751. {
  752. Vector<ReflectionProbe*> probes;
  753. Scene::getRootScene()->findObjectByType<ReflectionProbe>(probes);
  754. for (U32 i = 0; i < probes.size(); i++)
  755. {
  756. if (probes[i]->isClientObject())
  757. continue;
  758. bakeProbe(probes[i]);
  759. }
  760. }
  761. DefineEngineMethod(RenderProbeMgr, bakeProbe, void, (ReflectionProbe* probe), (nullAsType< ReflectionProbe*>()),
  762. "@brief Bakes the cubemaps for a reflection probe\n\n.")
  763. {
  764. if(probe != nullptr)
  765. object->bakeProbe(probe);
  766. }
  767. DefineEngineMethod(RenderProbeMgr, bakeProbes, void, (),, "@brief Iterates over all reflection probes in the scene and bakes their cubemaps\n\n.")
  768. {
  769. object->bakeProbes();
  770. }