reflectionProbe.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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. bool liveUpdates = Con::getBoolVariable("$Probes::liveUpdates", false);
  163. if (liveUpdates)
  164. {
  165. bake();
  166. }
  167. // Flag the network mask to send the updates
  168. // to the client object
  169. setMaskBits(-1);
  170. }
  171. bool ReflectionProbe::_setEnabled(void *object, const char *index, const char *data)
  172. {
  173. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  174. probe->mEnabled = dAtob(data);
  175. probe->setMaskBits(EnabledMask);
  176. return true;
  177. }
  178. bool ReflectionProbe::_doBake(void *object, const char *index, const char *data)
  179. {
  180. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  181. probe->bake();
  182. probe->setMaskBits(StaticDataMask);
  183. return false;
  184. }
  185. bool ReflectionProbe::_toggleEditPosOffset(void *object, const char *index, const char *data)
  186. {
  187. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  188. probe->mEditPosOffset = !probe->mEditPosOffset;
  189. return false;
  190. }
  191. bool ReflectionProbe::_setRadius(void *object, const char *index, const char *data)
  192. {
  193. ReflectionProbe* probe = reinterpret_cast<ReflectionProbe*>(object);
  194. if (probe->mProbeShapeType != ProbeRenderInst::Sphere)
  195. return false;
  196. probe->mObjScale = Point3F(probe->mRadius, probe->mRadius, probe->mRadius);
  197. probe->setMaskBits(StaticDataMask);
  198. return true;
  199. }
  200. bool ReflectionProbe::_setReflectionMode(void *object, const char *index, const char *data)
  201. {
  202. ReflectionProbe* probe = reinterpret_cast<ReflectionProbe*>(object);
  203. if (!dStrcmp(data,"Static Cubemap"))
  204. {
  205. probe->mReflectionModeType = StaticCubemap;
  206. }
  207. else if (!dStrcmp(data, "Baked Cubemap"))
  208. {
  209. //Clear our cubemap if we changed it to be baked, just for cleanliness
  210. probe->mReflectionModeType = BakedCubemap;
  211. probe->mCubemapName = "";
  212. }
  213. probe->setMaskBits(StaticDataMask);
  214. return true;
  215. }
  216. bool ReflectionProbe::onAdd()
  217. {
  218. if (!Parent::onAdd())
  219. return false;
  220. mEditPosOffset = false;
  221. mObjBox.minExtents.set(-0.5, -0.5, -0.5);
  222. mObjBox.maxExtents.set(0.5, 0.5, 0.5);
  223. // Skip our transform... it just dirties mask bits.
  224. Parent::setTransform(mObjToWorld);
  225. resetWorldBox();
  226. // Add this object to the scene
  227. addToScene();
  228. if (isServerObject())
  229. {
  230. if (!mPersistentId)
  231. mPersistentId = getOrCreatePersistentId();
  232. mProbeUniqueID = String::ToString(mPersistentId->getUUID().getHash());
  233. }
  234. // Refresh this object's material (if any)
  235. if (isClientObject())
  236. {
  237. if (!createClientResources())
  238. return false;
  239. updateProbeParams();
  240. }
  241. setMaskBits(-1);
  242. return true;
  243. }
  244. void ReflectionProbe::onRemove()
  245. {
  246. if (isClientObject())
  247. {
  248. PROBEMGR->unregisterProbe(mProbeInfo->mProbeIdx);
  249. mProbeInfo = nullptr;
  250. }
  251. // Remove this object from the scene
  252. removeFromScene();
  253. Parent::onRemove();
  254. }
  255. void ReflectionProbe::handleDeleteAction()
  256. {
  257. //we're deleting it?
  258. //Then we need to clear out the processed cubemaps(if we have them)
  259. if (mReflectionModeType != StaticCubemap)
  260. {
  261. String prefilPath = getPrefilterMapPath();
  262. if (Platform::isFile(prefilPath))
  263. {
  264. Platform::fileDelete(prefilPath);
  265. }
  266. String irrPath = getIrradianceMapPath();
  267. if (Platform::isFile(irrPath))
  268. {
  269. Platform::fileDelete(irrPath);
  270. }
  271. }
  272. Parent::handleDeleteAction();
  273. }
  274. void ReflectionProbe::setTransform(const MatrixF & mat)
  275. {
  276. // Let SceneObject handle all of the matrix manipulation
  277. if (!mEditPosOffset)
  278. {
  279. Parent::setTransform(mat);
  280. setMaskBits(TransformMask);
  281. }
  282. else
  283. {
  284. mProbeRefOffset = mat.getPosition();
  285. setMaskBits(StaticDataMask);
  286. }
  287. mDirty = true;
  288. }
  289. const MatrixF& ReflectionProbe::getTransform() const
  290. {
  291. if (!mEditPosOffset)
  292. return mObjToWorld;
  293. else
  294. {
  295. MatrixF transformMat = MatrixF::Identity;
  296. transformMat.setPosition(mProbeRefOffset);
  297. return transformMat;
  298. }
  299. }
  300. void ReflectionProbe::setScale(const VectorF &scale)
  301. {
  302. if (!mEditPosOffset)
  303. {
  304. Parent::setScale(scale);
  305. setMaskBits(TransformMask);
  306. }
  307. else
  308. {
  309. mProbeRefScale = scale;
  310. setMaskBits(StaticDataMask);
  311. }
  312. mDirty = true;
  313. }
  314. const VectorF& ReflectionProbe::getScale() const
  315. {
  316. if (!mEditPosOffset)
  317. return mObjScale;
  318. else
  319. return mProbeRefScale;
  320. }
  321. bool ReflectionProbe::writeField(StringTableEntry fieldname, const char *value)
  322. {
  323. if (fieldname == StringTable->insert("Bake") || fieldname == StringTable->insert("EditPosOffset"))
  324. return false;
  325. return Parent::writeField(fieldname, value);
  326. }
  327. U32 ReflectionProbe::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  328. {
  329. // Allow the Parent to get a crack at writing its info
  330. U32 retMask = Parent::packUpdate(conn, mask, stream);
  331. // Write our transform information
  332. if (stream->writeFlag(mask & TransformMask))
  333. {
  334. stream->writeFlag(mEditPosOffset);
  335. mathWrite(*stream, mObjToWorld);
  336. mathWrite(*stream, mObjScale);
  337. mathWrite(*stream, mProbeRefOffset);
  338. mathWrite(*stream, mProbeRefScale);
  339. }
  340. if (stream->writeFlag(mask & StaticDataMask))
  341. {
  342. stream->write((U32)mProbeShapeType);
  343. stream->write(mRadius);
  344. stream->write(mProbeUniqueID);
  345. stream->write((U32)mReflectionModeType);
  346. stream->write(mCubemapName);
  347. }
  348. if (stream->writeFlag(mask & EnabledMask))
  349. {
  350. stream->writeFlag(mEnabled);
  351. }
  352. return retMask;
  353. }
  354. void ReflectionProbe::unpackUpdate(NetConnection *conn, BitStream *stream)
  355. {
  356. // Let the Parent read any info it sent
  357. Parent::unpackUpdate(conn, stream);
  358. if (stream->readFlag()) // TransformMask
  359. {
  360. mEditPosOffset = stream->readFlag();
  361. mathRead(*stream, &mObjToWorld);
  362. mathRead(*stream, &mObjScale);
  363. Parent::setTransform(mObjToWorld);
  364. resetWorldBox();
  365. mathRead(*stream, &mProbeRefOffset);
  366. mathRead(*stream, &mProbeRefScale);
  367. mDirty = true;
  368. }
  369. if (stream->readFlag()) // StaticDataMask
  370. {
  371. U32 shapeType = ProbeRenderInst::Sphere;
  372. stream->read(&shapeType);
  373. mProbeShapeType = (ProbeRenderInst::ProbeShapeType)shapeType;
  374. stream->read(&mRadius);
  375. stream->read(&mProbeUniqueID);
  376. U32 oldReflectModeType = mReflectionModeType;
  377. U32 reflectModeType = BakedCubemap;
  378. stream->read(&reflectModeType);
  379. mReflectionModeType = (ReflectionModeType)reflectModeType;
  380. String oldCubemapName = mCubemapName;
  381. stream->read(&mCubemapName);
  382. if(oldReflectModeType != mReflectionModeType || oldCubemapName != mCubemapName)
  383. mCubemapDirty = true;
  384. mDirty = true;
  385. }
  386. if (stream->readFlag()) // EnabledMask
  387. {
  388. mEnabled = stream->readFlag();
  389. mDirty = true;
  390. }
  391. if (mDirty)
  392. {
  393. updateProbeParams();
  394. }
  395. }
  396. //-----------------------------------------------------------------------------
  397. // Object Rendering
  398. //-----------------------------------------------------------------------------
  399. void ReflectionProbe::updateProbeParams()
  400. {
  401. if (!mProbeInfo)
  402. return;
  403. mProbeInfo->mIsEnabled = mEnabled;
  404. mProbeInfo->mProbeShapeType = mProbeShapeType;
  405. if (mProbeShapeType == ProbeRenderInst::Sphere)
  406. mObjScale.set(mRadius, mRadius, mRadius);
  407. Box3F bounds;
  408. if (mProbeShapeType == ProbeRenderInst::Skylight)
  409. {
  410. mProbeInfo->mPosition = Point3F::Zero;
  411. mProbeInfo->mTransform = MatrixF::Identity;
  412. mProbeInfo->mIsSkylight = true;
  413. F32 visDist = gClientSceneGraph->getVisibleDistance();
  414. Box3F skylightBounds = Box3F(visDist * 2);
  415. skylightBounds.setCenter(Point3F::Zero);
  416. bounds = skylightBounds;
  417. setGlobalBounds();
  418. mProbeInfo->mScore = -1.0f;
  419. }
  420. else
  421. {
  422. MatrixF transform = getTransform();
  423. mProbeInfo->mPosition = getPosition();
  424. transform.scale(getScale());
  425. mProbeInfo->mTransform = transform.inverse();
  426. mProbeInfo->mIsSkylight = false;
  427. bounds = mWorldBox;
  428. mProbeInfo->mScore = mMaxDrawDistance;
  429. }
  430. // Skip our transform... it just dirties mask bits.
  431. Parent::setTransform(mObjToWorld);
  432. resetWorldBox();
  433. mProbeInfo->mBounds = bounds;
  434. mProbeInfo->mExtents = getScale();
  435. mProbeInfo->mRadius = mRadius;
  436. mProbeInfo->mProbeRefOffset = mProbeRefOffset;
  437. mProbeInfo->mProbeRefScale = mProbeRefScale;
  438. mProbeInfo->mDirty = true;
  439. if (mCubemapDirty)
  440. {
  441. if (mReflectionModeType == StaticCubemap)
  442. processStaticCubemap();
  443. else if (mReflectionModeType == BakedCubemap)
  444. processBakedCubemap();
  445. else
  446. processDynamicCubemap();
  447. }
  448. PROBEMGR->updateProbes();
  449. }
  450. void ReflectionProbe::processDynamicCubemap()
  451. {
  452. //if (!mProbeInfo)
  453. return;
  454. mEnabled = false;
  455. if (mReflectionModeType == DynamicCubemap && !mDynamicCubemap.isNull())
  456. {
  457. mProbeInfo->mPrefilterCubemap = mDynamicCubemap;
  458. //mCubeReflector.registerReflector(this, reflectorDesc); //need to decide how we wanna do the reflectorDesc. static name or a field
  459. }
  460. if (mEnabled)
  461. mProbeInfo->mIsEnabled = true;
  462. else
  463. mProbeInfo->mIsEnabled = false;
  464. mCubemapDirty = false;
  465. //Update the probe manager with our new texture!
  466. //if (!mProbeInfo->mIsSkylight && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  467. // PROBEMGR->updateProbeTexture(mProbeInfo->mProbeIdx);
  468. }
  469. void ReflectionProbe::processBakedCubemap()
  470. {
  471. if (!mProbeInfo)
  472. return;
  473. mProbeInfo->mIsEnabled = false;
  474. if ((mReflectionModeType != BakedCubemap) || mProbeUniqueID.isEmpty())
  475. return;
  476. String irrPath = getIrradianceMapPath();
  477. if (Platform::isFile(irrPath))
  478. {
  479. mIrridianceMap->setCubemapFile(FileName(irrPath));
  480. mIrridianceMap->updateFaces();
  481. }
  482. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  483. {
  484. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  485. return;
  486. }
  487. String prefilPath = getPrefilterMapPath();
  488. if (Platform::isFile(prefilPath))
  489. {
  490. mPrefilterMap->setCubemapFile(FileName(prefilPath));
  491. mPrefilterMap->updateFaces();
  492. }
  493. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  494. {
  495. Con::errorf("ReflectionProbe::processDynamicCubemap() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  496. return;
  497. }
  498. mProbeInfo->mPrefilterCubemap = mPrefilterMap->mCubemap;
  499. mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  500. if (mEnabled && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  501. {
  502. mProbeInfo->mIsEnabled = true;
  503. mCubemapDirty = false;
  504. //Update the probe manager with our new texture!
  505. PROBEMGR->updateProbeTexture(mProbeInfo);
  506. }
  507. }
  508. void ReflectionProbe::processStaticCubemap()
  509. {
  510. if (!mProbeInfo)
  511. return;
  512. mProbeInfo->mIsEnabled = false;
  513. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  514. char irradFileName[256];
  515. dSprintf(irradFileName, 256, "%s_Irradiance.dds", path.c_str(), mCubemapName.c_str());
  516. if (Platform::isFile(irradFileName))
  517. {
  518. mIrridianceMap->setCubemapFile(FileName(irradFileName));
  519. mIrridianceMap->updateFaces();
  520. }
  521. if (mIrridianceMap == nullptr || mIrridianceMap->mCubemap.isNull())
  522. {
  523. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked irradiance map at %s", irradFileName);
  524. return;
  525. }
  526. char prefilterFileName[256];
  527. dSprintf(prefilterFileName, 256, "%s%s_Prefilter.dds", path.c_str(), mCubemapName.c_str());
  528. if (Platform::isFile(prefilterFileName))
  529. {
  530. mPrefilterMap->setCubemapFile(FileName(prefilterFileName));
  531. mPrefilterMap->updateFaces();
  532. }
  533. if (mPrefilterMap == nullptr || mPrefilterMap->mCubemap.isNull())
  534. {
  535. Con::errorf("ReflectionProbe::processStaticCubemap() - Unable to load baked prefilter map at %s", prefilterFileName);
  536. return;
  537. }
  538. if (!Platform::isFile(prefilterFileName) || !Platform::isFile(irradFileName))
  539. {
  540. //If we are missing either of the files, just re-run the bake
  541. Sim::findObject(mCubemapName, mStaticCubemap);
  542. if (!mStaticCubemap)
  543. {
  544. Con::errorf("ReflectionProbe::updateMaterial() - unable to find static cubemap file!");
  545. return;
  546. }
  547. if (mStaticCubemap->mCubemap == nullptr)
  548. {
  549. mStaticCubemap->createMap();
  550. mStaticCubemap->updateFaces();
  551. }
  552. if (mUseHDRCaptures)
  553. {
  554. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  555. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  556. }
  557. else
  558. {
  559. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  560. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  561. }
  562. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  563. IBLUtilities::GenerateIrradianceMap(renderTarget, mStaticCubemap->mCubemap, mIrridianceMap->mCubemap);
  564. IBLUtilities::GeneratePrefilterMap(renderTarget, mStaticCubemap->mCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  565. IBLUtilities::SaveCubeMap(irradFileName, mIrridianceMap->mCubemap);
  566. IBLUtilities::SaveCubeMap(prefilterFileName, mPrefilterMap->mCubemap);
  567. }
  568. if ((mIrridianceMap != nullptr || !mIrridianceMap->mCubemap.isNull()) && (mPrefilterMap != nullptr || !mPrefilterMap->mCubemap.isNull()))
  569. {
  570. mProbeInfo->mPrefilterCubemap = mPrefilterMap->mCubemap;
  571. mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  572. }
  573. if (mEnabled && mProbeInfo->mPrefilterCubemap->isInitialized() && mProbeInfo->mIrradianceCubemap->isInitialized())
  574. {
  575. mProbeInfo->mIsEnabled = true;
  576. mCubemapDirty = false;
  577. //Update the probe manager with our new texture!
  578. PROBEMGR->updateProbeTexture(mProbeInfo);
  579. }
  580. }
  581. bool ReflectionProbe::createClientResources()
  582. {
  583. if (mProbeInfo == nullptr)
  584. {
  585. mProbeInfo = PROBEMGR->registerProbe();
  586. if (!mProbeInfo)
  587. return false;
  588. mProbeInfo->mIsEnabled = false;
  589. }
  590. //irridiance resources
  591. if (!mIrridianceMap)
  592. {
  593. mIrridianceMap = new CubemapData();
  594. mIrridianceMap->registerObject();
  595. mIrridianceMap->createMap();
  596. }
  597. //
  598. if (!mPrefilterMap)
  599. {
  600. mPrefilterMap = new CubemapData();
  601. mPrefilterMap->registerObject();
  602. mPrefilterMap->createMap();
  603. }
  604. mResourcesCreated = true;
  605. mCubemapDirty = true;
  606. return true;
  607. }
  608. String ReflectionProbe::getPrefilterMapPath()
  609. {
  610. if (mProbeUniqueID.isEmpty())
  611. {
  612. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  613. return "";
  614. }
  615. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  616. char fileName[256];
  617. dSprintf(fileName, 256, "%s%s_Prefilter.dds", path.c_str(), mProbeUniqueID.c_str());
  618. return fileName;
  619. }
  620. String ReflectionProbe::getIrradianceMapPath()
  621. {
  622. if (mProbeUniqueID.isEmpty())
  623. {
  624. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  625. return "";
  626. }
  627. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  628. char fileName[256];
  629. dSprintf(fileName, 256, "%s%s_Irradiance.dds", path.c_str(), mProbeUniqueID.c_str());
  630. return fileName;
  631. }
  632. void ReflectionProbe::bake()
  633. {
  634. if (mReflectionModeType != BakedCubemap)
  635. return;
  636. PROBEMGR->bakeProbe(this);
  637. setMaskBits(-1);
  638. }
  639. //-----------------------------------------------------------------------------
  640. //Rendering of editing/debug stuff
  641. //-----------------------------------------------------------------------------
  642. void ReflectionProbe::createGeometry()
  643. {
  644. // Clean up our previous shape
  645. if (mEditorShapeInst)
  646. SAFE_DELETE(mEditorShapeInst);
  647. mEditorShape = NULL;
  648. String shapeFile = "tools/resources/ReflectProbeSphere.dae";
  649. // Attempt to get the resource from the ResourceManager
  650. mEditorShape = ResourceManager::get().load(shapeFile);
  651. if (mEditorShape)
  652. {
  653. mEditorShapeInst = new TSShapeInstance(mEditorShape, isClientObject());
  654. }
  655. }
  656. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  657. {
  658. if (!mEnabled || !RenderProbeMgr::smRenderReflectionProbes)
  659. return;
  660. Point3F distVec = getRenderPosition() - state->getCameraPosition();
  661. F32 dist = distVec.len();
  662. //Culling distance. Can be adjusted for performance options considerations via the scalar
  663. if (dist > mMaxDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  664. {
  665. mProbeInfo->mScore = mMaxDrawDistance;
  666. return;
  667. }
  668. if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS))
  669. {
  670. bake();
  671. mDynamicLastBakeMS = Platform::getRealMilliseconds();
  672. }
  673. //Submit our probe to actually do the probe action
  674. // Get a handy pointer to our RenderPassmanager
  675. //RenderPassManager *renderPass = state->getRenderPass();
  676. //Update our score based on our radius, distance
  677. mProbeInfo->mScore = mProbeInfo->mRadius/mMax(dist,1.0f);
  678. Point3F vect = distVec;
  679. vect.normalizeSafe();
  680. mProbeInfo->mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  681. //Register
  682. //PROBEMGR->registerProbe(mProbeInfoIdx);
  683. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mPrefilterMap != nullptr)
  684. {
  685. if(!mEditorShapeInst)
  686. createGeometry();
  687. GFXTransformSaver saver;
  688. // Calculate the distance of this object from the camera
  689. Point3F cameraOffset;
  690. getRenderTransform().getColumn(3, &cameraOffset);
  691. cameraOffset -= state->getDiffuseCameraPosition();
  692. dist = cameraOffset.len();
  693. if (dist < 0.01f)
  694. dist = 0.01f;
  695. // Set up the LOD for the shape
  696. F32 invScale = (1.0f / getMax(getMax(mObjScale.x, mObjScale.y), mObjScale.z));
  697. mEditorShapeInst->setDetailFromDistance(state, dist * invScale);
  698. // Make sure we have a valid level of detail
  699. if (mEditorShapeInst->getCurrentDetail() < 0)
  700. return;
  701. BaseMatInstance* probePrevMat = mEditorShapeInst->getMaterialList()->getMaterialInst(0);
  702. setPreviewMatParameters(state, probePrevMat);
  703. // GFXTransformSaver is a handy helper class that restores
  704. // the current GFX matrices to their original values when
  705. // it goes out of scope at the end of the function
  706. // Set up our TS render state
  707. TSRenderState rdata;
  708. rdata.setSceneState(state);
  709. rdata.setFadeOverride(1.0f);
  710. if(mReflectionModeType != DynamicCubemap)
  711. rdata.setCubemap(mPrefilterMap->mCubemap);
  712. else
  713. rdata.setCubemap(mDynamicCubemap);
  714. // We might have some forward lit materials
  715. // so pass down a query to gather lights.
  716. LightQuery query;
  717. query.init(getWorldSphere());
  718. rdata.setLightQuery(&query);
  719. // Set the world matrix to the objects render transform
  720. MatrixF mat = getRenderTransform();
  721. GFX->setWorldMatrix(mat);
  722. // Animate the the shape
  723. mEditorShapeInst->animate();
  724. // Allow the shape to submit the RenderInst(s) for itself
  725. mEditorShapeInst->render(rdata);
  726. saver.restore();
  727. }
  728. // If the light is selected or light visualization
  729. // is enabled then register the callback.
  730. const bool isSelectedInEditor = (gEditingMission && isSelected());
  731. if (isSelectedInEditor)
  732. {
  733. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  734. ri->renderDelegate.bind(this, &ReflectionProbe::_onRenderViz);
  735. ri->type = RenderPassManager::RIT_Editor;
  736. state->getRenderPass()->addInst(ri);
  737. }
  738. }
  739. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  740. SceneRenderState *state,
  741. BaseMatInstance *overrideMat)
  742. {
  743. if (!RenderProbeMgr::smRenderReflectionProbes)
  744. return;
  745. GFXDrawUtil *draw = GFX->getDrawUtil();
  746. GFXStateBlockDesc desc;
  747. desc.setZReadWrite(true, false);
  748. desc.setCullMode(GFXCullNone);
  749. desc.setBlend(true);
  750. //desc.fillMode = GFXFillWireframe;
  751. // Base the sphere color on the light color.
  752. ColorI color = ColorI(255, 0, 255, 63);
  753. const MatrixF worldToObjectXfm = mObjToWorld;
  754. if (mProbeShapeType == ProbeRenderInst::Sphere)
  755. {
  756. draw->drawSphere(desc, mRadius, getPosition(), color);
  757. }
  758. else
  759. {
  760. Point3F tscl = worldToObjectXfm.getScale();
  761. Box3F projCube(-mObjScale/2, mObjScale / 2);
  762. projCube.setCenter(getPosition());
  763. draw->drawCube(desc, projCube, color, &worldToObjectXfm);
  764. }
  765. Point3F renderPos = getRenderTransform().getPosition();
  766. Box3F refCube = Box3F(-mProbeRefScale / 2, mProbeRefScale / 2);
  767. refCube.setCenter(renderPos + mProbeRefOffset);
  768. color = ColorI(0, 255, 255, 63);
  769. draw->drawCube(desc, refCube, color, &worldToObjectXfm);
  770. }
  771. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  772. {
  773. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  774. return;
  775. //Set up the params
  776. MaterialParameters *matParams = mat->getMaterialParameters();
  777. //Get the deferred render target
  778. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  779. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  780. if (!deferredTexObject)
  781. return;
  782. GFX->setTexture(0, deferredTexObject);
  783. //Set the cubemap
  784. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  785. //Set the invViewMat
  786. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  787. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  788. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  789. matParams->setSafe(invViewMat, worldToCameraXfm);
  790. }
  791. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  792. "A utility method for forcing a network update.\n")
  793. {
  794. object->inspectPostApply();
  795. }
  796. DefineEngineMethod(ReflectionProbe, Bake, void, (), ,
  797. "@brief returns true if control object is inside the fog\n\n.")
  798. {
  799. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  800. if (clientProbe)
  801. {
  802. clientProbe->bake();
  803. }
  804. }