reflectionProbe.cpp 32 KB

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