reflectionProbe.cpp 30 KB

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