BsLightProbes.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsLightProbes.h"
  4. #include "BsLightProbeVolume.h"
  5. #include "BsGpuBuffer.h"
  6. #include "BsRendererView.h"
  7. #include "BsIBLUtility.h"
  8. #include "BsRendererManager.h"
  9. #include "BsRenderBeast.h"
  10. namespace bs { namespace ct
  11. {
  12. LightProbes::LightProbes()
  13. :mTetrahedronVolumeDirty(false), mNumAllocatedEntries(0), mNumUsedEntries(0)
  14. {
  15. resizeCoefficientBuffer(512);
  16. }
  17. void LightProbes::notifyAdded(const SPtr<LightProbeVolume>& volume)
  18. {
  19. UINT32 handle = (UINT32)mVolumes.size();
  20. VolumeInfo info;
  21. info.volume = volume;
  22. info.isDirty = true;
  23. info.lastUpdatedProbe = 0;
  24. mVolumes.push_back(info);
  25. volume->setRendererId(handle);
  26. notifyDirty(volume);
  27. }
  28. void LightProbes::notifyDirty(const SPtr<LightProbeVolume>& volume)
  29. {
  30. volume->prune(mEmptyEntries);
  31. UINT32 handle = volume->getRendererId();
  32. mVolumes[handle].isDirty = true;
  33. mVolumes[handle].lastUpdatedProbe = 0;
  34. mTetrahedronVolumeDirty = true;
  35. }
  36. void LightProbes::notifyRemoved(const SPtr<LightProbeVolume>& volume)
  37. {
  38. volume->prune(mEmptyEntries, true);
  39. UINT32 handle = volume->getRendererId();
  40. LightProbeVolume* lastVolume = mVolumes.back().volume.get();
  41. UINT32 lastHandle = lastVolume->getRendererId();
  42. if (handle != lastHandle)
  43. {
  44. // Swap current last element with the one we want to erase
  45. std::swap(mVolumes[handle], mVolumes[lastHandle]);
  46. lastVolume->setRendererId(handle);
  47. }
  48. // Erase last (empty) element
  49. mVolumes.erase(mVolumes.end() - 1);
  50. mTetrahedronVolumeDirty = true;
  51. }
  52. void LightProbes::updateProbes(const FrameInfo& frameInfo, UINT32 maxProbes)
  53. {
  54. if(mTetrahedronVolumeDirty)
  55. {
  56. // Gather all positions
  57. for(auto& entry : mVolumes)
  58. {
  59. const Vector<Vector3>& positions = entry.volume->getLightProbePositions();
  60. Vector3 offset = entry.volume->getPosition();
  61. Quaternion rotation = entry.volume->getRotation();
  62. for(auto& localPos : positions)
  63. {
  64. Vector3 transformedPos = rotation.rotate(localPos) + offset;
  65. mTempTetrahedronPositions.push_back(transformedPos);
  66. }
  67. }
  68. mTetrahedronInfos.clear();
  69. mTetrahedronBounds.clear();
  70. generateTetrahedronData(mTempTetrahedronPositions, mTetrahedronInfos, false);
  71. // Generate bounds
  72. for(auto& entry : mTetrahedronInfos)
  73. {
  74. // Skipping outer faces
  75. if (entry.volume.neighbors[3] < 0)
  76. continue;
  77. AABox aabox = AABox(Vector3::INF, -Vector3::INF);
  78. for (int i = 0; i < 4; ++i)
  79. aabox.merge(mTempTetrahedronPositions[entry.volume.neighbors[i]]);
  80. mTetrahedronBounds.push_back(aabox);
  81. }
  82. mTempTetrahedronPositions.clear();
  83. mTetrahedronVolumeDirty = false;
  84. }
  85. // Render dirty probes
  86. UINT32 numProbeUpdates = 0;
  87. for(auto& entry : mVolumes)
  88. {
  89. if (!entry.isDirty)
  90. continue;
  91. Vector<LightProbeInfo>& probes = entry.volume->getLightProbeInfos();
  92. const Vector<Vector3>& probePositions = entry.volume->getLightProbePositions();
  93. for (; entry.lastUpdatedProbe < (UINT32)probes.size(); ++entry.lastUpdatedProbe)
  94. {
  95. LightProbeInfo& probeInfo = probes[entry.lastUpdatedProbe];
  96. // Assign buffer idx, if not assigned
  97. if(probeInfo.bufferIdx == -1)
  98. {
  99. if(!mEmptyEntries.empty())
  100. {
  101. probeInfo.bufferIdx = mEmptyEntries.back();
  102. mEmptyEntries.erase(mEmptyEntries.end() - 1);
  103. }
  104. else
  105. {
  106. if(mNumUsedEntries >= mNumAllocatedEntries)
  107. resizeCoefficientBuffer(mNumAllocatedEntries * 2);
  108. probeInfo.bufferIdx = mNumUsedEntries++;
  109. }
  110. }
  111. if(probeInfo.flags == LightProbeFlags::Dirty)
  112. {
  113. TEXTURE_DESC cubemapDesc;
  114. cubemapDesc.type = TEX_TYPE_CUBE_MAP;
  115. cubemapDesc.format = PF_FLOAT16_RGB;
  116. cubemapDesc.width = IBLUtility::IRRADIANCE_CUBEMAP_SIZE;
  117. cubemapDesc.height = IBLUtility::REFLECTION_CUBEMAP_SIZE;
  118. cubemapDesc.usage = TU_STATIC | TU_RENDERTARGET;
  119. SPtr<Texture> cubemap = Texture::create(cubemapDesc);
  120. RenderBeast& renderer = static_cast<RenderBeast&>(*RendererManager::instance().getActive());
  121. renderer.captureSceneCubeMap(cubemap, probePositions[entry.lastUpdatedProbe], true, frameInfo);
  122. IBLUtility::filterCubemapForIrradiance(cubemap, mProbeCoefficientsGPU, probeInfo.bufferIdx);
  123. probeInfo.flags = LightProbeFlags::Clean;
  124. numProbeUpdates++;
  125. }
  126. if (maxProbes != 0 && numProbeUpdates >= numProbeUpdates)
  127. break;
  128. }
  129. if (entry.lastUpdatedProbe == (UINT32)probes.size())
  130. entry.isDirty = false;
  131. }
  132. }
  133. void LightProbes::resizeTetrahedronBuffers(VisibleLightProbeData& data, UINT32 count)
  134. {
  135. {
  136. GPU_BUFFER_DESC desc;
  137. desc.type = GBT_STRUCTURED;
  138. desc.elementSize = sizeof(TetrahedronBoundsGPU);
  139. desc.elementCount = count;
  140. desc.usage = GBU_STATIC;
  141. desc.format = BF_UNKNOWN;
  142. SPtr<GpuBuffer> newBuffer = GpuBuffer::create(desc);
  143. if (data.tetrahedronBounds)
  144. newBuffer->copyData(*data.tetrahedronBounds, 0, 0, data.tetrahedronBounds->getSize(), true);
  145. data.tetrahedronBounds = newBuffer;
  146. }
  147. {
  148. GPU_BUFFER_DESC desc;
  149. desc.type = GBT_STRUCTURED;
  150. desc.elementSize = sizeof(TetrahedronDataGPU);
  151. desc.elementCount = count;
  152. desc.usage = GBU_STATIC;
  153. desc.format = BF_UNKNOWN;
  154. SPtr<GpuBuffer> newBuffer = GpuBuffer::create(desc);
  155. if (data.tetrahedronInfos)
  156. newBuffer->copyData(*data.tetrahedronInfos, 0, 0, data.tetrahedronInfos->getSize(), true);
  157. data.tetrahedronInfos = newBuffer;
  158. }
  159. data.maxNumEntries = count;
  160. }
  161. void LightProbes::resizeCoefficientBuffer(UINT32 count)
  162. {
  163. GPU_BUFFER_DESC desc;
  164. desc.type = GBT_STRUCTURED;
  165. desc.elementSize = sizeof(SHVector3RGB);
  166. desc.elementCount = count;
  167. desc.usage = GBU_STATIC;
  168. desc.format = BF_UNKNOWN;
  169. SPtr<GpuBuffer> newBuffer = GpuBuffer::create(desc);
  170. if (mProbeCoefficientsGPU)
  171. newBuffer->copyData(*mProbeCoefficientsGPU, 0, 0, mProbeCoefficientsGPU->getSize(), true);
  172. mProbeCoefficientsGPU = newBuffer;
  173. mNumAllocatedEntries = count;
  174. }
  175. void LightProbes::updateVisibleProbes(const RendererView& view, VisibleLightProbeData& output)
  176. {
  177. // Ignore all probes past this point
  178. static const float MAX_PROBE_DISTANCE = 100.0f;
  179. const RendererViewProperties& viewProps = view.getProperties();
  180. const ConvexVolume& worldFrustum = viewProps.cullFrustum;
  181. const float maxProbeDistance2 = MAX_PROBE_DISTANCE * MAX_PROBE_DISTANCE;
  182. for (UINT32 i = 0; i < (UINT32)mTetrahedronBounds.size(); i++)
  183. {
  184. float distance2 = viewProps.viewOrigin.squaredDistance(mTetrahedronBounds[i].getCenter());
  185. if (distance2 > maxProbeDistance2)
  186. continue;
  187. if (worldFrustum.intersects(mTetrahedronBounds[i]))
  188. mTempTetrahedronVisibility.push_back(i);
  189. }
  190. UINT32 numVisibleTets = (UINT32)mTempTetrahedronVisibility.size();
  191. if (numVisibleTets > output.maxNumEntries)
  192. {
  193. UINT32 newBufferSize = 256;
  194. if(output.maxNumEntries > 0)
  195. newBufferSize = Math::divideAndRoundUp(numVisibleTets, output.maxNumEntries) * output.maxNumEntries;
  196. resizeTetrahedronBuffers(output, newBufferSize);
  197. }
  198. // Write bounds
  199. {
  200. TetrahedronBoundsGPU* dst = (TetrahedronBoundsGPU*)output.tetrahedronBounds->lock(0,
  201. output.tetrahedronBounds->getSize(), GBL_WRITE_ONLY_DISCARD);
  202. for (auto& entry : mTempTetrahedronVisibility)
  203. {
  204. const AABox& aabox = mTetrahedronBounds[entry];
  205. dst->center = aabox.getCenter();
  206. dst->extents = aabox.getHalfSize();
  207. dst++;
  208. }
  209. output.tetrahedronBounds->unlock();
  210. }
  211. // Write other information
  212. {
  213. TetrahedronDataGPU* dst = (TetrahedronDataGPU*)output.tetrahedronInfos->lock(0,
  214. output.tetrahedronInfos->getSize(), GBL_WRITE_ONLY_DISCARD);
  215. for (auto& entry : mTempTetrahedronVisibility)
  216. {
  217. const TetrahedronData& data = mTetrahedronInfos[entry];
  218. memcpy(dst->indices, data.volume.vertices, sizeof(UINT32) * 4);
  219. memcpy(&dst->transform, &data.transform, sizeof(float) * 12);
  220. dst++;
  221. }
  222. output.tetrahedronBounds->unlock();
  223. }
  224. mTempTetrahedronVisibility.clear();
  225. }
  226. /** Hash value generator for std::pair<INT32, INT32>. */
  227. struct pair_hash
  228. {
  229. size_t operator()(const std::pair<INT32, INT32>& key) const
  230. {
  231. size_t hash = 0;
  232. bs::hash_combine(hash, key.first);
  233. bs::hash_combine(hash, key.second);
  234. return hash;
  235. }
  236. };
  237. void LightProbes::generateTetrahedronData(const Vector<Vector3>& positions, Vector<TetrahedronData>& output,
  238. bool includeOuterFaces)
  239. {
  240. bs_frame_mark();
  241. {
  242. TetrahedronVolume volume = Triangulation::tetrahedralize(positions);
  243. // Generate matrices
  244. UINT32 numOutputTets = (UINT32)volume.tetrahedra.size();
  245. if (includeOuterFaces)
  246. numOutputTets += (UINT32)volume.outerFaces.size();
  247. output.reserve(includeOuterFaces);
  248. // Insert innert tetrahedrons, generate matrices
  249. for(UINT32 i = 0; i < (UINT32)volume.tetrahedra.size(); ++i)
  250. {
  251. TetrahedronData entry;
  252. entry.volume = volume.tetrahedra[i];
  253. // Generate a matrix that can be used for calculating barycentric coordinates
  254. // To determine a point within a tetrahedron, using barycentric coordinates, we use:
  255. // P = (P1 - P4) * a + (P2 - P4) * b + (P3 - P4) * c + P4
  256. //
  257. // Where P1, P2, P3, P4 are the corners of the tetrahedron.
  258. //
  259. // Expanded for each coordinate this is:
  260. // x = (x1 - x4) * a + (x2 - x4) * b + (x3 - x4) * c + x4
  261. // y = (y1 - y4) * a + (y2 - y4) * b + (y3 - y4) * c + y4
  262. // z = (z1 - z4) * a + (z2 - z4) * b + (z3 - z4) * c + z4
  263. //
  264. // In matrix form this is:
  265. // a
  266. // P = [P1 - P4, P2 - P4, P3 - P4, P4] [b]
  267. // c
  268. // 1
  269. //
  270. // Solved for barycentric coordinates:
  271. // a
  272. // [b] = Minv * P
  273. // c
  274. // 1
  275. //
  276. // Where Minv is the inverse of the matrix above.
  277. const Vector3& P1 = positions[volume.tetrahedra[i].vertices[0]];
  278. const Vector3& P2 = positions[volume.tetrahedra[i].vertices[1]];
  279. const Vector3& P3 = positions[volume.tetrahedra[i].vertices[2]];
  280. const Vector3& P4 = positions[volume.tetrahedra[i].vertices[3]];
  281. Matrix4 mat;
  282. mat.setColumn(0, Vector4(P1 - P4, 0.0f));
  283. mat.setColumn(1, Vector4(P2 - P4, 0.0f));
  284. mat.setColumn(2, Vector4(P3 - P4, 0.0f));
  285. mat.setColumn(3, Vector4(P4, 1.0f));
  286. entry.transform = mat.inverse();
  287. output.push_back(entry);
  288. }
  289. if (includeOuterFaces)
  290. {
  291. // Put outer faces into the Tetrahedron structure, for convenience
  292. UINT32 outerFaceOffset = (UINT32)volume.tetrahedra.size();
  293. FrameVector<Tetrahedron> outerTetrahedrons;
  294. outerTetrahedrons.resize(volume.outerFaces.size());
  295. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  296. {
  297. Tetrahedron outerTetrahedron;
  298. memcpy(outerTetrahedron.vertices, volume.outerFaces[i].vertices, sizeof(INT32) * 3);
  299. memset(outerTetrahedron.neighbors, -1, sizeof(INT32) * 3);
  300. outerTetrahedron.vertices[4] = -1; // Marks the tetrahedron as an outer face
  301. outerTetrahedron.neighbors[4] = volume.outerFaces[i].tetrahedron;
  302. outerTetrahedrons[i] = outerTetrahedron;
  303. }
  304. // Connect boundary tetrahedrons with these new outer tetrahedrons
  305. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  306. {
  307. Tetrahedron& tet = volume.tetrahedra[volume.outerFaces[i].tetrahedron];
  308. for (UINT32 j = 0; j < 4; j++)
  309. {
  310. if (tet.neighbors[j] == -1)
  311. tet.neighbors[j] = outerFaceOffset + i;
  312. }
  313. }
  314. // Make a map between outer edges and faces, used in the following algorithms
  315. struct Edge
  316. {
  317. INT32 faces[2];
  318. INT32 oppositeVerts[2];
  319. };
  320. FrameUnorderedMap<std::pair<INT32, INT32>, Edge, pair_hash> edgeMap;
  321. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  322. {
  323. for (UINT32 j = 0; j < 3; ++j)
  324. {
  325. INT32 v0 = volume.outerFaces[i].vertices[j];
  326. INT32 v1 = volume.outerFaces[i].vertices[(j + 1) % 3];
  327. // Keep the same ordering so other faces can find the same edge
  328. if (v0 > v1)
  329. std::swap(v0, v1);
  330. auto iterFind = edgeMap.find(std::make_pair(v0, v1));
  331. if (iterFind != edgeMap.end())
  332. {
  333. iterFind->second.faces[1] = i;
  334. iterFind->second.oppositeVerts[1] = (j + 2) % 3;
  335. }
  336. else
  337. {
  338. Edge edge;
  339. edge.faces[0] = i;
  340. edge.oppositeVerts[0] = (j + 2) % 3;
  341. edgeMap.insert(std::make_pair(std::make_pair(v0, v1), edge));
  342. }
  343. }
  344. }
  345. // Form connections between outer tetrahedrons
  346. for (auto& entry : edgeMap)
  347. {
  348. const Edge& edge = entry.second;
  349. Tetrahedron& tet0 = outerTetrahedrons[outerFaceOffset + edge.faces[0]];
  350. tet0.neighbors[edge.oppositeVerts[0]] = outerFaceOffset + edge.faces[1];
  351. Tetrahedron& tet1 = outerTetrahedrons[outerFaceOffset + edge.faces[1]];
  352. tet1.neighbors[edge.oppositeVerts[1]] = outerFaceOffset + edge.faces[0];
  353. }
  354. // Generate face normals
  355. FrameVector<Vector3> faceNormals(volume.outerFaces.size());
  356. for (UINT32 i = 0; i < (UINT32)volume.outerFaces.size(); ++i)
  357. {
  358. const Vector3& v0 = positions[volume.outerFaces[i].vertices[0]];
  359. const Vector3& v1 = positions[volume.outerFaces[i].vertices[1]];
  360. const Vector3& v2 = positions[volume.outerFaces[i].vertices[2]];
  361. Vector3 e0 = v1 - v0;
  362. Vector3 e1 = v2 - v0;
  363. faceNormals[i] = Vector3::normalize(e1.cross(e0));
  364. }
  365. // Generate vertex normals
  366. struct VertexAccum
  367. {
  368. Vector3 sum;
  369. float weight;
  370. };
  371. FrameUnorderedMap<INT32, Vector3> vertexNormals;
  372. for (auto& entry : edgeMap)
  373. {
  374. const Edge& edge = entry.second;
  375. auto accumulateNormalForEdgeVertex = [&](UINT32 v0Idx, UINT32 v1Idx)
  376. {
  377. auto iter = vertexNormals.insert(std::make_pair(v0Idx, Vector3(BsZero)));
  378. Vector3& accum = iter.first->second;
  379. const Vector3& v0 = positions[v0Idx];
  380. auto accumulateNormalForFace = [&](INT32 faceIdx, INT32 v2LocIdx)
  381. {
  382. const TetrahedronFace& face = volume.outerFaces[faceIdx];
  383. // Vertices on the face, that aren't the vertex we're calculating the normal for
  384. const Vector3& v1 = positions[v1Idx];
  385. const Vector3& v2 = positions[face.vertices[v2LocIdx]];
  386. // Weight the contribution to the normal based on the angle spanned by the triangle
  387. Vector3 e0 = Vector3::normalize(v1 - v0);
  388. Vector3 e1 = Vector3::normalize(v2 - v0);
  389. float weight = acos(e0.dot(e1));
  390. accum += weight * faceNormals[faceIdx];
  391. };
  392. accumulateNormalForFace(edge.faces[0], entry.second.oppositeVerts[0]);
  393. accumulateNormalForFace(edge.faces[1], entry.second.oppositeVerts[1]);
  394. };
  395. accumulateNormalForEdgeVertex(entry.first.first, entry.first.second);
  396. accumulateNormalForEdgeVertex(entry.first.second, entry.first.first);
  397. }
  398. for (auto& entry : vertexNormals)
  399. entry.second.normalize();
  400. // Insert outer tetrahedrons, generate matrices
  401. for(UINT32 i = 0; i < (UINT32)outerTetrahedrons.size(); ++i)
  402. {
  403. TetrahedronData entry;
  404. entry.volume = outerTetrahedrons[i];
  405. // We need a way to project a point outside the tetrahedron volume onto an outer face, then calculate
  406. // triangle's barycentric coordinates. Use use the per-vertex normals to extrude the triangle face into
  407. // infinity.
  408. // Our point can be represented as:
  409. // p == a (p0 + t*v0) + b (p1 + t*v1) + c (p2 + t*v2)
  410. //
  411. // where a, b and c are barycentric coordinates,
  412. // p0, p1, p2 are the corners of the face
  413. // v0, v1, v2 are the vertex normals, per corner
  414. // t is the distance from the triangle to the point
  415. //
  416. // Essentially we're calculating the corners of a bigger triangle that's "t" units away from the
  417. // face, and its corners lie along the per-vertex normals. Point "p" will lie on that triangle, for which
  418. // we can then calculate barycentric coordinates normally.
  419. //
  420. // First we substitute: c = 1 - a - b
  421. // p == a (p0 + t v0) + b (p1 + t v1) + (1 - a - b) (p2 + t v2)
  422. // p == a (p0 + t v0) + b (p1 + t v1) + (p2 + t v2) - a (p2 + t v2) - b (p2 + t v2)
  423. // p == a (p0 - p2 + t v0 - t v2) + b (p1 - p2 + t v1 - t v2) + (p2 + t v2)
  424. //
  425. // And move everything to one side:
  426. // p - p2 - t v2 == a (p0 - p2 + t ( v0 - v2)) + b (p1 - p2 + t ( v1 - v2))
  427. // a (p0 - p2 + t ( v0 - v2)) + b (p1 - p2 + t ( v1 - v2)) - (p - p2 - t v2) == 0
  428. //
  429. // We rewrite it using:
  430. // Ap = p0 - p2
  431. // Av = v0 - v2
  432. // Bp = p1 - p2
  433. // Bv = v1 - v2
  434. // Cp = p - p2
  435. // Cv = -v2
  436. //
  437. // Which yields:
  438. // a (Ap + t Av) + b (Bp + t Bv) - (Cp + t Cv) == 0
  439. //
  440. // Which can be written in matrix form:
  441. //
  442. // M = {Ap + t Av, Bp + t Bv, Cp + t Cv}
  443. // a 0
  444. // M * [ b ] = [0]
  445. // -1 0
  446. //
  447. // From that we can tell that matrix M cannot be inverted, because if we multiply the zero vector with the
  448. // inverted matrix the result would be zero, and not [a, b, -1]. Since the matrix cannot be inverted
  449. // det(M) == 0.
  450. //
  451. // We can use that fact to calculate "t". After we have "t" we can calculate barycentric coordinates
  452. // normally.
  453. //
  454. // Solving equation det(M) == 0 yields a cubic in form:
  455. // p t^3 + q t^2 + r t + s = 0
  456. //
  457. // We'll convert this to monic form, by dividing by p:
  458. // t^3 + q/p t^2 + r/p t + s/p = 0
  459. //
  460. // Or if p ends up being zero, we end up with a quadratic instead:
  461. // q t^2 + r t + s = 0
  462. //
  463. // We want to create a matrix that when multiplied with the position, yields us the three coefficients,
  464. // which we can then use to solve for "t". For this we create a 4x3 matrix, where each row represents
  465. // a solution for one of the coefficients. We factor contributons to each coefficient whether they depend on
  466. // position x, y, z, or don't depend on position (row columns, in that order respectively).
  467. const Vector3& p0 = positions[entry.volume.vertices[0]];
  468. const Vector3& p1 = positions[entry.volume.vertices[1]];
  469. const Vector3& p2 = positions[entry.volume.vertices[2]];
  470. const Vector3& v0 = vertexNormals[entry.volume.vertices[0]];
  471. const Vector3& v1 = vertexNormals[entry.volume.vertices[1]];
  472. const Vector3& v2 = vertexNormals[entry.volume.vertices[2]];
  473. float p =
  474. v2.x * v1.y * v0.z -
  475. v1.x * v2.y * v0.z -
  476. v2.x * v0.y * v1.z +
  477. v0.x * v2.y * v1.z +
  478. v1.x * v0.y * v2.z -
  479. v0.x * v1.y * v2.z;
  480. 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;
  481. 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;
  482. 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;
  483. 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 +
  484. v1.y * v0.z * p2.x - v0.y * v1.z * p2.x - v2.x * v1.z * p0.y + v1.x * v2.z * p0.y +
  485. v2.x * v0.z * p1.y - v0.x * v2.z * p1.y - v1.x * v0.z * p2.y + v0.x * v1.z * p2.y +
  486. v2.x * v1.y * p0.z - v1.x * v2.y * p0.z - v2.x * v0.y * p1.z + v0.x * v2.y * p1.z +
  487. v1.x * v0.y * p2.z - v0.x * v1.y * p2.z;
  488. 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 -
  489. v1.y * p0.z + v2.y * p0.z + v0.y * p1.z - v2.y * p1.z - v0.y * p2.z + v1.y * p2.z;
  490. 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 +
  491. v1.x * p0.z - v2.x * p0.z - v0.x * p1.z + v2.x * p1.z + v0.x * p2.z - v1.x * p2.z;
  492. 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 -
  493. v1.x * p0.y + v2.x * p0.y + v0.x * p1.y - v2.x * p1.y - v0.x * p2.y + v1.x * p2.y;
  494. 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 +
  495. v1.z * p0.x * p2.y - v0.z * p1.x * p2.y - v2.y * p1.x * p0.z + v1.y * p2.x * p0.z +
  496. v2.x * p1.y * p0.z - v1.x * p2.y * p0.z + v2.y * p0.x * p1.z - v0.y * p2.x * p1.z -
  497. v2.x * p0.y * p1.z + v0.x * p2.y * p1.z - v1.y * p0.x * p2.z + v0.y * p1.x * p2.z +
  498. v1.x * p0.y * p2.z - v0.x * p1.y * p2.z;
  499. 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;
  500. 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;
  501. 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;
  502. float sw = p2.x * p1.y * p0.z - p1.x * p2.y * p0.z - p2.x * p0.y * p1.z +
  503. p0.x * p2.y * p1.z + p1.x * p0.y * p2.z - p0.x * p1.y * p2.z;
  504. entry.transform[0][0] = qx;
  505. entry.transform[0][1] = qy;
  506. entry.transform[0][2] = qz;
  507. entry.transform[0][3] = qw;
  508. entry.transform[1][0] = rx;
  509. entry.transform[1][1] = ry;
  510. entry.transform[1][2] = rz;
  511. entry.transform[1][3] = rw;
  512. entry.transform[2][0] = sx;
  513. entry.transform[2][1] = sy;
  514. entry.transform[2][2] = sz;
  515. entry.transform[2][3] = sw;
  516. // Unused
  517. entry.transform[3][0] = 0.0f;
  518. entry.transform[3][1] = 0.0f;
  519. entry.transform[3][2] = 0.0f;
  520. entry.transform[3][3] = 0.0f;
  521. if (fabs(p) > 0.00001f)
  522. entry.transform = entry.transform * (1.0f / p);
  523. else // Quadratic
  524. entry.volume.neighbors[3] = -2;
  525. output.push_back(entry);
  526. }
  527. }
  528. }
  529. bs_frame_clear();
  530. }
  531. }}