BsLightProbes.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsLightProbes.h"
  4. #include "Renderer/BsLightProbeVolume.h"
  5. #include "RenderAPI/BsGpuBuffer.h"
  6. #include "BsRendererView.h"
  7. #include "BsRenderBeastIBLUtility.h"
  8. #include "Mesh/BsMesh.h"
  9. #include "RenderAPI/BsVertexDataDesc.h"
  10. #include "Material/BsGpuParamsSet.h"
  11. #include "Renderer/BsRendererUtility.h"
  12. #include "Renderer/BsSkybox.h"
  13. #include "BsRendererTextures.h"
  14. namespace bs { namespace ct
  15. {
  16. TetrahedraRenderParamDef gTetrahedraRenderParamDef;
  17. ShaderVariation TetrahedraRenderMat::VAR_FullMSAA = ShaderVariation({
  18. ShaderVariation::Param("MSAA", true)
  19. });
  20. ShaderVariation TetrahedraRenderMat::VAR_SingleMSAA = ShaderVariation({
  21. ShaderVariation::Param("MSAA", true),
  22. ShaderVariation::Param("MSAA_RESOLVE_0TH", true)
  23. });
  24. ShaderVariation TetrahedraRenderMat::VAR_NoMSAA = ShaderVariation();
  25. TetrahedraRenderMat::TetrahedraRenderMat()
  26. {
  27. SPtr<GpuParams> params = mParamsSet->getGpuParams();
  28. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gDepthBufferTex", mDepthBufferTex);
  29. SAMPLER_STATE_DESC pointSampDesc;
  30. pointSampDesc.minFilter = FO_POINT;
  31. pointSampDesc.magFilter = FO_POINT;
  32. pointSampDesc.mipFilter = FO_POINT;
  33. pointSampDesc.addressMode.u = TAM_CLAMP;
  34. pointSampDesc.addressMode.v = TAM_CLAMP;
  35. pointSampDesc.addressMode.w = TAM_CLAMP;
  36. SPtr<SamplerState> pointSampState = SamplerState::create(pointSampDesc);
  37. if(params->hasSamplerState(GPT_FRAGMENT_PROGRAM, "gDepthBufferSamp"))
  38. params->setSamplerState(GPT_FRAGMENT_PROGRAM, "gDepthBufferSamp", pointSampState);
  39. else if(params->hasSamplerState(GPT_FRAGMENT_PROGRAM, "gDepthBufferTex"))
  40. params->setSamplerState(GPT_FRAGMENT_PROGRAM, "gDepthBufferTex", pointSampState);
  41. mParamBuffer = gTetrahedraRenderParamDef.createBuffer();
  42. params->setParamBlockBuffer("Params", mParamBuffer);
  43. }
  44. void TetrahedraRenderMat::_initVariations(ShaderVariations& variations)
  45. {
  46. variations.add(VAR_FullMSAA);
  47. variations.add(VAR_SingleMSAA);
  48. variations.add(VAR_NoMSAA);
  49. }
  50. void TetrahedraRenderMat::execute(const RendererView& view, const SPtr<Texture>& sceneDepth, const SPtr<Mesh>& mesh,
  51. const SPtr<RenderTexture>& output)
  52. {
  53. const TextureProperties& texProps = sceneDepth->getProperties();
  54. Vector2I texSize(texProps.getWidth(), texProps.getHeight());
  55. gTetrahedraRenderParamDef.gDepthTexSize.set(mParamBuffer, texSize);
  56. mDepthBufferTex.set(sceneDepth);
  57. mParamsSet->getGpuParams()->setParamBlockBuffer("PerCamera", view.getPerViewBuffer());
  58. RenderAPI& rapi = RenderAPI::instance();
  59. rapi.setRenderTarget(output);
  60. gRendererUtility().setPass(mMaterial);
  61. gRendererUtility().setPassParams(mParamsSet);
  62. gRendererUtility().draw(mesh);
  63. }
  64. void TetrahedraRenderMat::getOutputDesc(const RendererView& view, POOLED_RENDER_TEXTURE_DESC& colorDesc,
  65. POOLED_RENDER_TEXTURE_DESC& depthDesc)
  66. {
  67. const RendererViewProperties& viewProps = view.getProperties();
  68. UINT32 width = viewProps.viewRect.width;
  69. UINT32 height = viewProps.viewRect.height;
  70. UINT32 numSamples = viewProps.numSamples;
  71. colorDesc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R16U, width, height, TU_RENDERTARGET, numSamples);
  72. depthDesc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_D32, width, height, TU_DEPTHSTENCIL, numSamples);
  73. }
  74. TetrahedraRenderMat* TetrahedraRenderMat::getVariation(bool msaa, bool singleSampleMSAA)
  75. {
  76. if (msaa)
  77. {
  78. if (singleSampleMSAA)
  79. return get(VAR_SingleMSAA);
  80. return get(VAR_FullMSAA);
  81. }
  82. return get(VAR_NoMSAA);
  83. }
  84. IrradianceEvaluateParamDef gIrradianceEvaluateParamDef;
  85. ShaderVariation IrradianceEvaluateMat::VAR_FullMSAA_Probes = ShaderVariation({
  86. ShaderVariation::Param("MSAA_COUNT", 2),
  87. ShaderVariation::Param("MSAA", true),
  88. ShaderVariation::Param("SKY_ONLY", false)
  89. });
  90. ShaderVariation IrradianceEvaluateMat::VAR_SingleMSAA_Probes = ShaderVariation({
  91. ShaderVariation::Param("MSAA_COUNT", 2),
  92. ShaderVariation::Param("MSAA", true),
  93. ShaderVariation::Param("MSAA_RESOLVE_0TH", true),
  94. ShaderVariation::Param("SKY_ONLY", false)
  95. });
  96. ShaderVariation IrradianceEvaluateMat::VAR_NoMSAA_Probes = ShaderVariation({
  97. ShaderVariation::Param("MSAA_COUNT", 1),
  98. ShaderVariation::Param("SKY_ONLY", false)
  99. });
  100. ShaderVariation IrradianceEvaluateMat::VAR_FullMSAA_Sky = ShaderVariation({
  101. ShaderVariation::Param("MSAA_COUNT", 2),
  102. ShaderVariation::Param("MSAA", true),
  103. ShaderVariation::Param("SKY_ONLY", true)
  104. });
  105. ShaderVariation IrradianceEvaluateMat::VAR_SingleMSAA_Sky = ShaderVariation({
  106. ShaderVariation::Param("MSAA_COUNT", 2),
  107. ShaderVariation::Param("MSAA", true),
  108. ShaderVariation::Param("MSAA_RESOLVE_0TH", true),
  109. ShaderVariation::Param("SKY_ONLY", true)
  110. });
  111. ShaderVariation IrradianceEvaluateMat::VAR_NoMSAA_Sky = ShaderVariation({
  112. ShaderVariation::Param("MSAA_COUNT", 1),
  113. ShaderVariation::Param("SKY_ONLY", true)
  114. });
  115. IrradianceEvaluateMat::IrradianceEvaluateMat()
  116. :mGBufferParams(mMaterial, mParamsSet)
  117. {
  118. mSkyOnly = mVariation.getBool("SKY_ONLY");
  119. SPtr<GpuParams> params = mParamsSet->getGpuParams();
  120. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gSkyIrradianceTex", mParamSkyIrradianceTex);
  121. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gAmbientOcclusionTex", mParamAmbientOcclusionTex);
  122. if(!mSkyOnly)
  123. {
  124. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gInputTex", mParamInputTex);
  125. params->getBufferParam(GPT_FRAGMENT_PROGRAM, "gSHCoeffs", mParamSHCoeffsBuffer);
  126. params->getBufferParam(GPT_FRAGMENT_PROGRAM, "gTetrahedra", mParamTetrahedraBuffer);
  127. params->getBufferParam(GPT_FRAGMENT_PROGRAM, "gTetFaces", mParamTetFacesBuffer);
  128. }
  129. mParamBuffer = gIrradianceEvaluateParamDef.createBuffer();
  130. params->setParamBlockBuffer("Params", mParamBuffer);
  131. }
  132. void IrradianceEvaluateMat::_initVariations(ShaderVariations& variations)
  133. {
  134. variations.add(VAR_FullMSAA_Probes);
  135. variations.add(VAR_FullMSAA_Sky);
  136. variations.add(VAR_SingleMSAA_Probes);
  137. variations.add(VAR_SingleMSAA_Sky);
  138. variations.add(VAR_NoMSAA_Probes);
  139. variations.add(VAR_NoMSAA_Sky);
  140. }
  141. void IrradianceEvaluateMat::execute(const RendererView& view, const GBufferTextures& gbuffer,
  142. const SPtr<Texture>& lightProbeIndices, const LightProbesInfo& lightProbesInfo, const Skybox* skybox,
  143. const SPtr<Texture>& ambientOcclusion, const SPtr<RenderTexture>& output)
  144. {
  145. const RendererViewProperties& viewProps = view.getProperties();
  146. mGBufferParams.bind(gbuffer);
  147. float skyBrightness = 1.0f;
  148. SPtr<Texture> skyIrradiance;
  149. if (skybox != nullptr)
  150. {
  151. skyIrradiance = skybox->getIrradiance();
  152. skyBrightness = skybox->getBrightness();
  153. }
  154. if(skyIrradiance == nullptr)
  155. skyIrradiance = RendererTextures::defaultIndirect;
  156. mParamSkyIrradianceTex.set(skyIrradiance);
  157. mParamAmbientOcclusionTex.set(ambientOcclusion);
  158. if(!mSkyOnly)
  159. {
  160. mParamInputTex.set(lightProbeIndices);
  161. mParamSHCoeffsBuffer.set(lightProbesInfo.shCoefficients);
  162. mParamTetrahedraBuffer.set(lightProbesInfo.tetrahedra);
  163. mParamTetFacesBuffer.set(lightProbesInfo.faces);
  164. }
  165. gIrradianceEvaluateParamDef.gSkyBrightness.set(mParamBuffer, skyBrightness);
  166. gIrradianceEvaluateParamDef.gNumTetrahedra.set(mParamBuffer, lightProbesInfo.numTetrahedra);
  167. mParamBuffer->flushToGPU();
  168. mParamsSet->getGpuParams()->setParamBlockBuffer("PerCamera", view.getPerViewBuffer());
  169. // Render
  170. RenderAPI& rapi = RenderAPI::instance();
  171. rapi.setRenderTarget(output, FBT_DEPTH | FBT_STENCIL, RT_COLOR0);
  172. gRendererUtility().setPass(mMaterial);
  173. gRendererUtility().setPassParams(mParamsSet);
  174. gRendererUtility().drawScreenQuad(Rect2(0.0f, 0.0f, (float)viewProps.viewRect.width,
  175. (float)viewProps.viewRect.height));
  176. rapi.setRenderTarget(nullptr);
  177. }
  178. IrradianceEvaluateMat* IrradianceEvaluateMat::getVariation(bool msaa, bool singleSampleMSAA, bool skyOnly)
  179. {
  180. if(skyOnly)
  181. {
  182. if (msaa)
  183. {
  184. if (singleSampleMSAA)
  185. return get(VAR_SingleMSAA_Sky);
  186. return get(VAR_FullMSAA_Sky);
  187. }
  188. return get(VAR_NoMSAA_Sky);
  189. }
  190. else
  191. {
  192. if (msaa)
  193. {
  194. if (singleSampleMSAA)
  195. return get(VAR_SingleMSAA_Probes);
  196. return get(VAR_FullMSAA_Probes);
  197. }
  198. return get(VAR_NoMSAA_Probes);
  199. }
  200. }
  201. /** Hash value generator for std::pair<INT32, INT32>. */
  202. struct pair_hash
  203. {
  204. size_t operator()(const std::pair<INT32, INT32>& key) const
  205. {
  206. size_t hash = 0;
  207. bs::hash_combine(hash, key.first);
  208. bs::hash_combine(hash, key.second);
  209. return hash;
  210. }
  211. };
  212. /** Information about a single tetrahedron, for use on the GPU. */
  213. struct TetrahedronDataGPU
  214. {
  215. UINT32 indices[4];
  216. Matrix3x4 transform;
  217. };
  218. /** Information about a single tetrahedron face, for use on the GPU. */
  219. struct TetrahedronFaceDataGPU
  220. {
  221. Vector4 corners[3];
  222. Vector4 normals[3];
  223. UINT32 isQuadratic;
  224. float padding[3];
  225. };
  226. LightProbes::LightProbes()
  227. :mTetrahedronVolumeDirty(false), mMaxCoefficients(0), mMaxTetrahedra(0), mMaxFaces(0), mNumValidTetrahedra(0)
  228. { }
  229. void LightProbes::notifyAdded(LightProbeVolume* volume)
  230. {
  231. UINT32 handle = (UINT32)mVolumes.size();
  232. VolumeInfo info;
  233. info.volume = volume;
  234. info.isDirty = true;
  235. mVolumes.push_back(info);
  236. volume->setRendererId(handle);
  237. notifyDirty(volume);
  238. }
  239. void LightProbes::notifyDirty(LightProbeVolume* volume)
  240. {
  241. UINT32 handle = volume->getRendererId();
  242. mVolumes[handle].isDirty = true;
  243. mTetrahedronVolumeDirty = true;
  244. }
  245. void LightProbes::notifyRemoved(LightProbeVolume* volume)
  246. {
  247. UINT32 handle = volume->getRendererId();
  248. LightProbeVolume* lastVolume = mVolumes.back().volume;
  249. UINT32 lastHandle = lastVolume->getRendererId();
  250. if (handle != lastHandle)
  251. {
  252. // Swap current last element with the one we want to erase
  253. std::swap(mVolumes[handle], mVolumes[lastHandle]);
  254. lastVolume->setRendererId(handle);
  255. }
  256. // Erase last (empty) element
  257. mVolumes.erase(mVolumes.end() - 1);
  258. mTetrahedronVolumeDirty = true;
  259. }
  260. void LightProbes::updateProbes()
  261. {
  262. if (!mTetrahedronVolumeDirty)
  263. return;
  264. // Move all coefficients into the global buffer
  265. UINT32 numCoeffs = 0;
  266. for(auto& entry : mVolumes)
  267. {
  268. UINT32 numProbes = (UINT32)entry.volume->getLightProbePositions().size();
  269. numCoeffs += numProbes;
  270. }
  271. if(numCoeffs > mMaxCoefficients)
  272. {
  273. UINT32 newSize = Math::divideAndRoundUp(numCoeffs, 32U) * 32U;
  274. resizeCoefficientBuffer(newSize);
  275. }
  276. UINT32 writePos = 0;
  277. for(auto& entry : mVolumes)
  278. {
  279. UINT32 numProbes = (UINT32)entry.volume->getLightProbePositions().size();
  280. UINT32 size = numProbes * sizeof(LightProbeSHCoefficients);
  281. SPtr<GpuBuffer> localBuffer = entry.volume->getCoefficientsBuffer();
  282. // Note: Some of the coefficients might still be dirty (unrendered). Check for this and write them as black?
  283. mProbeCoefficientsGPU->copyData(*localBuffer, 0, writePos, size);
  284. writePos += size;
  285. }
  286. // Gather all positions
  287. UINT32 bufferOffset = 0;
  288. for(auto& entry : mVolumes)
  289. {
  290. const Vector<LightProbeInfo>& infos = entry.volume->getLightProbeInfos();
  291. const Vector<Vector3>& positions = entry.volume->getLightProbePositions();
  292. UINT32 numProbes = entry.volume->getNumActiveProbes();
  293. if (numProbes == 0)
  294. continue;
  295. const Transform& tfrm = entry.volume->getTransform();
  296. Vector3 offset = tfrm.getPosition();
  297. Quaternion rotation = tfrm.getRotation();
  298. for(UINT32 i = 0; i < numProbes; i++)
  299. {
  300. Vector3 localPos = positions[i];
  301. Vector3 transformedPos = rotation.rotate(localPos) + offset;
  302. mTempTetrahedronPositions.push_back(transformedPos);
  303. mTempTetrahedronBufferIndices.push_back(bufferOffset + infos[i].bufferIdx);
  304. }
  305. bufferOffset += (UINT32)positions.size();
  306. }
  307. mTetrahedronInfos.clear();
  308. Vector<TetrahedronFaceData> outerFaces;
  309. generateTetrahedronData(mTempTetrahedronPositions, mTetrahedronInfos, outerFaces, true);
  310. // Find valid tetrahedrons
  311. UINT32 numTetrahedra = (UINT32)mTetrahedronInfos.size();
  312. bool* validTets = (bool*)bs_stack_alloc(sizeof(bool) * numTetrahedra);
  313. mNumValidTetrahedra = 0;
  314. for (UINT32 i = 0; i < (UINT32)mTetrahedronInfos.size(); i++)
  315. {
  316. const TetrahedronData& entry = mTetrahedronInfos[i];
  317. const Vector3& P1 = mTempTetrahedronPositions[entry.volume.vertices[0]];
  318. const Vector3& P2 = mTempTetrahedronPositions[entry.volume.vertices[1]];
  319. const Vector3& P3 = mTempTetrahedronPositions[entry.volume.vertices[2]];
  320. const Vector3& P4 = mTempTetrahedronPositions[entry.volume.vertices[3]];
  321. Vector3 E1 = P1 - P4;
  322. Vector3 E2 = P2 - P4;
  323. Vector3 E3 = P3 - P4;
  324. // If tetrahedron is co-planar just ignore it, shader will use some other nearby one instead. We can't
  325. // handle coplanar tetrahedrons because the matrix is not invertible, and for nearly co-planar ones the
  326. // math breaks down because of precision issues.
  327. validTets[i] = fabs(Vector3::dot(Vector3::normalize(Vector3::cross(E1, E2)), E3)) > 0.0001f;
  328. if (validTets[i])
  329. mNumValidTetrahedra++;
  330. }
  331. UINT32 numValidFaces = 0;
  332. for(auto& entry : outerFaces)
  333. {
  334. if (validTets[entry.tetrahedron])
  335. numValidFaces++;
  336. }
  337. // Generate a mesh out of all the tetrahedron triangles
  338. // Note: Currently the entire volume is rendered as a single large mesh, which will isn't optimal as we can't
  339. // perform frustum culling. A better option would be to split the mesh into multiple smaller volumes, do
  340. // frustum culling and possibly even sort by distance from camera.
  341. UINT32 numVertices = mNumValidTetrahedra * 4 * 3 + numValidFaces * 9 * 3;
  342. SPtr<VertexDataDesc> vertexDesc = bs_shared_ptr_new<VertexDataDesc>();
  343. vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION);
  344. vertexDesc->addVertElem(VET_UINT1, VES_TEXCOORD);
  345. SPtr<MeshData> meshData = MeshData::create(numVertices, numVertices, vertexDesc);
  346. auto posIter = meshData->getVec3DataIter(VES_POSITION);
  347. auto idIter = meshData->getDWORDDataIter(VES_TEXCOORD);
  348. UINT32* indices = meshData->getIndices32();
  349. // Insert inner tetrahedron triangles
  350. UINT32 tetIdx = 0;
  351. for (UINT32 i = 0; i < (UINT32)mTetrahedronInfos.size(); i++)
  352. {
  353. if (!validTets[i])
  354. continue;
  355. const Tetrahedron& volume = mTetrahedronInfos[i].volume;
  356. Vector3 center(BsZero);
  357. for(UINT32 j = 0; j < 4; j++)
  358. center += mTempTetrahedronPositions[volume.vertices[j]];
  359. center /= 4.0f;
  360. static const UINT32 Permutations[4][3] =
  361. {
  362. { 0, 1, 2 },
  363. { 0, 1, 3 },
  364. { 0, 2, 3 },
  365. { 1, 2, 3 }
  366. };
  367. for(UINT32 j = 0; j < 4; j++)
  368. {
  369. Vector3 A = mTempTetrahedronPositions[volume.vertices[Permutations[j][0]]];
  370. Vector3 B = mTempTetrahedronPositions[volume.vertices[Permutations[j][1]]];
  371. Vector3 C = mTempTetrahedronPositions[volume.vertices[Permutations[j][2]]];
  372. // Make sure the triangle is clockwise, facing away from the center
  373. Vector3 e0 = A - C;
  374. Vector3 e1 = B - C;
  375. Vector3 normal = e0.cross(e1);
  376. if (normal.dot(A - center) > 0.0f)
  377. std::swap(B, C);
  378. posIter.addValue(A);
  379. posIter.addValue(B);
  380. posIter.addValue(C);
  381. idIter.addValue(tetIdx);
  382. idIter.addValue(tetIdx);
  383. idIter.addValue(tetIdx);
  384. indices[0] = tetIdx * 4 * 3 + j * 3 + 0;
  385. indices[1] = tetIdx * 4 * 3 + j * 3 + 1;
  386. indices[2] = tetIdx * 4 * 3 + j * 3 + 2;
  387. indices += 3;
  388. }
  389. tetIdx++;
  390. }
  391. // Generate an edge map for outer faces (required for step below)
  392. struct Edge
  393. {
  394. UINT32 vertInner[2];
  395. UINT32 vertOuter[2];
  396. UINT32 face[2];
  397. };
  398. FrameUnorderedMap<std::pair<INT32, INT32>, Edge, pair_hash> edgeMap;
  399. for(UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  400. {
  401. if (!validTets[outerFaces[i].tetrahedron])
  402. continue;
  403. for (UINT32 j = 0; j < 3; ++j)
  404. {
  405. UINT32 v0 = outerFaces[i].innerVertices[j];
  406. UINT32 v1 = outerFaces[i].innerVertices[(j + 1) % 3];
  407. // Keep the same ordering so other faces can find the same edge
  408. if (v0 > v1)
  409. std::swap(v0, v1);
  410. auto iterFind = edgeMap.find(std::make_pair((INT32)v0, (INT32)v1));
  411. if (iterFind != edgeMap.end())
  412. {
  413. iterFind->second.face[1] = i;
  414. }
  415. else
  416. {
  417. Edge edge;
  418. edge.vertInner[0] = outerFaces[i].innerVertices[j];
  419. edge.vertInner[1] = outerFaces[i].innerVertices[(j + 1) % 3];
  420. edge.vertOuter[0] = outerFaces[i].outerVertices[j];
  421. edge.vertOuter[1] = outerFaces[i].outerVertices[(j + 1) % 3];
  422. edge.face[0] = i;
  423. edge.face[1] = -1;
  424. edgeMap.insert(std::make_pair(std::make_pair((INT32)v0, (INT32)v1), edge));
  425. }
  426. }
  427. }
  428. // Generate front and back triangles for extruded outer faces
  429. UINT32 faceIdx = 0;
  430. for(UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  431. {
  432. if (!validTets[outerFaces[i].tetrahedron])
  433. continue;
  434. const TetrahedronFaceData& entry = outerFaces[i];
  435. static const UINT32 Permutations[2][3] = { {0, 1, 2 }, { 3, 4, 5} };
  436. // Make sure the triangle is clockwise, facing away from the center
  437. Vector3 center(BsZero);
  438. for (UINT32 k = 0; k < 3; k++)
  439. {
  440. center += mTempTetrahedronPositions[entry.innerVertices[k]];
  441. center += mTempTetrahedronPositions[entry.outerVertices[k]];
  442. }
  443. center /= 6.0f;
  444. for(UINT32 j = 0; j < 2; ++j)
  445. {
  446. UINT32 idxA = Permutations[j][0];
  447. UINT32 idxB = Permutations[j][1];
  448. UINT32 idxC = Permutations[j][2];
  449. idxA = idxA > 2 ? entry.outerVertices[idxA - 3] : entry.innerVertices[idxA];
  450. idxB = idxB > 2 ? entry.outerVertices[idxB - 3] : entry.innerVertices[idxB];
  451. idxC = idxC > 2 ? entry.outerVertices[idxC - 3] : entry.innerVertices[idxC];
  452. Vector3 A = mTempTetrahedronPositions[idxA];
  453. Vector3 B = mTempTetrahedronPositions[idxB];
  454. Vector3 C = mTempTetrahedronPositions[idxC];
  455. Vector3 e0 = A - C;
  456. Vector3 e1 = B - C;
  457. Vector3 normal = e0.cross(e1);
  458. if (normal.dot(A - center) > 0.0f)
  459. std::swap(A, B);
  460. posIter.addValue(A);
  461. posIter.addValue(B);
  462. posIter.addValue(C);
  463. idIter.addValue(tetIdx + faceIdx);
  464. idIter.addValue(tetIdx + faceIdx);
  465. idIter.addValue(tetIdx + faceIdx);
  466. indices[0] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + j * 3 + 0;
  467. indices[1] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + j * 3 + 1;
  468. indices[2] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + j * 3 + 2;
  469. indices += 3;
  470. }
  471. faceIdx++;
  472. }
  473. // Generate sides for extruded outer faces
  474. UINT32 sideIdx = 0;
  475. for(auto& entry : edgeMap)
  476. {
  477. const Edge& edge = entry.second;
  478. for (UINT32 i = 0; i < 2; i++)
  479. {
  480. const TetrahedronFaceData& face = outerFaces[edge.face[i]];
  481. // Make sure the triangle is clockwise, facing away from the center
  482. Vector3 center(BsZero);
  483. for (UINT32 k = 0; k < 3; k++)
  484. {
  485. center += mTempTetrahedronPositions[face.innerVertices[k]];
  486. center += mTempTetrahedronPositions[face.outerVertices[k]];
  487. }
  488. center /= 6.0f;
  489. static const UINT32 Permutations[2][3] = { {0, 1, 2 }, { 1, 2, 3} };
  490. for(UINT32 j = 0; j < 2; ++j)
  491. {
  492. UINT32 idxA = Permutations[j][0];
  493. UINT32 idxB = Permutations[j][1];
  494. UINT32 idxC = Permutations[j][2];
  495. idxA = idxA > 1 ? edge.vertOuter[idxA - 2] : edge.vertInner[idxA];
  496. idxB = idxB > 1 ? edge.vertOuter[idxB - 2] : edge.vertInner[idxB];
  497. idxC = idxC > 1 ? edge.vertOuter[idxC - 2] : edge.vertInner[idxC];
  498. Vector3 A = mTempTetrahedronPositions[idxA];
  499. Vector3 B = mTempTetrahedronPositions[idxB];
  500. Vector3 C = mTempTetrahedronPositions[idxC];
  501. Vector3 e0 = A - C;
  502. Vector3 e1 = B - C;
  503. Vector3 normal = e0.cross(e1);
  504. if (normal.dot(A - center) > 0.0f)
  505. std::swap(A, B);
  506. posIter.addValue(A);
  507. posIter.addValue(B);
  508. posIter.addValue(C);
  509. idIter.addValue(tetIdx + edge.face[i]);
  510. idIter.addValue(tetIdx + edge.face[i]);
  511. idIter.addValue(tetIdx + edge.face[i]);
  512. indices[0] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + sideIdx * 2 * 3 + j * 3 + 0;
  513. indices[1] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + sideIdx * 2 * 3 + j * 3 + 1;
  514. indices[2] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + sideIdx * 2 * 3 + j * 3 + 2;
  515. indices += 3;
  516. }
  517. sideIdx++;
  518. }
  519. }
  520. // Generate "caps" on the end of the extruded volume
  521. UINT32 capIdx = 0;
  522. for(UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  523. {
  524. if (!validTets[outerFaces[i].tetrahedron])
  525. continue;
  526. const TetrahedronFaceData& entry = outerFaces[i];
  527. Vector3 A = mTempTetrahedronPositions[entry.outerVertices[0]];
  528. Vector3 B = mTempTetrahedronPositions[entry.outerVertices[1]];
  529. Vector3 C = mTempTetrahedronPositions[entry.outerVertices[2]];
  530. // Make sure the triangle is clockwise, facing toward the center
  531. const Tetrahedron& tet = mTetrahedronInfos[entry.tetrahedron].volume;
  532. Vector3 center(BsZero);
  533. for(UINT32 j = 0; j < 4; j++)
  534. center += mTempTetrahedronPositions[tet.vertices[j]];
  535. center /= 4.0f;
  536. Vector3 e0 = A - C;
  537. Vector3 e1 = B - C;
  538. Vector3 normal = e0.cross(e1);
  539. if (normal.dot(A - center) < 0.0f)
  540. std::swap(B, C);
  541. posIter.addValue(A);
  542. posIter.addValue(B);
  543. posIter.addValue(C);
  544. idIter.addValue(-1);
  545. idIter.addValue(-1);
  546. idIter.addValue(-1);
  547. indices[0] = tetIdx * 4 * 3 + faceIdx * 8 * 3 + capIdx * 3 + 0;
  548. indices[1] = tetIdx * 4 * 3 + faceIdx * 8 * 3 + capIdx * 3 + 1;
  549. indices[2] = tetIdx * 4 * 3 + faceIdx * 8 * 3 + capIdx * 3 + 2;
  550. indices += 3;
  551. capIdx++;
  552. }
  553. mVolumeMesh = Mesh::create(meshData);
  554. // Map vertices to actual SH coefficient indices, and write GPU buffer with tetrahedron information
  555. if ((mNumValidTetrahedra + numValidFaces) > mMaxTetrahedra)
  556. {
  557. UINT32 newSize = Math::divideAndRoundUp(mNumValidTetrahedra + numValidFaces, 64U) * 64U;
  558. resizeTetrahedronBuffer(newSize);
  559. }
  560. TetrahedronDataGPU* dst = (TetrahedronDataGPU*)mTetrahedronInfosGPU->lock(0, mTetrahedronInfosGPU->getSize(),
  561. GBL_WRITE_ONLY_DISCARD);
  562. // Write inner tetrahedron data
  563. for (UINT32 i = 0; i < (UINT32)mTetrahedronInfos.size(); i++)
  564. {
  565. if (!validTets[i])
  566. continue;
  567. TetrahedronData& entry = mTetrahedronInfos[i];
  568. for(UINT32 j = 0; j < 4; ++j)
  569. entry.volume.vertices[j] = mTempTetrahedronBufferIndices[entry.volume.vertices[j]];
  570. memcpy(dst->indices, entry.volume.vertices, sizeof(UINT32) * 4);
  571. memcpy(&dst->transform, &entry.transform, sizeof(float) * 12);
  572. dst++;
  573. }
  574. // Write extruded face data
  575. for (UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  576. {
  577. if (!validTets[outerFaces[i].tetrahedron])
  578. continue;
  579. const TetrahedronFaceData& entry = outerFaces[i];
  580. UINT32 indices[4];
  581. indices[0] = mTempTetrahedronBufferIndices[entry.innerVertices[0]];
  582. indices[1] = mTempTetrahedronBufferIndices[entry.innerVertices[1]];
  583. indices[2] = mTempTetrahedronBufferIndices[entry.innerVertices[2]];
  584. indices[3] = -1;
  585. memcpy(dst->indices, indices, sizeof(UINT32) * 4);
  586. memcpy(&dst->transform, &entry.transform, sizeof(float) * 12);
  587. dst++;
  588. }
  589. mTetrahedronInfosGPU->unlock();
  590. // Write data specific to faces
  591. if (numValidFaces > mMaxFaces)
  592. {
  593. UINT32 newSize = Math::divideAndRoundUp(numValidFaces, 64U) * 64U;
  594. resizeTetrahedronFaceBuffer(newSize);
  595. }
  596. TetrahedronFaceDataGPU* faceDst = (TetrahedronFaceDataGPU*)mTetrahedronFaceInfosGPU->lock(0,
  597. mTetrahedronFaceInfosGPU->getSize(), GBL_WRITE_ONLY_DISCARD);
  598. for (UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  599. {
  600. if (!validTets[outerFaces[i].tetrahedron])
  601. continue;
  602. const TetrahedronFaceData& entry = outerFaces[i];
  603. for (UINT32 j = 0; j < 3; j++)
  604. {
  605. faceDst->corners[j] = mTempTetrahedronPositions[entry.innerVertices[j]];
  606. faceDst->normals[j] = entry.normals[j];
  607. }
  608. faceDst->isQuadratic = entry.quadratic ? 1 : 0;
  609. faceDst++;
  610. }
  611. mTetrahedronFaceInfosGPU->unlock();
  612. bs_stack_free(validTets);
  613. mTempTetrahedronPositions.clear();
  614. mTempTetrahedronBufferIndices.clear();
  615. mTetrahedronVolumeDirty = false;
  616. }
  617. bool LightProbes::hasAnyProbes() const
  618. {
  619. for(auto& entry : mVolumes)
  620. {
  621. UINT32 numProbes = entry.volume->getNumActiveProbes();
  622. if (numProbes > 0)
  623. return true;
  624. }
  625. return false;
  626. }
  627. LightProbesInfo LightProbes::getInfo() const
  628. {
  629. LightProbesInfo info;
  630. info.shCoefficients = mProbeCoefficientsGPU;
  631. info.tetrahedra = mTetrahedronInfosGPU;
  632. info.faces = mTetrahedronFaceInfosGPU;
  633. info.tetrahedraVolume = mVolumeMesh;
  634. info.numTetrahedra = mNumValidTetrahedra;
  635. return info;
  636. }
  637. void LightProbes::resizeTetrahedronBuffer(UINT32 count)
  638. {
  639. GPU_BUFFER_DESC desc;
  640. desc.type = GBT_STRUCTURED;
  641. desc.elementSize = sizeof(TetrahedronDataGPU);
  642. desc.elementCount = count;
  643. desc.usage = GBU_STATIC;
  644. desc.format = BF_UNKNOWN;
  645. mTetrahedronInfosGPU = GpuBuffer::create(desc);
  646. mMaxTetrahedra = count;
  647. }
  648. void LightProbes::resizeTetrahedronFaceBuffer(UINT32 count)
  649. {
  650. GPU_BUFFER_DESC desc;
  651. desc.type = GBT_STRUCTURED;
  652. desc.elementSize = sizeof(TetrahedronFaceDataGPU);
  653. desc.elementCount = count;
  654. desc.usage = GBU_STATIC;
  655. desc.format = BF_UNKNOWN;
  656. mTetrahedronFaceInfosGPU = GpuBuffer::create(desc);
  657. mMaxFaces = count;
  658. }
  659. void LightProbes::resizeCoefficientBuffer(UINT32 count)
  660. {
  661. GPU_BUFFER_DESC desc;
  662. desc.type = GBT_STRUCTURED;
  663. desc.elementSize = sizeof(LightProbeSHCoefficients);
  664. desc.elementCount = count;
  665. desc.usage = GBU_STATIC;
  666. desc.format = BF_UNKNOWN;
  667. mProbeCoefficientsGPU = GpuBuffer::create(desc);
  668. mMaxCoefficients = count;
  669. }
  670. void LightProbes::generateTetrahedronData(Vector<Vector3>& positions, Vector<TetrahedronData>& tetrahedra,
  671. Vector<TetrahedronFaceData>& faces, bool generateExtrapolationVolume)
  672. {
  673. bs_frame_mark();
  674. {
  675. TetrahedronVolume volume = Triangulation::tetrahedralize(positions);
  676. if (generateExtrapolationVolume)
  677. {
  678. // Add geometry so we can handle the case when the interpolation position falls outside of the tetrahedra
  679. // volume. We use this geometry to project the position to the nearest face.
  680. UINT32 numOuterFaces = (UINT32)volume.outerFaces.size();
  681. // Calculate face normals for outer faces
  682. //// Make an edge map
  683. struct Edge
  684. {
  685. INT32 faces[2];
  686. INT32 oppositeVerts[2];
  687. };
  688. FrameUnorderedMap<std::pair<INT32, INT32>, Edge, pair_hash> edgeMap;
  689. for (UINT32 i = 0; i < numOuterFaces; ++i)
  690. {
  691. for (UINT32 j = 0; j < 3; ++j)
  692. {
  693. INT32 v0 = volume.outerFaces[i].vertices[j];
  694. INT32 v1 = volume.outerFaces[i].vertices[(j + 1) % 3];
  695. // Keep the same ordering so other faces can find the same edge
  696. if (v0 > v1)
  697. std::swap(v0, v1);
  698. auto iterFind = edgeMap.find(std::make_pair(v0, v1));
  699. if (iterFind != edgeMap.end())
  700. {
  701. iterFind->second.faces[1] = i;
  702. iterFind->second.oppositeVerts[1] = (j + 2) % 3;
  703. }
  704. else
  705. {
  706. Edge edge;
  707. edge.faces[0] = i;
  708. edge.oppositeVerts[0] = (j + 2) % 3;
  709. edgeMap.insert(std::make_pair(std::make_pair(v0, v1), edge));
  710. }
  711. }
  712. }
  713. //// Generate face normals
  714. struct FaceVertex
  715. {
  716. Vector3 normal = Vector3::ZERO;
  717. UINT32 outerIdx = -1;
  718. };
  719. FrameVector<Vector3> faceNormals(volume.outerFaces.size());
  720. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  721. {
  722. const Vector3& v0 = positions[volume.outerFaces[i].vertices[0]];
  723. const Vector3& v1 = positions[volume.outerFaces[i].vertices[1]];
  724. const Vector3& v2 = positions[volume.outerFaces[i].vertices[2]];
  725. Vector3 e0 = v1 - v0;
  726. Vector3 e1 = v2 - v0;
  727. // Make sure the normal is facing away from the center
  728. const Tetrahedron& tet = volume.tetrahedra[volume.outerFaces[i].tetrahedron];
  729. Vector3 center(BsZero);
  730. for(UINT32 j = 0; j < 4; j++)
  731. center += positions[tet.vertices[j]];
  732. center /= 4.0f;
  733. Vector3 normal = Vector3::normalize(e0.cross(e1));
  734. if (normal.dot(v0 - center) < 0.0f)
  735. normal = -normal;
  736. faceNormals[i] = normal;
  737. }
  738. //// Generate vertex normals
  739. FrameUnorderedMap<INT32, FaceVertex> faceVertices;
  740. for (auto& entry : edgeMap)
  741. {
  742. const Edge& edge = entry.second;
  743. auto accumulateNormalForEdgeVertex = [&](UINT32 v0Idx, UINT32 v1Idx)
  744. {
  745. auto iter = faceVertices.insert(std::make_pair(v0Idx, FaceVertex()));
  746. FaceVertex& accum = iter.first->second;
  747. const Vector3& v0 = positions[v0Idx];
  748. auto accumulateNormalForFace = [&](INT32 faceIdx, INT32 v2LocIdx)
  749. {
  750. const TetrahedronFace& face = volume.outerFaces[faceIdx];
  751. // Vertices on the face, that aren't the vertex we're calculating the normal for
  752. const Vector3& v1 = positions[v1Idx];
  753. const Vector3& v2 = positions[face.vertices[v2LocIdx]];
  754. // Weight the contribution to the normal based on the angle spanned by the triangle
  755. Vector3 e0 = Vector3::normalize(v1 - v0);
  756. Vector3 e1 = Vector3::normalize(v2 - v0);
  757. float weight = acos(e0.dot(e1));
  758. accum.normal += weight * faceNormals[faceIdx];
  759. };
  760. accumulateNormalForFace(edge.faces[0], entry.second.oppositeVerts[0]);
  761. accumulateNormalForFace(edge.faces[1], entry.second.oppositeVerts[1]);
  762. };
  763. accumulateNormalForEdgeVertex(entry.first.first, entry.first.second);
  764. accumulateNormalForEdgeVertex(entry.first.second, entry.first.first);
  765. }
  766. for (auto& entry : faceVertices)
  767. entry.second.normal.normalize();
  768. // For each face vertex, generate an outer vertex along its normal
  769. static const float ExtrapolationDistance = 5.0f;
  770. for(auto& entry : faceVertices)
  771. {
  772. entry.second.outerIdx = (UINT32)positions.size();
  773. Vector3 outerPos = positions[entry.first] + entry.second.normal * ExtrapolationDistance;
  774. positions.push_back(outerPos);
  775. }
  776. // Generate face data
  777. for (UINT32 i = 0; i < numOuterFaces; ++i)
  778. {
  779. const TetrahedronFace& face = volume.outerFaces[i];
  780. TetrahedronFaceData faceData;
  781. faceData.tetrahedron = face.tetrahedron;
  782. for (UINT32 j = 0; j < 3; j++)
  783. {
  784. const FaceVertex& faceVertex = faceVertices[face.vertices[j]];
  785. faceData.innerVertices[j] = face.vertices[j];
  786. faceData.outerVertices[j] = faceVertex.outerIdx;
  787. faceData.normals[j] = faceVertex.normal;
  788. }
  789. // Add a link on the source tetrahedron to the face data
  790. Tetrahedron& innerTet = volume.tetrahedra[face.tetrahedron];
  791. for(UINT32 j = 0; j < 4; j++)
  792. {
  793. if (innerTet.neighbors[j] == -1)
  794. {
  795. // Note: Not searching for opposite neighbor here. If tet. has multiple free faces then we
  796. // can't just pick the first one
  797. innerTet.neighbors[j] = (UINT32)volume.tetrahedra.size() + (UINT32)faces.size();
  798. break;
  799. }
  800. }
  801. // We need a way to project a point outside the tetrahedron volume onto an outer face, then calculate
  802. // triangle's barycentric coordinates. Use use the per-vertex normals to extrude the triangle face into
  803. // infinity.
  804. // Our point can be represented as:
  805. // p == a (p0 + t*v0) + b (p1 + t*v1) + c (p2 + t*v2)
  806. //
  807. // where a, b and c are barycentric coordinates,
  808. // p0, p1, p2 are the corners of the face
  809. // v0, v1, v2 are the vertex normals, per corner
  810. // t is the distance from the triangle to the point
  811. //
  812. // Essentially we're calculating the corners of a bigger triangle that's "t" units away from the
  813. // face, and its corners lie along the per-vertex normals. Point "p" will lie on that triangle, for which
  814. // we can then calculate barycentric coordinates normally.
  815. //
  816. // First we substitute: c = 1 - a - b
  817. // p == a (p0 + t v0) + b (p1 + t v1) + (1 - a - b) (p2 + t v2)
  818. // p == a (p0 + t v0) + b (p1 + t v1) + (p2 + t v2) - a (p2 + t v2) - b (p2 + t v2)
  819. // p == a (p0 - p2 + t v0 - t v2) + b (p1 - p2 + t v1 - t v2) + (p2 + t v2)
  820. //
  821. // And move everything to one side:
  822. // p - p2 - t v2 == a (p0 - p2 + t ( v0 - v2)) + b (p1 - p2 + t ( v1 - v2))
  823. // a (p0 - p2 + t ( v0 - v2)) + b (p1 - p2 + t ( v1 - v2)) - (p - p2 - t v2) == 0
  824. //
  825. // We rewrite it using:
  826. // Ap = p0 - p2
  827. // Av = v0 - v2
  828. // Bp = p1 - p2
  829. // Bv = v1 - v2
  830. // Cp = p - p2
  831. // Cv = -v2
  832. //
  833. // Which yields:
  834. // a (Ap + t Av) + b (Bp + t Bv) - (Cp + t Cv) == 0
  835. //
  836. // Which can be written in matrix form:
  837. //
  838. // M = {Ap + t Av, Bp + t Bv, Cp + t Cv}
  839. // a 0
  840. // M * [ b ] = [0]
  841. // -1 0
  842. //
  843. // From that we can tell that matrix M cannot be inverted, because if we multiply the zero vector with the
  844. // inverted matrix the result would be zero, and not [a, b, -1]. Since the matrix cannot be inverted
  845. // det(M) == 0.
  846. //
  847. // We can use that fact to calculate "t". After we have "t" we can calculate barycentric coordinates
  848. // normally.
  849. //
  850. // Solving equation det(M) == 0 yields a cubic in form:
  851. // p t^3 + q t^2 + r t + s = 0
  852. //
  853. // We'll convert this to monic form, by dividing by p:
  854. // t^3 + q/p t^2 + r/p t + s/p = 0
  855. //
  856. // Or if p ends up being zero, we end up with a quadratic instead:
  857. // q t^2 + r t + s = 0
  858. //
  859. // We want to create a matrix that when multiplied with the position, yields us the three coefficients,
  860. // which we can then use to solve for "t". For this we create a 4x3 matrix, where each row represents
  861. // a solution for one of the coefficients. We factor contributons to each coefficient whether they depend on
  862. // position x, y, z, or don't depend on position (row columns, in that order respectively).
  863. const Vector3& p0 = positions[faceData.innerVertices[0]];
  864. const Vector3& p1 = positions[faceData.innerVertices[1]];
  865. const Vector3& p2 = positions[faceData.innerVertices[2]];
  866. const Vector3& v0 = faceVertices[faceData.innerVertices[0]].normal;
  867. const Vector3& v1 = faceVertices[faceData.innerVertices[1]].normal;
  868. const Vector3& v2 = faceVertices[faceData.innerVertices[2]].normal;
  869. float p =
  870. v2.x * v1.y * v0.z -
  871. v1.x * v2.y * v0.z -
  872. v2.x * v0.y * v1.z +
  873. v0.x * v2.y * v1.z +
  874. v1.x * v0.y * v2.z -
  875. v0.x * v1.y * v2.z;
  876. float qx = -v1.y * v0.z + v2.y * v0.z + v0.y * v1.z - v2.y * v1.z - v0.y * v2.z + v1.y * v2.z;
  877. float qy = v1.x * v0.z - v2.x * v0.z - v0.x * v1.z + v2.x * v1.z + v0.x * v2.z - v1.x * v2.z;
  878. float qz = -v1.x * v0.y + v2.x * v0.y + v0.x * v1.y - v2.x * v1.y - v0.x * v2.y + v1.x * v2.y;
  879. float qw = v2.y * v1.z * p0.x - v1.y * v2.z * p0.x - v2.y * v0.z * p1.x + v0.y * v2.z * p1.x +
  880. v1.y * v0.z * p2.x - v0.y * v1.z * p2.x - v2.x * v1.z * p0.y + v1.x * v2.z * p0.y +
  881. v2.x * v0.z * p1.y - v0.x * v2.z * p1.y - v1.x * v0.z * p2.y + v0.x * v1.z * p2.y +
  882. v2.x * v1.y * p0.z - v1.x * v2.y * p0.z - v2.x * v0.y * p1.z + v0.x * v2.y * p1.z +
  883. v1.x * v0.y * p2.z - v0.x * v1.y * p2.z;
  884. float rx = v1.z * p0.y - v2.z * p0.y - v0.z * p1.y + v2.z * p1.y + v0.z * p2.y - v1.z * p2.y -
  885. v1.y * p0.z + v2.y * p0.z + v0.y * p1.z - v2.y * p1.z - v0.y * p2.z + v1.y * p2.z;
  886. float ry = -v1.z * p0.x + v2.z * p0.x + v0.z * p1.x - v2.z * p1.x - v0.z * p2.x + v1.z * p2.x +
  887. v1.x * p0.z - v2.x * p0.z - v0.x * p1.z + v2.x * p1.z + v0.x * p2.z - v1.x * p2.z;
  888. float rz = v1.y * p0.x - v2.y * p0.x - v0.y * p1.x + v2.y * p1.x + v0.y * p2.x - v1.y * p2.x -
  889. v1.x * p0.y + v2.x * p0.y + v0.x * p1.y - v2.x * p1.y - v0.x * p2.y + v1.x * p2.y;
  890. float rw = v2.z * p1.x * p0.y - v1.z * p2.x * p0.y - v2.z * p0.x * p1.y + v0.z * p2.x * p1.y +
  891. v1.z * p0.x * p2.y - v0.z * p1.x * p2.y - v2.y * p1.x * p0.z + v1.y * p2.x * p0.z +
  892. v2.x * p1.y * p0.z - v1.x * p2.y * p0.z + v2.y * p0.x * p1.z - v0.y * p2.x * p1.z -
  893. v2.x * p0.y * p1.z + v0.x * p2.y * p1.z - v1.y * p0.x * p2.z + v0.y * p1.x * p2.z +
  894. v1.x * p0.y * p2.z - v0.x * p1.y * p2.z;
  895. float sx = -p1.y * p0.z + p2.y * p0.z + p0.y * p1.z - p2.y * p1.z - p0.y * p2.z + p1.y * p2.z;
  896. float sy = p1.x * p0.z - p2.x * p0.z - p0.x * p1.z + p2.x * p1.z + p0.x * p2.z - p1.x * p2.z;
  897. float sz = -p1.x * p0.y + p2.x * p0.y + p0.x * p1.y - p2.x * p1.y - p0.x * p2.y + p1.x * p2.y;
  898. float sw = p2.x * p1.y * p0.z - p1.x * p2.y * p0.z - p2.x * p0.y * p1.z +
  899. p0.x * p2.y * p1.z + p1.x * p0.y * p2.z - p0.x * p1.y * p2.z;
  900. faceData.transform[0][0] = qx;
  901. faceData.transform[0][1] = qy;
  902. faceData.transform[0][2] = qz;
  903. faceData.transform[0][3] = qw;
  904. faceData.transform[1][0] = rx;
  905. faceData.transform[1][1] = ry;
  906. faceData.transform[1][2] = rz;
  907. faceData.transform[1][3] = rw;
  908. faceData.transform[2][0] = sx;
  909. faceData.transform[2][1] = sy;
  910. faceData.transform[2][2] = sz;
  911. faceData.transform[2][3] = sw;
  912. // Unused
  913. faceData.transform[3][0] = 0.0f;
  914. faceData.transform[3][1] = 0.0f;
  915. faceData.transform[3][2] = 0.0f;
  916. faceData.transform[3][3] = 0.0f;
  917. if (fabs(p) > 0.00001f)
  918. {
  919. faceData.transform = faceData.transform * (1.0f / p);
  920. faceData.quadratic = false;
  921. }
  922. else // Quadratic
  923. {
  924. faceData.quadratic = true;
  925. }
  926. faces.push_back(faceData);
  927. }
  928. }
  929. else
  930. {
  931. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  932. {
  933. const TetrahedronFace& face = volume.outerFaces[i];
  934. TetrahedronFaceData faceData;
  935. for (UINT32 j = 0; j < 3; j++)
  936. {
  937. faceData.innerVertices[j] = face.vertices[j];
  938. faceData.outerVertices[j] = -1;
  939. faceData.normals[j] = Vector3::ZERO;
  940. }
  941. faceData.tetrahedron = face.tetrahedron;
  942. faceData.transform = Matrix4::IDENTITY;
  943. faceData.quadratic = false;
  944. faces.push_back(faceData);
  945. }
  946. }
  947. // Generate matrices
  948. UINT32 numOutputTets = (UINT32)volume.tetrahedra.size();
  949. tetrahedra.reserve(numOutputTets);
  950. //// For inner tetrahedrons
  951. for(UINT32 i = 0; i < (UINT32)numOutputTets; ++i)
  952. {
  953. TetrahedronData entry;
  954. entry.volume = volume.tetrahedra[i];
  955. // Generate a matrix that can be used for calculating barycentric coordinates
  956. // To determine a point within a tetrahedron, using barycentric coordinates, we use:
  957. // P = (P1 - P4) * a + (P2 - P4) * b + (P3 - P4) * c + P4
  958. //
  959. // Where P1, P2, P3, P4 are the corners of the tetrahedron.
  960. //
  961. // Expanded for each coordinate this is:
  962. // x = (x1 - x4) * a + (x2 - x4) * b + (x3 - x4) * c + x4
  963. // y = (y1 - y4) * a + (y2 - y4) * b + (y3 - y4) * c + y4
  964. // z = (z1 - z4) * a + (z2 - z4) * b + (z3 - z4) * c + z4
  965. //
  966. // In matrix form this is:
  967. // a
  968. // P = [P1 - P4, P2 - P4, P3 - P4, P4] [b]
  969. // c
  970. // 1
  971. //
  972. // Solved for barycentric coordinates:
  973. // a
  974. // [b] = Minv * P
  975. // c
  976. // 1
  977. //
  978. // Where Minv is the inverse of the matrix above.
  979. const Vector3& P1 = positions[volume.tetrahedra[i].vertices[0]];
  980. const Vector3& P2 = positions[volume.tetrahedra[i].vertices[1]];
  981. const Vector3& P3 = positions[volume.tetrahedra[i].vertices[2]];
  982. const Vector3& P4 = positions[volume.tetrahedra[i].vertices[3]];
  983. Vector3 E1 = P1 - P4;
  984. Vector3 E2 = P2 - P4;
  985. Vector3 E3 = P3 - P4;
  986. Matrix4 mat;
  987. mat.setColumn(0, Vector4(E1, 0.0f));
  988. mat.setColumn(1, Vector4(E2, 0.0f));
  989. mat.setColumn(2, Vector4(E3, 0.0f));
  990. mat.setColumn(3, Vector4(P4, 1.0f));
  991. entry.transform = mat.inverse();
  992. tetrahedra.push_back(entry);
  993. }
  994. }
  995. bs_frame_clear();
  996. }
  997. }}