reflectionProbe.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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 <string>
  39. #include "T3D/gameFunctions.h"
  40. #include "postFx/postEffect.h"
  41. #include "renderInstance/renderProbeMgr.h"
  42. #include "lighting/probeManager.h"
  43. #include "math/util/sphereMesh.h"
  44. #include "materials/materialManager.h"
  45. #include "math/util/matrixSet.h"
  46. #include "gfx/bitmap/cubemapSaver.h"
  47. #include "materials/materialFeatureTypes.h"
  48. #include "gfx/gfxTextureManager.h"
  49. #include "T3D/lighting/IBLUtilities.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(IndrectLightingModeEnum,
  71. "Type of mesh data available in a shape.\n"
  72. "@ingroup gameObjects")
  73. { ReflectionProbe::NoIndirect, "No Lighting", "This probe does not provide any local indirect lighting data" },
  74. { ReflectionProbe::AmbientColor, "Ambient Color", "Adds a flat color to act as the local indirect lighting" },
  75. { ReflectionProbe::SphericalHarmonics, "Spherical Harmonics", "Creates spherical harmonics data based off the reflection data" },
  76. EndImplementEnumType;
  77. ImplementEnumType(ReflectionModeEnum,
  78. "Type of mesh data available in a shape.\n"
  79. "@ingroup gameObjects")
  80. { ReflectionProbe::NoReflection, "No Reflections", "This probe does not provide any local reflection data"},
  81. { ReflectionProbe::StaticCubemap, "Static Cubemap", "Uses a static CubemapData" },
  82. { ReflectionProbe::BakedCubemap, "Baked Cubemap", "Uses a cubemap baked from the probe's current position" },
  83. //{ ReflectionProbe::DynamicCubemap, "Dynamic Cubemap", "Uses a cubemap baked from the probe's current position, updated at a set rate" },
  84. EndImplementEnumType;
  85. //-----------------------------------------------------------------------------
  86. // Object setup and teardown
  87. //-----------------------------------------------------------------------------
  88. ReflectionProbe::ReflectionProbe()
  89. {
  90. // Flag this object so that it will always
  91. // be sent across the network to clients
  92. mNetFlags.set(Ghostable | ScopeAlways);
  93. mTypeMask = LightObjectType | MarkerObjectType;
  94. mProbeShapeType = ProbeRenderInst::Box;
  95. mIndrectLightingModeType = NoIndirect;
  96. mReflectionModeType = BakedCubemap;
  97. mEnabled = true;
  98. mBake = false;
  99. mDirty = false;
  100. mRadius = 10;
  101. mUseCubemap = false;
  102. mUseHDRCaptures = true;
  103. mStaticCubemap = NULL;
  104. mReflectionPath = "";
  105. mProbeUniqueID = "";
  106. mEditorShapeInst = NULL;
  107. mEditorShape = NULL;
  108. mRefreshRateMS = 200;
  109. mDynamicLastBakeMS = 0;
  110. mMaxDrawDistance = 75;
  111. mResourcesCreated = false;
  112. mProbeInfo = nullptr;
  113. mPrefilterSize = 64;
  114. mPrefilterMipLevels = mLog2(F32(mPrefilterSize));
  115. mPrefilterMap = nullptr;
  116. mIrridianceMap = nullptr;
  117. mProbePosOffset = Point3F::Zero;
  118. mEditPosOffset = false;
  119. }
  120. ReflectionProbe::~ReflectionProbe()
  121. {
  122. if (mEditorShapeInst)
  123. SAFE_DELETE(mEditorShapeInst);
  124. if (mProbeInfo)
  125. SAFE_DELETE(mProbeInfo);
  126. if (mReflectionModeType != StaticCubemap && mStaticCubemap)
  127. mStaticCubemap->deleteObject();
  128. }
  129. //-----------------------------------------------------------------------------
  130. // Object Editing
  131. //-----------------------------------------------------------------------------
  132. void ReflectionProbe::initPersistFields()
  133. {
  134. addGroup("Rendering");
  135. addProtectedField("enabled", TypeBool, Offset(mEnabled, ReflectionProbe),
  136. &_setEnabled, &defaultProtectedGetFn, "Regenerate Voxel Grid");
  137. addField("ProbeShape", TypeReflectProbeType, Offset(mProbeShapeType, ReflectionProbe),
  138. "The type of mesh data to use for collision queries.");
  139. addField("radius", TypeF32, Offset(mRadius, ReflectionProbe), "The name of the material used to render the mesh.");
  140. addField("posOffset", TypePoint3F, Offset(mProbePosOffset, ReflectionProbe), "");
  141. //addProtectedField("EditPosOffset", TypeBool, Offset(mEditPosOffset, ReflectionProbe),
  142. // &_toggleEditPosOffset, &defaultProtectedGetFn, "Toggle Edit Pos Offset Mode", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  143. endGroup("Rendering");
  144. addGroup("Reflection");
  145. addField("ReflectionMode", TypeReflectionModeEnum, Offset(mReflectionModeType, ReflectionProbe),
  146. "The type of mesh data to use for collision queries.");
  147. addField("reflectionPath", TypeImageFilename, Offset(mReflectionPath, ReflectionProbe),
  148. "The type of mesh data to use for collision queries.");
  149. addField("StaticCubemap", TypeCubemapName, Offset(mCubemapName, ReflectionProbe), "Cubemap used instead of reflection texture if fullReflect is off.");
  150. addProtectedField("Bake", TypeBool, Offset(mBake, ReflectionProbe),
  151. &_doBake, &defaultProtectedGetFn, "Regenerate Voxel Grid", AbstractClassRep::FieldFlags::FIELD_ComponentInspectors);
  152. endGroup("Reflection");
  153. Con::addVariable("$Light::renderReflectionProbes", TypeBool, &ProbeManager::smRenderReflectionProbes,
  154. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  155. "@note Only works for shadow mapped lights.\n\n"
  156. "@ingroup Lighting");
  157. Con::addVariable("$Light::renderPreviewProbes", TypeBool, &ReflectionProbe::smRenderPreviewProbes,
  158. "Toggles rendering of light frustums when the light is selected in the editor.\n\n"
  159. "@note Only works for shadow mapped lights.\n\n"
  160. "@ingroup Lighting");
  161. // SceneObject already handles exposing the transform
  162. Parent::initPersistFields();
  163. }
  164. void ReflectionProbe::inspectPostApply()
  165. {
  166. Parent::inspectPostApply();
  167. mDirty = true;
  168. // Flag the network mask to send the updates
  169. // to the client object
  170. setMaskBits(-1);
  171. }
  172. bool ReflectionProbe::_setEnabled(void *object, const char *index, const char *data)
  173. {
  174. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  175. probe->mEnabled = dAtob(data);
  176. probe->setMaskBits(-1);
  177. return true;
  178. }
  179. bool ReflectionProbe::_doBake(void *object, const char *index, const char *data)
  180. {
  181. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  182. //if (probe->mDirty)
  183. // probe->bake(probe->mReflectionPath, 256);
  184. ReflectionProbe *clientProbe = (ReflectionProbe*)probe->getClientObject();
  185. if (clientProbe)
  186. {
  187. clientProbe->bake(clientProbe->mReflectionPath, 64);
  188. }
  189. return false;
  190. }
  191. bool ReflectionProbe::_toggleEditPosOffset(void *object, const char *index, const char *data)
  192. {
  193. ReflectionProbe* probe = reinterpret_cast< ReflectionProbe* >(object);
  194. probe->mEditPosOffset = !probe->mEditPosOffset;
  195. //if (probe->mDirty)
  196. // probe->bake(probe->mReflectionPath, 256);
  197. return false;
  198. }
  199. bool ReflectionProbe::onAdd()
  200. {
  201. if (!Parent::onAdd())
  202. return false;
  203. mEditPosOffset = false;
  204. mObjBox.minExtents.set(-1, -1, -1);
  205. mObjBox.maxExtents.set(1, 1, 1);
  206. //mObjScale.set(mRadius/2, mRadius/2, mRadius/2);
  207. // Skip our transform... it just dirties mask bits.
  208. Parent::setTransform(mObjToWorld);
  209. resetWorldBox();
  210. // Add this object to the scene
  211. addToScene();
  212. if (isServerObject())
  213. {
  214. if (!mPersistentId)
  215. mPersistentId = getOrCreatePersistentId();
  216. mProbeUniqueID = std::to_string(mPersistentId->getUUID().getHash()).c_str();
  217. }
  218. // Refresh this object's material (if any)
  219. if (isClientObject())
  220. {
  221. createGeometry();
  222. updateProbeParams();
  223. }
  224. setMaskBits(-1);
  225. return true;
  226. }
  227. void ReflectionProbe::onRemove()
  228. {
  229. // Remove this object from the scene
  230. removeFromScene();
  231. Parent::onRemove();
  232. }
  233. void ReflectionProbe::setTransform(const MatrixF & mat)
  234. {
  235. // Let SceneObject handle all of the matrix manipulation
  236. if (!mEditPosOffset)
  237. Parent::setTransform(mat);
  238. else
  239. mProbePosOffset = mat.getPosition();
  240. mDirty = true;
  241. // Dirty our network mask so that the new transform gets
  242. // transmitted to the client object
  243. setMaskBits(TransformMask);
  244. }
  245. U32 ReflectionProbe::packUpdate(NetConnection *conn, U32 mask, BitStream *stream)
  246. {
  247. // Allow the Parent to get a crack at writing its info
  248. U32 retMask = Parent::packUpdate(conn, mask, stream);
  249. // Write our transform information
  250. if (stream->writeFlag(mask & TransformMask))
  251. {
  252. mathWrite(*stream, getTransform());
  253. mathWrite(*stream, getScale());
  254. mathWrite(*stream, mProbePosOffset);
  255. }
  256. if (stream->writeFlag(mask & ShapeTypeMask))
  257. {
  258. stream->write((U32)mProbeShapeType);
  259. }
  260. if (stream->writeFlag(mask & UpdateMask))
  261. {
  262. stream->write(mRadius);
  263. }
  264. if (stream->writeFlag(mask & BakeInfoMask))
  265. {
  266. stream->write(mReflectionPath);
  267. stream->write(mProbeUniqueID);
  268. }
  269. if (stream->writeFlag(mask & EnabledMask))
  270. {
  271. stream->writeFlag(mEnabled);
  272. }
  273. if (stream->writeFlag(mask & ModeMask))
  274. {
  275. stream->write((U32)mIndrectLightingModeType);
  276. stream->write((U32)mReflectionModeType);
  277. }
  278. if (stream->writeFlag(mask & CubemapMask))
  279. {
  280. stream->writeFlag(mUseCubemap);
  281. stream->write(mCubemapName);
  282. }
  283. return retMask;
  284. }
  285. void ReflectionProbe::unpackUpdate(NetConnection *conn, BitStream *stream)
  286. {
  287. // Let the Parent read any info it sent
  288. Parent::unpackUpdate(conn, stream);
  289. if (stream->readFlag()) // TransformMask
  290. {
  291. mathRead(*stream, &mObjToWorld);
  292. mathRead(*stream, &mObjScale);
  293. setTransform(mObjToWorld);
  294. mathRead(*stream, &mProbePosOffset);
  295. }
  296. if (stream->readFlag()) // ShapeTypeMask
  297. {
  298. U32 shapeType = ProbeRenderInst::Sphere;
  299. stream->read(&shapeType);
  300. mProbeShapeType = (ProbeRenderInst::ProbeShapeType)shapeType;
  301. createGeometry();
  302. }
  303. if (stream->readFlag()) // UpdateMask
  304. {
  305. stream->read(&mRadius);
  306. }
  307. if (stream->readFlag()) // BakeInfoMask
  308. {
  309. stream->read(&mReflectionPath);
  310. stream->read(&mProbeUniqueID);
  311. }
  312. if (stream->readFlag()) // EnabledMask
  313. {
  314. mEnabled = stream->readFlag();
  315. }
  316. bool isMaterialDirty = false;
  317. if (stream->readFlag()) // ModeMask
  318. {
  319. U32 indirectModeType = AmbientColor;
  320. stream->read(&indirectModeType);
  321. mIndrectLightingModeType = (IndrectLightingModeType)indirectModeType;
  322. U32 reflectModeType = BakedCubemap;
  323. stream->read(&reflectModeType);
  324. mReflectionModeType = (ReflectionModeType)reflectModeType;
  325. isMaterialDirty = true;
  326. }
  327. if (stream->readFlag()) // CubemapMask
  328. {
  329. mUseCubemap = stream->readFlag();
  330. stream->read(&mCubemapName);
  331. isMaterialDirty = true;
  332. }
  333. updateProbeParams();
  334. if (isMaterialDirty)
  335. {
  336. updateMaterial();
  337. }
  338. }
  339. void ReflectionProbe::createGeometry()
  340. {
  341. // Clean up our previous shape
  342. if (mEditorShapeInst)
  343. SAFE_DELETE(mEditorShapeInst);
  344. mEditorShape = NULL;
  345. String shapeFile = "tools/resources/ReflectProbeSphere.dae";
  346. // Attempt to get the resource from the ResourceManager
  347. mEditorShape = ResourceManager::get().load(shapeFile);
  348. if (mEditorShape)
  349. {
  350. mEditorShapeInst = new TSShapeInstance(mEditorShape, isClientObject());
  351. }
  352. }
  353. //-----------------------------------------------------------------------------
  354. // Object Rendering
  355. //-----------------------------------------------------------------------------
  356. void ReflectionProbe::updateProbeParams()
  357. {
  358. if (mProbeInfo == nullptr)
  359. {
  360. mProbeInfo = new ProbeRenderInst();
  361. mProbeInfo->mIsEnabled = false;
  362. }
  363. updateMaterial();
  364. mProbeInfo->mAmbient = LinearColorF(0, 0, 0, 0);
  365. mProbeInfo->mProbeShapeType = mProbeShapeType;
  366. mProbeInfo->mTransform = getWorldTransform();
  367. mProbeInfo->setPosition(getPosition());
  368. //Point3F pos = mProbeInfo->mTransform.getPosition();
  369. //Update the bounds
  370. //mObjBox.minExtents.set(-1, -1, -1);
  371. //mObjBox.maxExtents.set(1, 1, 1);
  372. mObjScale.set(mRadius, mRadius, mRadius);
  373. // Skip our transform... it just dirties mask bits.
  374. Parent::setTransform(mObjToWorld);
  375. resetWorldBox();
  376. mProbeInfo->mBounds = mWorldBox;
  377. mProbeInfo->mRadius = mRadius;
  378. mProbeInfo->mIsSkylight = false;
  379. mProbeInfo->mProbePosOffset = mProbePosOffset;
  380. mProbeInfo->mDirty = true;
  381. }
  382. void ReflectionProbe::updateMaterial()
  383. {
  384. createClientResources();
  385. if (mReflectionModeType != DynamicCubemap)
  386. {
  387. if ((mReflectionModeType == BakedCubemap) && !mProbeUniqueID.isEmpty())
  388. {
  389. if (mPrefilterMap != nullptr && mPrefilterMap->mCubemap.isValid())
  390. {
  391. mProbeInfo->mCubemap = &mPrefilterMap->mCubemap;
  392. }
  393. if (mIrridianceMap != nullptr && mIrridianceMap->mCubemap.isValid())
  394. {
  395. mProbeInfo->mIrradianceCubemap = &mIrridianceMap->mCubemap;
  396. }
  397. if (mBrdfTexture.isValid())
  398. {
  399. mProbeInfo->mBRDFTexture = &mBrdfTexture;
  400. }
  401. }
  402. else if (mReflectionModeType == StaticCubemap && !mCubemapName.isEmpty())
  403. {
  404. Sim::findObject(mCubemapName, mStaticCubemap);
  405. if (!mStaticCubemap)
  406. {
  407. Con::errorf("ReflectionProbe::updateMaterial() - unable to find static cubemap file!");
  408. return;
  409. }
  410. if (mStaticCubemap->mCubemap == nullptr)
  411. {
  412. mStaticCubemap->createMap();
  413. mStaticCubemap->updateFaces();
  414. }
  415. //GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  416. //IBLUtilities::GenerateIrradianceMap(renderTarget, mStaticCubemap->mCubemap, mIrridianceMap->mCubemap);
  417. //IBLUtilities::GeneratePrefilterMap(renderTarget, mStaticCubemap->mCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  418. mProbeInfo->mCubemap = &mStaticCubemap->mCubemap;
  419. mProbeInfo->mIrradianceCubemap = &mStaticCubemap->mCubemap;
  420. /*if (mPrefilterMap != nullptr && mPrefilterMap->mCubemap.isValid())
  421. {
  422. mProbeInfo->mCubemap = &mPrefilterMap->mCubemap;
  423. }
  424. if (mIrridianceMap != nullptr && mIrridianceMap->mCubemap.isValid())
  425. {
  426. mProbeInfo->mIrradianceCubemap = &mIrridianceMap->mCubemap;
  427. }*/
  428. if (mBrdfTexture.isValid())
  429. {
  430. mProbeInfo->mBRDFTexture = &mBrdfTexture;
  431. }
  432. }
  433. }
  434. else if (mReflectionModeType == DynamicCubemap && !mDynamicCubemap.isNull())
  435. {
  436. mProbeInfo->mCubemap = &mDynamicCubemap;
  437. }
  438. //Make us ready to render
  439. if (mEnabled)
  440. mProbeInfo->mIsEnabled = true;
  441. else
  442. mProbeInfo->mIsEnabled = false;
  443. }
  444. bool ReflectionProbe::createClientResources()
  445. {
  446. //irridiance resources
  447. if (!mIrridianceMap)
  448. {
  449. mIrridianceMap = new CubemapData();
  450. mIrridianceMap->registerObject();
  451. mIrridianceMap->createMap();
  452. }
  453. if (!mUseHDRCaptures)
  454. {
  455. String irrPath = getIrradianceMapPath();
  456. if (Platform::isFile(irrPath))
  457. {
  458. mIrridianceMap->setCubemapFile(FileName(irrPath));
  459. mIrridianceMap->updateFaces();
  460. }
  461. if (mIrridianceMap->mCubemap.isNull())
  462. Con::errorf("ReflectionProbe::createClientResources() - Unable to load baked irradiance map at %s", getIrradianceMapPath().c_str());
  463. }
  464. //
  465. if (!mPrefilterMap)
  466. {
  467. mPrefilterMap = new CubemapData();
  468. mPrefilterMap->registerObject();
  469. mPrefilterMap->createMap();
  470. }
  471. if (!mUseHDRCaptures)
  472. {
  473. String prefilPath = getPrefilterMapPath();
  474. if (Platform::isFile(prefilPath))
  475. {
  476. mPrefilterMap->setCubemapFile(FileName(prefilPath));
  477. mPrefilterMap->updateFaces();
  478. }
  479. if (mPrefilterMap->mCubemap.isNull())
  480. Con::errorf("ReflectionProbe::createClientResources() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str());
  481. }
  482. //brdf lookup resources
  483. //make the brdf lookup texture the same size as the prefilter texture
  484. String brdfPath = Con::getVariable("$Core::BRDFTexture", "core/art/brdfTexture.dds");
  485. mBrdfTexture = TEXMGR->createTexture(brdfPath, &GFXTexturePersistentProfile);// TEXMGR->createTexture(mPrefilterSize, mPrefilterSize, GFXFormatR16G16B16A16F, &GFXRenderTargetProfile, 1, 0);
  486. if (!mBrdfTexture)
  487. {
  488. mBrdfTexture = IBLUtilities::GenerateAndSaveBRDFTexture(brdfPath, 512);
  489. }
  490. mResourcesCreated = true;
  491. return true;
  492. }
  493. void ReflectionProbe::generateTextures()
  494. {
  495. }
  496. void ReflectionProbe::prepRenderImage(SceneRenderState *state)
  497. {
  498. if (!mEnabled || !ProbeManager::smRenderReflectionProbes)
  499. return;
  500. Point3F distVec = getRenderPosition() - state->getCameraPosition();
  501. F32 dist = distVec.len();
  502. //Culling distance. Can be adjusted for performance options considerations via the scalar
  503. if (dist > mMaxDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0))
  504. return;
  505. if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS))
  506. {
  507. bake("", 32);
  508. mDynamicLastBakeMS = Platform::getRealMilliseconds();
  509. }
  510. //Submit our probe to actually do the probe action
  511. // Get a handy pointer to our RenderPassmanager
  512. //RenderPassManager *renderPass = state->getRenderPass();
  513. //Update our score based on our radius, distance
  514. mProbeInfo->mScore = mProbeInfo->mRadius/mMax(dist,1.0f);
  515. Point3F vect = distVec;
  516. vect.normalizeSafe();
  517. mProbeInfo->mScore *= mMax(mAbs(mDot(vect, state->getCameraTransform().getForwardVector())),0.001f);
  518. //Register
  519. //PROBEMGR->registerProbe(mProbeInfo, this);
  520. if (ReflectionProbe::smRenderPreviewProbes && gEditingMission && mEditorShapeInst && mPrefilterMap != nullptr)
  521. {
  522. GFXTransformSaver saver;
  523. // Calculate the distance of this object from the camera
  524. Point3F cameraOffset;
  525. getRenderTransform().getColumn(3, &cameraOffset);
  526. cameraOffset -= state->getDiffuseCameraPosition();
  527. F32 dist = cameraOffset.len();
  528. if (dist < 0.01f)
  529. dist = 0.01f;
  530. // Set up the LOD for the shape
  531. F32 invScale = (1.0f / getMax(getMax(mObjScale.x, mObjScale.y), mObjScale.z));
  532. mEditorShapeInst->setDetailFromDistance(state, dist * invScale);
  533. // Make sure we have a valid level of detail
  534. if (mEditorShapeInst->getCurrentDetail() < 0)
  535. return;
  536. BaseMatInstance* probePrevMat = mEditorShapeInst->getMaterialList()->getMaterialInst(0);
  537. setPreviewMatParameters(state, probePrevMat);
  538. // GFXTransformSaver is a handy helper class that restores
  539. // the current GFX matrices to their original values when
  540. // it goes out of scope at the end of the function
  541. // Set up our TS render state
  542. TSRenderState rdata;
  543. rdata.setSceneState(state);
  544. rdata.setFadeOverride(1.0f);
  545. if(mReflectionModeType != DynamicCubemap)
  546. rdata.setCubemap(mPrefilterMap->mCubemap);
  547. else
  548. rdata.setCubemap(mDynamicCubemap);
  549. // We might have some forward lit materials
  550. // so pass down a query to gather lights.
  551. LightQuery query;
  552. query.init(getWorldSphere());
  553. rdata.setLightQuery(&query);
  554. // Set the world matrix to the objects render transform
  555. MatrixF mat = getRenderTransform();
  556. mat.scale(Point3F(1, 1, 1));
  557. Point3F centerPos = mat.getPosition();
  558. centerPos += mProbePosOffset;
  559. mat.setPosition(centerPos);
  560. GFX->setWorldMatrix(mat);
  561. // Animate the the shape
  562. mEditorShapeInst->animate();
  563. // Allow the shape to submit the RenderInst(s) for itself
  564. mEditorShapeInst->render(rdata);
  565. saver.restore();
  566. }
  567. // If the light is selected or light visualization
  568. // is enabled then register the callback.
  569. const bool isSelectedInEditor = (gEditingMission && isSelected());
  570. if (isSelectedInEditor)
  571. {
  572. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  573. ri->renderDelegate.bind(this, &ReflectionProbe::_onRenderViz);
  574. ri->type = RenderPassManager::RIT_Editor;
  575. state->getRenderPass()->addInst(ri);
  576. }
  577. }
  578. void ReflectionProbe::_onRenderViz(ObjectRenderInst *ri,
  579. SceneRenderState *state,
  580. BaseMatInstance *overrideMat)
  581. {
  582. if (!ProbeManager::smRenderReflectionProbes)
  583. return;
  584. GFXDrawUtil *draw = GFX->getDrawUtil();
  585. GFXStateBlockDesc desc;
  586. desc.setZReadWrite(true, false);
  587. desc.setCullMode(GFXCullNone);
  588. desc.setBlend(true);
  589. // Base the sphere color on the light color.
  590. ColorI color = ColorI::WHITE;
  591. color.alpha = 25;
  592. if (mProbeShapeType == ProbeRenderInst::Sphere)
  593. {
  594. draw->drawSphere(desc, mRadius, getPosition(), color);
  595. }
  596. else
  597. {
  598. const MatrixF worldToObjectXfm = getTransform();
  599. Box3F cube(-Point3F(mRadius, mRadius, mRadius),Point3F(mRadius, mRadius, mRadius));
  600. cube.setCenter(getPosition()+mProbePosOffset);
  601. draw->drawCube(desc, cube, color, &worldToObjectXfm);
  602. }
  603. }
  604. void ReflectionProbe::setPreviewMatParameters(SceneRenderState* renderState, BaseMatInstance* mat)
  605. {
  606. if (!mat->getFeatures().hasFeature(MFT_isDeferred))
  607. return;
  608. //Set up the params
  609. MaterialParameters *matParams = mat->getMaterialParameters();
  610. //Get the deferred render target
  611. NamedTexTarget* deferredTexTarget = NamedTexTarget::find("deferred");
  612. GFXTextureObject *deferredTexObject = deferredTexTarget->getTexture();
  613. if (!deferredTexObject)
  614. return;
  615. GFX->setTexture(0, deferredTexObject);
  616. //Set the cubemap
  617. GFX->setCubeTexture(1, mPrefilterMap->mCubemap);
  618. //Set the invViewMat
  619. MatrixSet &matrixSet = renderState->getRenderPass()->getMatrixSet();
  620. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  621. MaterialParameterHandle *invViewMat = mat->getMaterialParameterHandle("$invViewMat");
  622. matParams->setSafe(invViewMat, worldToCameraXfm);
  623. }
  624. DefineEngineMethod(ReflectionProbe, postApply, void, (), ,
  625. "A utility method for forcing a network update.\n")
  626. {
  627. object->inspectPostApply();
  628. }
  629. String ReflectionProbe::getPrefilterMapPath()
  630. {
  631. if (mReflectionPath.isEmpty() || mProbeUniqueID.isEmpty())
  632. {
  633. Con::errorf("ReflectionProbe::getPrefilterMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  634. return "";
  635. }
  636. char fileName[256];
  637. dSprintf(fileName, 256, "%s%s_Prefilter.DDS", mReflectionPath.c_str(), mProbeUniqueID.c_str());
  638. return fileName;
  639. }
  640. String ReflectionProbe::getIrradianceMapPath()
  641. {
  642. if (mReflectionPath.isEmpty() || mProbeUniqueID.isEmpty())
  643. {
  644. Con::errorf("ReflectionProbe::getIrradianceMapPath() - We don't have a set output path or persistant id, so no valid path can be provided!");
  645. return "";
  646. }
  647. char fileName[256];
  648. dSprintf(fileName, 256, "%s%s_Irradiance.DDS", mReflectionPath.c_str(), mProbeUniqueID.c_str());
  649. return fileName;
  650. }
  651. void ReflectionProbe::bake(String outputPath, S32 resolution, bool renderWithProbes)
  652. {
  653. GFXDEBUGEVENT_SCOPE(ReflectionProbe_Bake, ColorI::WHITE);
  654. Con::warnf("ReflectionProbe::bake() - Beginning bake!");
  655. U32 startMSTime = Platform::getRealMilliseconds();
  656. /*PostEffect *preCapture = dynamic_cast<PostEffect*>(Sim::findObject("AL_PreCapture"));
  657. PostEffect *deferredShading = dynamic_cast<PostEffect*>(Sim::findObject("AL_DeferredShading"));
  658. if (preCapture)
  659. {
  660. preCapture->setShaderConst("$radius",String::ToString(mRadius));
  661. preCapture->setShaderConst("$captureRez", String::ToString(F32(resolution)));
  662. preCapture->enable();
  663. }
  664. if (deferredShading)
  665. deferredShading->disable();*/
  666. GFXCubemapHandle sceneCaptureCubemap;
  667. if (mReflectionModeType == DynamicCubemap && mDynamicCubemap.isNull())
  668. {
  669. //mCubemap->createMap();
  670. mDynamicCubemap = GFX->createCubemap();
  671. if(mUseHDRCaptures)
  672. mDynamicCubemap->initDynamic(resolution, GFXFormatR16G16B16A16);
  673. else
  674. mDynamicCubemap->initDynamic(resolution, GFXFormatB8G8R8A8);
  675. sceneCaptureCubemap = mDynamicCubemap;
  676. }
  677. else if (mReflectionModeType != DynamicCubemap)
  678. {
  679. //Prep our bake path
  680. if (mReflectionPath.isEmpty())
  681. {
  682. Con::errorf("ReflectionProbe::bake() - Unable to bake our captures because probe doesn't have a path set");
  683. return;
  684. }
  685. if (mProbeUniqueID.isEmpty())
  686. {
  687. Con::errorf("ReflectionProbe::bake() - Unable to bake our captures because probe doesn't have a unique ID set");
  688. return;
  689. }
  690. sceneCaptureCubemap = GFX->createCubemap();
  691. if (mUseHDRCaptures)
  692. sceneCaptureCubemap->initDynamic(resolution, GFXFormatR16G16B16A16F);
  693. else
  694. sceneCaptureCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  695. }
  696. bool validCubemap = true;
  697. // Save the current transforms so we can restore
  698. // it for child control rendering below.
  699. GFXTransformSaver saver;
  700. //bool saveEditingMission = gEditingMission;
  701. //gEditingMission = false;
  702. //Set this to true to use the prior method where it goes through the SPT_Reflect path for the bake
  703. bool probeRenderState = ProbeManager::smRenderReflectionProbes;
  704. if (!renderWithProbes)
  705. ProbeManager::smRenderReflectionProbes = false;
  706. for (U32 i = 0; i < 6; ++i)
  707. {
  708. GFXTexHandle blendTex;
  709. blendTex.set(resolution, resolution, GFXFormatR16G16B16A16, &GFXRenderTargetProfile, "");
  710. GFXTextureTargetRef baseTarget = GFX->allocRenderToTextureTarget();
  711. GFX->clearTextureStateImmediate(0);
  712. baseTarget->attachTexture(GFXTextureTarget::Color0, sceneCaptureCubemap, i);
  713. // Standard view that will be overridden below.
  714. VectorF vLookatPt(0.0f, 0.0f, 0.0f), vUpVec(0.0f, 0.0f, 0.0f), vRight(0.0f, 0.0f, 0.0f);
  715. switch (i)
  716. {
  717. case 0: // D3DCUBEMAP_FACE_POSITIVE_X:
  718. vLookatPt = VectorF(1.0f, 0.0f, 0.0f);
  719. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  720. break;
  721. case 1: // D3DCUBEMAP_FACE_NEGATIVE_X:
  722. vLookatPt = VectorF(-1.0f, 0.0f, 0.0f);
  723. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  724. break;
  725. case 2: // D3DCUBEMAP_FACE_POSITIVE_Y:
  726. vLookatPt = VectorF(0.0f, 1.0f, 0.0f);
  727. vUpVec = VectorF(0.0f, 0.0f, -1.0f);
  728. break;
  729. case 3: // D3DCUBEMAP_FACE_NEGATIVE_Y:
  730. vLookatPt = VectorF(0.0f, -1.0f, 0.0f);
  731. vUpVec = VectorF(0.0f, 0.0f, 1.0f);
  732. break;
  733. case 4: // D3DCUBEMAP_FACE_POSITIVE_Z:
  734. vLookatPt = VectorF(0.0f, 0.0f, 1.0f);
  735. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  736. break;
  737. case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
  738. vLookatPt = VectorF(0.0f, 0.0f, -1.0f);
  739. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  740. break;
  741. }
  742. // create camera matrix
  743. VectorF cross = mCross(vUpVec, vLookatPt);
  744. cross.normalizeSafe();
  745. MatrixF matView(true);
  746. matView.setColumn(0, cross);
  747. matView.setColumn(1, vLookatPt);
  748. matView.setColumn(2, vUpVec);
  749. matView.setPosition(getPosition()+mProbePosOffset);
  750. matView.inverse();
  751. // set projection to 90 degrees vertical and horizontal
  752. F32 left, right, top, bottom;
  753. F32 nearPlane = 0.01f;
  754. F32 farDist = 1000.f;
  755. MathUtils::makeFrustum(&left, &right, &top, &bottom, M_HALFPI_F, 1.0f, nearPlane);
  756. Frustum frustum(false, left, right, top, bottom, nearPlane, farDist);
  757. renderFrame(&baseTarget, matView, frustum, StaticObjectType | StaticShapeObjectType & EDITOR_RENDER_TYPEMASK, gCanvasClearColor);
  758. baseTarget->resolve();
  759. }
  760. if (sceneCaptureCubemap.isValid())
  761. {
  762. validCubemap = true;
  763. mDirty = false;
  764. }
  765. else
  766. {
  767. validCubemap = false;
  768. }
  769. //Now, save out the maps
  770. //create irridiance cubemap
  771. if (validCubemap)
  772. {
  773. bool se = isServerObject();
  774. //Just to ensure we're prepped for the generation
  775. createClientResources();
  776. //Prep it with whatever resolution we've dictated for our bake
  777. if (mUseHDRCaptures)
  778. {
  779. mIrridianceMap->mCubemap->initDynamic(resolution, GFXFormatR16G16B16A16);
  780. mPrefilterMap->mCubemap->initDynamic(resolution, GFXFormatR16G16B16A16);
  781. }
  782. else
  783. {
  784. mIrridianceMap->mCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  785. mPrefilterMap->mCubemap->initDynamic(resolution, GFXFormatR8G8B8A8);
  786. }
  787. //IBLUtilities::GenerateAndSaveIrradianceMap(getIrradianceMapPath(), resolution, sceneCaptureCubemap, mIrridianceMap->mCubemap);
  788. //IBLUtilities::GenerateAndSavePrefilterMap(getPrefilterMapPath(), resolution, sceneCaptureCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  789. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  790. IBLUtilities::GenerateIrradianceMap(renderTarget, sceneCaptureCubemap, mIrridianceMap->mCubemap);
  791. IBLUtilities::GeneratePrefilterMap(renderTarget, sceneCaptureCubemap, mPrefilterMipLevels, mPrefilterMap->mCubemap);
  792. //We can't save HDR captures at the moment
  793. if (!mUseHDRCaptures)
  794. {
  795. IBLUtilities::SaveCubeMap(getIrradianceMapPath(), mIrridianceMap->mCubemap);
  796. IBLUtilities::SaveCubeMap(getPrefilterMapPath(), mPrefilterMap->mCubemap);
  797. }
  798. }
  799. else
  800. {
  801. Con::errorf("ReflectionProbe::bake() - Didn't generate a valid scene capture cubemap, unable to generate prefilter and irradiance maps!");
  802. }
  803. if(!renderWithProbes)
  804. ProbeManager::smRenderReflectionProbes = probeRenderState;
  805. setMaskBits(-1);
  806. /*if (preCapture)
  807. preCapture->disable();
  808. if (deferredShading)
  809. deferredShading->enable();*/
  810. U32 endMSTime = Platform::getRealMilliseconds();
  811. F32 diffTime = F32(endMSTime - startMSTime);
  812. Con::warnf("ReflectionProbe::bake() - Finished bake! Took %g milliseconds", diffTime);
  813. }
  814. DefineEngineMethod(ReflectionProbe, Bake, void, (String outputPath, S32 resolution, bool renderWithProbes), ("", 64, false),
  815. "@brief returns true if control object is inside the fog\n\n.")
  816. {
  817. ReflectionProbe *clientProbe = (ReflectionProbe*)object->getClientObject();
  818. if (clientProbe)
  819. {
  820. clientProbe->bake(outputPath, resolution, renderWithProbes);
  821. }
  822. //object->bake(outputPath, resolution);
  823. }