reflectionProbe.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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. mBake = false;
  91. mDirty = false;
  92. mRadius = 10;
  93. mUseCubemap = false;
  94. mUseHDRCaptures = true;
  95. mStaticCubemap = NULL;
  96. mProbeUniqueID = "";
  97. mEditorShapeInst = NULL;
  98. mEditorShape = NULL;
  99. mRefreshRateMS = 200;
  100. mDynamicLastBakeMS = 0;
  101. mMaxDrawDistance = 75;
  102. mResourcesCreated = false;
  103. mProbeInfo = nullptr;
  104. mPrefilterSize = 64;
  105. mPrefilterMipLevels = mLog2(F32(mPrefilterSize));
  106. mPrefilterMap = nullptr;
  107. mIrridianceMap = nullptr;
  108. mProbePosOffset = Point3F::Zero;
  109. mEditPosOffset = false;
  110. mProbeInfoIdx = -1;
  111. mCaptureMask = REFLECTION_PROBE_CAPTURE_TYPEMASK;
  112. }
  113. ReflectionProbe::~ReflectionProbe()
  114. {
  115. if (mEditorShapeInst)
  116. SAFE_DELETE(mEditorShapeInst);
  117. if (mProbeInfo)
  118. SAFE_DELETE(mProbeInfo);
  119. if (mReflectionModeType != StaticCubemap && mStaticCubemap)
  120. mStaticCubemap->deleteObject();
  121. }
  122. //-----------------------------------------------------------------------------
  123. // Object Editing
  124. //-----------------------------------------------------------------------------
  125. void ReflectionProbe::initPersistFields()
  126. {
  127. addGroup("Rendering");
  128. addProtectedField("enabled", TypeBool, Offset(mEnabled, ReflectionProbe),
  129. &_setEnabled, &defaultProtectedGetFn, "Regenerate Voxel Grid");
  130. addField("radius", TypeF32, Offset(mRadius, ReflectionProbe), "The name of the material used to render the mesh.");
  131. addField("posOffset", TypePoint3F, Offset(mProbePosOffset, ReflectionProbe), "");
  132. //addProtectedField("EditPosOffset", TypeBool, Offset(mEditPosOffset, ReflectionProbe),
  133. // &_toggleEditPosOffset, &defaultProtectedGetFn, "Toggle Edit Pos Offset Mode", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  134. endGroup("Rendering");
  135. addGroup("Reflection");
  136. addField("ReflectionMode", TypeReflectionModeEnum, Offset(mReflectionModeType, ReflectionProbe),
  137. "The type of mesh data to use for collision queries.");
  138. addField("StaticCubemap", TypeCubemapName, Offset(mCubemapName, ReflectionProbe), "Cubemap used instead of reflection texture if fullReflect is off.");
  139. addProtectedField("Bake", TypeBool, Offset(mBake, ReflectionProbe),
  140. &_doBake, &defaultProtectedGetFn, "Regenerate Voxel Grid", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  141. endGroup("Reflection");
  142. Con::addVariable("$Light::renderReflectionProbes", TypeBool, &RenderProbeMgr::smRenderReflectionProbes,
  143. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  144. "@note Only works for shadow mapped lights.\n\n"
  145. "@ingroup Lighting");
  146. Con::addVariable("$Light::renderPreviewProbes", TypeBool, &ReflectionProbe::smRenderPreviewProbes,
  147. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  148. "@note Only works for shadow mapped lights.\n\n"
  149. "@ingroup Lighting");
  150. // SceneObject already handles exposing the transform
  151. Parent::initPersistFields();
  152. }
  153. void ReflectionProbe::inspectPostApply()
  154. {
  155. Parent::inspectPostApply();
  156. mDirty = true;
  157. // Flag the network mask to send the updates
  158. // to the client object
  159. setMaskBits(-1);
  160. }
  161. bool ReflectionProbe::_setEnabled(void *object, const char *index, const char *data)
  162. {
  163. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  164. probe->mEnabled = dAtob(data);
  165. probe->setMaskBits(-1);
  166. return true;
  167. }
  168. bool ReflectionProbe::_doBake(void *object, const char *index, const char *data)
  169. {
  170. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  171. //if (probe->mDirty)
  172. // probe->bake(probe->mReflectionPath, 256);
  173. ReflectionProbe *clientProbe = (ReflectionProbe*)probe->getClientObject();
  174. if (clientProbe)
  175. {
  176. clientProbe->bake();
  177. }
  178. return false;
  179. }
  180. bool ReflectionProbe::_toggleEditPosOffset(void *object, const char *index, const char *data)
  181. {
  182. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  183. probe->mEditPosOffset = !probe->mEditPosOffset;
  184. //if (probe->mDirty)
  185. // probe->bake(probe->mReflectionPath, 256);
  186. return false;
  187. }
  188. bool ReflectionProbe::onAdd()
  189. {
  190. if (!Parent::onAdd())
  191. return false;
  192. mEditPosOffset = false;
  193. mObjBox.minExtents.set(-1, -1, -1);
  194. mObjBox.maxExtents.set(1, 1, 1);
  195. //mObjScale.set(mRadius/2, mRadius/2, mRadius/2);
  196. // Skip our transform... it just dirties mask bits.
  197. Parent::setTransform(mObjToWorld);
  198. resetWorldBox();
  199. // Add this object to the scene
  200. addToScene();
  201. if (isServerObject())
  202. {
  203. if (!mPersistentId)
  204. mPersistentId = getOrCreatePersistentId();
  205. mProbeUniqueID = std::to_string(mPersistentId->getUUID().getHash()).c_str();
  206. }
  207. // Refresh this object's material (if any)
  208. if (isClientObject())
  209. {
  210. createGeometry();
  211. updateProbeParams();
  212. PROBEMGR->registerProbe(mProbeInfoIdx);
  213. }
  214. setMaskBits(-1);
  215. return true;
  216. }
  217. void ReflectionProbe::onRemove()
  218. {
  219. if (isClientObject())
  220. {
  221. PROBEMGR->unregisterProbe(mProbeInfoIdx);
  222. }
  223. // Remove this object from the scene
  224. removeFromScene();
  225. Parent::onRemove();
  226. }
  227. void ReflectionProbe::handleDeleteAction()
  228. {
  229. //we're deleting it?
  230. //Then we need to clear out the processed cubemaps(if we have them)
  231. String prefilPath = getPrefilterMapPath();
  232. if (Platform::isFile(prefilPath))
  233. {
  234. Platform::fileDelete(prefilPath);
  235. }
  236. String irrPath = getIrradianceMapPath();
  237. if (Platform::isFile(irrPath))
  238. {
  239. Platform::fileDelete(irrPath);
  240. }
  241. Parent::handleDeleteAction();
  242. }
  243. void ReflectionProbe::setTransform(const MatrixF & mat)
  244. {
  245. // Let SceneObject handle all of the matrix manipulation
  246. if (!mEditPosOffset)
  247. Parent::setTransform(mat);
  248. else
  249. mProbePosOffset = mat.getPosition();
  250. mDirty = true;
  251. // Dirty our network mask so that the new transform gets
  252. // transmitted to the client object
  253. setMaskBits(TransformMask);
  254. }
  255. U32 ReflectionProbe::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  256. {
  257. // Allow the Parent to get a crack at writing its info
  258. U32 retMask = Parent::packUpdate(conn, mask, stream);
  259. // Write our transform information
  260. if (stream->writeFlag(mask & TransformMask))
  261. {
  262. mathWrite(*stream, getTransform());
  263. mathWrite(*stream, getScale());
  264. mathWrite(*stream, mProbePosOffset);
  265. }
  266. if (stream->writeFlag(mask & ShapeTypeMask))
  267. {
  268. stream->write((U32)mProbeShapeType);
  269. }
  270. if (stream->writeFlag(mask & UpdateMask))
  271. {
  272. stream->write(mRadius);
  273. }
  274. if (stream->writeFlag(mask & BakeInfoMask))
  275. {
  276. stream->write(mProbeUniqueID);
  277. }
  278. if (stream->writeFlag(mask & EnabledMask))
  279. {
  280. stream->writeFlag(mEnabled);
  281. }
  282. if (stream->writeFlag(mask & ModeMask))
  283. {
  284. stream->write((U32)mReflectionModeType);
  285. }
  286. if (stream->writeFlag(mask & CubemapMask))
  287. {
  288. stream->writeFlag(mUseCubemap);
  289. stream->write(mCubemapName);
  290. }
  291. return retMask;
  292. }
  293. void ReflectionProbe::unpackUpdate(NetConnection *conn, BitStream *stream)
  294. {
  295. // Let the Parent read any info it sent
  296. Parent::unpackUpdate(conn, stream);
  297. if (stream->readFlag()) // TransformMask
  298. {
  299. mathRead(*stream, &mObjToWorld);
  300. mathRead(*stream, &mObjScale);
  301. setTransform(mObjToWorld);
  302. mathRead(*stream, &mProbePosOffset);
  303. }
  304. if (stream->readFlag()) // ShapeTypeMask
  305. {
  306. U32 shapeType = ProbeRenderInst::Sphere;
  307. stream->read(&shapeType);
  308. mProbeShapeType = (ProbeRenderInst::ProbeShapeType)shapeType;
  309. createGeometry();
  310. }
  311. if (stream->readFlag()) // UpdateMask
  312. {
  313. stream->read(&mRadius);
  314. }
  315. if (stream->readFlag()) // BakeInfoMask
  316. {
  317. stream->read(&mProbeUniqueID);
  318. }
  319. if (stream->readFlag()) // EnabledMask
  320. {
  321. mEnabled = stream->readFlag();
  322. }
  323. bool isMaterialDirty = false;
  324. if (stream->readFlag()) // ModeMask
  325. {
  326. U32 reflectModeType = BakedCubemap;
  327. stream->read(&reflectModeType);
  328. mReflectionModeType = (ReflectionModeType)reflectModeType;
  329. isMaterialDirty = true;
  330. }
  331. updateProbeParams();
  332. if (stream->readFlag()) // CubemapMask
  333. {
  334. mUseCubemap = stream->readFlag();
  335. String newCubemapName;
  336. stream->read(&mCubemapName);
  337. //if (newCubemapName != mCubemapName)
  338. {
  339. processStaticCubemap();
  340. }
  341. isMaterialDirty = true;
  342. }
  343. if (isMaterialDirty)
  344. {
  345. updateMaterial();
  346. }
  347. PROBEMGR->updateProbes();
  348. }
  349. void ReflectionProbe::createGeometry()
  350. {
  351. // Clean up our previous shape
  352. if (mEditorShapeInst)
  353. SAFE_DELETE(mEditorShapeInst);
  354. mEditorShape = NULL;
  355. String shapeFile = "tools/resources/ReflectProbeSphere.dae";
  356. // Attempt to get the resource from the ResourceManager
  357. mEditorShape = ResourceManager::get().load(shapeFile);
  358. if (mEditorShape)
  359. {
  360. mEditorShapeInst = new TSShapeInstance(mEditorShape, isClientObject());
  361. }
  362. }
  363. //-----------------------------------------------------------------------------
  364. // Object Rendering
  365. //-----------------------------------------------------------------------------
  366. void ReflectionProbe::updateProbeParams()
  367. {
  368. if (mProbeInfo == nullptr)
  369. {
  370. mProbeInfo = new ProbeRenderInst();
  371. mProbeInfoIdx = ProbeRenderInst::all.size() - 1;
  372. mProbeInfo->mIsEnabled = false;
  373. }
  374. updateMaterial();
  375. mProbeInfo->mProbeShapeType = mProbeShapeType;
  376. mProbeInfo->mTransform = getWorldTransform();
  377. mProbeInfo->mPosition = getPosition();
  378. mObjScale.set(mRadius, mRadius, mRadius);
  379. // Skip our transform... it just dirties mask bits.
  380. Parent::setTransform(mObjToWorld);
  381. resetWorldBox();
  382. mProbeInfo->mBounds = mWorldBox;
  383. mProbeInfo->mRadius = mRadius;
  384. mProbeInfo->mIsSkylight = false;
  385. mProbeInfo->mProbePosOffset = mProbePosOffset;
  386. mProbeInfo->mDirty = true;
  387. mProbeInfo->mScore = mMaxDrawDistance;
  388. }
  389. void ReflectionProbe::processStaticCubemap()
  390. {
  391. if (mReflectionModeType != StaticCubemap)
  392. return;
  393. createClientResources();
  394. Sim::findObject(mCubemapName, mStaticCubemap);
  395. if (!mStaticCubemap)
  396. {
  397. Con::errorf("ReflectionProbe::updateMaterial() - unable to find static cubemap file!");
  398. return;
  399. }
  400. if (mStaticCubemap->mCubemap == nullptr)
  401. {
  402. mStaticCubemap->createMap();
  403. mStaticCubemap->updateFaces();
  404. }
  405. String prefilPath = getPrefilterMapPath();
  406. String irrPath = getIrradianceMapPath();
  407. if (mUseHDRCaptures)
  408. {
  409. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  410. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR16G16B16A16F);
  411. }
  412. else
  413. {
  414. mIrridianceMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  415. mPrefilterMap->mCubemap->initDynamic(mPrefilterSize, GFXFormatR8G8B8A8);
  416. }
  417. //if (!Platform::isFile(irrPath) || !Platform::isFile(prefilPath))
  418. {
  419. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  420. IBLUtilities::GenerateIrradianceMap(renderTarget, mStaticCubemap->mCubemap, mIrridianceMap->mCubemap);
  421. IBLUtilities::GeneratePrefilterMap(renderTarget, mStaticCubemap->mCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  422. IBLUtilities::SaveCubeMap(getIrradianceMapPath(), mIrridianceMap->mCubemap);
  423. IBLUtilities::SaveCubeMap(getPrefilterMapPath(), mPrefilterMap->mCubemap);
  424. }
  425. mProbeInfo->mCubemap = mPrefilterMap->mCubemap;
  426. mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  427. }
  428. void ReflectionProbe::updateMaterial()
  429. {
  430. createClientResources();
  431. if (mReflectionModeType != DynamicCubemap)
  432. {
  433. mProbeInfo->mCubeReflector.unregisterReflector();
  434. if ((mReflectionModeType == BakedCubemap) && !mProbeUniqueID.isEmpty())
  435. {
  436. if (mPrefilterMap != nullptr && mPrefilterMap->mCubemap.isValid())
  437. {
  438. mProbeInfo->mCubemap = mPrefilterMap->mCubemap;
  439. }
  440. else
  441. {
  442. mEnabled = false;
  443. }
  444. if (mIrridianceMap != nullptr && mIrridianceMap->mCubemap.isValid())
  445. {
  446. mProbeInfo->mIrradianceCubemap = mIrridianceMap->mCubemap;
  447. }
  448. else
  449. {
  450. mEnabled = false;
  451. }
  452. }
  453. }
  454. else
  455. {
  456. if (mReflectionModeType == DynamicCubemap && !mDynamicCubemap.isNull())
  457. {
  458. mProbeInfo->mCubemap = mDynamicCubemap;
  459. mProbeInfo->mCubeReflector.registerReflector(this, reflectorDesc); //need to decide how we wanna do the reflectorDesc. static name or a field
  460. }
  461. else
  462. {
  463. mEnabled = false;
  464. }
  465. }
  466. //Make us ready to render
  467. if (mEnabled)
  468. mProbeInfo->mIsEnabled = true;
  469. else
  470. mProbeInfo->mIsEnabled = false;
  471. PROBEMGR->updateProbes();
  472. }
  473. bool ReflectionProbe::createClientResources()
  474. {
  475. //irridiance resources
  476. if (!mIrridianceMap)
  477. {
  478. mIrridianceMap = new CubemapData();
  479. mIrridianceMap->registerObject();
  480. mIrridianceMap->createMap();
  481. }
  482. String irrPath = getIrradianceMapPath();
  483. if (Platform::isFile(irrPath))
  484. {
  485. mIrridianceMap->setCubemapFile(FileName(irrPath));
  486. mIrridianceMap->updateFaces();
  487. }
  488. if (mIrridianceMap->mCubemap.isNull())
  489. Con::errorf("ReflectionProbe::createClientResources() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  490. //
  491. if (!mPrefilterMap)
  492. {
  493. mPrefilterMap = new CubemapData();
  494. mPrefilterMap->registerObject();
  495. mPrefilterMap->createMap();
  496. }
  497. String prefilPath = getPrefilterMapPath();
  498. if (Platform::isFile(prefilPath))
  499. {
  500. mPrefilterMap->setCubemapFile(FileName(prefilPath));
  501. mPrefilterMap->updateFaces();
  502. }
  503. if (mPrefilterMap->mCubemap.isNull())
  504. Con::errorf("ReflectionProbe::createClientResources() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  505. mResourcesCreated = true;
  506. return true;
  507. }
  508. void ReflectionProbe::generateTextures()
  509. {
  510. }
  511. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  512. {
  513. if (!mEnabled || !RenderProbeMgr::smRenderReflectionProbes)
  514. return;
  515. Point3F distVec = getRenderPosition() - state->getCameraPosition();
  516. F32 dist = distVec.len();
  517. //Culling distance. Can be adjusted for performance options considerations via the scalar
  518. if (dist > mMaxDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  519. {
  520. mProbeInfo->mScore = mMaxDrawDistance;
  521. return;
  522. }
  523. if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS))
  524. {
  525. bake();
  526. mDynamicLastBakeMS = Platform::getRealMilliseconds();
  527. }
  528. //Submit our probe to actually do the probe action
  529. // Get a handy pointer to our RenderPassmanager
  530. //RenderPassManager *renderPass = state->getRenderPass();
  531. //Update our score based on our radius, distance
  532. mProbeInfo->mScore = mProbeInfo->mRadius/mMax(dist,1.0f);
  533. Point3F vect = distVec;
  534. vect.normalizeSafe();
  535. mProbeInfo->mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  536. //Register
  537. //PROBEMGR->registerProbe(mProbeInfoIdx);
  538. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mEditorShapeInst && mPrefilterMap != nullptr)
  539. {
  540. GFXTransformSaver saver;
  541. // Calculate the distance of this object from the camera
  542. Point3F cameraOffset;
  543. getRenderTransform().getColumn(3, &cameraOffset);
  544. cameraOffset -= state->getDiffuseCameraPosition();
  545. dist = cameraOffset.len();
  546. if (dist < 0.01f)
  547. dist = 0.01f;
  548. // Set up the LOD for the shape
  549. F32 invScale = (1.0f / getMax(getMax(mObjScale.x, mObjScale.y), mObjScale.z));
  550. mEditorShapeInst->setDetailFromDistance(state, dist * invScale);
  551. // Make sure we have a valid level of detail
  552. if (mEditorShapeInst->getCurrentDetail() < 0)
  553. return;
  554. BaseMatInstance* probePrevMat = mEditorShapeInst->getMaterialList()->getMaterialInst(0);
  555. setPreviewMatParameters(state, probePrevMat);
  556. // GFXTransformSaver is a handy helper class that restores
  557. // the current GFX matrices to their original values when
  558. // it goes out of scope at the end of the function
  559. // Set up our TS render state
  560. TSRenderState rdata;
  561. rdata.setSceneState(state);
  562. rdata.setFadeOverride(1.0f);
  563. if(mReflectionModeType != DynamicCubemap)
  564. rdata.setCubemap(mPrefilterMap->mCubemap);
  565. else
  566. rdata.setCubemap(mDynamicCubemap);
  567. // We might have some forward lit materials
  568. // so pass down a query to gather lights.
  569. LightQuery query;
  570. query.init(getWorldSphere());
  571. rdata.setLightQuery(&query);
  572. // Set the world matrix to the objects render transform
  573. MatrixF mat = getRenderTransform();
  574. mat.scale(Point3F(1, 1, 1));
  575. Point3F centerPos = mat.getPosition();
  576. centerPos += mProbePosOffset;
  577. mat.setPosition(centerPos);
  578. GFX->setWorldMatrix(mat);
  579. // Animate the the shape
  580. mEditorShapeInst->animate();
  581. // Allow the shape to submit the RenderInst(s) for itself
  582. mEditorShapeInst->render(rdata);
  583. saver.restore();
  584. }
  585. // If the light is selected or light visualization
  586. // is enabled then register the callback.
  587. const bool isSelectedInEditor = (gEditingMission && isSelected());
  588. if (isSelectedInEditor)
  589. {
  590. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  591. ri->renderDelegate.bind(this, &ReflectionProbe::_onRenderViz);
  592. ri->type = RenderPassManager::RIT_Editor;
  593. state->getRenderPass()->addInst(ri);
  594. }
  595. }
  596. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  597. SceneRenderState *state,
  598. BaseMatInstance *overrideMat)
  599. {
  600. if (!RenderProbeMgr::smRenderReflectionProbes)
  601. return;
  602. GFXDrawUtil *draw = GFX->getDrawUtil();
  603. GFXStateBlockDesc desc;
  604. desc.setZReadWrite(true, false);
  605. desc.setCullMode(GFXCullNone);
  606. desc.setBlend(true);
  607. // Base the sphere color on the light color.
  608. ColorI color = ColorI::WHITE;
  609. color.alpha = 25;
  610. if (mProbeShapeType == ProbeRenderInst::Sphere)
  611. {
  612. draw->drawSphere(desc, mRadius, getPosition(), color);
  613. }
  614. else
  615. {
  616. const MatrixF worldToObjectXfm = getTransform();
  617. Box3F cube(-Point3F(mRadius, mRadius, mRadius),Point3F(mRadius, mRadius, mRadius));
  618. Box3F wb = getWorldBox();
  619. cube.setCenter(getPosition()+mProbePosOffset);
  620. wb.setCenter(getPosition() + mProbePosOffset);
  621. draw->drawCube(desc, cube, color, &worldToObjectXfm);
  622. draw->drawCube(desc, wb, color, &worldToObjectXfm);
  623. }
  624. }
  625. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  626. {
  627. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  628. return;
  629. //Set up the params
  630. MaterialParameters *matParams = mat->getMaterialParameters();
  631. //Get the deferred render target
  632. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  633. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  634. if (!deferredTexObject)
  635. return;
  636. GFX->setTexture(0, deferredTexObject);
  637. //Set the cubemap
  638. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  639. //Set the invViewMat
  640. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  641. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  642. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  643. matParams->setSafe(invViewMat, worldToCameraXfm);
  644. }
  645. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  646. "A utility method for forcing a network update.\n")
  647. {
  648. object->inspectPostApply();
  649. }
  650. String ReflectionProbe::getPrefilterMapPath()
  651. {
  652. if (mProbeUniqueID.isEmpty())
  653. {
  654. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  655. return "";
  656. }
  657. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  658. char fileName[256];
  659. dSprintf(fileName, 256, "%s%s_Prefilter.dds", path.c_str(), mProbeUniqueID.c_str());
  660. return fileName;
  661. }
  662. String ReflectionProbe::getIrradianceMapPath()
  663. {
  664. if (mProbeUniqueID.isEmpty())
  665. {
  666. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  667. return "";
  668. }
  669. String path = Con::getVariable("$pref::ReflectionProbes::CurrentLevelPath", "levels/");
  670. char fileName[256];
  671. dSprintf(fileName, 256, "%s%s_Irradiance.dds", path.c_str(), mProbeUniqueID.c_str());
  672. return fileName;
  673. }
  674. void ReflectionProbe::bake()
  675. {
  676. if (mReflectionModeType == DynamicCubemap)
  677. return;
  678. PROBEMGR->bakeProbe(this);
  679. setMaskBits(CubemapMask);
  680. }
  681. DefineEngineMethod(ReflectionProbe, Bake, void, (), ,
  682. "@brief returns true if control object is inside the fog\n\n.")
  683. {
  684. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  685. if (clientProbe)
  686. {
  687. clientProbe->bake();
  688. }
  689. }