reflectionProbe.cpp 30 KB

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