reflectionProbe.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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 "T3D/lighting/reflectionProbe.h"
  23. #include "math/mathIO.h"
  24. #include "scene/sceneRenderState.h"
  25. #include "console/consoleTypes.h"
  26. #include "core/stream/bitStream.h"
  27. #include "materials/baseMatInstance.h"
  28. #include "console/engineAPI.h"
  29. #include "gfx/gfxDrawUtil.h"
  30. #include "gfx/gfxDebugEvent.h"
  31. #include "gfx/gfxTransformSaver.h"
  32. #include "math/mathUtils.h"
  33. #include "gfx/bitmap/gBitmap.h"
  34. #include "core/stream/fileStream.h"
  35. #include "core/fileObject.h"
  36. #include "core/resourceManager.h"
  37. #include "console/simPersistID.h"
  38. #include "T3D/gameFunctions.h"
  39. #include "postFx/postEffect.h"
  40. #include "renderInstance/renderProbeMgr.h"
  41. #include "renderInstance/renderProbeMgr.h"
  42. #include "math/util/sphereMesh.h"
  43. #include "materials/materialManager.h"
  44. #include "math/util/matrixSet.h"
  45. #include "gfx/bitmap/cubemapSaver.h"
  46. #include "materials/materialFeatureTypes.h"
  47. #include "gfx/gfxTextureManager.h"
  48. #include "T3D/lighting/IBLUtilities.h"
  49. #include "scene/reflector.h"
  50. extern bool gEditingMission;
  51. extern ColorI gCanvasClearColor;
  52. bool ReflectionProbe::smRenderPreviewProbes = true;
  53. IMPLEMENT_CO_NETOBJECT_V1(ReflectionProbe);
  54. ConsoleDocClass(ReflectionProbe,
  55. "@brief An example scene object which renders a mesh.\n\n"
  56. "This class implements a basic SceneObject that can exist in the world at a "
  57. "3D position and render itself. There are several valid ways to render an "
  58. "object in Torque. This class implements the preferred rendering method which "
  59. "is to submit a MeshRenderInst along with a Material, vertex buffer, "
  60. "primitive buffer, and transform and allow the RenderMeshMgr handle the "
  61. "actual setup and rendering for you.\n\n"
  62. "See the C++ code for implementation details.\n\n"
  63. "@ingroup Examples\n");
  64. ImplementEnumType(ReflectProbeType,
  65. "Type of mesh data available in a shape.\n"
  66. "@ingroup gameObjects")
  67. { ProbeRenderInst::Sphere, "Sphere", "Sphere shaped" },
  68. { ProbeRenderInst::Box, "Box", "Box shape" }
  69. EndImplementEnumType;
  70. ImplementEnumType(ReflectionModeEnum,
  71. "Type of mesh data available in a shape.\n"
  72. "@ingroup gameObjects")
  73. { ReflectionProbe::NoReflection, "No Reflections", "This probe does not provide any local reflection data"},
  74. { ReflectionProbe::StaticCubemap, "Static Cubemap", "Uses a static CubemapData" },
  75. { ReflectionProbe::BakedCubemap, "Baked Cubemap", "Uses a cubemap baked from the probe's current position" },
  76. //{ ReflectionProbe::DynamicCubemap, "Dynamic Cubemap", "Uses a cubemap baked from the probe's current position, updated at a set rate" },
  77. EndImplementEnumType;
  78. //-----------------------------------------------------------------------------
  79. // Object setup and teardown
  80. //-----------------------------------------------------------------------------
  81. ReflectionProbe::ReflectionProbe() :
  82. cubeDescId(0),
  83. reflectorDesc(nullptr),
  84. mSphereVertCount(0),
  85. mSpherePrimitiveCount(0)
  86. {
  87. // Flag this object so that it will always
  88. // be sent across the network to clients
  89. mNetFlags.set(Ghostable | ScopeAlways);
  90. mTypeMask = LightObjectType | MarkerObjectType;
  91. mProbeShapeType = ProbeRenderInst::Box;
  92. mReflectionModeType = BakedCubemap;
  93. mEnabled = true;
  94. mBake = false;
  95. mDirty = false;
  96. mCubemapDirty = false;
  97. mRadius = 10;
  98. mObjScale = Point3F::One * 10;
  99. mProbeRefScale = Point3F::One*10;
  100. mUseHDRCaptures = true;
  101. mStaticCubemap = NULL;
  102. mProbeUniqueID = "";
  103. mEditorShapeInst = NULL;
  104. mEditorShape = NULL;
  105. mRefreshRateMS = 200;
  106. mDynamicLastBakeMS = 0;
  107. mMaxDrawDistance = 75;
  108. mResourcesCreated = false;
  109. mProbeInfo = nullptr;
  110. mPrefilterSize = 64;
  111. mPrefilterMipLevels = mLog2(F32(mPrefilterSize));
  112. mPrefilterMap = nullptr;
  113. mIrridianceMap = nullptr;
  114. mProbeRefOffset = Point3F::Zero;
  115. mEditPosOffset = false;
  116. mCaptureMask = REFLECTION_PROBE_CAPTURE_TYPEMASK;
  117. }
  118. ReflectionProbe::~ReflectionProbe()
  119. {
  120. if (mEditorShapeInst)
  121. SAFE_DELETE(mEditorShapeInst);
  122. if (mReflectionModeType == StaticCubemap && mStaticCubemap)
  123. mStaticCubemap->deleteObject();
  124. }
  125. //-----------------------------------------------------------------------------
  126. // Object Editing
  127. //-----------------------------------------------------------------------------
  128. void ReflectionProbe::initPersistFields()
  129. {
  130. addGroup("Rendering");
  131. addProtectedField("enabled", TypeBool, Offset(mEnabled, ReflectionProbe),
  132. &_setEnabled, &defaultProtectedGetFn, "Regenerate Voxel Grid");
  133. endGroup("Rendering");
  134. addGroup("Reflection");
  135. addProtectedField("radius", TypeF32, Offset(mRadius, ReflectionProbe), &_setRadius, &defaultProtectedGetFn,
  136. "The name of the material used to render the mesh.");
  137. addProtectedField("EditPosOffset", TypeBool, Offset(mEditPosOffset, ReflectionProbe),
  138. &_toggleEditPosOffset, &defaultProtectedGetFn, "Toggle Edit Pos Offset Mode", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  139. addField("refOffset", TypePoint3F, Offset(mProbeRefOffset, ReflectionProbe), "");
  140. addField("refScale", TypePoint3F, Offset(mProbeRefScale, ReflectionProbe), "");
  141. addProtectedField("ReflectionMode", TypeReflectionModeEnum, Offset(mReflectionModeType, ReflectionProbe), &_setReflectionMode, &defaultProtectedGetFn,
  142. "The type of mesh data to use for collision queries.");
  143. addField("StaticCubemap", TypeCubemapName, Offset(mCubemapName, ReflectionProbe), "Cubemap used instead of reflection texture if fullReflect is off.");
  144. addProtectedField("Bake", TypeBool, Offset(mBake, ReflectionProbe),
  145. &_doBake, &defaultProtectedGetFn, "Regenerate Voxel Grid", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  146. endGroup("Reflection");
  147. Con::addVariable("$Light::renderReflectionProbes", TypeBool, &RenderProbeMgr::smRenderReflectionProbes,
  148. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  149. "@note Only works for shadow mapped lights.\n\n"
  150. "@ingroup Lighting");
  151. Con::addVariable("$Light::renderPreviewProbes", TypeBool, &ReflectionProbe::smRenderPreviewProbes,
  152. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  153. "@note Only works for shadow mapped lights.\n\n"
  154. "@ingroup Lighting");
  155. // SceneObject already handles exposing the transform
  156. Parent::initPersistFields();
  157. }
  158. void ReflectionProbe::inspectPostApply()
  159. {
  160. Parent::inspectPostApply();
  161. mDirty = true;
  162. // Flag the network mask to send the updates
  163. // to the client object
  164. setMaskBits(-1);
  165. }
  166. bool ReflectionProbe::_setEnabled(void *object, const char *index, const char *data)
  167. {
  168. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  169. probe->mEnabled = dAtob(data);
  170. probe->setMaskBits(EnabledMask);
  171. return true;
  172. }
  173. bool ReflectionProbe::_doBake(void *object, const char *index, const char *data)
  174. {
  175. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  176. probe->bake();
  177. probe->setMaskBits(StaticDataMask);
  178. return false;
  179. }
  180. bool ReflectionProbe::_toggleEditPosOffset(void *object, const char *index, const char *data)
  181. {
  182. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  183. probe->mEditPosOffset = !probe->mEditPosOffset;
  184. return false;
  185. }
  186. bool ReflectionProbe::_setRadius(void *object, const char *index, const char *data)
  187. {
  188. ReflectionProbe* probe = reinterpret_cast<ReflectionProbe*>(object);
  189. if (probe->mProbeShapeType != ProbeRenderInst::Sphere)
  190. return false;
  191. probe->mObjScale = Point3F(probe->mRadius, probe->mRadius, probe->mRadius);
  192. probe->setMaskBits(StaticDataMask);
  193. return true;
  194. }
  195. bool ReflectionProbe::_setReflectionMode(void *object, const char *index, const char *data)
  196. {
  197. ReflectionProbe* probe = reinterpret_cast<ReflectionProbe*>(object);
  198. if (!dStrcmp(data,"Static Cubemap"))
  199. {
  200. probe->mReflectionModeType = StaticCubemap;
  201. }
  202. else if (!dStrcmp(data, "Baked Cubemap"))
  203. {
  204. //Clear our cubemap if we changed it to be baked, just for cleanliness
  205. probe->mReflectionModeType = BakedCubemap;
  206. probe->mCubemapName = "";
  207. }
  208. probe->setMaskBits(StaticDataMask);
  209. return true;
  210. }
  211. bool ReflectionProbe::onAdd()
  212. {
  213. if (!Parent::onAdd())
  214. return false;
  215. mEditPosOffset = false;
  216. mObjBox.minExtents.set(-0.5, -0.5, -0.5);
  217. mObjBox.maxExtents.set(0.5, 0.5, 0.5);
  218. // Skip our transform... it just dirties mask bits.
  219. Parent::setTransform(mObjToWorld);
  220. resetWorldBox();
  221. // Add this object to the scene
  222. addToScene();
  223. if (isServerObject())
  224. {
  225. if (!mPersistentId)
  226. mPersistentId = getOrCreatePersistentId();
  227. mProbeUniqueID = String::ToString(mPersistentId->getUUID().getHash());
  228. }
  229. // Refresh this object's material (if any)
  230. if (isClientObject())
  231. {
  232. if (!createClientResources())
  233. return false;
  234. updateProbeParams();
  235. }
  236. setMaskBits(-1);
  237. return true;
  238. }
  239. void ReflectionProbe::onRemove()
  240. {
  241. if (isClientObject())
  242. {
  243. PROBEMGR->unregisterProbe(mProbeInfo->mProbeIdx);
  244. mProbeInfo = nullptr;
  245. }
  246. // Remove this object from the scene
  247. removeFromScene();
  248. Parent::onRemove();
  249. }
  250. void ReflectionProbe::handleDeleteAction()
  251. {
  252. //we're deleting it?
  253. //Then we need to clear out the processed cubemaps(if we have them)
  254. if (mReflectionModeType != StaticCubemap)
  255. {
  256. String prefilPath = getPrefilterMapPath();
  257. if (Platform::isFile(prefilPath))
  258. {
  259. Platform::fileDelete(prefilPath);
  260. }
  261. String irrPath = getIrradianceMapPath();
  262. if (Platform::isFile(irrPath))
  263. {
  264. Platform::fileDelete(irrPath);
  265. }
  266. }
  267. Parent::handleDeleteAction();
  268. }
  269. void ReflectionProbe::setTransform(const MatrixF & mat)
  270. {
  271. // Let SceneObject handle all of the matrix manipulation
  272. if (!mEditPosOffset)
  273. {
  274. Parent::setTransform(mat);
  275. setMaskBits(TransformMask);
  276. }
  277. else
  278. {
  279. mProbeRefOffset = mat.getPosition();
  280. setMaskBits(StaticDataMask);
  281. }
  282. mDirty = true;
  283. }
  284. const MatrixF& ReflectionProbe::getTransform() const
  285. {
  286. if (!mEditPosOffset)
  287. return mObjToWorld;
  288. else
  289. {
  290. MatrixF transformMat = MatrixF::Identity;
  291. transformMat.setPosition(mProbeRefOffset);
  292. return transformMat;
  293. }
  294. }
  295. void ReflectionProbe::setScale(const VectorF &scale)
  296. {
  297. if (!mEditPosOffset)
  298. {
  299. Parent::setScale(scale);
  300. setMaskBits(TransformMask);
  301. }
  302. else
  303. {
  304. mProbeRefScale = scale;
  305. setMaskBits(StaticDataMask);
  306. }
  307. mDirty = true;
  308. }
  309. const VectorF& ReflectionProbe::getScale() const
  310. {
  311. if (!mEditPosOffset)
  312. return mObjScale;
  313. else
  314. return mProbeRefScale;
  315. }
  316. bool ReflectionProbe::writeField(StringTableEntry fieldname, const char *value)
  317. {
  318. if (fieldname == StringTable->insert("Bake") || fieldname == StringTable->insert("EditPosOffset"))
  319. return false;
  320. return Parent::writeField(fieldname, value);
  321. }
  322. U32 ReflectionProbe::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  323. {
  324. // Allow the Parent to get a crack at writing its info
  325. U32 retMask = Parent::packUpdate(conn, mask, stream);
  326. // Write our transform information
  327. if (stream->writeFlag(mask & TransformMask))
  328. {
  329. stream->writeFlag(mEditPosOffset);
  330. mathWrite(*stream, mObjToWorld);
  331. mathWrite(*stream, mObjScale);
  332. mathWrite(*stream, mProbeRefOffset);
  333. mathWrite(*stream, mProbeRefScale);
  334. }
  335. if (stream->writeFlag(mask & StaticDataMask))
  336. {
  337. stream->write((U32)mProbeShapeType);
  338. stream->write(mRadius);
  339. stream->write(mProbeUniqueID);
  340. stream->write((U32)mReflectionModeType);
  341. stream->write(mCubemapName);
  342. }
  343. if (stream->writeFlag(mask & EnabledMask))
  344. {
  345. stream->writeFlag(mEnabled);
  346. }
  347. return retMask;
  348. }
  349. void ReflectionProbe::unpackUpdate(NetConnection *conn, BitStream *stream)
  350. {
  351. // Let the Parent read any info it sent
  352. Parent::unpackUpdate(conn, stream);
  353. if (stream->readFlag()) // TransformMask
  354. {
  355. mEditPosOffset = stream->readFlag();
  356. mathRead(*stream, &mObjToWorld);
  357. mathRead(*stream, &mObjScale);
  358. Parent::setTransform(mObjToWorld);
  359. resetWorldBox();
  360. mathRead(*stream, &mProbeRefOffset);
  361. mathRead(*stream, &mProbeRefScale);
  362. mDirty = true;
  363. }
  364. if (stream->readFlag()) // StaticDataMask
  365. {
  366. U32 shapeType = ProbeRenderInst::Sphere;
  367. stream->read(&shapeType);
  368. mProbeShapeType = (ProbeRenderInst::ProbeShapeType)shapeType;
  369. stream->read(&mRadius);
  370. stream->read(&mProbeUniqueID);
  371. U32 oldReflectModeType = mReflectionModeType;
  372. U32 reflectModeType = BakedCubemap;
  373. stream->read(&reflectModeType);
  374. mReflectionModeType = (ReflectionModeType)reflectModeType;
  375. String oldCubemapName = mCubemapName;
  376. stream->read(&mCubemapName);
  377. if(oldReflectModeType != mReflectionModeType || oldCubemapName != mCubemapName)
  378. mCubemapDirty = true;
  379. mDirty = true;
  380. }
  381. if (stream->readFlag()) // EnabledMask
  382. {
  383. mEnabled = stream->readFlag();
  384. mDirty = true;
  385. }
  386. if (mDirty)
  387. {
  388. updateProbeParams();
  389. }
  390. }
  391. //-----------------------------------------------------------------------------
  392. // Object Rendering
  393. //-----------------------------------------------------------------------------
  394. void ReflectionProbe::updateProbeParams()
  395. {
  396. if (!mProbeInfo)
  397. return;
  398. mProbeInfo->mIsEnabled = mEnabled;
  399. mProbeInfo->mProbeShapeType = mProbeShapeType;
  400. if (mProbeShapeType == ProbeRenderInst::Sphere)
  401. mObjScale.set(mRadius, mRadius, mRadius);
  402. Box3F bounds;
  403. if (mProbeShapeType == ProbeRenderInst::Skylight)
  404. {
  405. mProbeInfo->mPosition = Point3F::Zero;
  406. mProbeInfo->mTransform = MatrixF::Identity;
  407. mProbeInfo->mIsSkylight = true;
  408. F32 visDist = gClientSceneGraph->getVisibleDistance();
  409. Box3F skylightBounds = Box3F(visDist * 2);
  410. skylightBounds.setCenter(Point3F::Zero);
  411. bounds = skylightBounds;
  412. setGlobalBounds();
  413. mProbeInfo->mScore = -1.0f;
  414. }
  415. else
  416. {
  417. MatrixF transform = getTransform();
  418. mProbeInfo->mPosition = getPosition();
  419. transform.scale(getScale());
  420. mProbeInfo->mTransform = transform.inverse();
  421. mProbeInfo->mIsSkylight = false;
  422. bounds = mWorldBox;
  423. mProbeInfo->mScore = mMaxDrawDistance;
  424. }
  425. // Skip our transform... it just dirties mask bits.
  426. Parent::setTransform(mObjToWorld);
  427. resetWorldBox();
  428. mProbeInfo->mBounds = bounds;
  429. mProbeInfo->mExtents = getScale();
  430. mProbeInfo->mRadius = mRadius;
  431. mProbeInfo->mProbeRefOffset = mProbeRefOffset;
  432. mProbeInfo->mProbeRefScale = mProbeRefScale;
  433. mProbeInfo->mDirty = true;
  434. if (mCubemapDirty)
  435. {
  436. if (mReflectionModeType == StaticCubemap)
  437. processStaticCubemap();
  438. else if (mReflectionModeType == BakedCubemap)
  439. processBakedCubemap();
  440. else
  441. processDynamicCubemap();
  442. }
  443. PROBEMGR->updateProbes();
  444. }
  445. void ReflectionProbe::processDynamicCubemap()
  446. {
  447. //if (!mProbeInfo)
  448. return;
  449. mEnabled = false;
  450. if (mReflectionModeType == DynamicCubemap && !mDynamicCubemap.isNull())
  451. {
  452. mProbeInfo->mPrefilterCubemap = mDynamicCubemap;
  453. //mCubeReflector.registerReflector(this, reflectorDesc); //need to decide how we wanna do the reflectorDesc. static name or a field
  454. }
  455. if (mEnabled)
  456. mProbeInfo->mIsEnabled = true;
  457. else
  458. mProbeInfo->mIsEnabled = false;
  459. mCubemapDirty = false;
  460. //Update the probe manager with our new texture!
  461. //if (!mProbeInfo->mIsSkylight && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  462. // PROBEMGR->updateProbeTexture(mProbeInfo->mProbeIdx);
  463. }
  464. void ReflectionProbe::processBakedCubemap()
  465. {
  466. if (!mProbeInfo)
  467. return;
  468. mProbeInfo->mIsEnabled = false;
  469. if ((mReflectionModeType != BakedCubemap) || mProbeUniqueID.isEmpty())
  470. return;
  471. String irrPath = getIrradianceMapPath();
  472. if (Platform::isFile(irrPath))
  473. {
  474. mIrridianceMap->setCubemapFile(FileName(irrPath));
  475. mIrridianceMap->updateFaces();
  476. }
  477. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  478. {
  479. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  480. return;
  481. }
  482. String prefilPath = getPrefilterMapPath();
  483. if (Platform::isFile(prefilPath))
  484. {
  485. mPrefilterMap->setCubemapFile(FileName(prefilPath));
  486. mPrefilterMap->updateFaces();
  487. }
  488. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  489. {
  490. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  491. return;
  492. }
  493. mProbeInfo->mPrefilterCubemap = mPrefilterMap->mCubemap;
  494. mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  495. if (mEnabled && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  496. {
  497. mProbeInfo->mIsEnabled = true;
  498. mCubemapDirty = false;
  499. //Update the probe manager with our new texture!
  500. PROBEMGR->updateProbeTexture(mProbeInfo);
  501. }
  502. }
  503. void ReflectionProbe::processStaticCubemap()
  504. {
  505. if (!mProbeInfo)
  506. return;
  507. mProbeInfo->mIsEnabled = false;
  508. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  509. char irradFileName[256];
  510. dSprintf(irradFileName, 256, "%s_Irradiance.dds", path.c_str(), mCubemapName.c_str());
  511. if (Platform::isFile(irradFileName))
  512. {
  513. mIrridianceMap->setCubemapFile(FileName(irradFileName));
  514. mIrridianceMap->updateFaces();
  515. }
  516. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  517. {
  518. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked irradiance map at %s", irradFileName);
  519. return;
  520. }
  521. char prefilterFileName[256];
  522. dSprintf(prefilterFileName, 256, "%s%s_Prefilter.dds", path.c_str(), mCubemapName.c_str());
  523. if (Platform::isFile(prefilterFileName))
  524. {
  525. mPrefilterMap->setCubemapFile(FileName(prefilterFileName));
  526. mPrefilterMap->updateFaces();
  527. }
  528. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  529. {
  530. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked prefilter map at %s", prefilterFileName);
  531. return;
  532. }
  533. if (!Platform::isFile(prefilterFileName) || !Platform::isFile(irradFileName))
  534. {
  535. //If we are missing either of the files, just re-run the bake
  536. Sim::findObject(mCubemapName, mStaticCubemap);
  537. if (!mStaticCubemap)
  538. {
  539. Con::errorf("ReflectionProbe::updateMaterial() - unable to find static cubemap file!");
  540. return;
  541. }
  542. if (mStaticCubemap->mCubemap == nullptr)
  543. {
  544. mStaticCubemap->createMap();
  545. mStaticCubemap->updateFaces();
  546. }
  547. if (mUseHDRCaptures)
  548. {
  549. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  550. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  551. }
  552. else
  553. {
  554. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  555. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  556. }
  557. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  558. IBLUtilities::GenerateIrradianceMap(renderTarget, mStaticCubemap->mCubemap, mIrridianceMap->mCubemap);
  559. IBLUtilities::GeneratePrefilterMap(renderTarget, mStaticCubemap->mCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  560. IBLUtilities::SaveCubeMap(irradFileName, mIrridianceMap->mCubemap);
  561. IBLUtilities::SaveCubeMap(prefilterFileName, mPrefilterMap->mCubemap);
  562. }
  563. if ((mIrridianceMap != nullptr || !mIrridianceMap->mCubemap.isNull()) && (mPrefilterMap != nullptr || !mPrefilterMap->mCubemap.isNull()))
  564. {
  565. mProbeInfo->mPrefilterCubemap = mPrefilterMap->mCubemap;
  566. mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  567. }
  568. if (mEnabled && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  569. {
  570. mProbeInfo->mIsEnabled = true;
  571. mCubemapDirty = false;
  572. //Update the probe manager with our new texture!
  573. PROBEMGR->updateProbeTexture(mProbeInfo);
  574. }
  575. }
  576. bool ReflectionProbe::createClientResources()
  577. {
  578. if (mProbeInfo == nullptr)
  579. {
  580. mProbeInfo = PROBEMGR->registerProbe();
  581. if (!mProbeInfo)
  582. return false;
  583. mProbeInfo->mIsEnabled = false;
  584. }
  585. //irridiance resources
  586. if (!mIrridianceMap)
  587. {
  588. mIrridianceMap = new CubemapData();
  589. mIrridianceMap->registerObject();
  590. mIrridianceMap->createMap();
  591. }
  592. //
  593. if (!mPrefilterMap)
  594. {
  595. mPrefilterMap = new CubemapData();
  596. mPrefilterMap->registerObject();
  597. mPrefilterMap->createMap();
  598. }
  599. mResourcesCreated = true;
  600. mCubemapDirty = true;
  601. return true;
  602. }
  603. String ReflectionProbe::getPrefilterMapPath()
  604. {
  605. if (mProbeUniqueID.isEmpty())
  606. {
  607. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  608. return "";
  609. }
  610. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  611. char fileName[256];
  612. dSprintf(fileName, 256, "%s%s_Prefilter.dds", path.c_str(), mProbeUniqueID.c_str());
  613. return fileName;
  614. }
  615. String ReflectionProbe::getIrradianceMapPath()
  616. {
  617. if (mProbeUniqueID.isEmpty())
  618. {
  619. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  620. return "";
  621. }
  622. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  623. char fileName[256];
  624. dSprintf(fileName, 256, "%s%s_Irradiance.dds", path.c_str(), mProbeUniqueID.c_str());
  625. return fileName;
  626. }
  627. void ReflectionProbe::bake()
  628. {
  629. if (mReflectionModeType != BakedCubemap)
  630. return;
  631. PROBEMGR->bakeProbe(this);
  632. setMaskBits(-1);
  633. }
  634. //-----------------------------------------------------------------------------
  635. //Rendering of editing/debug stuff
  636. //-----------------------------------------------------------------------------
  637. void ReflectionProbe::createGeometry()
  638. {
  639. // Clean up our previous shape
  640. if (mEditorShapeInst)
  641. SAFE_DELETE(mEditorShapeInst);
  642. mEditorShape = NULL;
  643. String shapeFile = "tools/resources/ReflectProbeSphere.dae";
  644. // Attempt to get the resource from the ResourceManager
  645. mEditorShape = ResourceManager::get().load(shapeFile);
  646. if (mEditorShape)
  647. {
  648. mEditorShapeInst = new TSShapeInstance(mEditorShape, isClientObject());
  649. }
  650. }
  651. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  652. {
  653. if (!mEnabled || !RenderProbeMgr::smRenderReflectionProbes)
  654. return;
  655. Point3F distVec = getRenderPosition() - state->getCameraPosition();
  656. F32 dist = distVec.len();
  657. //Culling distance. Can be adjusted for performance options considerations via the scalar
  658. if (dist > mMaxDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  659. {
  660. mProbeInfo->mScore = mMaxDrawDistance;
  661. return;
  662. }
  663. if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS))
  664. {
  665. bake();
  666. mDynamicLastBakeMS = Platform::getRealMilliseconds();
  667. }
  668. //Submit our probe to actually do the probe action
  669. // Get a handy pointer to our RenderPassmanager
  670. //RenderPassManager *renderPass = state->getRenderPass();
  671. //Update our score based on our radius, distance
  672. mProbeInfo->mScore = mProbeInfo->mRadius/mMax(dist,1.0f);
  673. Point3F vect = distVec;
  674. vect.normalizeSafe();
  675. mProbeInfo->mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  676. //Register
  677. //PROBEMGR->registerProbe(mProbeInfoIdx);
  678. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mPrefilterMap != nullptr)
  679. {
  680. if(!mEditorShapeInst)
  681. createGeometry();
  682. GFXTransformSaver saver;
  683. // Calculate the distance of this object from the camera
  684. Point3F cameraOffset;
  685. getRenderTransform().getColumn(3, &cameraOffset);
  686. cameraOffset -= state->getDiffuseCameraPosition();
  687. dist = cameraOffset.len();
  688. if (dist < 0.01f)
  689. dist = 0.01f;
  690. // Set up the LOD for the shape
  691. F32 invScale = (1.0f / getMax(getMax(mObjScale.x, mObjScale.y), mObjScale.z));
  692. mEditorShapeInst->setDetailFromDistance(state, dist * invScale);
  693. // Make sure we have a valid level of detail
  694. if (mEditorShapeInst->getCurrentDetail() < 0)
  695. return;
  696. BaseMatInstance* probePrevMat = mEditorShapeInst->getMaterialList()->getMaterialInst(0);
  697. setPreviewMatParameters(state, probePrevMat);
  698. // GFXTransformSaver is a handy helper class that restores
  699. // the current GFX matrices to their original values when
  700. // it goes out of scope at the end of the function
  701. // Set up our TS render state
  702. TSRenderState rdata;
  703. rdata.setSceneState(state);
  704. rdata.setFadeOverride(1.0f);
  705. if(mReflectionModeType != DynamicCubemap)
  706. rdata.setCubemap(mPrefilterMap->mCubemap);
  707. else
  708. rdata.setCubemap(mDynamicCubemap);
  709. // We might have some forward lit materials
  710. // so pass down a query to gather lights.
  711. LightQuery query;
  712. query.init(getWorldSphere());
  713. rdata.setLightQuery(&query);
  714. // Set the world matrix to the objects render transform
  715. MatrixF mat = getRenderTransform();
  716. GFX->setWorldMatrix(mat);
  717. // Animate the the shape
  718. mEditorShapeInst->animate();
  719. // Allow the shape to submit the RenderInst(s) for itself
  720. mEditorShapeInst->render(rdata);
  721. saver.restore();
  722. }
  723. // If the light is selected or light visualization
  724. // is enabled then register the callback.
  725. const bool isSelectedInEditor = (gEditingMission && isSelected());
  726. if (isSelectedInEditor)
  727. {
  728. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  729. ri->renderDelegate.bind(this, &ReflectionProbe::_onRenderViz);
  730. ri->type = RenderPassManager::RIT_Editor;
  731. state->getRenderPass()->addInst(ri);
  732. }
  733. }
  734. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  735. SceneRenderState *state,
  736. BaseMatInstance *overrideMat)
  737. {
  738. if (!RenderProbeMgr::smRenderReflectionProbes)
  739. return;
  740. GFXDrawUtil *draw = GFX->getDrawUtil();
  741. GFXStateBlockDesc desc;
  742. desc.setZReadWrite(true, false);
  743. desc.setCullMode(GFXCullNone);
  744. desc.setBlend(true);
  745. //desc.fillMode = GFXFillWireframe;
  746. // Base the sphere color on the light color.
  747. ColorI color = ColorI(255, 0, 255, 63);
  748. const MatrixF worldToObjectXfm = mObjToWorld;
  749. if (mProbeShapeType == ProbeRenderInst::Sphere)
  750. {
  751. draw->drawSphere(desc, mRadius, getPosition(), color);
  752. }
  753. else
  754. {
  755. Point3F tscl = worldToObjectXfm.getScale();
  756. Box3F projCube(-mObjScale/2, mObjScale / 2);
  757. projCube.setCenter(getPosition());
  758. draw->drawCube(desc, projCube, color, &worldToObjectXfm);
  759. }
  760. Point3F renderPos = getRenderTransform().getPosition();
  761. Box3F refCube = Box3F(-mProbeRefScale / 2, mProbeRefScale / 2);
  762. refCube.setCenter(renderPos + mProbeRefOffset);
  763. color = ColorI(0, 255, 255, 63);
  764. draw->drawCube(desc, refCube, color, &worldToObjectXfm);
  765. }
  766. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  767. {
  768. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  769. return;
  770. //Set up the params
  771. MaterialParameters *matParams = mat->getMaterialParameters();
  772. //Get the deferred render target
  773. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  774. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  775. if (!deferredTexObject)
  776. return;
  777. GFX->setTexture(0, deferredTexObject);
  778. //Set the cubemap
  779. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  780. //Set the invViewMat
  781. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  782. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  783. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  784. matParams->setSafe(invViewMat, worldToCameraXfm);
  785. }
  786. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  787. "A utility method for forcing a network update.\n")
  788. {
  789. object->inspectPostApply();
  790. }
  791. DefineEngineMethod(ReflectionProbe, Bake, void, (), ,
  792. "@brief returns true if control object is inside the fog\n\n.")
  793. {
  794. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  795. if (clientProbe)
  796. {
  797. clientProbe->bake();
  798. }
  799. }