reflectionProbe.cpp 25 KB

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