BsLightProbes.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  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->getTextureParam(GPT_FRAGMENT_PROGRAM, "gSHCoeffs", mParamSHCoeffsTexture);
  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. mParamSHCoeffsTexture.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. Vector2I offsets[4];
  217. Matrix3x4 transform;
  218. };
  219. /** Information about a single tetrahedron face, for use on the GPU. */
  220. struct TetrahedronFaceDataGPU
  221. {
  222. Vector4 corners[3];
  223. Vector4 normals[3];
  224. UINT32 isQuadratic;
  225. float padding[3];
  226. };
  227. LightProbes::LightProbes()
  228. :mTetrahedronVolumeDirty(false), mMaxCoefficientRows(0), mMaxTetrahedra(0), mMaxFaces(0), mNumValidTetrahedra(0)
  229. { }
  230. void LightProbes::notifyAdded(LightProbeVolume* volume)
  231. {
  232. UINT32 handle = (UINT32)mVolumes.size();
  233. VolumeInfo info;
  234. info.volume = volume;
  235. info.isDirty = true;
  236. mVolumes.push_back(info);
  237. volume->setRendererId(handle);
  238. notifyDirty(volume);
  239. }
  240. void LightProbes::notifyDirty(LightProbeVolume* volume)
  241. {
  242. UINT32 handle = volume->getRendererId();
  243. mVolumes[handle].isDirty = true;
  244. mTetrahedronVolumeDirty = true;
  245. }
  246. void LightProbes::notifyRemoved(LightProbeVolume* volume)
  247. {
  248. UINT32 handle = volume->getRendererId();
  249. LightProbeVolume* lastVolume = mVolumes.back().volume;
  250. UINT32 lastHandle = lastVolume->getRendererId();
  251. if (handle != lastHandle)
  252. {
  253. // Swap current last element with the one we want to erase
  254. std::swap(mVolumes[handle], mVolumes[lastHandle]);
  255. lastVolume->setRendererId(handle);
  256. }
  257. // Erase last (empty) element
  258. mVolumes.erase(mVolumes.end() - 1);
  259. mTetrahedronVolumeDirty = true;
  260. }
  261. void LightProbes::updateProbes()
  262. {
  263. if (!mTetrahedronVolumeDirty)
  264. return;
  265. // Move all coefficients into the global buffer
  266. UINT32 numRows = 0;
  267. for(auto& entry : mVolumes)
  268. {
  269. SPtr<Texture> localTexture = entry.volume->getCoefficientsTexture();
  270. numRows += localTexture->getProperties().getHeight();
  271. }
  272. if(numRows > mMaxCoefficientRows)
  273. resizeCoefficientTexture(numRows + 4);
  274. UINT32 rowIdx = 0;
  275. for(auto& entry : mVolumes)
  276. {
  277. TEXTURE_COPY_DESC copyDesc;
  278. copyDesc.dstPosition = Vector3I(0, rowIdx, 0);
  279. SPtr<Texture> localTexture = entry.volume->getCoefficientsTexture();
  280. localTexture->copy(mProbeCoefficientsGPU, copyDesc);
  281. rowIdx += localTexture->getProperties().getHeight();
  282. }
  283. // Gather all positions
  284. UINT32 bufferOffset = 0;
  285. rowIdx = 0;
  286. for(auto& entry : mVolumes)
  287. {
  288. const Vector<LightProbeInfo>& infos = entry.volume->getLightProbeInfos();
  289. const Vector<Vector3>& positions = entry.volume->getLightProbePositions();
  290. UINT32 numProbes = entry.volume->getNumActiveProbes();
  291. if (numProbes == 0)
  292. continue;
  293. const Transform& tfrm = entry.volume->getTransform();
  294. Vector3 offset = tfrm.getPosition();
  295. Quaternion rotation = tfrm.getRotation();
  296. for (UINT32 i = 0; i < numProbes; i++)
  297. {
  298. Vector3 localPos = positions[i];
  299. Vector3 transformedPos = rotation.rotate(localPos) + offset;
  300. mTempTetrahedronPositions.push_back(transformedPos);
  301. mTempTetrahedronBufferIndices.push_back(bufferOffset + infos[i].bufferIdx);
  302. Vector2I offset = IBLUtility::getSHCoeffXYFromIdx(infos[i].bufferIdx, 3);
  303. mTempTetrahedronBufferOffsets.push_back(offset);
  304. }
  305. SPtr<Texture> localTexture = entry.volume->getCoefficientsTexture();
  306. rowIdx += localTexture->getProperties().getHeight();
  307. bufferOffset += (UINT32)positions.size();
  308. }
  309. mTetrahedronInfos.clear();
  310. Vector<TetrahedronFaceData> outerFaces;
  311. generateTetrahedronData(mTempTetrahedronPositions, mTetrahedronInfos, outerFaces, true);
  312. // Find valid tetrahedrons
  313. UINT32 numTetrahedra = (UINT32)mTetrahedronInfos.size();
  314. bool* validTets = (bool*)bs_stack_alloc(sizeof(bool) * numTetrahedra);
  315. mNumValidTetrahedra = 0;
  316. for (UINT32 i = 0; i < (UINT32)mTetrahedronInfos.size(); i++)
  317. {
  318. const TetrahedronData& entry = mTetrahedronInfos[i];
  319. const Vector3& P1 = mTempTetrahedronPositions[entry.volume.vertices[0]];
  320. const Vector3& P2 = mTempTetrahedronPositions[entry.volume.vertices[1]];
  321. const Vector3& P3 = mTempTetrahedronPositions[entry.volume.vertices[2]];
  322. const Vector3& P4 = mTempTetrahedronPositions[entry.volume.vertices[3]];
  323. Vector3 E1 = P1 - P4;
  324. Vector3 E2 = P2 - P4;
  325. Vector3 E3 = P3 - P4;
  326. // If tetrahedron is co-planar just ignore it, shader will use some other nearby one instead. We can't
  327. // handle coplanar tetrahedrons because the matrix is not invertible, and for nearly co-planar ones the
  328. // math breaks down because of precision issues.
  329. validTets[i] = fabs(Vector3::dot(Vector3::normalize(Vector3::cross(E1, E2)), E3)) > 0.0001f;
  330. if (validTets[i])
  331. mNumValidTetrahedra++;
  332. }
  333. UINT32 numValidFaces = 0;
  334. for(auto& entry : outerFaces)
  335. {
  336. if (validTets[entry.tetrahedron])
  337. numValidFaces++;
  338. }
  339. // Generate a mesh out of all the tetrahedron triangles
  340. // Note: Currently the entire volume is rendered as a single large mesh, which will isn't optimal as we can't
  341. // perform frustum culling. A better option would be to split the mesh into multiple smaller volumes, do
  342. // frustum culling and possibly even sort by distance from camera.
  343. UINT32 numVertices = mNumValidTetrahedra * 4 * 3 + numValidFaces * 9 * 3;
  344. SPtr<VertexDataDesc> vertexDesc = bs_shared_ptr_new<VertexDataDesc>();
  345. vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION);
  346. vertexDesc->addVertElem(VET_UINT1, VES_TEXCOORD);
  347. SPtr<MeshData> meshData = MeshData::create(numVertices, numVertices, vertexDesc);
  348. auto posIter = meshData->getVec3DataIter(VES_POSITION);
  349. auto idIter = meshData->getDWORDDataIter(VES_TEXCOORD);
  350. UINT32* indices = meshData->getIndices32();
  351. // Insert inner tetrahedron triangles
  352. UINT32 tetIdx = 0;
  353. for (UINT32 i = 0; i < (UINT32)mTetrahedronInfos.size(); i++)
  354. {
  355. if (!validTets[i])
  356. continue;
  357. const Tetrahedron& volume = mTetrahedronInfos[i].volume;
  358. Vector3 center(BsZero);
  359. for(UINT32 j = 0; j < 4; j++)
  360. center += mTempTetrahedronPositions[volume.vertices[j]];
  361. center /= 4.0f;
  362. static const UINT32 Permutations[4][3] =
  363. {
  364. { 0, 1, 2 },
  365. { 0, 1, 3 },
  366. { 0, 2, 3 },
  367. { 1, 2, 3 }
  368. };
  369. for(UINT32 j = 0; j < 4; j++)
  370. {
  371. Vector3 A = mTempTetrahedronPositions[volume.vertices[Permutations[j][0]]];
  372. Vector3 B = mTempTetrahedronPositions[volume.vertices[Permutations[j][1]]];
  373. Vector3 C = mTempTetrahedronPositions[volume.vertices[Permutations[j][2]]];
  374. // Make sure the triangle is clockwise, facing away from the center
  375. Vector3 e0 = A - C;
  376. Vector3 e1 = B - C;
  377. Vector3 normal = e0.cross(e1);
  378. if (normal.dot(A - center) > 0.0f)
  379. std::swap(B, C);
  380. posIter.addValue(A);
  381. posIter.addValue(B);
  382. posIter.addValue(C);
  383. idIter.addValue(tetIdx);
  384. idIter.addValue(tetIdx);
  385. idIter.addValue(tetIdx);
  386. indices[0] = tetIdx * 4 * 3 + j * 3 + 0;
  387. indices[1] = tetIdx * 4 * 3 + j * 3 + 1;
  388. indices[2] = tetIdx * 4 * 3 + j * 3 + 2;
  389. indices += 3;
  390. }
  391. tetIdx++;
  392. }
  393. // Generate an edge map for outer faces (required for step below)
  394. struct Edge
  395. {
  396. UINT32 vertInner[2];
  397. UINT32 vertOuter[2];
  398. UINT32 face[2];
  399. };
  400. FrameUnorderedMap<std::pair<INT32, INT32>, Edge, pair_hash> edgeMap;
  401. for(UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  402. {
  403. if (!validTets[outerFaces[i].tetrahedron])
  404. continue;
  405. for (UINT32 j = 0; j < 3; ++j)
  406. {
  407. UINT32 v0 = outerFaces[i].innerVertices[j];
  408. UINT32 v1 = outerFaces[i].innerVertices[(j + 1) % 3];
  409. // Keep the same ordering so other faces can find the same edge
  410. if (v0 > v1)
  411. std::swap(v0, v1);
  412. auto iterFind = edgeMap.find(std::make_pair((INT32)v0, (INT32)v1));
  413. if (iterFind != edgeMap.end())
  414. {
  415. iterFind->second.face[1] = i;
  416. }
  417. else
  418. {
  419. Edge edge;
  420. edge.vertInner[0] = outerFaces[i].innerVertices[j];
  421. edge.vertInner[1] = outerFaces[i].innerVertices[(j + 1) % 3];
  422. edge.vertOuter[0] = outerFaces[i].outerVertices[j];
  423. edge.vertOuter[1] = outerFaces[i].outerVertices[(j + 1) % 3];
  424. edge.face[0] = i;
  425. edge.face[1] = -1;
  426. edgeMap.insert(std::make_pair(std::make_pair((INT32)v0, (INT32)v1), edge));
  427. }
  428. }
  429. }
  430. // Generate front and back triangles for extruded outer faces
  431. UINT32 faceIdx = 0;
  432. for(UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  433. {
  434. if (!validTets[outerFaces[i].tetrahedron])
  435. continue;
  436. const TetrahedronFaceData& entry = outerFaces[i];
  437. static const UINT32 Permutations[2][3] = { {0, 1, 2 }, { 3, 4, 5} };
  438. // Make sure the triangle is clockwise, facing away from the center
  439. Vector3 center(BsZero);
  440. for (UINT32 k = 0; k < 3; k++)
  441. {
  442. center += mTempTetrahedronPositions[entry.innerVertices[k]];
  443. center += mTempTetrahedronPositions[entry.outerVertices[k]];
  444. }
  445. center /= 6.0f;
  446. for(UINT32 j = 0; j < 2; ++j)
  447. {
  448. UINT32 idxA = Permutations[j][0];
  449. UINT32 idxB = Permutations[j][1];
  450. UINT32 idxC = Permutations[j][2];
  451. idxA = idxA > 2 ? entry.outerVertices[idxA - 3] : entry.innerVertices[idxA];
  452. idxB = idxB > 2 ? entry.outerVertices[idxB - 3] : entry.innerVertices[idxB];
  453. idxC = idxC > 2 ? entry.outerVertices[idxC - 3] : entry.innerVertices[idxC];
  454. Vector3 A = mTempTetrahedronPositions[idxA];
  455. Vector3 B = mTempTetrahedronPositions[idxB];
  456. Vector3 C = mTempTetrahedronPositions[idxC];
  457. Vector3 e0 = A - C;
  458. Vector3 e1 = B - C;
  459. Vector3 normal = e0.cross(e1);
  460. if (normal.dot(A - center) > 0.0f)
  461. std::swap(A, B);
  462. posIter.addValue(A);
  463. posIter.addValue(B);
  464. posIter.addValue(C);
  465. idIter.addValue(tetIdx + faceIdx);
  466. idIter.addValue(tetIdx + faceIdx);
  467. idIter.addValue(tetIdx + faceIdx);
  468. indices[0] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + j * 3 + 0;
  469. indices[1] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + j * 3 + 1;
  470. indices[2] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + j * 3 + 2;
  471. indices += 3;
  472. }
  473. faceIdx++;
  474. }
  475. // Generate sides for extruded outer faces
  476. UINT32 sideIdx = 0;
  477. for(auto& entry : edgeMap)
  478. {
  479. const Edge& edge = entry.second;
  480. for (UINT32 i = 0; i < 2; i++)
  481. {
  482. const TetrahedronFaceData& face = outerFaces[edge.face[i]];
  483. // Make sure the triangle is clockwise, facing away from the center
  484. Vector3 center(BsZero);
  485. for (UINT32 k = 0; k < 3; k++)
  486. {
  487. center += mTempTetrahedronPositions[face.innerVertices[k]];
  488. center += mTempTetrahedronPositions[face.outerVertices[k]];
  489. }
  490. center /= 6.0f;
  491. static const UINT32 Permutations[2][3] = { {0, 1, 2 }, { 1, 2, 3} };
  492. for(UINT32 j = 0; j < 2; ++j)
  493. {
  494. UINT32 idxA = Permutations[j][0];
  495. UINT32 idxB = Permutations[j][1];
  496. UINT32 idxC = Permutations[j][2];
  497. idxA = idxA > 1 ? edge.vertOuter[idxA - 2] : edge.vertInner[idxA];
  498. idxB = idxB > 1 ? edge.vertOuter[idxB - 2] : edge.vertInner[idxB];
  499. idxC = idxC > 1 ? edge.vertOuter[idxC - 2] : edge.vertInner[idxC];
  500. Vector3 A = mTempTetrahedronPositions[idxA];
  501. Vector3 B = mTempTetrahedronPositions[idxB];
  502. Vector3 C = mTempTetrahedronPositions[idxC];
  503. Vector3 e0 = A - C;
  504. Vector3 e1 = B - C;
  505. Vector3 normal = e0.cross(e1);
  506. if (normal.dot(A - center) > 0.0f)
  507. std::swap(A, B);
  508. posIter.addValue(A);
  509. posIter.addValue(B);
  510. posIter.addValue(C);
  511. idIter.addValue(tetIdx + edge.face[i]);
  512. idIter.addValue(tetIdx + edge.face[i]);
  513. idIter.addValue(tetIdx + edge.face[i]);
  514. indices[0] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + sideIdx * 2 * 3 + j * 3 + 0;
  515. indices[1] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + sideIdx * 2 * 3 + j * 3 + 1;
  516. indices[2] = tetIdx * 4 * 3 + faceIdx * 2 * 3 + sideIdx * 2 * 3 + j * 3 + 2;
  517. indices += 3;
  518. }
  519. sideIdx++;
  520. }
  521. }
  522. // Generate "caps" on the end of the extruded volume
  523. UINT32 capIdx = 0;
  524. for(UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  525. {
  526. if (!validTets[outerFaces[i].tetrahedron])
  527. continue;
  528. const TetrahedronFaceData& entry = outerFaces[i];
  529. Vector3 A = mTempTetrahedronPositions[entry.outerVertices[0]];
  530. Vector3 B = mTempTetrahedronPositions[entry.outerVertices[1]];
  531. Vector3 C = mTempTetrahedronPositions[entry.outerVertices[2]];
  532. // Make sure the triangle is clockwise, facing toward the center
  533. const Tetrahedron& tet = mTetrahedronInfos[entry.tetrahedron].volume;
  534. Vector3 center(BsZero);
  535. for(UINT32 j = 0; j < 4; j++)
  536. center += mTempTetrahedronPositions[tet.vertices[j]];
  537. center /= 4.0f;
  538. Vector3 e0 = A - C;
  539. Vector3 e1 = B - C;
  540. Vector3 normal = e0.cross(e1);
  541. if (normal.dot(A - center) < 0.0f)
  542. std::swap(B, C);
  543. posIter.addValue(A);
  544. posIter.addValue(B);
  545. posIter.addValue(C);
  546. idIter.addValue(-1);
  547. idIter.addValue(-1);
  548. idIter.addValue(-1);
  549. indices[0] = tetIdx * 4 * 3 + faceIdx * 8 * 3 + capIdx * 3 + 0;
  550. indices[1] = tetIdx * 4 * 3 + faceIdx * 8 * 3 + capIdx * 3 + 1;
  551. indices[2] = tetIdx * 4 * 3 + faceIdx * 8 * 3 + capIdx * 3 + 2;
  552. indices += 3;
  553. capIdx++;
  554. }
  555. mVolumeMesh = Mesh::create(meshData);
  556. // Map vertices to actual SH coefficient indices, and write GPU buffer with tetrahedron information
  557. if ((mNumValidTetrahedra + numValidFaces) > mMaxTetrahedra)
  558. {
  559. UINT32 newSize = Math::divideAndRoundUp(mNumValidTetrahedra + numValidFaces, 64U) * 64U;
  560. resizeTetrahedronBuffer(newSize);
  561. }
  562. TetrahedronDataGPU* dst = (TetrahedronDataGPU*)mTetrahedronInfosGPU->lock(0, mTetrahedronInfosGPU->getSize(),
  563. GBL_WRITE_ONLY_DISCARD);
  564. // Write inner tetrahedron data
  565. for (UINT32 i = 0; i < (UINT32)mTetrahedronInfos.size(); i++)
  566. {
  567. if (!validTets[i])
  568. continue;
  569. TetrahedronData& entry = mTetrahedronInfos[i];
  570. Vector2I offsets[4];
  571. for(UINT32 j = 0; j < 4; ++j)
  572. {
  573. entry.volume.vertices[j] = mTempTetrahedronBufferIndices[entry.volume.vertices[j]];
  574. offsets[j] = mTempTetrahedronBufferOffsets[entry.volume.vertices[j]];
  575. }
  576. memcpy(dst->indices, entry.volume.vertices, sizeof(UINT32) * 4);
  577. memcpy(dst->offsets, &offsets, sizeof(offsets));
  578. memcpy(&dst->transform, &entry.transform, sizeof(float) * 12);
  579. dst++;
  580. }
  581. // Write extruded face data
  582. for (UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  583. {
  584. if (!validTets[outerFaces[i].tetrahedron])
  585. continue;
  586. const TetrahedronFaceData& entry = outerFaces[i];
  587. UINT32 indices[4];
  588. Vector2I offsets[4];
  589. for(UINT32 j = 0; j < 3; j++)
  590. {
  591. indices[j] = mTempTetrahedronBufferIndices[entry.innerVertices[j]];
  592. offsets[j] = mTempTetrahedronBufferOffsets[entry.innerVertices[j]];
  593. }
  594. indices[3] = -1;
  595. memcpy(dst->indices, indices, sizeof(UINT32) * 4);
  596. memcpy(dst->offsets, offsets, sizeof(offsets));
  597. memcpy(&dst->transform, &entry.transform, sizeof(float) * 12);
  598. dst++;
  599. }
  600. mTetrahedronInfosGPU->unlock();
  601. // Write data specific to faces
  602. if (numValidFaces > mMaxFaces)
  603. {
  604. UINT32 newSize = Math::divideAndRoundUp(numValidFaces, 64U) * 64U;
  605. resizeTetrahedronFaceBuffer(newSize);
  606. }
  607. TetrahedronFaceDataGPU* faceDst = (TetrahedronFaceDataGPU*)mTetrahedronFaceInfosGPU->lock(0,
  608. mTetrahedronFaceInfosGPU->getSize(), GBL_WRITE_ONLY_DISCARD);
  609. for (UINT32 i = 0; i < (UINT32)outerFaces.size(); i++)
  610. {
  611. if (!validTets[outerFaces[i].tetrahedron])
  612. continue;
  613. const TetrahedronFaceData& entry = outerFaces[i];
  614. for (UINT32 j = 0; j < 3; j++)
  615. {
  616. faceDst->corners[j] = mTempTetrahedronPositions[entry.innerVertices[j]];
  617. faceDst->normals[j] = entry.normals[j];
  618. }
  619. faceDst->isQuadratic = entry.quadratic ? 1 : 0;
  620. faceDst++;
  621. }
  622. mTetrahedronFaceInfosGPU->unlock();
  623. bs_stack_free(validTets);
  624. mTempTetrahedronPositions.clear();
  625. mTempTetrahedronBufferIndices.clear();
  626. mTetrahedronVolumeDirty = false;
  627. }
  628. bool LightProbes::hasAnyProbes() const
  629. {
  630. for(auto& entry : mVolumes)
  631. {
  632. UINT32 numProbes = entry.volume->getNumActiveProbes();
  633. if (numProbes > 0)
  634. return true;
  635. }
  636. return false;
  637. }
  638. LightProbesInfo LightProbes::getInfo() const
  639. {
  640. LightProbesInfo info;
  641. info.shCoefficients = mProbeCoefficientsGPU;
  642. info.tetrahedra = mTetrahedronInfosGPU;
  643. info.faces = mTetrahedronFaceInfosGPU;
  644. info.tetrahedraVolume = mVolumeMesh;
  645. info.numTetrahedra = mNumValidTetrahedra;
  646. return info;
  647. }
  648. void LightProbes::resizeTetrahedronBuffer(UINT32 count)
  649. {
  650. GPU_BUFFER_DESC desc;
  651. desc.type = GBT_STRUCTURED;
  652. desc.elementSize = sizeof(TetrahedronDataGPU);
  653. desc.elementCount = count;
  654. desc.usage = GBU_STATIC;
  655. desc.format = BF_UNKNOWN;
  656. mTetrahedronInfosGPU = GpuBuffer::create(desc);
  657. mMaxTetrahedra = count;
  658. }
  659. void LightProbes::resizeTetrahedronFaceBuffer(UINT32 count)
  660. {
  661. GPU_BUFFER_DESC desc;
  662. desc.type = GBT_STRUCTURED;
  663. desc.elementSize = sizeof(TetrahedronFaceDataGPU);
  664. desc.elementCount = count;
  665. desc.usage = GBU_STATIC;
  666. desc.format = BF_UNKNOWN;
  667. mTetrahedronFaceInfosGPU = GpuBuffer::create(desc);
  668. mMaxFaces = count;
  669. }
  670. void LightProbes::resizeCoefficientTexture(UINT32 numRows)
  671. {
  672. TEXTURE_DESC desc;
  673. desc.width = 4096;
  674. desc.height = numRows;
  675. desc.usage = TU_LOADSTORE | TU_RENDERTARGET;
  676. desc.format = PF_RGBA32F;
  677. SPtr<Texture> newTexture = Texture::create(desc);
  678. if (mProbeCoefficientsGPU)
  679. mProbeCoefficientsGPU->copy(newTexture);
  680. mProbeCoefficientsGPU = newTexture;
  681. mMaxCoefficientRows = numRows;
  682. }
  683. void LightProbes::generateTetrahedronData(Vector<Vector3>& positions, Vector<TetrahedronData>& tetrahedra,
  684. Vector<TetrahedronFaceData>& faces, bool generateExtrapolationVolume)
  685. {
  686. bs_frame_mark();
  687. {
  688. TetrahedronVolume volume = Triangulation::tetrahedralize(positions);
  689. if (generateExtrapolationVolume)
  690. {
  691. // Add geometry so we can handle the case when the interpolation position falls outside of the tetrahedra
  692. // volume. We use this geometry to project the position to the nearest face.
  693. UINT32 numOuterFaces = (UINT32)volume.outerFaces.size();
  694. // Calculate face normals for outer faces
  695. //// Make an edge map
  696. struct Edge
  697. {
  698. INT32 faces[2];
  699. INT32 oppositeVerts[2];
  700. };
  701. FrameUnorderedMap<std::pair<INT32, INT32>, Edge, pair_hash> edgeMap;
  702. for (UINT32 i = 0; i < numOuterFaces; ++i)
  703. {
  704. for (UINT32 j = 0; j < 3; ++j)
  705. {
  706. INT32 v0 = volume.outerFaces[i].vertices[j];
  707. INT32 v1 = volume.outerFaces[i].vertices[(j + 1) % 3];
  708. // Keep the same ordering so other faces can find the same edge
  709. if (v0 > v1)
  710. std::swap(v0, v1);
  711. auto iterFind = edgeMap.find(std::make_pair(v0, v1));
  712. if (iterFind != edgeMap.end())
  713. {
  714. iterFind->second.faces[1] = i;
  715. iterFind->second.oppositeVerts[1] = (j + 2) % 3;
  716. }
  717. else
  718. {
  719. Edge edge;
  720. edge.faces[0] = i;
  721. edge.oppositeVerts[0] = (j + 2) % 3;
  722. edgeMap.insert(std::make_pair(std::make_pair(v0, v1), edge));
  723. }
  724. }
  725. }
  726. //// Generate face normals
  727. struct FaceVertex
  728. {
  729. Vector3 normal = Vector3::ZERO;
  730. UINT32 outerIdx = -1;
  731. };
  732. FrameVector<Vector3> faceNormals(volume.outerFaces.size());
  733. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  734. {
  735. const Vector3& v0 = positions[volume.outerFaces[i].vertices[0]];
  736. const Vector3& v1 = positions[volume.outerFaces[i].vertices[1]];
  737. const Vector3& v2 = positions[volume.outerFaces[i].vertices[2]];
  738. Vector3 e0 = v1 - v0;
  739. Vector3 e1 = v2 - v0;
  740. // Make sure the normal is facing away from the center
  741. const Tetrahedron& tet = volume.tetrahedra[volume.outerFaces[i].tetrahedron];
  742. Vector3 center(BsZero);
  743. for(UINT32 j = 0; j < 4; j++)
  744. center += positions[tet.vertices[j]];
  745. center /= 4.0f;
  746. Vector3 normal = Vector3::normalize(e0.cross(e1));
  747. if (normal.dot(v0 - center) < 0.0f)
  748. normal = -normal;
  749. faceNormals[i] = normal;
  750. }
  751. //// Generate vertex normals
  752. FrameUnorderedMap<INT32, FaceVertex> faceVertices;
  753. for (auto& entry : edgeMap)
  754. {
  755. const Edge& edge = entry.second;
  756. auto accumulateNormalForEdgeVertex = [&](UINT32 v0Idx, UINT32 v1Idx)
  757. {
  758. auto iter = faceVertices.insert(std::make_pair(v0Idx, FaceVertex()));
  759. FaceVertex& accum = iter.first->second;
  760. const Vector3& v0 = positions[v0Idx];
  761. auto accumulateNormalForFace = [&](INT32 faceIdx, INT32 v2LocIdx)
  762. {
  763. const TetrahedronFace& face = volume.outerFaces[faceIdx];
  764. // Vertices on the face, that aren't the vertex we're calculating the normal for
  765. const Vector3& v1 = positions[v1Idx];
  766. const Vector3& v2 = positions[face.vertices[v2LocIdx]];
  767. // Weight the contribution to the normal based on the angle spanned by the triangle
  768. Vector3 e0 = Vector3::normalize(v1 - v0);
  769. Vector3 e1 = Vector3::normalize(v2 - v0);
  770. float weight = acos(e0.dot(e1));
  771. accum.normal += weight * faceNormals[faceIdx];
  772. };
  773. accumulateNormalForFace(edge.faces[0], entry.second.oppositeVerts[0]);
  774. accumulateNormalForFace(edge.faces[1], entry.second.oppositeVerts[1]);
  775. };
  776. accumulateNormalForEdgeVertex(entry.first.first, entry.first.second);
  777. accumulateNormalForEdgeVertex(entry.first.second, entry.first.first);
  778. }
  779. for (auto& entry : faceVertices)
  780. entry.second.normal.normalize();
  781. // For each face vertex, generate an outer vertex along its normal
  782. static const float ExtrapolationDistance = 5.0f;
  783. for(auto& entry : faceVertices)
  784. {
  785. entry.second.outerIdx = (UINT32)positions.size();
  786. Vector3 outerPos = positions[entry.first] + entry.second.normal * ExtrapolationDistance;
  787. positions.push_back(outerPos);
  788. }
  789. // Generate face data
  790. for (UINT32 i = 0; i < numOuterFaces; ++i)
  791. {
  792. const TetrahedronFace& face = volume.outerFaces[i];
  793. TetrahedronFaceData faceData;
  794. faceData.tetrahedron = face.tetrahedron;
  795. for (UINT32 j = 0; j < 3; j++)
  796. {
  797. const FaceVertex& faceVertex = faceVertices[face.vertices[j]];
  798. faceData.innerVertices[j] = face.vertices[j];
  799. faceData.outerVertices[j] = faceVertex.outerIdx;
  800. faceData.normals[j] = faceVertex.normal;
  801. }
  802. // Add a link on the source tetrahedron to the face data
  803. Tetrahedron& innerTet = volume.tetrahedra[face.tetrahedron];
  804. for(UINT32 j = 0; j < 4; j++)
  805. {
  806. if (innerTet.neighbors[j] == -1)
  807. {
  808. // Note: Not searching for opposite neighbor here. If tet. has multiple free faces then we
  809. // can't just pick the first one
  810. innerTet.neighbors[j] = (UINT32)volume.tetrahedra.size() + (UINT32)faces.size();
  811. break;
  812. }
  813. }
  814. // We need a way to project a point outside the tetrahedron volume onto an outer face, then calculate
  815. // triangle's barycentric coordinates. Use use the per-vertex normals to extrude the triangle face into
  816. // infinity.
  817. // Our point can be represented as:
  818. // p == a (p0 + t*v0) + b (p1 + t*v1) + c (p2 + t*v2)
  819. //
  820. // where a, b and c are barycentric coordinates,
  821. // p0, p1, p2 are the corners of the face
  822. // v0, v1, v2 are the vertex normals, per corner
  823. // t is the distance from the triangle to the point
  824. //
  825. // Essentially we're calculating the corners of a bigger triangle that's "t" units away from the
  826. // face, and its corners lie along the per-vertex normals. Point "p" will lie on that triangle, for which
  827. // we can then calculate barycentric coordinates normally.
  828. //
  829. // First we substitute: c = 1 - a - b
  830. // p == a (p0 + t v0) + b (p1 + t v1) + (1 - a - b) (p2 + t v2)
  831. // p == a (p0 + t v0) + b (p1 + t v1) + (p2 + t v2) - a (p2 + t v2) - b (p2 + t v2)
  832. // p == a (p0 - p2 + t v0 - t v2) + b (p1 - p2 + t v1 - t v2) + (p2 + t v2)
  833. //
  834. // And move everything to one side:
  835. // p - p2 - t v2 == a (p0 - p2 + t ( v0 - v2)) + b (p1 - p2 + t ( v1 - v2))
  836. // a (p0 - p2 + t ( v0 - v2)) + b (p1 - p2 + t ( v1 - v2)) - (p - p2 - t v2) == 0
  837. //
  838. // We rewrite it using:
  839. // Ap = p0 - p2
  840. // Av = v0 - v2
  841. // Bp = p1 - p2
  842. // Bv = v1 - v2
  843. // Cp = p - p2
  844. // Cv = -v2
  845. //
  846. // Which yields:
  847. // a (Ap + t Av) + b (Bp + t Bv) - (Cp + t Cv) == 0
  848. //
  849. // Which can be written in matrix form:
  850. //
  851. // M = {Ap + t Av, Bp + t Bv, Cp + t Cv}
  852. // a 0
  853. // M * [ b ] = [0]
  854. // -1 0
  855. //
  856. // From that we can tell that matrix M cannot be inverted, because if we multiply the zero vector with the
  857. // inverted matrix the result would be zero, and not [a, b, -1]. Since the matrix cannot be inverted
  858. // det(M) == 0.
  859. //
  860. // We can use that fact to calculate "t". After we have "t" we can calculate barycentric coordinates
  861. // normally.
  862. //
  863. // Solving equation det(M) == 0 yields a cubic in form:
  864. // p t^3 + q t^2 + r t + s = 0
  865. //
  866. // We'll convert this to monic form, by dividing by p:
  867. // t^3 + q/p t^2 + r/p t + s/p = 0
  868. //
  869. // Or if p ends up being zero, we end up with a quadratic instead:
  870. // q t^2 + r t + s = 0
  871. //
  872. // We want to create a matrix that when multiplied with the position, yields us the three coefficients,
  873. // which we can then use to solve for "t". For this we create a 4x3 matrix, where each row represents
  874. // a solution for one of the coefficients. We factor contributons to each coefficient whether they depend on
  875. // position x, y, z, or don't depend on position (row columns, in that order respectively).
  876. const Vector3& p0 = positions[faceData.innerVertices[0]];
  877. const Vector3& p1 = positions[faceData.innerVertices[1]];
  878. const Vector3& p2 = positions[faceData.innerVertices[2]];
  879. const Vector3& v0 = faceVertices[faceData.innerVertices[0]].normal;
  880. const Vector3& v1 = faceVertices[faceData.innerVertices[1]].normal;
  881. const Vector3& v2 = faceVertices[faceData.innerVertices[2]].normal;
  882. float p =
  883. v2.x * v1.y * v0.z -
  884. v1.x * v2.y * v0.z -
  885. v2.x * v0.y * v1.z +
  886. v0.x * v2.y * v1.z +
  887. v1.x * v0.y * v2.z -
  888. v0.x * v1.y * v2.z;
  889. 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;
  890. 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;
  891. 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;
  892. 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 +
  893. v1.y * v0.z * p2.x - v0.y * v1.z * p2.x - v2.x * v1.z * p0.y + v1.x * v2.z * p0.y +
  894. v2.x * v0.z * p1.y - v0.x * v2.z * p1.y - v1.x * v0.z * p2.y + v0.x * v1.z * p2.y +
  895. v2.x * v1.y * p0.z - v1.x * v2.y * p0.z - v2.x * v0.y * p1.z + v0.x * v2.y * p1.z +
  896. v1.x * v0.y * p2.z - v0.x * v1.y * p2.z;
  897. 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 -
  898. v1.y * p0.z + v2.y * p0.z + v0.y * p1.z - v2.y * p1.z - v0.y * p2.z + v1.y * p2.z;
  899. 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 +
  900. v1.x * p0.z - v2.x * p0.z - v0.x * p1.z + v2.x * p1.z + v0.x * p2.z - v1.x * p2.z;
  901. 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 -
  902. v1.x * p0.y + v2.x * p0.y + v0.x * p1.y - v2.x * p1.y - v0.x * p2.y + v1.x * p2.y;
  903. 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 +
  904. v1.z * p0.x * p2.y - v0.z * p1.x * p2.y - v2.y * p1.x * p0.z + v1.y * p2.x * p0.z +
  905. v2.x * p1.y * p0.z - v1.x * p2.y * p0.z + v2.y * p0.x * p1.z - v0.y * p2.x * p1.z -
  906. v2.x * p0.y * p1.z + v0.x * p2.y * p1.z - v1.y * p0.x * p2.z + v0.y * p1.x * p2.z +
  907. v1.x * p0.y * p2.z - v0.x * p1.y * p2.z;
  908. 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;
  909. 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;
  910. 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;
  911. float sw = p2.x * p1.y * p0.z - p1.x * p2.y * p0.z - p2.x * p0.y * p1.z +
  912. p0.x * p2.y * p1.z + p1.x * p0.y * p2.z - p0.x * p1.y * p2.z;
  913. faceData.transform[0][0] = qx;
  914. faceData.transform[0][1] = qy;
  915. faceData.transform[0][2] = qz;
  916. faceData.transform[0][3] = qw;
  917. faceData.transform[1][0] = rx;
  918. faceData.transform[1][1] = ry;
  919. faceData.transform[1][2] = rz;
  920. faceData.transform[1][3] = rw;
  921. faceData.transform[2][0] = sx;
  922. faceData.transform[2][1] = sy;
  923. faceData.transform[2][2] = sz;
  924. faceData.transform[2][3] = sw;
  925. // Unused
  926. faceData.transform[3][0] = 0.0f;
  927. faceData.transform[3][1] = 0.0f;
  928. faceData.transform[3][2] = 0.0f;
  929. faceData.transform[3][3] = 0.0f;
  930. if (fabs(p) > 0.00001f)
  931. {
  932. faceData.transform = faceData.transform * (1.0f / p);
  933. faceData.quadratic = false;
  934. }
  935. else // Quadratic
  936. {
  937. faceData.quadratic = true;
  938. }
  939. faces.push_back(faceData);
  940. }
  941. }
  942. else
  943. {
  944. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  945. {
  946. const TetrahedronFace& face = volume.outerFaces[i];
  947. TetrahedronFaceData faceData;
  948. for (UINT32 j = 0; j < 3; j++)
  949. {
  950. faceData.innerVertices[j] = face.vertices[j];
  951. faceData.outerVertices[j] = -1;
  952. faceData.normals[j] = Vector3::ZERO;
  953. }
  954. faceData.tetrahedron = face.tetrahedron;
  955. faceData.transform = Matrix4::IDENTITY;
  956. faceData.quadratic = false;
  957. faces.push_back(faceData);
  958. }
  959. }
  960. // Generate matrices
  961. UINT32 numOutputTets = (UINT32)volume.tetrahedra.size();
  962. tetrahedra.reserve(numOutputTets);
  963. //// For inner tetrahedrons
  964. for(UINT32 i = 0; i < (UINT32)numOutputTets; ++i)
  965. {
  966. TetrahedronData entry;
  967. entry.volume = volume.tetrahedra[i];
  968. // Generate a matrix that can be used for calculating barycentric coordinates
  969. // To determine a point within a tetrahedron, using barycentric coordinates, we use:
  970. // P = (P1 - P4) * a + (P2 - P4) * b + (P3 - P4) * c + P4
  971. //
  972. // Where P1, P2, P3, P4 are the corners of the tetrahedron.
  973. //
  974. // Expanded for each coordinate this is:
  975. // x = (x1 - x4) * a + (x2 - x4) * b + (x3 - x4) * c + x4
  976. // y = (y1 - y4) * a + (y2 - y4) * b + (y3 - y4) * c + y4
  977. // z = (z1 - z4) * a + (z2 - z4) * b + (z3 - z4) * c + z4
  978. //
  979. // In matrix form this is:
  980. // a
  981. // P = [P1 - P4, P2 - P4, P3 - P4, P4] [b]
  982. // c
  983. // 1
  984. //
  985. // Solved for barycentric coordinates:
  986. // a
  987. // [b] = Minv * P
  988. // c
  989. // 1
  990. //
  991. // Where Minv is the inverse of the matrix above.
  992. const Vector3& P1 = positions[volume.tetrahedra[i].vertices[0]];
  993. const Vector3& P2 = positions[volume.tetrahedra[i].vertices[1]];
  994. const Vector3& P3 = positions[volume.tetrahedra[i].vertices[2]];
  995. const Vector3& P4 = positions[volume.tetrahedra[i].vertices[3]];
  996. Vector3 E1 = P1 - P4;
  997. Vector3 E2 = P2 - P4;
  998. Vector3 E3 = P3 - P4;
  999. Matrix4 mat;
  1000. mat.setColumn(0, Vector4(E1, 0.0f));
  1001. mat.setColumn(1, Vector4(E2, 0.0f));
  1002. mat.setColumn(2, Vector4(E3, 0.0f));
  1003. mat.setColumn(3, Vector4(P4, 1.0f));
  1004. entry.transform = mat.inverse();
  1005. tetrahedra.push_back(entry);
  1006. }
  1007. }
  1008. bs_frame_clear();
  1009. }
  1010. }}