ETManifoldMesh.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. // David Eberly, Geometric Tools, Redmond WA 98052
  2. // Copyright (c) 1998-2020
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // https://www.boost.org/LICENSE_1_0.txt
  5. // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
  6. // Version: 4.0.2019.08.13
  7. #pragma once
  8. #include <Mathematics/Logger.h>
  9. #include <Mathematics/EdgeKey.h>
  10. #include <Mathematics/TriangleKey.h>
  11. #include <map>
  12. #include <memory>
  13. #include <vector>
  14. namespace WwiseGTE
  15. {
  16. class ETManifoldMesh
  17. {
  18. public:
  19. // Edge data types.
  20. class Edge;
  21. typedef std::shared_ptr<Edge>(*ECreator)(int, int);
  22. typedef std::map<EdgeKey<false>, std::shared_ptr<Edge>> EMap;
  23. // Triangle data types.
  24. class Triangle;
  25. typedef std::shared_ptr<Triangle>(*TCreator)(int, int, int);
  26. typedef std::map<TriangleKey<true>, std::shared_ptr<Triangle>> TMap;
  27. // Edge object.
  28. class Edge
  29. {
  30. public:
  31. virtual ~Edge() = default;
  32. Edge(int v0, int v1)
  33. :
  34. V{ v0, v1 }
  35. {
  36. }
  37. // Vertices of the edge.
  38. std::array<int, 2> V;
  39. // Triangles sharing the edge.
  40. std::array<std::weak_ptr<Triangle>, 2> T;
  41. };
  42. // Triangle object.
  43. class Triangle
  44. {
  45. public:
  46. virtual ~Triangle() = default;
  47. Triangle(int v0, int v1, int v2)
  48. :
  49. V{ v0, v1, v2 }
  50. {
  51. }
  52. // Vertices, listed in counterclockwise order (V[0],V[1],V[2]).
  53. int V[3];
  54. // Adjacent edges. E[i] points to edge (V[i],V[(i+1)%3]).
  55. std::array<std::weak_ptr<Edge>, 3> E;
  56. // Adjacent triangles. T[i] points to the adjacent triangle
  57. // sharing edge E[i].
  58. std::array<std::weak_ptr<Triangle>, 3> T;
  59. };
  60. // Construction and destruction.
  61. virtual ~ETManifoldMesh() = default;
  62. ETManifoldMesh(ECreator eCreator = nullptr, TCreator tCreator = nullptr)
  63. :
  64. mECreator(eCreator ? eCreator : CreateEdge),
  65. mTCreator(tCreator ? tCreator : CreateTriangle),
  66. mThrowOnNonmanifoldInsertion(true)
  67. {
  68. }
  69. // Support for a deep copy of the mesh. The mEMap and mTMap objects
  70. // have dynamically allocated memory for edges and triangles. A
  71. // shallow copy of the pointers to this memory is problematic.
  72. // Allowing sharing, say, via std::shared_ptr, is an option but not
  73. // really the intent of copying the mesh graph.
  74. ETManifoldMesh(ETManifoldMesh const& mesh)
  75. {
  76. *this = mesh;
  77. }
  78. ETManifoldMesh& operator=(ETManifoldMesh const& mesh)
  79. {
  80. Clear();
  81. mECreator = mesh.mECreator;
  82. mTCreator = mesh.mTCreator;
  83. mThrowOnNonmanifoldInsertion = mesh.mThrowOnNonmanifoldInsertion;
  84. for (auto const& element : mesh.mTMap)
  85. {
  86. Insert(element.first.V[0], element.first.V[1], element.first.V[2]);
  87. }
  88. return *this;
  89. }
  90. // Member access.
  91. inline EMap const& GetEdges() const
  92. {
  93. return mEMap;
  94. }
  95. inline TMap const& GetTriangles() const
  96. {
  97. return mTMap;
  98. }
  99. // If the insertion of a triangle fails because the mesh would become
  100. // nonmanifold, the default behavior is to throw an exception. You
  101. // can disable this behavior and continue gracefully without an
  102. // exception. The return value is the previous value of the internal
  103. // state mAssertOnNonmanifoldInsertion.
  104. bool ThrowOnNonmanifoldInsertion(bool doException)
  105. {
  106. std::swap(doException, mThrowOnNonmanifoldInsertion);
  107. return doException; // return the previous state
  108. }
  109. // If <v0,v1,v2> is not in the mesh, a Triangle object is created and
  110. // returned; otherwise, <v0,v1,v2> is in the mesh and nullptr is
  111. // returned. If the insertion leads to a nonmanifold mesh, the call
  112. // fails with a nullptr returned.
  113. virtual std::shared_ptr<Triangle> Insert(int v0, int v1, int v2)
  114. {
  115. TriangleKey<true> tkey(v0, v1, v2);
  116. if (mTMap.find(tkey) != mTMap.end())
  117. {
  118. // The triangle already exists. Return a null pointer as a
  119. // signal to the caller that the insertion failed.
  120. return nullptr;
  121. }
  122. // Create the new triangle. It will be added to mTMap at the end
  123. // of the function so that if an assertion is triggered and the
  124. // function returns early, the (bad) triangle will not be part of
  125. // the mesh.
  126. std::shared_ptr<Triangle> tri = mTCreator(v0, v1, v2);
  127. // Add the edges to the mesh if they do not already exist.
  128. for (int i0 = 2, i1 = 0; i1 < 3; i0 = i1++)
  129. {
  130. EdgeKey<false> ekey(tri->V[i0], tri->V[i1]);
  131. std::shared_ptr<Edge> edge;
  132. auto eiter = mEMap.find(ekey);
  133. if (eiter == mEMap.end())
  134. {
  135. // This is the first time the edge is encountered.
  136. edge = mECreator(tri->V[i0], tri->V[i1]);
  137. mEMap[ekey] = edge;
  138. // Update the edge and triangle.
  139. edge->T[0] = tri;
  140. tri->E[i0] = edge;
  141. }
  142. else
  143. {
  144. // This is the second time the edge is encountered.
  145. edge = eiter->second;
  146. LogAssert(edge != nullptr, "Unexpected condition.");
  147. // Update the edge.
  148. if (edge->T[1].lock())
  149. {
  150. if (mThrowOnNonmanifoldInsertion)
  151. {
  152. LogError("Attempt to create nonmanifold mesh.");
  153. }
  154. else
  155. {
  156. return nullptr;
  157. }
  158. }
  159. edge->T[1] = tri;
  160. // Update the adjacent triangles.
  161. auto adjacent = edge->T[0].lock();
  162. LogAssert(adjacent != nullptr, "Unexpected condition.");
  163. for (int j = 0; j < 3; ++j)
  164. {
  165. if (adjacent->E[j].lock() == edge)
  166. {
  167. adjacent->T[j] = tri;
  168. break;
  169. }
  170. }
  171. // Update the triangle.
  172. tri->E[i0] = edge;
  173. tri->T[i0] = adjacent;
  174. }
  175. }
  176. mTMap[tkey] = tri;
  177. return tri;
  178. }
  179. // If <v0,v1,v2> is in the mesh, it is removed and 'true' is
  180. // returned; otherwise, <v0,v1,v2> is not in the mesh and 'false' is
  181. // returned.
  182. virtual bool Remove(int v0, int v1, int v2)
  183. {
  184. TriangleKey<true> tkey(v0, v1, v2);
  185. auto titer = mTMap.find(tkey);
  186. if (titer == mTMap.end())
  187. {
  188. // The triangle does not exist.
  189. return false;
  190. }
  191. // Get the triangle.
  192. std::shared_ptr<Triangle> tri = titer->second;
  193. // Remove the edges and update adjacent triangles if necessary.
  194. for (int i = 0; i < 3; ++i)
  195. {
  196. // Inform the edges the triangle is being deleted.
  197. auto edge = tri->E[i].lock();
  198. LogAssert(edge != nullptr, "Unexpected condition.");
  199. if (edge->T[0].lock() == tri)
  200. {
  201. // One-triangle edges always have pointer at index zero.
  202. edge->T[0] = edge->T[1];
  203. edge->T[1].reset();
  204. }
  205. else if (edge->T[1].lock() == tri)
  206. {
  207. edge->T[1].reset();
  208. }
  209. else
  210. {
  211. LogError("Unexpected condition.");
  212. }
  213. // Remove the edge if you have the last reference to it.
  214. if (!edge->T[0].lock() && !edge->T[1].lock())
  215. {
  216. EdgeKey<false> ekey(edge->V[0], edge->V[1]);
  217. mEMap.erase(ekey);
  218. }
  219. // Inform adjacent triangles the triangle is being deleted.
  220. auto adjacent = tri->T[i].lock();
  221. if (adjacent)
  222. {
  223. for (int j = 0; j < 3; ++j)
  224. {
  225. if (adjacent->T[j].lock() == tri)
  226. {
  227. adjacent->T[j].reset();
  228. break;
  229. }
  230. }
  231. }
  232. }
  233. mTMap.erase(tkey);
  234. return true;
  235. }
  236. // Destroy the edges and triangles to obtain an empty mesh.
  237. virtual void Clear()
  238. {
  239. mEMap.clear();
  240. mTMap.clear();
  241. }
  242. // A manifold mesh is closed if each edge is shared twice. A closed
  243. // mesh is not necessarily oriented. For example, you could have a
  244. // mesh with spherical topology. The upper hemisphere has outer
  245. // facing normals and the lower hemisphere has inner-facing normals.
  246. // The discontinuity in orientation occurs on the circle shared by the
  247. // hemispheres.
  248. bool IsClosed() const
  249. {
  250. for (auto const& element : mEMap)
  251. {
  252. auto edge = element.second;
  253. if (!edge->T[0].lock() || !edge->T[1].lock())
  254. {
  255. return false;
  256. }
  257. }
  258. return true;
  259. }
  260. // Test whether all triangles in the mesh are oriented consistently
  261. // and that no two triangles are coincident. The latter means that
  262. // you cannot have both triangles <v0,v1,v2> and <v0,v2,v1> in the
  263. // mesh to be considered oriented.
  264. bool IsOriented() const
  265. {
  266. for (auto const& element : mEMap)
  267. {
  268. auto edge = element.second;
  269. if (edge->T[0].lock() && edge->T[1].lock())
  270. {
  271. // In each triangle, find the ordered edge that
  272. // corresponds to the unordered edge element.first. Also
  273. // find the vertex opposite that edge.
  274. bool edgePositive[2] = { false, false };
  275. int vOpposite[2] = { -1, -1 };
  276. for (int j = 0; j < 2; ++j)
  277. {
  278. auto tri = edge->T[j].lock();
  279. for (int i = 0; i < 3; ++i)
  280. {
  281. if (tri->V[i] == element.first.V[0])
  282. {
  283. int vNext = tri->V[(i + 1) % 3];
  284. if (vNext == element.first.V[1])
  285. {
  286. edgePositive[j] = true;
  287. vOpposite[j] = tri->V[(i + 2) % 3];
  288. }
  289. else
  290. {
  291. edgePositive[j] = false;
  292. vOpposite[j] = vNext;
  293. }
  294. break;
  295. }
  296. }
  297. }
  298. // To be oriented consistently, the edges must have
  299. // reversed ordering and the oppositive vertices cannot
  300. // match.
  301. if (edgePositive[0] == edgePositive[1] || vOpposite[0] == vOpposite[1])
  302. {
  303. return false;
  304. }
  305. }
  306. }
  307. return true;
  308. }
  309. // Compute the connected components of the edge-triangle graph that
  310. // the mesh represents. The first function returns pointers into
  311. // 'this' object's containers, so you must consume the components
  312. // before clearing or destroying 'this'. The second function returns
  313. // triangle keys, which requires three times as much storage as the
  314. // pointers but allows you to clear or destroy 'this' before consuming
  315. // the components.
  316. void GetComponents(std::vector<std::vector<std::shared_ptr<Triangle>>>& components) const
  317. {
  318. // visited: 0 (unvisited), 1 (discovered), 2 (finished)
  319. std::map<std::shared_ptr<Triangle>, int> visited;
  320. for (auto const& element : mTMap)
  321. {
  322. visited.insert(std::make_pair(element.second, 0));
  323. }
  324. for (auto& element : mTMap)
  325. {
  326. auto tri = element.second;
  327. if (visited[tri] == 0)
  328. {
  329. std::vector<std::shared_ptr<Triangle>> component;
  330. DepthFirstSearch(tri, visited, component);
  331. components.push_back(component);
  332. }
  333. }
  334. }
  335. void GetComponents(std::vector<std::vector<TriangleKey<true>>>& components) const
  336. {
  337. // visited: 0 (unvisited), 1 (discovered), 2 (finished)
  338. std::map<std::shared_ptr<Triangle>, int> visited;
  339. for (auto const& element : mTMap)
  340. {
  341. visited.insert(std::make_pair(element.second, 0));
  342. }
  343. for (auto& element : mTMap)
  344. {
  345. std::shared_ptr<Triangle> tri = element.second;
  346. if (visited[tri] == 0)
  347. {
  348. std::vector<std::shared_ptr<Triangle>> component;
  349. DepthFirstSearch(tri, visited, component);
  350. std::vector<TriangleKey<true>> keyComponent;
  351. keyComponent.reserve(component.size());
  352. for (auto const& t : component)
  353. {
  354. keyComponent.push_back(TriangleKey<true>(t->V[0], t->V[1], t->V[2]));
  355. }
  356. components.push_back(keyComponent);
  357. }
  358. }
  359. }
  360. protected:
  361. // The edge data and default edge creation.
  362. static std::shared_ptr<Edge> CreateEdge(int v0, int v1)
  363. {
  364. return std::make_shared<Edge>(v0, v1);
  365. }
  366. ECreator mECreator;
  367. EMap mEMap;
  368. // The triangle data and default triangle creation.
  369. static std::shared_ptr<Triangle> CreateTriangle(int v0, int v1, int v2)
  370. {
  371. return std::make_shared<Triangle>(v0, v1, v2);
  372. }
  373. TCreator mTCreator;
  374. TMap mTMap;
  375. bool mThrowOnNonmanifoldInsertion; // default: true
  376. // Support for computing connected components. This is a
  377. // straightforward depth-first search of the graph but uses a
  378. // preallocated stack rather than a recursive function that could
  379. // possibly overflow the call stack.
  380. void DepthFirstSearch(std::shared_ptr<Triangle> const& tInitial,
  381. std::map<std::shared_ptr<Triangle>, int>& visited,
  382. std::vector<std::shared_ptr<Triangle>>& component) const
  383. {
  384. // Allocate the maximum-size stack that can occur in the
  385. // depth-first search. The stack is empty when the index top
  386. // is -1.
  387. std::vector<std::shared_ptr<Triangle>> tStack(mTMap.size());
  388. int top = -1;
  389. tStack[++top] = tInitial;
  390. while (top >= 0)
  391. {
  392. std::shared_ptr<Triangle> tri = tStack[top];
  393. visited[tri] = 1;
  394. int i;
  395. for (i = 0; i < 3; ++i)
  396. {
  397. std::shared_ptr<Triangle> adj = tri->T[i].lock();
  398. if (adj && visited[adj] == 0)
  399. {
  400. tStack[++top] = adj;
  401. break;
  402. }
  403. }
  404. if (i == 3)
  405. {
  406. visited[tri] = 2;
  407. component.push_back(tri);
  408. --top;
  409. }
  410. }
  411. }
  412. };
  413. }