IBLUtilities.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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/IBLUtilities.h"
  23. #include "console/engineAPI.h"
  24. #include "materials/shaderData.h"
  25. #include "gfx/gfxTextureManager.h"
  26. #include "gfx/gfxTransformSaver.h"
  27. #include "gfx/bitmap/cubemapSaver.h"
  28. #include "core/stream/fileStream.h"
  29. #include "gfx/bitmap/imageUtils.h"
  30. namespace IBLUtilities
  31. {
  32. void GenerateIrradianceMap(GFXTextureTargetRef renderTarget, GFXCubemapHandle cubemap, GFXCubemapHandle &cubemapOut)
  33. {
  34. GFXTransformSaver saver;
  35. GFXStateBlockRef irrStateBlock;
  36. ShaderData *irrShaderData;
  37. GFXShaderRef irrShader = Sim::findObject("IrradianceShader", irrShaderData) ? irrShaderData->getShader() : NULL;
  38. if (!irrShader)
  39. {
  40. Con::errorf("IBLUtilities::GenerateIrradianceMap() - could not find IrradianceShader");
  41. return;
  42. }
  43. GFXShaderConstBufferRef irrConsts = irrShader->allocConstBuffer();
  44. GFXShaderConstHandle* irrEnvMapSC = irrShader->getShaderConstHandle("$environmentMap");
  45. GFXShaderConstHandle* irrFaceSC = irrShader->getShaderConstHandle("$face");
  46. GFXStateBlockDesc desc;
  47. desc.zEnable = false;
  48. desc.samplersDefined = true;
  49. desc.samplers[0].addressModeU = GFXAddressClamp;
  50. desc.samplers[0].addressModeV = GFXAddressClamp;
  51. desc.samplers[0].addressModeW = GFXAddressClamp;
  52. desc.samplers[0].magFilter = GFXTextureFilterLinear;
  53. desc.samplers[0].minFilter = GFXTextureFilterLinear;
  54. desc.samplers[0].mipFilter = GFXTextureFilterLinear;
  55. irrStateBlock = GFX->createStateBlock(desc);
  56. GFX->pushActiveRenderTarget();
  57. GFX->setShader(irrShader);
  58. GFX->setShaderConstBuffer(irrConsts);
  59. GFX->setStateBlock(irrStateBlock);
  60. GFX->setVertexBuffer(NULL);
  61. GFX->setCubeTexture(0, cubemap);
  62. for (U32 i = 0; i < 6; i++)
  63. {
  64. renderTarget->attachTexture(GFXTextureTarget::Color0, cubemapOut, i);
  65. irrConsts->setSafe(irrFaceSC, (S32)i);
  66. GFX->setActiveRenderTarget(renderTarget);
  67. GFX->clear(GFXClearTarget, LinearColorF::BLACK, 1.0f, 0);
  68. GFX->drawPrimitive(GFXTriangleList, 0, 1);
  69. renderTarget->resolve();
  70. }
  71. GFX->popActiveRenderTarget();
  72. }
  73. void GenerateAndSaveIrradianceMap(String outputPath, S32 resolution, GFXCubemapHandle cubemap, GFXCubemapHandle &cubemapOut)
  74. {
  75. if (outputPath.isEmpty())
  76. {
  77. Con::errorf("IBLUtilities::GenerateAndSaveIrradianceMap - Cannot save to an empty path!");
  78. return;
  79. }
  80. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  81. IBLUtilities::GenerateIrradianceMap(renderTarget, cubemap, cubemapOut);
  82. //Write it out
  83. CubemapSaver::save(cubemapOut, outputPath);
  84. if (!Platform::isFile(outputPath))
  85. {
  86. Con::errorf("IBLUtilities::GenerateAndSaveIrradianceMap - Failed to properly save out the baked irradiance!");
  87. }
  88. }
  89. void SaveCubeMap(String outputPath, GFXCubemapHandle &cubemap)
  90. {
  91. if (outputPath.isEmpty())
  92. {
  93. Con::errorf("IBLUtilities::SaveCubeMap - Cannot save to an empty path!");
  94. return;
  95. }
  96. //Write it out
  97. CubemapSaver::save(cubemap, outputPath);
  98. if (!Platform::isFile(outputPath))
  99. {
  100. Con::errorf("IBLUtilities::SaveCubeMap - Failed to properly save out the baked irradiance!");
  101. }
  102. }
  103. void GeneratePrefilterMap(GFXTextureTargetRef renderTarget, GFXCubemapHandle cubemap, U32 mipLevels, GFXCubemapHandle &cubemapOut)
  104. {
  105. GFXTransformSaver saver;
  106. ShaderData *prefilterShaderData;
  107. GFXShaderRef prefilterShader = Sim::findObject("PrefiterCubemapShader", prefilterShaderData) ? prefilterShaderData->getShader() : NULL;
  108. if (!prefilterShader)
  109. {
  110. Con::errorf("IBLUtilities::GeneratePrefilterMap() - could not find PrefiterCubemapShader");
  111. return;
  112. }
  113. GFXShaderConstBufferRef prefilterConsts = prefilterShader->allocConstBuffer();
  114. GFXShaderConstHandle* prefilterEnvMapSC = prefilterShader->getShaderConstHandle("$environmentMap");
  115. GFXShaderConstHandle* prefilterFaceSC = prefilterShader->getShaderConstHandle("$face");
  116. GFXShaderConstHandle* prefilterRoughnessSC = prefilterShader->getShaderConstHandle("$roughness");
  117. GFXShaderConstHandle* prefilterMipSizeSC = prefilterShader->getShaderConstHandle("$mipSize");
  118. GFXShaderConstHandle* prefilterResolutionSC = prefilterShader->getShaderConstHandle("$resolution");
  119. GFXStateBlockDesc desc;
  120. desc.zEnable = false;
  121. desc.samplersDefined = true;
  122. desc.samplers[0].addressModeU = GFXAddressClamp;
  123. desc.samplers[0].addressModeV = GFXAddressClamp;
  124. desc.samplers[0].addressModeW = GFXAddressClamp;
  125. desc.samplers[0].magFilter = GFXTextureFilterLinear;
  126. desc.samplers[0].minFilter = GFXTextureFilterLinear;
  127. desc.samplers[0].mipFilter = GFXTextureFilterLinear;
  128. GFXStateBlockRef preStateBlock;
  129. preStateBlock = GFX->createStateBlock(desc);
  130. GFX->setStateBlock(preStateBlock);
  131. GFX->pushActiveRenderTarget();
  132. GFX->setShader(prefilterShader);
  133. GFX->setShaderConstBuffer(prefilterConsts);
  134. GFX->setCubeTexture(0, cubemap);
  135. U32 prefilterSize = cubemapOut->getSize();
  136. U32 resolutionSize = prefilterSize;
  137. for (U32 face = 0; face < 6; face++)
  138. {
  139. prefilterConsts->setSafe(prefilterFaceSC, (S32)face);
  140. prefilterConsts->setSafe(prefilterResolutionSC, (S32)resolutionSize);
  141. for (U32 mip = 0; mip < mipLevels; mip++)
  142. {
  143. S32 mipSize = prefilterSize >> mip;
  144. F32 roughness = (float)mip / (float)(mipLevels - 1);
  145. prefilterConsts->setSafe(prefilterRoughnessSC, roughness);
  146. prefilterConsts->setSafe(prefilterMipSizeSC, mipSize);
  147. U32 size = prefilterSize * mPow(0.5f, mip);
  148. renderTarget->attachTexture(GFXTextureTarget::Color0, cubemapOut, face, mip);
  149. GFX->setActiveRenderTarget(renderTarget, false);//we set the viewport ourselves
  150. GFX->setViewport(RectI(0, 0, size, size));
  151. GFX->clear(GFXClearTarget, LinearColorF::BLACK, 1.0f, 0);
  152. GFX->drawPrimitive(GFXTriangleList, 0, 1);
  153. renderTarget->resolve();
  154. }
  155. }
  156. GFX->popActiveRenderTarget();
  157. }
  158. void GenerateAndSavePrefilterMap(String outputPath, S32 resolution, GFXCubemapHandle cubemap, U32 mipLevels, GFXCubemapHandle &cubemapOut)
  159. {
  160. if (outputPath.isEmpty())
  161. {
  162. Con::errorf("IBLUtilities::GenerateAndSavePrefilterMap - Cannot save to an empty path!");
  163. return;
  164. }
  165. GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(false);
  166. IBLUtilities::GeneratePrefilterMap(renderTarget, cubemap, mipLevels, cubemapOut);
  167. //Write it out
  168. CubemapSaver::save(cubemapOut, outputPath);
  169. if (!Platform::isFile(outputPath))
  170. {
  171. Con::errorf("IBLUtilities::GenerateAndSavePrefilterMap - Failed to properly save out the baked irradiance!");
  172. }
  173. }
  174. void bakeReflection(String outputPath, S32 resolution)
  175. {
  176. //GFXDEBUGEVENT_SCOPE(ReflectionProbe_Bake, ColorI::WHITE);
  177. /*PostEffect *preCapture = dynamic_cast<PostEffect*>(Sim::findObject("AL_PreCapture"));
  178. PostEffect *deferredShading = dynamic_cast<PostEffect*>(Sim::findObject("AL_DeferredShading"));
  179. if (preCapture)
  180. preCapture->enable();
  181. if (deferredShading)
  182. deferredShading->disable();
  183. //if (mReflectionModeType == StaticCubemap || mReflectionModeType == BakedCubemap || mReflectionModeType == SkyLight)
  184. {
  185. if (!mCubemap)
  186. {
  187. mCubemap = new CubemapData();
  188. mCubemap->registerObject();
  189. }
  190. }
  191. if (mReflectionModeType == DynamicCubemap && mDynamicCubemap.isNull())
  192. {
  193. //mCubemap->createMap();
  194. mDynamicCubemap = GFX->createCubemap();
  195. mDynamicCubemap->initDynamic(resolution, GFXFormatR8G8B8);
  196. }
  197. else if (mReflectionModeType != DynamicCubemap)
  198. {
  199. if (mReflectionPath.isEmpty() || !mPersistentId)
  200. {
  201. if (!mPersistentId)
  202. mPersistentId = getOrCreatePersistentId();
  203. mReflectionPath = outputPath.c_str();
  204. mProbeUniqueID = std::to_string(mPersistentId->getUUID().getHash()).c_str();
  205. }
  206. }
  207. bool validCubemap = true;
  208. // Save the current transforms so we can restore
  209. // it for child control rendering below.
  210. GFXTransformSaver saver;
  211. //bool saveEditingMission = gEditingMission;
  212. //gEditingMission = false;
  213. //Set this to true to use the prior method where it goes through the SPT_Reflect path for the bake
  214. bool probeRenderState = ReflectionProbe::smRenderReflectionProbes;
  215. ReflectionProbe::smRenderReflectionProbes = false;
  216. for (U32 i = 0; i < 6; ++i)
  217. {
  218. GFXTexHandle blendTex;
  219. blendTex.set(resolution, resolution, GFXFormatR8G8B8A8, &GFXRenderTargetProfile, "");
  220. GFXTextureTargetRef mBaseTarget = GFX->allocRenderToTextureTarget();
  221. GFX->clearTextureStateImmediate(0);
  222. if (mReflectionModeType == DynamicCubemap)
  223. mBaseTarget->attachTexture(GFXTextureTarget::Color0, mDynamicCubemap, i);
  224. else
  225. mBaseTarget->attachTexture(GFXTextureTarget::Color0, blendTex);
  226. // Standard view that will be overridden below.
  227. VectorF vLookatPt(0.0f, 0.0f, 0.0f), vUpVec(0.0f, 0.0f, 0.0f), vRight(0.0f, 0.0f, 0.0f);
  228. switch (i)
  229. {
  230. case 0: // D3DCUBEMAP_FACE_POSITIVE_X:
  231. vLookatPt = VectorF(1.0f, 0.0f, 0.0f);
  232. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  233. break;
  234. case 1: // D3DCUBEMAP_FACE_NEGATIVE_X:
  235. vLookatPt = VectorF(-1.0f, 0.0f, 0.0f);
  236. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  237. break;
  238. case 2: // D3DCUBEMAP_FACE_POSITIVE_Y:
  239. vLookatPt = VectorF(0.0f, 1.0f, 0.0f);
  240. vUpVec = VectorF(0.0f, 0.0f, -1.0f);
  241. break;
  242. case 3: // D3DCUBEMAP_FACE_NEGATIVE_Y:
  243. vLookatPt = VectorF(0.0f, -1.0f, 0.0f);
  244. vUpVec = VectorF(0.0f, 0.0f, 1.0f);
  245. break;
  246. case 4: // D3DCUBEMAP_FACE_POSITIVE_Z:
  247. vLookatPt = VectorF(0.0f, 0.0f, 1.0f);
  248. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  249. break;
  250. case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
  251. vLookatPt = VectorF(0.0f, 0.0f, -1.0f);
  252. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  253. break;
  254. }
  255. // create camera matrix
  256. VectorF cross = mCross(vUpVec, vLookatPt);
  257. cross.normalizeSafe();
  258. MatrixF matView(true);
  259. matView.setColumn(0, cross);
  260. matView.setColumn(1, vLookatPt);
  261. matView.setColumn(2, vUpVec);
  262. matView.setPosition(getPosition());
  263. matView.inverse();
  264. // set projection to 90 degrees vertical and horizontal
  265. F32 left, right, top, bottom;
  266. F32 nearPlane = 0.01f;
  267. F32 farDist = 1000.f;
  268. MathUtils::makeFrustum(&left, &right, &top, &bottom, M_HALFPI_F, 1.0f, nearPlane);
  269. Frustum frustum(false, left, right, top, bottom, nearPlane, farDist);
  270. renderFrame(&mBaseTarget, matView, frustum, StaticObjectType | StaticShapeObjectType & EDITOR_RENDER_TYPEMASK, gCanvasClearColor);
  271. mBaseTarget->resolve();
  272. mCubemap->setCubeFaceTexture(i, blendTex);
  273. }
  274. if (mReflectionModeType != DynamicCubemap && validCubemap)
  275. {
  276. if (mCubemap->mCubemap)
  277. mCubemap->updateFaces();
  278. else
  279. mCubemap->createMap();
  280. char fileName[256];
  281. dSprintf(fileName, 256, "%s%s.DDS", mReflectionPath.c_str(), mProbeUniqueID.c_str());
  282. CubemapSaver::save(mCubemap->mCubemap, fileName);
  283. if (!Platform::isFile(fileName))
  284. {
  285. validCubemap = false; //if we didn't save right, just
  286. Con::errorf("Failed to properly save out the skylight baked cubemap!");
  287. }
  288. mDirty = false;
  289. }
  290. //calculateSHTerms();
  291. ReflectionProbe::smRenderReflectionProbes = probeRenderState;
  292. setMaskBits(-1);
  293. if (preCapture)
  294. preCapture->disable();
  295. if (deferredShading)
  296. deferredShading->enable();*/
  297. }
  298. LinearColorF decodeSH(Point3F normal, const LinearColorF SHTerms[9], const F32 SHConstants[5])
  299. {
  300. float x = normal.x;
  301. float y = normal.y;
  302. float z = normal.z;
  303. LinearColorF l00 = SHTerms[0];
  304. LinearColorF l10 = SHTerms[1];
  305. LinearColorF l11 = SHTerms[2];
  306. LinearColorF l12 = SHTerms[3];
  307. LinearColorF l20 = SHTerms[4];
  308. LinearColorF l21 = SHTerms[5];
  309. LinearColorF l22 = SHTerms[6];
  310. LinearColorF l23 = SHTerms[7];
  311. LinearColorF l24 = SHTerms[8];
  312. LinearColorF result = (
  313. l00 * SHConstants[0] +
  314. l12 * SHConstants[1] * x +
  315. l10 * SHConstants[1] * y +
  316. l11 * SHConstants[1] * z +
  317. l20 * SHConstants[2] * x*y +
  318. l21 * SHConstants[2] * y*z +
  319. l22 * SHConstants[3] * (3.0*z*z - 1.0) +
  320. l23 * SHConstants[2] * x*z +
  321. l24 * SHConstants[4] * (x*x - y * y)
  322. );
  323. return LinearColorF(mMax(result.red, 0), mMax(result.green, 0), mMax(result.blue, 0));
  324. }
  325. MatrixF getSideMatrix(U32 side)
  326. {
  327. // Standard view that will be overridden below.
  328. VectorF vLookatPt(0.0f, 0.0f, 0.0f), vUpVec(0.0f, 0.0f, 0.0f), vRight(0.0f, 0.0f, 0.0f);
  329. switch (side)
  330. {
  331. case 0: // D3DCUBEMAP_FACE_POSITIVE_X:
  332. vLookatPt = VectorF(1.0f, 0.0f, 0.0f);
  333. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  334. break;
  335. case 1: // D3DCUBEMAP_FACE_NEGATIVE_X:
  336. vLookatPt = VectorF(-1.0f, 0.0f, 0.0f);
  337. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  338. break;
  339. case 2: // D3DCUBEMAP_FACE_POSITIVE_Y:
  340. vLookatPt = VectorF(0.0f, 1.0f, 0.0f);
  341. vUpVec = VectorF(0.0f, 0.0f, -1.0f);
  342. break;
  343. case 3: // D3DCUBEMAP_FACE_NEGATIVE_Y:
  344. vLookatPt = VectorF(0.0f, -1.0f, 0.0f);
  345. vUpVec = VectorF(0.0f, 0.0f, 1.0f);
  346. break;
  347. case 4: // D3DCUBEMAP_FACE_POSITIVE_Z:
  348. vLookatPt = VectorF(0.0f, 0.0f, 1.0f);
  349. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  350. break;
  351. case 5: // D3DCUBEMAP_FACE_NEGATIVE_Z:
  352. vLookatPt = VectorF(0.0f, 0.0f, -1.0f);
  353. vUpVec = VectorF(0.0f, 1.0f, 0.0f);
  354. break;
  355. }
  356. // create camera matrix
  357. VectorF cross = mCross(vUpVec, vLookatPt);
  358. cross.normalizeSafe();
  359. MatrixF rotMat(true);
  360. rotMat.setColumn(0, cross);
  361. rotMat.setColumn(1, vLookatPt);
  362. rotMat.setColumn(2, vUpVec);
  363. //rotMat.inverse();
  364. return rotMat;
  365. }
  366. F32 harmonics(U32 termId, Point3F normal)
  367. {
  368. F32 x = normal.x;
  369. F32 y = normal.y;
  370. F32 z = normal.z;
  371. switch (termId)
  372. {
  373. case 0:
  374. return 1.0;
  375. case 1:
  376. return y;
  377. case 2:
  378. return z;
  379. case 3:
  380. return x;
  381. case 4:
  382. return x * y;
  383. case 5:
  384. return y * z;
  385. case 6:
  386. return 3.0*z*z - 1.0;
  387. case 7:
  388. return x * z;
  389. default:
  390. return x * x - y * y;
  391. }
  392. }
  393. LinearColorF sampleSide(GBitmap* cubeFaceBitmaps[6], const U32& cubemapResolution, const U32& termindex, const U32& sideIndex)
  394. {
  395. MatrixF sideRot = getSideMatrix(sideIndex);
  396. LinearColorF result = LinearColorF::ZERO;
  397. F32 divider = 0;
  398. for (int y = 0; y<cubemapResolution; y++)
  399. {
  400. for (int x = 0; x<cubemapResolution; x++)
  401. {
  402. Point2F sidecoord = ((Point2F(x, y) + Point2F(0.5, 0.5)) / Point2F(cubemapResolution, cubemapResolution))*2.0 - Point2F(1.0, 1.0);
  403. Point3F normal = Point3F(sidecoord.x, sidecoord.y, -1.0);
  404. normal.normalize();
  405. F32 minBrightness = Con::getFloatVariable("$pref::GI::Cubemap_Sample_MinBrightness", 0.001f);
  406. LinearColorF texel = cubeFaceBitmaps[sideIndex]->sampleTexel(y, x);
  407. texel = LinearColorF(mMax(texel.red, minBrightness), mMax(texel.green, minBrightness), mMax(texel.blue, minBrightness)) * Con::getFloatVariable("$pref::GI::Cubemap_Gain", 1.5);
  408. Point3F dir;
  409. sideRot.mulP(normal, &dir);
  410. result += texel * harmonics(termindex, dir) * -normal.z;
  411. divider += -normal.z;
  412. }
  413. }
  414. result /= divider;
  415. return result;
  416. }
  417. //
  418. //SH Calculations
  419. // From http://sunandblackcat.com/tipFullView.php?l=eng&topicid=32&topic=Spherical-Harmonics-From-Cube-Texture
  420. // With shader decode logic from https://github.com/nicknikolov/cubemap-sh
  421. void calculateSHTerms(GFXCubemapHandle cubemap, LinearColorF SHTerms[9], F32 SHConstants[5])
  422. {
  423. if (!cubemap)
  424. return;
  425. const VectorF cubemapFaceNormals[6] =
  426. {
  427. // D3DCUBEMAP_FACE_POSITIVE_X:
  428. VectorF(1.0f, 0.0f, 0.0f),
  429. // D3DCUBEMAP_FACE_NEGATIVE_X:
  430. VectorF(-1.0f, 0.0f, 0.0f),
  431. // D3DCUBEMAP_FACE_POSITIVE_Y:
  432. VectorF(0.0f, 1.0f, 0.0f),
  433. // D3DCUBEMAP_FACE_NEGATIVE_Y:
  434. VectorF(0.0f, -1.0f, 0.0f),
  435. // D3DCUBEMAP_FACE_POSITIVE_Z:
  436. VectorF(0.0f, 0.0f, 1.0f),
  437. // D3DCUBEMAP_FACE_NEGATIVE_Z:
  438. VectorF(0.0f, 0.0f, -1.0f),
  439. };
  440. U32 cubemapResolution = cubemap->getSize();
  441. GBitmap* cubeFaceBitmaps[6];
  442. for (U32 i = 0; i < 6; i++)
  443. {
  444. cubeFaceBitmaps[i] = new GBitmap(cubemapResolution, cubemapResolution, false, GFXFormatR16G16B16A16F);
  445. }
  446. //If we fail to parse the cubemap for whatever reason, we really can't continue
  447. if (!CubemapSaver::getBitmaps(cubemap, GFXFormatR8G8B8A8, cubeFaceBitmaps))
  448. return;
  449. //Set up our constants
  450. F32 L0 = Con::getFloatVariable("$pref::GI::SH_Term_L0", 1.0f);
  451. F32 L1 = Con::getFloatVariable("$pref::GI::SH_Term_L1", 1.8f);
  452. F32 L2 = Con::getFloatVariable("$pref::GI::SH_Term_L2", 0.83f);
  453. F32 L2m2_L2m1_L21 = Con::getFloatVariable("$pref::GI::SH_Term_L2m2", 2.9f);
  454. F32 L20 = Con::getFloatVariable("$pref::GI::SH_Term_L20", 0.58f);
  455. F32 L22 = Con::getFloatVariable("$pref::GI::SH_Term_L22", 1.1f);
  456. SHConstants[0] = L0;
  457. SHConstants[1] = L1;
  458. SHConstants[2] = L2 * L2m2_L2m1_L21;
  459. SHConstants[3] = L2 * L20;
  460. SHConstants[4] = L2 * L22;
  461. for (U32 i = 0; i < 9; i++)
  462. {
  463. //Clear it, just to be sure
  464. SHTerms[i] = LinearColorF(0.f, 0.f, 0.f);
  465. //Now, encode for each side
  466. SHTerms[i] = sampleSide(cubeFaceBitmaps, cubemapResolution, i, 0); //POS_X
  467. SHTerms[i] += sampleSide(cubeFaceBitmaps, cubemapResolution, i, 1); //NEG_X
  468. SHTerms[i] += sampleSide(cubeFaceBitmaps, cubemapResolution, i, 2); //POS_Y
  469. SHTerms[i] += sampleSide(cubeFaceBitmaps, cubemapResolution, i, 3); //NEG_Y
  470. SHTerms[i] += sampleSide(cubeFaceBitmaps, cubemapResolution, i, 4); //POS_Z
  471. SHTerms[i] += sampleSide(cubeFaceBitmaps, cubemapResolution, i, 5); //NEG_Z
  472. //Average
  473. SHTerms[i] /= 6;
  474. }
  475. for (U32 i = 0; i < 6; i++)
  476. SAFE_DELETE(cubeFaceBitmaps[i]);
  477. /*bool mExportSHTerms = false;
  478. if (mExportSHTerms)
  479. {
  480. for (U32 f = 0; f < 6; f++)
  481. {
  482. char fileName[256];
  483. dSprintf(fileName, 256, "%s%s_DecodedFaces_%d.png", mReflectionPath.c_str(),
  484. mProbeUniqueID.c_str(), f);
  485. LinearColorF color = decodeSH(cubemapFaceNormals[f]);
  486. FileStream stream;
  487. if (stream.open(fileName, Torque::FS::File::Write))
  488. {
  489. GBitmap bitmap(mCubemapResolution, mCubemapResolution, false, GFXFormatR8G8B8);
  490. bitmap.fill(color.toColorI());
  491. bitmap.writeBitmap("png", stream);
  492. }
  493. }
  494. for (U32 f = 0; f < 9; f++)
  495. {
  496. char fileName[256];
  497. dSprintf(fileName, 256, "%s%s_SHTerms_%d.png", mReflectionPath.c_str(),
  498. mProbeUniqueID.c_str(), f);
  499. LinearColorF color = mProbeInfo->SHTerms[f];
  500. FileStream stream;
  501. if (stream.open(fileName, Torque::FS::File::Write))
  502. {
  503. GBitmap bitmap(mCubemapResolution, mCubemapResolution, false, GFXFormatR8G8B8);
  504. bitmap.fill(color.toColorI());
  505. bitmap.writeBitmap("png", stream);
  506. }
  507. }
  508. }*/
  509. }
  510. F32 areaElement(F32 x, F32 y)
  511. {
  512. return mAtan2(x * y, (F32)mSqrt(x * x + y * y + 1.0));
  513. }
  514. F32 texelSolidAngle(F32 aU, F32 aV, U32 width, U32 height)
  515. {
  516. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  517. // ( 0.5 is for texel center addressing)
  518. const F32 U = (2.0 * (aU + 0.5) / width) - 1.0;
  519. const F32 V = (2.0 * (aV + 0.5) / height) - 1.0;
  520. // shift from a demi texel, mean 1.0 / size with U and V in [-1..1]
  521. const F32 invResolutionW = 1.0 / width;
  522. const F32 invResolutionH = 1.0 / height;
  523. // U and V are the -1..1 texture coordinate on the current face.
  524. // get projected area for this texel
  525. const F32 x0 = U - invResolutionW;
  526. const F32 y0 = V - invResolutionH;
  527. const F32 x1 = U + invResolutionW;
  528. const F32 y1 = V + invResolutionH;
  529. const F32 angle = areaElement(x0, y0) - areaElement(x0, y1) - areaElement(x1, y0) + areaElement(x1, y1);
  530. return angle;
  531. }
  532. };