reflectionProbe.cpp 30 KB

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