probeManager.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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("SklyightMaterial",
  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. invViewMat(NULL),
  659. cubeMips(NULL)
  660. {
  661. Material *mat = MATMGR->getMaterialDefinitionByName(matName);
  662. if (!mat)
  663. return;
  664. matInstance = new ReflectProbeMatInstance(*mat);
  665. const Vector<GFXShaderMacro> &macros = Vector<GFXShaderMacro>();
  666. for (U32 i = 0; i < macros.size(); i++)
  667. matInstance->addShaderMacro(macros[i].name, macros[i].value);
  668. matInstance->init(MATMGR->getDefaultFeatures(), vertexFormat);
  669. attenuation = matInstance->getMaterialParameterHandle("$attenuation");
  670. radius = matInstance->getMaterialParameterHandle("$radius");
  671. probeLSPos = matInstance->getMaterialParameterHandle("$probeLSPos");
  672. probeWSPos = matInstance->getMaterialParameterHandle("$probeWSPos");
  673. farPlane = matInstance->getMaterialParameterHandle("$farPlane");
  674. vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane");
  675. negFarPlaneDotEye = matInstance->getMaterialParameterHandle("$negFarPlaneDotEye");
  676. zNearFarInvNearFar = matInstance->getMaterialParameterHandle("$zNearFarInvNearFar");
  677. invViewMat = matInstance->getMaterialParameterHandle("$invViewMat");
  678. useCubemap = matInstance->getMaterialParameterHandle("$useCubemap");
  679. cubemap = matInstance->getMaterialParameterHandle("$cubeMap");
  680. cubeMips = matInstance->getMaterialParameterHandle("$cubeMips");
  681. eyePosWorld = matInstance->getMaterialParameterHandle("$eyePosWorld");
  682. bbMin = matInstance->getMaterialParameterHandle("$bbMin");
  683. bbMax = matInstance->getMaterialParameterHandle("$bbMax");
  684. useSphereMode = matInstance->getMaterialParameterHandle("$useSphereMode");
  685. for (U32 i = 0; i < 9; i++)
  686. shTerms[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHTerms%d", i));
  687. for (U32 i = 0; i < 5; i++)
  688. shConsts[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHConsts%d", i));
  689. }
  690. ProbeManager::ReflectProbeMaterialInfo::~ReflectProbeMaterialInfo()
  691. {
  692. SAFE_DELETE(matInstance);
  693. }
  694. void ProbeManager::ReflectProbeMaterialInfo::setViewParameters(const F32 _zNear,
  695. const F32 _zFar,
  696. const Point3F &_eyePos,
  697. const PlaneF &_farPlane,
  698. const PlaneF &_vsFarPlane, const MatrixF &_inverseViewMatrix)
  699. {
  700. MaterialParameters *matParams = matInstance->getMaterialParameters();
  701. matParams->setSafe(farPlane, *((const Point4F *)&_farPlane));
  702. matParams->setSafe(vsFarPlane, *((const Point4F *)&_vsFarPlane));
  703. if (negFarPlaneDotEye->isValid())
  704. {
  705. // -dot( farPlane, eyePos )
  706. const F32 negFarPlaneDotEyeVal = -(mDot(*((const Point3F *)&_farPlane), _eyePos) + _farPlane.d);
  707. matParams->set(negFarPlaneDotEye, negFarPlaneDotEyeVal);
  708. }
  709. matParams->setSafe(zNearFarInvNearFar, Point4F(_zNear, _zFar, 1.0f / _zNear, 1.0f / _zFar));
  710. matParams->setSafe(invViewMat, _inverseViewMatrix);
  711. Point4F frPlane = *((const Point4F *)&_farPlane);
  712. Point4F vsFrPlane = *((const Point4F *)&_vsFarPlane);
  713. Point4F nearFarInvNearFar = Point4F(_zNear, _zFar, 1.0f / _zNear, 1.0f / _zFar);
  714. const F32 negFarPlaneDotEyeVal = -(mDot(*((const Point3F *)&_farPlane), _eyePos) + _farPlane.d);
  715. }
  716. void ProbeManager::ReflectProbeMaterialInfo::setProbeParameters(const ProbeRenderInst *probeInfo, const SceneRenderState* renderState, const MatrixF &worldViewOnly)
  717. {
  718. //Set up the params
  719. MaterialParameters *matParams = matInstance->getMaterialParameters();
  720. matParams->setSafe(radius, probeInfo->mRadius);
  721. Point3F probePos = probeInfo->getPosition() + probeInfo->mProbePosOffset;
  722. //worldViewOnly.mulP(probeInfo->getPosition(), &probePos);
  723. matParams->setSafe(probeWSPos, probePos);
  724. worldViewOnly.mulP(probeInfo->getPosition(), &probePos);
  725. matParams->setSafe(probeLSPos, probePos);
  726. // Get the attenuation falloff ratio and normalize it.
  727. Point3F attenRatio = Point3F(0.0f, 1.0f, 1.0f);
  728. F32 total = attenRatio.x + attenRatio.y + attenRatio.z;
  729. if (total > 0.0f)
  730. attenRatio /= total;
  731. F32 radius = probeInfo->mRadius;
  732. Point2F attenParams((1.0f / radius) * attenRatio.y,
  733. (1.0f / (radius * radius)) * attenRatio.z);
  734. matParams->setSafe(attenuation, attenParams);
  735. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  736. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  737. if (!deferredTexObject) return;
  738. GFX->setTexture(0, deferredTexObject);
  739. NamedTexTarget* matInfoTexTarget = NamedTexTarget::find("matinfo");
  740. GFXTextureObject *matInfoTexObject = matInfoTexTarget->getTexture();
  741. if (!matInfoTexObject) return;
  742. GFX->setTexture(1, matInfoTexObject);
  743. if (probeInfo->mCubemap && !probeInfo->mCubemap->isNull())
  744. {
  745. GFX->setCubeTexture(2, probeInfo->mCubemap->getPointer());
  746. }
  747. else
  748. {
  749. GFX->setCubeTexture(2, NULL);
  750. }
  751. if (probeInfo->mIrradianceCubemap && !probeInfo->mIrradianceCubemap->isNull())
  752. {
  753. GFX->setCubeTexture(3, probeInfo->mIrradianceCubemap->getPointer());
  754. }
  755. else
  756. {
  757. GFX->setCubeTexture(3, NULL);
  758. }
  759. if (probeInfo->mBRDFTexture && !probeInfo->mBRDFTexture->isNull())
  760. {
  761. GFX->setTexture(4, probeInfo->mBRDFTexture->getPointer());
  762. }
  763. else
  764. {
  765. GFX->setTexture(4, NULL);
  766. }
  767. if (probeInfo->mCubemap->isValid())
  768. matParams->setSafe(cubeMips, mPow(probeInfo->mCubemap->getPointer()->getMipMapLevels(), 2.0f));
  769. else
  770. matParams->setSafe(cubeMips, F32(0.0));
  771. matParams->setSafe(eyePosWorld, renderState->getCameraPosition());
  772. matParams->setSafe(bbMin, probeInfo->mBounds.minExtents);
  773. matParams->setSafe(bbMax, probeInfo->mBounds.maxExtents);
  774. matParams->setSafe(useSphereMode, probeInfo->mProbeShapeType == ProbeRenderInst::Sphere ? 1.0f : 0.0f);
  775. //SH Terms
  776. //static AlignedArray<Point3F> shTermsArray(9, sizeof(Point3F));
  777. //dMemset(shTermsArray.getBuffer(), 0, shTermsArray.getBufferSize());
  778. for (U32 i = 0; i < 9; i++)
  779. {
  780. matParams->setSafe(shTerms[i], probeInfo->mSHTerms[i]);
  781. }
  782. for (U32 i = 0; i < 5; i++)
  783. {
  784. matParams->setSafe(shConsts[i], probeInfo->mSHConstants[i]);
  785. }
  786. const MatrixF worldToObjectXfm = probeInfo->mTransform;
  787. MaterialParameterHandle *worldToObjMat = matInstance->getMaterialParameterHandle("$worldToObj");
  788. matParams->setSafe(worldToObjMat, worldToObjectXfm);
  789. }
  790. //
  791. //
  792. //
  793. ProbeManager::SkylightMaterialInfo::SkylightMaterialInfo(const String &matName,
  794. const GFXVertexFormat *vertexFormat)
  795. : ReflectProbeMaterialInfo(matName, vertexFormat)
  796. {
  797. Material *mat = MATMGR->getMaterialDefinitionByName(matName);
  798. if (!mat)
  799. return;
  800. matInstance = new SkylightMatInstance(*mat);
  801. const Vector<GFXShaderMacro> &macros = Vector<GFXShaderMacro>();
  802. for (U32 i = 0; i < macros.size(); i++)
  803. matInstance->addShaderMacro(macros[i].name, macros[i].value);
  804. matInstance->init(MATMGR->getDefaultFeatures(), vertexFormat);
  805. farPlane = matInstance->getMaterialParameterHandle("$farPlane");
  806. vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane");
  807. negFarPlaneDotEye = matInstance->getMaterialParameterHandle("$negFarPlaneDotEye");
  808. zNearFarInvNearFar = matInstance->getMaterialParameterHandle("$zNearFarInvNearFar");
  809. invViewMat = matInstance->getMaterialParameterHandle("$invViewMat");
  810. useCubemap = matInstance->getMaterialParameterHandle("$useCubemap");
  811. cubemap = matInstance->getMaterialParameterHandle("$cubeMap");
  812. eyePosWorld = matInstance->getMaterialParameterHandle("$eyePosWorld");
  813. for (U32 i = 0; i < 9; i++)
  814. shTerms[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHTerms%d", i));
  815. for (U32 i = 0; i < 5; i++)
  816. shConsts[i] = matInstance->getMaterialParameterHandle(String::ToString("$SHConsts%d", i));
  817. }
  818. ProbeManager::SkylightMaterialInfo::~SkylightMaterialInfo()
  819. {
  820. SAFE_DELETE(matInstance);
  821. }
  822. /*bool ProbeManager::lightScene( const char* callback, const char* param )
  823. {
  824. BitSet32 flags = 0;
  825. if ( param )
  826. {
  827. if ( !dStricmp( param, "forceAlways" ) )
  828. flags.set( SceneLighting::ForceAlways );
  829. else if ( !dStricmp(param, "forceWritable" ) )
  830. flags.set( SceneLighting::ForceWritable );
  831. else if ( !dStricmp(param, "loadOnly" ) )
  832. flags.set( SceneLighting::LoadOnly );
  833. }
  834. // The SceneLighting object will delete itself
  835. // once the lighting process is complete.
  836. SceneLighting* sl = new SceneLighting( getSceneLightingInterface() );
  837. return sl->lightScene( callback, flags );
  838. }*/
  839. /*RenderDeferredMgr* ProbeManager::_findDeferredRenderBin()
  840. {
  841. RenderPassManager* rpm = getSceneManager()->getDefaultRenderPass();
  842. for( U32 i = 0; i < rpm->getManagerCount(); i++ )
  843. {
  844. RenderBinManager *bin = rpm->getManager( i );
  845. if( bin->getRenderInstType() == RenderDeferredMgr::RIT_Deferred )
  846. {
  847. return ( RenderDeferredMgr* ) bin;
  848. }
  849. }
  850. return NULL;
  851. }*/
  852. DefineEngineFunction( CreateProbeManager, bool, (),,
  853. "Finds and activates the named light manager.\n"
  854. "@return Returns true if the light manager is found and activated.\n"
  855. "@ingroup Lighting\n" )
  856. {
  857. ProbeManager* probeManager = new ProbeManager();
  858. if (probeManager != nullptr && gClientSceneGraph != nullptr)
  859. {
  860. probeManager->activate(gClientSceneGraph);
  861. return true;
  862. }
  863. return false;
  864. }
  865. DefineEngineFunction( resetProbeManager, void, (),,
  866. "@brief Deactivates and then activates the currently active light manager."
  867. "This causes most shaders to be regenerated and is often used when global "
  868. "rendering changes have occured.\n"
  869. "@ingroup Lighting\n" )
  870. {
  871. ProbeManager *pm = PROBEMGR;
  872. if ( !pm)
  873. return;
  874. /*SceneManager *sm = lm->getSceneManager();
  875. lm->deactivate();
  876. lm->activate( sm );*/
  877. }