reflectionProbe.cpp 33 KB

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