probeManager.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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 "platform/platform.h"
  23. #include "lighting/probeManager.h"
  24. #include "console/console.h"
  25. #include "console/consoleTypes.h"
  26. #include "core/util/safeDelete.h"
  27. #include "console/sim.h"
  28. #include "console/simSet.h"
  29. #include "scene/sceneManager.h"
  30. #include "materials/materialManager.h"
  31. #include "materials/sceneData.h"
  32. #include "lighting/lightInfo.h"
  33. #include "lighting/lightingInterfaces.h"
  34. #include "T3D/gameBase/gameConnection.h"
  35. #include "gfx/gfxStringEnumTranslate.h"
  36. #include "console/engineAPI.h"
  37. #include "renderInstance/renderDeferredMgr.h"
  38. #include "shaderGen/shaderGenVars.h"
  39. #include "math/util/sphereMesh.h"
  40. Signal<void(const char*,bool)> ProbeManager::smActivateSignal;
  41. ProbeManager *ProbeManager::smProbeManager = NULL;
  42. bool ProbeManager::smRenderReflectionProbes = true;
  43. //
  44. //
  45. ProbeRenderInst::ProbeRenderInst() : SystemInterface(),
  46. mTransform(true),
  47. mDirty(false),
  48. mAmbient(0.0f, 0.0f, 0.0f, 1.0f),
  49. mPriority(1.0f),
  50. mScore(0.0f),
  51. mDebugRender(false),
  52. mCubemap(NULL),
  53. mIrradianceCubemap(NULL),
  54. mBRDFTexture(NULL),
  55. mRadius(1.0f),
  56. mIntensity(1.0f),
  57. mProbePosOffset(0,0,0),
  58. numPrims(0)
  59. {
  60. for (U32 i = 0; i < 5; ++i)
  61. {
  62. mSHConstants[i] = 0;
  63. }
  64. }
  65. ProbeRenderInst::~ProbeRenderInst()
  66. {
  67. if (mCubemap && mCubemap->isValid())
  68. {
  69. mCubemap->free();
  70. }
  71. if (mIrradianceCubemap && mIrradianceCubemap->isValid())
  72. {
  73. mIrradianceCubemap->free();
  74. }
  75. if (mBRDFTexture && mBRDFTexture->isValid())
  76. {
  77. mBRDFTexture->free();
  78. }
  79. }
  80. void ProbeRenderInst::set(const ProbeRenderInst *probeInfo)
  81. {
  82. mTransform = probeInfo->mTransform;
  83. mAmbient = probeInfo->mAmbient;
  84. mCubemap = probeInfo->mCubemap;
  85. mIrradianceCubemap = probeInfo->mIrradianceCubemap;
  86. mBRDFTexture = probeInfo->mBRDFTexture;
  87. mRadius = probeInfo->mRadius;
  88. mIntensity = probeInfo->mIntensity;
  89. mProbeShapeType = probeInfo->mProbeShapeType;
  90. numPrims = probeInfo->numPrims;
  91. numVerts = probeInfo->numVerts;
  92. numIndicesForPoly = probeInfo->numIndicesForPoly;
  93. mBounds = probeInfo->mBounds;
  94. for (U32 i = 0; i < 9; i++)
  95. {
  96. mSHTerms[i] = probeInfo->mSHTerms[i];
  97. }
  98. for (U32 i = 0; i < 5; i++)
  99. {
  100. mSHConstants[i] = probeInfo->mSHConstants[i];
  101. }
  102. }
  103. void ProbeRenderInst::getWorldToLightProj(MatrixF *outMatrix) const
  104. {
  105. *outMatrix = getTransform();
  106. outMatrix->inverse();
  107. }
  108. ProbeShaderConstants::ProbeShaderConstants()
  109. : mInit(false),
  110. mShader(NULL),
  111. mProbeParamsSC(NULL),
  112. mProbePositionSC(NULL),
  113. mProbeRadiusSC(NULL),
  114. mProbeBoxMinSC(NULL),
  115. mProbeBoxMaxSC(NULL),
  116. mProbeIsSphereSC(NULL),
  117. mProbeLocalPosSC(NULL),
  118. mProbeCubemapSC(NULL)
  119. {
  120. }
  121. ProbeShaderConstants::~ProbeShaderConstants()
  122. {
  123. if (mShader.isValid())
  124. {
  125. mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
  126. mShader = NULL;
  127. }
  128. }
  129. void ProbeShaderConstants::init(GFXShader* shader)
  130. {
  131. if (mShader.getPointer() != shader)
  132. {
  133. if (mShader.isValid())
  134. mShader->getReloadSignal().remove(this, &ProbeShaderConstants::_onShaderReload);
  135. mShader = shader;
  136. mShader->getReloadSignal().notify(this, &ProbeShaderConstants::_onShaderReload);
  137. }
  138. mProbeParamsSC = shader->getShaderConstHandle("$probeParams");
  139. //Reflection Probes
  140. mProbePositionSC = shader->getShaderConstHandle(ShaderGenVars::probePosition);
  141. mProbeRadiusSC = shader->getShaderConstHandle(ShaderGenVars::probeRadius);
  142. mProbeBoxMinSC = shader->getShaderConstHandle(ShaderGenVars::probeBoxMin);
  143. mProbeBoxMaxSC = shader->getShaderConstHandle(ShaderGenVars::probeBoxMax);
  144. mProbeIsSphereSC = shader->getShaderConstHandle(ShaderGenVars::probeIsSphere);
  145. mProbeLocalPosSC = shader->getShaderConstHandle(ShaderGenVars::probeLocalPos);
  146. mProbeCubemapSC = shader->getShaderConstHandle(ShaderGenVars::probeCubemap);
  147. mInit = true;
  148. }
  149. void ProbeShaderConstants::_onShaderReload()
  150. {
  151. if (mShader.isValid())
  152. init(mShader);
  153. }
  154. ProbeManager::ProbeManager()
  155. : mSceneManager( NULL ),
  156. mCullPos( Point3F::Zero )
  157. {
  158. mLastShader = NULL;
  159. mLastConstants = NULL;
  160. mSkylightMaterial = nullptr;
  161. mReflectProbeMaterial = nullptr;
  162. }
  163. ProbeManager::~ProbeManager()
  164. {
  165. }
  166. ProbeRenderInst* ProbeManager::createProbeInfo(ProbeRenderInst* probe /* = NULL */)
  167. {
  168. ProbeRenderInst *outProbe = (probe != NULL) ? probe : new ProbeRenderInst;
  169. /*ProbeManagerMap &ProbeManagers = _getProbeManagers();
  170. ProbeManagerMap::Iterator iter = ProbeManagers.begin();
  171. for ( ; iter != ProbeManagers.end(); iter++ )
  172. {
  173. ProbeManager *lm = iter->value;
  174. lm->_addLightInfoEx( outLight );
  175. }*/
  176. return outProbe;
  177. }
  178. /*void ProbeManager::initLightFields()
  179. {
  180. ProbeManagerMap &ProbeManagers = _getProbeManagers();
  181. ProbeManagerMap::Iterator iter = ProbeManagers.begin();
  182. for ( ; iter != ProbeManagers.end(); iter++ )
  183. {
  184. ProbeManager *lm = iter->value;
  185. lm->_initLightFields();
  186. }
  187. }*/
  188. IMPLEMENT_GLOBAL_CALLBACK( onProbeManagerActivate, void, ( const char *name ), ( name ),
  189. "A callback called by the engine when a light manager is activated.\n"
  190. "@param name The name of the light manager being activated.\n"
  191. "@ingroup Lighting\n" );
  192. void ProbeManager::activate( SceneManager *sceneManager )
  193. {
  194. AssertFatal( sceneManager, "ProbeManager::activate() - Got null scene manager!" );
  195. //AssertFatal( mIsActive == false, "ProbeManager::activate() - Already activated!" );
  196. AssertFatal(smProbeManager == NULL, "ProbeManager::activate() - A previous ProbeManager is still active!" );
  197. mSceneManager = sceneManager;
  198. smProbeManager = this;
  199. }
  200. IMPLEMENT_GLOBAL_CALLBACK( onProbeManagerDeactivate, void, ( const char *name ), ( name ),
  201. "A callback called by the engine when a light manager is deactivated.\n"
  202. "@param name The name of the light manager being deactivated.\n"
  203. "@ingroup Lighting\n" );
  204. void ProbeManager::deactivate()
  205. {
  206. //AssertFatal( mIsActive == true, "ProbeManager::deactivate() - Already deactivated!" );
  207. AssertFatal( smProbeManager == this, "ProbeManager::activate() - This isn't the active light manager!" );
  208. //if( Sim::getRootGroup() ) // To protect against shutdown.
  209. // onProbeManagerDeactivate_callback( getName() );
  210. //mIsActive = false;
  211. mSceneManager = NULL;
  212. smProbeManager = NULL;
  213. }
  214. ProbeShaderConstants* ProbeManager::getProbeShaderConstants(GFXShaderConstBuffer* buffer)
  215. {
  216. if (!buffer)
  217. return NULL;
  218. PROFILE_SCOPE(ProbeManager_GetProbeShaderConstants);
  219. GFXShader* shader = buffer->getShader();
  220. // Check to see if this is the same shader, we'll get hit repeatedly by
  221. // the same one due to the render bin loops.
  222. if (mLastShader.getPointer() != shader)
  223. {
  224. ProbeConstantMap::Iterator iter = mConstantLookup.find(shader);
  225. if (iter != mConstantLookup.end())
  226. {
  227. mLastConstants = iter->value;
  228. }
  229. else
  230. {
  231. ProbeShaderConstants* psc = new ProbeShaderConstants();
  232. mConstantLookup[shader] = psc;
  233. mLastConstants = psc;
  234. }
  235. // Set our new shader
  236. mLastShader = shader;
  237. }
  238. mLastConstants = new ProbeShaderConstants();
  239. // Make sure that our current lighting constants are initialized
  240. if (!mLastConstants->mInit)
  241. mLastConstants->init(shader);
  242. return mLastConstants;
  243. }
  244. void ProbeManager::_update4ProbeConsts( const SceneData &sgData,
  245. MatrixSet &matSet,
  246. GFXShaderConstHandle *probePositionSC,
  247. GFXShaderConstHandle *probeRadiusSC,
  248. GFXShaderConstHandle *probeBoxMinSC,
  249. GFXShaderConstHandle *probeBoxMaxSC,
  250. GFXShaderConstHandle *probeCubemapSC,
  251. GFXShaderConstHandle *probeIsSphereSC,
  252. GFXShaderConstHandle *probeLocalPosSC,
  253. GFXShaderConstBuffer *shaderConsts )
  254. {
  255. PROFILE_SCOPE( ProbeManager_Update4ProbeConsts );
  256. // Skip over gathering lights if we don't have to!
  257. if (probePositionSC->isValid() ||
  258. probeRadiusSC->isValid() ||
  259. probeBoxMinSC->isValid() ||
  260. probeBoxMaxSC->isValid() ||
  261. probeCubemapSC->isValid() && (!ProbeRenderInst::all.empty()))
  262. {
  263. PROFILE_SCOPE(ProbeManager_Update4ProbeConsts_setProbes);
  264. static AlignedArray<Point3F> probePositions(4, sizeof(Point3F));
  265. static AlignedArray<F32> probeRadius(4, sizeof(F32));
  266. static AlignedArray<Point3F> probeBoxMins(4, sizeof(Point3F));
  267. static AlignedArray<Point3F> probeBoxMaxs(4, sizeof(Point3F));
  268. static AlignedArray<Point3F> probeLocalPositions(4, sizeof(Point3F));
  269. static AlignedArray<F32> probeIsSphere(4, sizeof(F32));
  270. //static AlignedArray<CubemapData> probeCubemap(4, sizeof(CubemapData));
  271. F32 range;
  272. // Need to clear the buffers so that we don't leak
  273. // lights from previous passes or have NaNs.
  274. dMemset(probePositions.getBuffer(), 0, probePositions.getBufferSize());
  275. dMemset(probeRadius.getBuffer(), 0, probeRadius.getBufferSize());
  276. dMemset(probeBoxMins.getBuffer(), 0, probeBoxMins.getBufferSize());
  277. dMemset(probeBoxMaxs.getBuffer(), 0, probeBoxMaxs.getBufferSize());
  278. dMemset(probeLocalPositions.getBuffer(), 0, probeLocalPositions.getBufferSize());
  279. dMemset(probeIsSphere.getBuffer(), 0, probeRadius.getBufferSize());
  280. //dMemset(probeCubemap.getBuffer(), 0, probeCubemap.getBufferSize());
  281. matSet.restoreSceneViewProjection();
  282. const MatrixF &worldToCameraXfm = matSet.getWorldToCamera();
  283. // Gather the data for the first 4 probes.
  284. const ProbeRenderInst *probe;
  285. for (U32 i = 0; i < 4; i++)
  286. {
  287. if (i >= ProbeRenderInst::all.size())
  288. break;
  289. probe = ProbeRenderInst::all[i];
  290. if (!probe)
  291. continue;
  292. if (!probe->mIsEnabled)
  293. continue;
  294. // The light positions and spot directions are
  295. // in SoA order to make optimal use of the GPU.
  296. const Point3F &probePos = probe->getPosition();
  297. probePositions[i].x = probePos.x;
  298. probePositions[i].y = probePos.y;
  299. probePositions[i].z = probePos.z;
  300. probeRadius[i] = probe->mRadius;
  301. const Point3F &minExt = probe->mBounds.minExtents;
  302. probeBoxMins[i].x = minExt.x;
  303. probeBoxMins[i].y = minExt.y;
  304. probeBoxMins[i].z = minExt.z;
  305. const Point3F &maxExt = probe->mBounds.maxExtents;
  306. probeBoxMaxs[i].x = maxExt.x;
  307. probeBoxMaxs[i].y = maxExt.y;
  308. probeBoxMaxs[i].z = maxExt.z;
  309. probeIsSphere[i] = probe->mProbeShapeType == ProbeRenderInst::Sphere ? 1.0 : 0.0;
  310. Point3F localProbePos;
  311. worldToCameraXfm.mulP(probe->getPosition(), &localProbePos);
  312. probeLocalPositions[i].x = localProbePos.x;
  313. probeLocalPositions[i].y = localProbePos.y;
  314. probeLocalPositions[i].z = localProbePos.z;
  315. if (probe->mCubemap && !probe->mCubemap->isNull())
  316. {
  317. S32 samplerReg = probeCubemapSC->getSamplerRegister();
  318. if(samplerReg != -1)
  319. GFX->setCubeTexture(samplerReg + i, probe->mCubemap->getPointer());
  320. }
  321. }
  322. shaderConsts->setSafe(probePositionSC, probePositions);
  323. shaderConsts->setSafe(probeRadiusSC, probeRadius);
  324. shaderConsts->setSafe(probeBoxMinSC, probeBoxMins);
  325. shaderConsts->setSafe(probeBoxMaxSC, probeBoxMaxs);
  326. shaderConsts->setSafe(probeLocalPosSC, probeLocalPositions);
  327. shaderConsts->setSafe(probeIsSphereSC, probeIsSphere);
  328. //
  329. //shaderConsts->setSafe(lightSpotAngleSC, lightSpotAngle);
  330. //shaderConsts->setSafe(lightSpotFalloffSC, lightSpotFalloff);
  331. }
  332. else
  333. {
  334. /*if (probe->mCubemap && !probe->mCubemap->isNull())
  335. {
  336. GFX->setCubeTexture(1, probe->mCubemap->getPointer());
  337. }*/
  338. if (probeCubemapSC->isValid())
  339. {
  340. for(U32 i=0; i < 4; ++i)
  341. GFX->setCubeTexture(probeCubemapSC->getSamplerRegister() + i, NULL);
  342. }
  343. }
  344. }
  345. void ProbeManager::setProbeInfo(ProcessedMaterial *pmat,
  346. const Material *mat,
  347. const SceneData &sgData,
  348. const SceneRenderState *state,
  349. U32 pass,
  350. GFXShaderConstBuffer *shaderConsts)
  351. {
  352. // Skip this if we're rendering from the deferred bin.
  353. if ( sgData.binType == SceneData::DeferredBin )
  354. return;
  355. // if (mRegisteredProbes.empty())
  356. // return;
  357. PROFILE_SCOPE(ProbeManager_setProbeInfo);
  358. ProbeShaderConstants *psc = getProbeShaderConstants(shaderConsts);
  359. //ProbeInfo *probe;
  360. //probe = mRegisteredProbes[0];
  361. // NOTE: If you encounter a crash from this point forward
  362. // while setting a shader constant its probably because the
  363. // mConstantLookup has bad shaders/constants in it.
  364. //
  365. // This is a known crash bug that can occur if materials/shaders
  366. // are reloaded and the light manager is not reset.
  367. //
  368. // We should look to fix this by clearing the table.
  369. MatrixSet matSet = state->getRenderPass()->getMatrixSet();
  370. // Update the forward shading light constants.
  371. _update4ProbeConsts( sgData,
  372. matSet,
  373. psc->mProbePositionSC,
  374. psc->mProbeRadiusSC,
  375. psc->mProbeBoxMinSC,
  376. psc->mProbeBoxMaxSC,
  377. psc->mProbeCubemapSC,
  378. psc->mProbeIsSphereSC,
  379. psc->mProbeLocalPosSC,
  380. shaderConsts );
  381. // Static
  382. /*if (lsm && light->getCastShadows())
  383. {
  384. if (psc->mWorldToLightProjSC->isValid())
  385. shaderConsts->set(psc->mWorldToLightProjSC,
  386. lsm->getWorldToLightProj(),
  387. psc->mWorldToLightProjSC->getType());
  388. if (psc->mViewToLightProjSC->isValid())
  389. {
  390. // TODO: Should probably cache these results and
  391. // not do this mul here on every material that needs
  392. // this transform.
  393. shaderConsts->set(psc->mViewToLightProjSC,
  394. lsm->getWorldToLightProj() * state->getCameraTransform(),
  395. psc->mViewToLightProjSC->getType());
  396. }
  397. shaderConsts->setSafe(psc->mShadowMapSizeSC, 1.0f / (F32)lsm->getTexSize());
  398. // Do this last so that overrides can properly override parameters previously set
  399. lsm->setShaderParameters(shaderConsts, psc);
  400. }
  401. else
  402. {
  403. if (psc->mViewToLightProjSC->isValid())
  404. {
  405. // TODO: Should probably cache these results and
  406. // not do this mul here on every material that needs
  407. // this transform.
  408. MatrixF proj;
  409. light->getWorldToLightProj(&proj);
  410. shaderConsts->set(psc->mViewToLightProjSC,
  411. proj * state->getCameraTransform(),
  412. psc->mViewToLightProjSC->getType());
  413. }
  414. }
  415. // Dynamic
  416. if (dynamicShadowMap)
  417. {
  418. if (psc->mDynamicWorldToLightProjSC->isValid())
  419. shaderConsts->set(psc->mDynamicWorldToLightProjSC,
  420. dynamicShadowMap->getWorldToLightProj(),
  421. psc->mDynamicWorldToLightProjSC->getType());
  422. if (psc->mDynamicViewToLightProjSC->isValid())
  423. {
  424. // TODO: Should probably cache these results and
  425. // not do this mul here on every material that needs
  426. // this transform.
  427. shaderConsts->set(psc->mDynamicViewToLightProjSC,
  428. dynamicShadowMap->getWorldToLightProj() * state->getCameraTransform(),
  429. psc->mDynamicViewToLightProjSC->getType());
  430. }
  431. shaderConsts->setSafe(psc->mShadowMapSizeSC, 1.0f / (F32)dynamicShadowMap->getTexSize());
  432. // Do this last so that overrides can properly override parameters previously set
  433. dynamicShadowMap->setShaderParameters(shaderConsts, psc);
  434. }
  435. else
  436. {
  437. if (psc->mDynamicViewToLightProjSC->isValid())
  438. {
  439. // TODO: Should probably cache these results and
  440. // not do this mul here on every material that needs
  441. // this transform.
  442. MatrixF proj;
  443. light->getWorldToLightProj(&proj);
  444. shaderConsts->set(psc->mDynamicViewToLightProjSC,
  445. proj * state->getCameraTransform(),
  446. psc->mDynamicViewToLightProjSC->getType());
  447. }
  448. }*/
  449. }
  450. /// Allows us to set textures during the Material::setTextureStage call, return true if we've done work.
  451. bool ProbeManager::setTextureStage(const SceneData &sgData,
  452. const U32 currTexFlag,
  453. const U32 textureSlot,
  454. GFXShaderConstBuffer *shaderConsts,
  455. ShaderConstHandles *handles)
  456. {
  457. return false;
  458. }
  459. AvailableSLInterfaces* ProbeManager::getSceneLightingInterface()
  460. {
  461. //if ( !mAvailableSLInterfaces )
  462. // mAvailableSLInterfaces = new AvailableSLInterfaces();
  463. return NULL;
  464. }
  465. void ProbeManager::updateDirtyProbes()
  466. {
  467. for (U32 i = 0; i < ProbeRenderInst::all.size(); i++)
  468. {
  469. ProbeRenderInst* probe = ProbeRenderInst::all[i];
  470. if (probe->mDirty)
  471. {
  472. //make sure we have a fill-out on our primitives, materials, etc
  473. //so we don't have to always force an update when it's not needed
  474. if (probe->mIsSkylight)
  475. {
  476. setupSkylightProbe(probe);
  477. }
  478. else
  479. {
  480. if (probe->mProbeShapeType == ProbeRenderInst::Sphere)
  481. {
  482. setupSphereReflectionProbe(probe);
  483. }
  484. else if(probe->mProbeShapeType == ProbeRenderInst::Box)
  485. {
  486. setupConvexReflectionProbe(probe);
  487. }
  488. }
  489. probe->mDirty = false;
  490. }
  491. }
  492. }
  493. ProbeManager::SkylightMaterialInfo* ProbeManager::getSkylightMaterial()
  494. {
  495. PROFILE_SCOPE(AdvancedLightBinManager_getSkylightMaterial);
  496. //ReflectProbeMaterialInfo *info = NULL;
  497. if (!mSkylightMaterial)
  498. // Now create the material info object.
  499. mSkylightMaterial = new SkylightMaterialInfo("SkyLightMaterial",
  500. getGFXVertexFormat<GFXVertexPC>());
  501. return mSkylightMaterial;
  502. }
  503. ProbeManager::ReflectProbeMaterialInfo* ProbeManager::getReflectProbeMaterial()
  504. {
  505. PROFILE_SCOPE(AdvancedLightBinManager_getReflectProbeMaterial);
  506. //ReflectProbeMaterialInfo *info = NULL;
  507. if (!mReflectProbeMaterial)
  508. // Now create the material info object.
  509. mReflectProbeMaterial = new ReflectProbeMaterialInfo("ReflectionProbeMaterial",
  510. getGFXVertexFormat<GFXVertexPC>());
  511. return mReflectProbeMaterial;
  512. }
  513. void ProbeManager::setupSkylightProbe(ProbeRenderInst *probeInfo)
  514. {
  515. probeInfo->vertBuffer = getSphereMesh(probeInfo->numPrims, probeInfo->primBuffer);
  516. if (!mSkylightMaterial)
  517. mSkylightMaterial = getSkylightMaterial();
  518. }
  519. void ProbeManager::setupSphereReflectionProbe(ProbeRenderInst *probeInfo)
  520. {
  521. probeInfo->vertBuffer = getSphereMesh(probeInfo->numPrims, probeInfo->primBuffer);
  522. if (!mReflectProbeMaterial)
  523. mReflectProbeMaterial = getReflectProbeMaterial();
  524. }
  525. void ProbeManager::setupConvexReflectionProbe(ProbeRenderInst *probeInfo)
  526. {
  527. static const Point3F cubePoints[8] =
  528. {
  529. Point3F(1, -1, -1), Point3F(1, -1, 1), Point3F(1, 1, -1), Point3F(1, 1, 1),
  530. Point3F(-1, -1, -1), Point3F(-1, 1, -1), Point3F(-1, -1, 1), Point3F(-1, 1, 1)
  531. };
  532. /*static const Point3F cubeNormals[6] =
  533. {
  534. Point3F(1, 0, 0), Point3F(-1, 0, 0), Point3F(0, 1, 0),
  535. Point3F(0, -1, 0), Point3F(0, 0, 1), Point3F(0, 0, -1)
  536. };*/
  537. /*static const Point2F cubeTexCoords[4] =
  538. {
  539. Point2F(0, 0), Point2F(0, -1),
  540. Point2F(1, 0), Point2F(1, -1)
  541. };*/
  542. static const U32 cubeFaces[36][3] =
  543. {
  544. { 3, 0, 3 },{ 0, 0, 0 },{ 1, 0, 1 },
  545. { 2, 0, 2 },{ 0, 0, 0 },{ 3, 0, 3 },
  546. { 7, 1, 1 },{ 4, 1, 2 },{ 5, 1, 0 },
  547. { 6, 1, 3 },{ 4, 1, 2 },{ 7, 1, 1 },
  548. { 3, 2, 1 },{ 5, 2, 2 },{ 2, 2, 0 },
  549. { 7, 2, 3 },{ 5, 2, 2 },{ 3, 2, 1 },
  550. { 1, 3, 3 },{ 4, 3, 0 },{ 6, 3, 1 },
  551. { 0, 3, 2 },{ 4, 3, 0 },{ 1, 3, 3 },
  552. { 3, 4, 3 },{ 6, 4, 0 },{ 7, 4, 1 },
  553. { 1, 4, 2 },{ 6, 4, 0 },{ 3, 4, 3 },
  554. { 2, 5, 1 },{ 4, 5, 2 },{ 0, 5, 0 },
  555. { 5, 5, 3 },{ 4, 5, 2 },{ 2, 5, 1 }
  556. };
  557. // Fill the vertex buffer
  558. GFXVertexPC *pVert = NULL;
  559. probeInfo->numVerts = 36;
  560. probeInfo->vertBuffer.set(GFX, 36, GFXBufferTypeStatic);
  561. pVert = probeInfo->vertBuffer.lock();
  562. Point3F halfSize = Point3F(probeInfo->mRadius, probeInfo->mRadius, probeInfo->mRadius);
  563. for (U32 i = 0; i < 36; i++)
  564. {
  565. const U32& vdx = cubeFaces[i][0];
  566. pVert[i].point = cubePoints[vdx] * halfSize;
  567. }
  568. probeInfo->vertBuffer.unlock();
  569. // Fill the primitive buffer
  570. U16 *pIdx = NULL;
  571. probeInfo->primBuffer.set(GFX, 36, 12, GFXBufferTypeStatic);
  572. probeInfo->primBuffer.lock(&pIdx);
  573. for (U16 i = 0; i < 36; i++)
  574. pIdx[i] = i;
  575. probeInfo->primBuffer.unlock();
  576. probeInfo->numPrims = 12;
  577. if (!mReflectProbeMaterial)
  578. mReflectProbeMaterial = getReflectProbeMaterial();
  579. //
  580. // mReflectProbeBin.push_back(pEntry);
  581. }
  582. GFXVertexBufferHandle<GFXVertexPC> ProbeManager::getSphereMesh(U32 &outNumPrimitives, GFXPrimitiveBufferHandle &outPrimitives)
  583. {
  584. static SphereMesh sSphereMesh;
  585. if (mSphereGeometry.isNull())
  586. {
  587. const SphereMesh::TriangleMesh * sphereMesh = sSphereMesh.getMesh(3);
  588. S32 numPoly = sphereMesh->numPoly;
  589. mSpherePrimitiveCount = 0;
  590. mSphereGeometry.set(GFX, numPoly * 3, GFXBufferTypeStatic);
  591. mSphereGeometry.lock();
  592. S32 vertexIndex = 0;
  593. for (S32 i = 0; i<numPoly; i++)
  594. {
  595. mSpherePrimitiveCount++;
  596. mSphereGeometry[vertexIndex].point = sphereMesh->poly[i].pnt[0];
  597. mSphereGeometry[vertexIndex].color = ColorI::WHITE;
  598. vertexIndex++;
  599. mSphereGeometry[vertexIndex].point = sphereMesh->poly[i].pnt[1];
  600. mSphereGeometry[vertexIndex].color = ColorI::WHITE;
  601. vertexIndex++;
  602. mSphereGeometry[vertexIndex].point = sphereMesh->poly[i].pnt[2];
  603. mSphereGeometry[vertexIndex].color = ColorI::WHITE;
  604. vertexIndex++;
  605. }
  606. mSphereGeometry.unlock();
  607. }
  608. outNumPrimitives = mSpherePrimitiveCount;
  609. outPrimitives = NULL; // For now
  610. return mSphereGeometry;
  611. }
  612. //
  613. //
  614. bool ReflectProbeMatInstance::init(const FeatureSet &features, const GFXVertexFormat *vertexFormat)
  615. {
  616. bool success = Parent::init(features, vertexFormat);
  617. // If the initialization failed don't continue.
  618. if (!success || !mProcessedMaterial || mProcessedMaterial->getNumPasses() == 0)
  619. return false;
  620. return true;
  621. }
  622. bool ReflectProbeMatInstance::setupPass(SceneRenderState *state, const SceneData &sgData)
  623. {
  624. // Go no further if the material failed to initialize properly.
  625. if (!mProcessedMaterial ||
  626. mProcessedMaterial->getNumPasses() == 0)
  627. return false;
  628. bool bRetVal = Parent::setupPass(state, sgData);;
  629. AssertFatal(mProcessedMaterial->getNumPasses() > 0, "No passes created! Ohnoes");
  630. const RenderPassData *rpd = mProcessedMaterial->getPass(0);
  631. AssertFatal(rpd, "No render pass data!");
  632. AssertFatal(rpd->mRenderStates[0], "No render state 0!");
  633. if (!mProjectionState)
  634. {
  635. GFXStateBlockDesc desc;
  636. desc.setZReadWrite(false);
  637. desc.zWriteEnable = false;
  638. desc.setCullMode(GFXCullNone);
  639. desc.setBlend(true, GFXBlendSrcAlpha, GFXBlendDestAlpha, GFXBlendOpMax);
  640. mProjectionState = GFX->createStateBlock(desc);
  641. }
  642. // Now override stateblock with our own
  643. GFX->setStateBlock(mProjectionState);
  644. return bRetVal;
  645. }
  646. //
  647. //
  648. ProbeManager::ReflectProbeMaterialInfo::ReflectProbeMaterialInfo(const String &matName,
  649. const GFXVertexFormat *vertexFormat)
  650. : matInstance(NULL),
  651. zNearFarInvNearFar(NULL),
  652. farPlane(NULL),
  653. vsFarPlane(NULL),
  654. negFarPlaneDotEye(NULL),
  655. probeWSPos(NULL),
  656. attenuation(NULL),
  657. radius(NULL),
  658. cubeMips(NULL)
  659. {
  660. Material *mat = MATMGR->getMaterialDefinitionByName(matName);
  661. if (!mat)
  662. return;
  663. matInstance = new ReflectProbeMatInstance(*mat);
  664. const Vector<GFXShaderMacro> &macros = Vector<GFXShaderMacro>();
  665. for (U32 i = 0; i < macros.size(); i++)
  666. matInstance->addShaderMacro(macros[i].name, macros[i].value);
  667. matInstance->init(MATMGR->getDefaultFeatures(), vertexFormat);
  668. attenuation = matInstance->getMaterialParameterHandle("$attenuation");
  669. radius = matInstance->getMaterialParameterHandle("$radius");
  670. probeLSPos = matInstance->getMaterialParameterHandle("$probeLSPos");
  671. probeWSPos = matInstance->getMaterialParameterHandle("$probeWSPos");
  672. farPlane = matInstance->getMaterialParameterHandle("$farPlane");
  673. vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane");
  674. negFarPlaneDotEye = matInstance->getMaterialParameterHandle("$negFarPlaneDotEye");
  675. zNearFarInvNearFar = matInstance->getMaterialParameterHandle("$zNearFarInvNearFar");
  676. useCubemap = matInstance->getMaterialParameterHandle("$useCubemap");
  677. cubemap = matInstance->getMaterialParameterHandle("$cubeMap");
  678. cubeMips = matInstance->getMaterialParameterHandle("$cubeMips");
  679. eyePosWorld = matInstance->getMaterialParameterHandle("$eyePosWorld");
  680. bbMin = matInstance->getMaterialParameterHandle("$bbMin");
  681. bbMax = matInstance->getMaterialParameterHandle("$bbMax");
  682. useSphereMode = matInstance->getMaterialParameterHandle("$useSphereMode");
  683. for (U32 i = 0; i < 9; i++)
  684. shTerms[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHTerms%d", i));
  685. for (U32 i = 0; i < 5; i++)
  686. shConsts[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHConsts%d", i));
  687. }
  688. ProbeManager::ReflectProbeMaterialInfo::~ReflectProbeMaterialInfo()
  689. {
  690. SAFE_DELETE(matInstance);
  691. }
  692. void ProbeManager::ReflectProbeMaterialInfo::setViewParameters(const F32 _zNear,
  693. const F32 _zFar,
  694. const Point3F &_eyePos,
  695. const PlaneF &_farPlane,
  696. const PlaneF &_vsFarPlane)
  697. {
  698. MaterialParameters *matParams = matInstance->getMaterialParameters();
  699. matParams->setSafe(farPlane, *((const Point4F *)&_farPlane));
  700. matParams->setSafe(vsFarPlane, *((const Point4F *)&_vsFarPlane));
  701. if (negFarPlaneDotEye->isValid())
  702. {
  703. // -dot( farPlane, eyePos )
  704. const F32 negFarPlaneDotEyeVal = -(mDot(*((const Point3F *)&_farPlane), _eyePos) + _farPlane.d);
  705. matParams->set(negFarPlaneDotEye, negFarPlaneDotEyeVal);
  706. }
  707. matParams->setSafe(zNearFarInvNearFar, Point4F(_zNear, _zFar, 1.0f / _zNear, 1.0f / _zFar));
  708. Point4F frPlane = *((const Point4F *)&_farPlane);
  709. Point4F vsFrPlane = *((const Point4F *)&_vsFarPlane);
  710. Point4F nearFarInvNearFar = Point4F(_zNear, _zFar, 1.0f / _zNear, 1.0f / _zFar);
  711. const F32 negFarPlaneDotEyeVal = -(mDot(*((const Point3F *)&_farPlane), _eyePos) + _farPlane.d);
  712. }
  713. void ProbeManager::ReflectProbeMaterialInfo::setProbeParameters(const ProbeRenderInst *probeInfo, const SceneRenderState* renderState, const MatrixF &worldViewOnly)
  714. {
  715. //Set up the params
  716. MaterialParameters *matParams = matInstance->getMaterialParameters();
  717. matParams->setSafe(radius, probeInfo->mRadius);
  718. Point3F probePos = probeInfo->getPosition() + probeInfo->mProbePosOffset;
  719. //worldViewOnly.mulP(probeInfo->getPosition(), &probePos);
  720. matParams->setSafe(probeWSPos, probePos);
  721. worldViewOnly.mulP(probeInfo->getPosition(), &probePos);
  722. matParams->setSafe(probeLSPos, probePos);
  723. // Get the attenuation falloff ratio and normalize it.
  724. Point3F attenRatio = Point3F(0.0f, 1.0f, 1.0f);
  725. F32 total = attenRatio.x + attenRatio.y + attenRatio.z;
  726. if (total > 0.0f)
  727. attenRatio /= total;
  728. F32 probeRadius = probeInfo->mRadius;
  729. Point2F attenParams((1.0f / probeRadius) * attenRatio.y,
  730. (1.0f / (probeRadius * probeRadius)) * attenRatio.z);
  731. matParams->setSafe(attenuation, attenParams);
  732. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  733. NamedTexTarget* matInfoTexTarget = NamedTexTarget::find("matinfo");
  734. NamedTexTarget* colorTexTarget = NamedTexTarget::find("color");
  735. if (!deferredTexTarget || !matInfoTexTarget || !colorTexTarget)
  736. {
  737. Con::errorf("ProbeManager::ReflectProbeMaterialInfo::setProbeParameters: Could not retrieve gbuffer");
  738. return;
  739. }
  740. //set textures
  741. GFX->setTexture(0, deferredTexTarget->getTexture());
  742. GFX->setTexture(1, matInfoTexTarget->getTexture());
  743. GFX->setTexture(2, colorTexTarget->getTexture());
  744. GFX->setCubeTexture(3, probeInfo->mCubemap->getPointer());
  745. GFX->setCubeTexture(4, probeInfo->mIrradianceCubemap->getPointer());
  746. GFX->setTexture(5, probeInfo->mBRDFTexture->getPointer());
  747. //set material params
  748. matParams->setSafe(cubeMips, mPow(probeInfo->mCubemap->getPointer()->getMipMapLevels(), 2.0f));
  749. matParams->setSafe(eyePosWorld, renderState->getCameraPosition());
  750. matParams->setSafe(bbMin, probeInfo->mBounds.minExtents);
  751. matParams->setSafe(bbMax, probeInfo->mBounds.maxExtents);
  752. matParams->setSafe(useSphereMode, probeInfo->mProbeShapeType == ProbeRenderInst::Sphere ? 1.0f : 0.0f);
  753. //SH Terms
  754. //static AlignedArray<Point3F> shTermsArray(9, sizeof(Point3F));
  755. //dMemset(shTermsArray.getBuffer(), 0, shTermsArray.getBufferSize());
  756. /*for (U32 i = 0; i < 9; i++)
  757. {
  758. matParams->setSafe(shTerms[i], probeInfo->mSHTerms[i]);
  759. }
  760. for (U32 i = 0; i < 5; i++)
  761. {
  762. matParams->setSafe(shConsts[i], probeInfo->mSHConstants[i]);
  763. }*/
  764. const MatrixF worldToObjectXfm = probeInfo->mTransform;
  765. MaterialParameterHandle *worldToObjMat = matInstance->getMaterialParameterHandle("$worldToObj");
  766. matParams->setSafe(worldToObjMat, worldToObjectXfm);
  767. }
  768. //
  769. //
  770. //
  771. ProbeManager::SkylightMaterialInfo::SkylightMaterialInfo(const String &matName,
  772. const GFXVertexFormat *vertexFormat)
  773. : ReflectProbeMaterialInfo(matName, vertexFormat)
  774. {
  775. Material *mat = MATMGR->getMaterialDefinitionByName(matName);
  776. if (!mat)
  777. return;
  778. matInstance = new SkylightMatInstance(*mat);
  779. const Vector<GFXShaderMacro> &macros = Vector<GFXShaderMacro>();
  780. for (U32 i = 0; i < macros.size(); i++)
  781. matInstance->addShaderMacro(macros[i].name, macros[i].value);
  782. matInstance->init(MATMGR->getDefaultFeatures(), vertexFormat);
  783. farPlane = matInstance->getMaterialParameterHandle("$farPlane");
  784. vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane");
  785. negFarPlaneDotEye = matInstance->getMaterialParameterHandle("$negFarPlaneDotEye");
  786. zNearFarInvNearFar = matInstance->getMaterialParameterHandle("$zNearFarInvNearFar");
  787. useCubemap = matInstance->getMaterialParameterHandle("$useCubemap");
  788. cubemap = matInstance->getMaterialParameterHandle("$cubeMap");
  789. eyePosWorld = matInstance->getMaterialParameterHandle("$eyePosWorld");
  790. /*for (U32 i = 0; i < 9; i++)
  791. shTerms[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHTerms%d", i));
  792. for (U32 i = 0; i < 5; i++)
  793. shConsts[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHConsts%d", i));*/
  794. }
  795. ProbeManager::SkylightMaterialInfo::~SkylightMaterialInfo()
  796. {
  797. SAFE_DELETE(matInstance);
  798. }
  799. /*bool ProbeManager::lightScene( const char* callback, const char* param )
  800. {
  801. BitSet32 flags = 0;
  802. if ( param )
  803. {
  804. if ( !dStricmp( param, "forceAlways" ) )
  805. flags.set( SceneLighting::ForceAlways );
  806. else if ( !dStricmp(param, "forceWritable" ) )
  807. flags.set( SceneLighting::ForceWritable );
  808. else if ( !dStricmp(param, "loadOnly" ) )
  809. flags.set( SceneLighting::LoadOnly );
  810. }
  811. // The SceneLighting object will delete itself
  812. // once the lighting process is complete.
  813. SceneLighting* sl = new SceneLighting( getSceneLightingInterface() );
  814. return sl->lightScene( callback, flags );
  815. }*/
  816. /*RenderDeferredMgr* ProbeManager::_findDeferredRenderBin()
  817. {
  818. RenderPassManager* rpm = getSceneManager()->getDefaultRenderPass();
  819. for( U32 i = 0; i < rpm->getManagerCount(); i++ )
  820. {
  821. RenderBinManager *bin = rpm->getManager( i );
  822. if( bin->getRenderInstType() == RenderDeferredMgr::RIT_Deferred )
  823. {
  824. return ( RenderDeferredMgr* ) bin;
  825. }
  826. }
  827. return NULL;
  828. }*/
  829. DefineEngineFunction( CreateProbeManager, bool, (),,
  830. "Finds and activates the named light manager.\n"
  831. "@return Returns true if the light manager is found and activated.\n"
  832. "@ingroup Lighting\n" )
  833. {
  834. ProbeManager* probeManager = new ProbeManager();
  835. if (probeManager != nullptr && gClientSceneGraph != nullptr)
  836. {
  837. probeManager->activate(gClientSceneGraph);
  838. return true;
  839. }
  840. return false;
  841. }
  842. DefineEngineFunction( resetProbeManager, void, (),,
  843. "@brief Deactivates and then activates the currently active light manager."
  844. "This causes most shaders to be regenerated and is often used when global "
  845. "rendering changes have occured.\n"
  846. "@ingroup Lighting\n" )
  847. {
  848. ProbeManager *pm = PROBEMGR;
  849. if ( !pm)
  850. return;
  851. /*SceneManager *sm = lm->getSceneManager();
  852. lm->deactivate();
  853. lm->activate( sm );*/
  854. }