reflectionProbe.cpp 29 KB

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