SurfaceExtractor.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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/Math.h>
  10. #include <algorithm>
  11. #include <array>
  12. #include <cstdint>
  13. #include <map>
  14. #include <vector>
  15. namespace WwiseGTE
  16. {
  17. // The image type T must be one of the integer types: int8_t, int16_t,
  18. // int32_t, uint8_t, uint16_t or uint32_t. Internal integer computations
  19. // are performed using int64_t. The type Real is for extraction to
  20. // floating-point vertices.
  21. template <typename T, typename Real>
  22. class SurfaceExtractor
  23. {
  24. public:
  25. // Abstract base class.
  26. virtual ~SurfaceExtractor() = default;
  27. // The level surfaces form a graph of vertices, edges and triangles.
  28. // The vertices are computed as triples of nonnegative rational
  29. // numbers. Vertex represents the rational triple
  30. // (xNumer/xDenom, yNumer/yDenom, zNumer/zDenom)
  31. // as
  32. // (xNumer, xDenom, yNumer, yDenom, zNumer, zDenom)
  33. // where all components are nonnegative. The edges connect pairs of
  34. // vertices and the triangles connect triples of vertices, forming
  35. // a graph that represents the level set.
  36. struct Vertex
  37. {
  38. Vertex() = default;
  39. Vertex(int64_t inXNumer, int64_t inXDenom, int64_t inYNumer, int64_t inYDenom,
  40. int64_t inZNumer, int64_t inZDenom)
  41. {
  42. // The vertex generation leads to the numerator and
  43. // denominator having the same sign. This constructor changes
  44. // sign to ensure the numerator and denominator are both
  45. // positive.
  46. if (inXDenom > 0)
  47. {
  48. xNumer = inXNumer;
  49. xDenom = inXDenom;
  50. }
  51. else
  52. {
  53. xNumer = -inXNumer;
  54. xDenom = -inXDenom;
  55. }
  56. if (inYDenom > 0)
  57. {
  58. yNumer = inYNumer;
  59. yDenom = inYDenom;
  60. }
  61. else
  62. {
  63. yNumer = -inYNumer;
  64. yDenom = -inYDenom;
  65. }
  66. if (inZDenom > 0)
  67. {
  68. zNumer = inZNumer;
  69. zDenom = inZDenom;
  70. }
  71. else
  72. {
  73. zNumer = -inZNumer;
  74. zDenom = -inZDenom;
  75. }
  76. }
  77. // The non-default constructor guarantees that xDenom > 0,
  78. // yDenom > 0 and zDenom > 0. The following comparison operators
  79. // assume that the denominators are positive.
  80. bool operator==(Vertex const& other) const
  81. {
  82. return
  83. // xn0/xd0 == xn1/xd1
  84. xNumer * other.xDenom == other.xNumer * xDenom
  85. &&
  86. // yn0/yd0 == yn1/yd1
  87. yNumer * other.yDenom == other.yNumer * yDenom
  88. &&
  89. // zn0/zd0 == zn1/zd1
  90. zNumer * other.zDenom == other.zNumer * zDenom;
  91. }
  92. bool operator<(Vertex const& other) const
  93. {
  94. int64_t xn0txd1 = xNumer * other.xDenom;
  95. int64_t xn1txd0 = other.xNumer * xDenom;
  96. if (xn0txd1 < xn1txd0)
  97. {
  98. // xn0/xd0 < xn1/xd1
  99. return true;
  100. }
  101. if (xn0txd1 > xn1txd0)
  102. {
  103. // xn0/xd0 > xn1/xd1
  104. return false;
  105. }
  106. int64_t yn0tyd1 = yNumer * other.yDenom;
  107. int64_t yn1tyd0 = other.yNumer * yDenom;
  108. if (yn0tyd1 < yn1tyd0)
  109. {
  110. // yn0/yd0 < yn1/yd1
  111. return true;
  112. }
  113. if (yn0tyd1 > yn1tyd0)
  114. {
  115. // yn0/yd0 > yn1/yd1
  116. return false;
  117. }
  118. int64_t zn0tzd1 = zNumer * other.zDenom;
  119. int64_t zn1tzd0 = other.zNumer * zDenom;
  120. // zn0/zd0 < zn1/zd1
  121. return zn0tzd1 < zn1tzd0;
  122. }
  123. int64_t xNumer, xDenom, yNumer, yDenom, zNumer, zDenom;
  124. };
  125. struct Triangle
  126. {
  127. Triangle() = default;
  128. Triangle(int v0, int v1, int v2)
  129. {
  130. // After the code is executed, (v[0],v[1],v[2]) is a cyclic
  131. // permutation of (v0,v1,v2) with v[0] = min{v0,v1,v2}.
  132. if (v0 < v1)
  133. {
  134. if (v0 < v2)
  135. {
  136. v[0] = v0;
  137. v[1] = v1;
  138. v[2] = v2;
  139. }
  140. else
  141. {
  142. v[0] = v2;
  143. v[1] = v0;
  144. v[2] = v1;
  145. }
  146. }
  147. else
  148. {
  149. if (v1 < v2)
  150. {
  151. v[0] = v1;
  152. v[1] = v2;
  153. v[2] = v0;
  154. }
  155. else
  156. {
  157. v[0] = v2;
  158. v[1] = v0;
  159. v[2] = v1;
  160. }
  161. }
  162. }
  163. bool operator==(Triangle const& other) const
  164. {
  165. return v[0] == other.v[0] && v[1] == other.v[1] && v[2] == other.v[2];
  166. }
  167. bool operator<(Triangle const& other) const
  168. {
  169. for (int i = 0; i < 3; ++i)
  170. {
  171. if (v[i] < other.v[i])
  172. {
  173. return true;
  174. }
  175. if (v[i] > other.v[i])
  176. {
  177. return false;
  178. }
  179. }
  180. return false;
  181. }
  182. std::array<int, 3> v;
  183. };
  184. // Extract level surfaces and return rational vertices.
  185. virtual void Extract(T level, std::vector<Vertex>& vertices,
  186. std::vector<Triangle>& triangles) = 0;
  187. void Extract(T level, bool removeDuplicateVertices,
  188. std::vector<std::array<Real, 3>>& vertices, std::vector<Triangle>& triangles)
  189. {
  190. std::vector<Vertex> rationalVertices;
  191. Extract(level, rationalVertices, triangles);
  192. if (removeDuplicateVertices)
  193. {
  194. MakeUnique(rationalVertices, triangles);
  195. }
  196. Convert(rationalVertices, vertices);
  197. }
  198. // The extraction has duplicate vertices on edges shared by voxels.
  199. // This function will eliminate the duplicates.
  200. void MakeUnique(std::vector<Vertex>& vertices, std::vector<Triangle>& triangles)
  201. {
  202. size_t numVertices = vertices.size();
  203. size_t numTriangles = triangles.size();
  204. if (numVertices == 0 || numTriangles == 0)
  205. {
  206. return;
  207. }
  208. // Compute the map of unique vertices and assign to them new and
  209. // unique indices.
  210. std::map<Vertex, int> vmap;
  211. int nextVertex = 0;
  212. for (size_t v = 0; v < numVertices; ++v)
  213. {
  214. // Keep only unique vertices.
  215. auto result = vmap.insert(std::make_pair(vertices[v], nextVertex));
  216. if (result.second)
  217. {
  218. ++nextVertex;
  219. }
  220. }
  221. // Compute the map of unique triangles and assign to them new and
  222. // unique indices.
  223. std::map<Triangle, int> tmap;
  224. int nextTriangle = 0;
  225. for (size_t t = 0; t < numTriangles; ++t)
  226. {
  227. Triangle& triangle = triangles[t];
  228. for (int i = 0; i < 3; ++i)
  229. {
  230. auto iter = vmap.find(vertices[triangle.v[i]]);
  231. LogAssert(iter != vmap.end(), "Expecting the vertex to be in the vmap.");
  232. triangle.v[i] = iter->second;
  233. }
  234. // Keep only unique triangles.
  235. auto result = tmap.insert(std::make_pair(triangle, nextTriangle));
  236. if (result.second)
  237. {
  238. ++nextTriangle;
  239. }
  240. }
  241. // Pack the vertices into an array.
  242. vertices.resize(vmap.size());
  243. for (auto const& element : vmap)
  244. {
  245. vertices[element.second] = element.first;
  246. }
  247. // Pack the triangles into an array.
  248. triangles.resize(tmap.size());
  249. for (auto const& element : tmap)
  250. {
  251. triangles[element.second] = element.first;
  252. }
  253. }
  254. // Convert from Vertex to std::array<Real, 3> rationals.
  255. void Convert(std::vector<Vertex> const& input, std::vector<std::array<Real, 3>>& output)
  256. {
  257. output.resize(input.size());
  258. for (size_t i = 0; i < input.size(); ++i)
  259. {
  260. Real rxNumer = static_cast<Real>(input[i].xNumer);
  261. Real rxDenom = static_cast<Real>(input[i].xDenom);
  262. Real ryNumer = static_cast<Real>(input[i].yNumer);
  263. Real ryDenom = static_cast<Real>(input[i].yDenom);
  264. Real rzNumer = static_cast<Real>(input[i].zNumer);
  265. Real rzDenom = static_cast<Real>(input[i].zDenom);
  266. output[i][0] = rxNumer / rxDenom;
  267. output[i][1] = ryNumer / ryDenom;
  268. output[i][2] = rzNumer / rzDenom;
  269. }
  270. }
  271. // The extraction does not use any topological information about the
  272. // level surfaces. The triangles can be a mixture of clockwise-ordered
  273. // and counterclockwise-ordered. This function is an attempt to give
  274. // the triangles a consistent ordering by selecting a normal in
  275. // approximately the same direction as the average gradient at the
  276. // vertices (when sameDir is true), or in the opposite direction (when
  277. // sameDir is false). This might not always produce a consistent
  278. // order, but is fast. A consistent order can be computed by
  279. // choosing a winding order for each triangle so that any corner of
  280. // the voxel containing the triangle and that has positive sign sees
  281. // a counterclockwise order. Of course, you can also choose that the
  282. // positive sign corners of the voxel always see the voxel-contained
  283. // triangles in clockwise order.
  284. void OrientTriangles(std::vector<std::array<Real, 3>>& vertices,
  285. std::vector<Triangle>& triangles, bool sameDir)
  286. {
  287. for (auto& triangle : triangles)
  288. {
  289. // Get the triangle vertices.
  290. std::array<Real, 3> v0 = vertices[triangle.v[0]];
  291. std::array<Real, 3> v1 = vertices[triangle.v[1]];
  292. std::array<Real, 3> v2 = vertices[triangle.v[2]];
  293. // Construct the triangle normal based on the current
  294. // orientation.
  295. std::array<Real, 3> edge1, edge2, normal;
  296. for (int i = 0; i < 3; ++i)
  297. {
  298. edge1[i] = v1[i] - v0[i];
  299. edge2[i] = v2[i] - v0[i];
  300. }
  301. normal[0] = edge1[1] * edge2[2] - edge1[2] * edge2[1];
  302. normal[1] = edge1[2] * edge2[0] - edge1[0] * edge2[2];
  303. normal[2] = edge1[0] * edge2[1] - edge1[1] * edge2[0];
  304. // Get the image gradient at the vertices.
  305. std::array<Real, 3> grad0 = GetGradient(v0);
  306. std::array<Real, 3> grad1 = GetGradient(v1);
  307. std::array<Real, 3> grad2 = GetGradient(v2);
  308. // Compute the average gradient.
  309. std::array<Real, 3> gradAvr;
  310. for (int i = 0; i < 3; ++i)
  311. {
  312. gradAvr[i] = (grad0[i] + grad1[i] + grad2[i]) / (Real)3;
  313. }
  314. // Compute the dot product of normal and average gradient.
  315. Real dot = gradAvr[0] * normal[0] + gradAvr[1] * normal[1] + gradAvr[2] * normal[2];
  316. // Choose triangle orientation based on gradient direction.
  317. if (sameDir)
  318. {
  319. if (dot < (Real)0)
  320. {
  321. // Wrong orientation, reorder it.
  322. std::swap(triangle.v[1], triangle.v[2]);
  323. }
  324. }
  325. else
  326. {
  327. if (dot > (Real)0)
  328. {
  329. // Wrong orientation, reorder it.
  330. std::swap(triangle.v[1], triangle.v[2]);
  331. }
  332. }
  333. }
  334. }
  335. // Use this function if you want vertex normals for dynamic lighting
  336. // of the mesh.
  337. void ComputeNormals(std::vector<std::array<Real, 3>> const& vertices,
  338. std::vector<Triangle> const& triangles,
  339. std::vector<std::array<Real, 3>>& normals)
  340. {
  341. // Compute a vertex normal to be area-weighted sums of the normals
  342. // to the triangles that share that vertex.
  343. std::array<Real, 3> const zero{ (Real)0, (Real)0, (Real)0 };
  344. normals.resize(vertices.size());
  345. std::fill(normals.begin(), normals.end(), zero);
  346. for (auto const& triangle : triangles)
  347. {
  348. // Get the triangle vertices.
  349. std::array<Real, 3> v0 = vertices[triangle.v[0]];
  350. std::array<Real, 3> v1 = vertices[triangle.v[1]];
  351. std::array<Real, 3> v2 = vertices[triangle.v[2]];
  352. // Construct the triangle normal.
  353. std::array<Real, 3> edge1, edge2, normal;
  354. for (int i = 0; i < 3; ++i)
  355. {
  356. edge1[i] = v1[i] - v0[i];
  357. edge2[i] = v2[i] - v0[i];
  358. }
  359. normal[0] = edge1[1] * edge2[2] - edge1[2] * edge2[1];
  360. normal[1] = edge1[2] * edge2[0] - edge1[0] * edge2[2];
  361. normal[2] = edge1[0] * edge2[1] - edge1[1] * edge2[0];
  362. // Maintain the sum of normals at each vertex.
  363. for (int i = 0; i < 3; ++i)
  364. {
  365. for (int j = 0; j < 3; ++j)
  366. {
  367. normals[triangle.v[i]][j] += normal[j];
  368. }
  369. }
  370. }
  371. // The normal vector storage was used to accumulate the sum of
  372. // triangle normals. Now these vectors must be rescaled to be
  373. // unit length.
  374. for (auto& normal : normals)
  375. {
  376. Real sqrLength = normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2];
  377. Real length = std::sqrt(sqrLength);
  378. if (length > (Real)0)
  379. {
  380. for (int i = 0; i < 3; ++i)
  381. {
  382. normal[i] /= length;
  383. }
  384. }
  385. else
  386. {
  387. for (int i = 0; i < 3; ++i)
  388. {
  389. normal[i] = (Real)0;
  390. }
  391. }
  392. }
  393. }
  394. protected:
  395. // The input is a 3D image with lexicographically ordered voxels
  396. // (x,y,z) stored in a linear array. Voxel (x,y,z) is stored in the
  397. // array at location index = x + xBound * (y + yBound * z). The
  398. // inputs xBound, yBound and zBound must each be 2 or larger so that
  399. // there is at least one image cube to process. The inputVoxels must
  400. // be nonnull and point to contiguous storage that contains at least
  401. // xBound * yBound * zBound elements.
  402. SurfaceExtractor(int xBound, int yBound, int zBound, T const* inputVoxels)
  403. :
  404. mXBound(xBound),
  405. mYBound(yBound),
  406. mZBound(zBound),
  407. mXYBound(xBound * yBound),
  408. mInputVoxels(inputVoxels)
  409. {
  410. static_assert(std::is_integral<T>::value && sizeof(T) <= 4,
  411. "Type T must be int{8,16,32}_t or uint{8,16,32}_t.");
  412. LogAssert(xBound > 1 && yBound > 1 && zBound > 1 && mInputVoxels != nullptr,
  413. "Invalid input.");
  414. mVoxels.resize(static_cast<size_t>(mXBound * mYBound * mZBound));
  415. }
  416. virtual std::array<Real, 3> GetGradient(std::array<Real, 3> const& pos) = 0;
  417. int mXBound, mYBound, mZBound, mXYBound;
  418. T const* mInputVoxels;
  419. std::vector<int64_t> mVoxels;
  420. };
  421. }