quick_hull.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /*************************************************************************/
  2. /* quick_hull.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "quick_hull.h"
  31. #include "core/map.h"
  32. uint32_t QuickHull::debug_stop_after = 0xFFFFFFFF;
  33. bool QuickHull::_flag_warnings = true;
  34. Error QuickHull::build(const Vector<Vector3> &p_points, Geometry::MeshData &r_mesh, real_t p_over_tolerance_epsilon) {
  35. /* CREATE AABB VOLUME */
  36. AABB aabb;
  37. aabb.create_from_points(p_points);
  38. if (aabb.size == Vector3()) {
  39. return ERR_CANT_CREATE;
  40. }
  41. Vector<bool> valid_points;
  42. valid_points.resize(p_points.size());
  43. Set<Vector3> valid_cache;
  44. for (int i = 0; i < p_points.size(); i++) {
  45. Vector3 sp = p_points[i].snapped(Vector3(0.0001, 0.0001, 0.0001));
  46. if (valid_cache.has(sp)) {
  47. valid_points.write[i] = false;
  48. } else {
  49. valid_points.write[i] = true;
  50. valid_cache.insert(sp);
  51. }
  52. }
  53. /* CREATE INITIAL SIMPLEX */
  54. int longest_axis = aabb.get_longest_axis_index();
  55. //first two vertices are the most distant
  56. int simplex[4] = { 0 };
  57. {
  58. real_t max = 0, min = 0;
  59. for (int i = 0; i < p_points.size(); i++) {
  60. if (!valid_points[i]) {
  61. continue;
  62. }
  63. real_t d = p_points[i][longest_axis];
  64. if (i == 0 || d < min) {
  65. simplex[0] = i;
  66. min = d;
  67. }
  68. if (i == 0 || d > max) {
  69. simplex[1] = i;
  70. max = d;
  71. }
  72. }
  73. }
  74. //third vertex is one most further away from the line
  75. {
  76. real_t maxd = 0;
  77. Vector3 rel12 = p_points[simplex[0]] - p_points[simplex[1]];
  78. for (int i = 0; i < p_points.size(); i++) {
  79. if (!valid_points[i]) {
  80. continue;
  81. }
  82. Vector3 n = rel12.cross(p_points[simplex[0]] - p_points[i]).cross(rel12).normalized();
  83. real_t d = Math::abs(n.dot(p_points[simplex[0]]) - n.dot(p_points[i]));
  84. if (i == 0 || d > maxd) {
  85. maxd = d;
  86. simplex[2] = i;
  87. }
  88. }
  89. }
  90. //fourth vertex is the one most further away from the plane
  91. {
  92. real_t maxd = 0;
  93. Plane p(p_points[simplex[0]], p_points[simplex[1]], p_points[simplex[2]]);
  94. for (int i = 0; i < p_points.size(); i++) {
  95. if (!valid_points[i]) {
  96. continue;
  97. }
  98. real_t d = Math::abs(p.distance_to(p_points[i]));
  99. if (i == 0 || d > maxd) {
  100. maxd = d;
  101. simplex[3] = i;
  102. }
  103. }
  104. }
  105. //compute center of simplex, this is a point always warranted to be inside
  106. Vector3 center;
  107. for (int i = 0; i < 4; i++) {
  108. center += p_points[simplex[i]];
  109. }
  110. center /= 4.0;
  111. //add faces
  112. List<Face> faces;
  113. for (int i = 0; i < 4; i++) {
  114. static const int face_order[4][3] = {
  115. { 0, 1, 2 },
  116. { 0, 1, 3 },
  117. { 0, 2, 3 },
  118. { 1, 2, 3 }
  119. };
  120. Face f;
  121. for (int j = 0; j < 3; j++) {
  122. f.vertices[j] = simplex[face_order[i][j]];
  123. }
  124. Plane p(p_points[f.vertices[0]], p_points[f.vertices[1]], p_points[f.vertices[2]]);
  125. if (p.is_point_over(center)) {
  126. //flip face to clockwise if facing inwards
  127. SWAP(f.vertices[0], f.vertices[1]);
  128. p = -p;
  129. }
  130. f.plane = p;
  131. faces.push_back(f);
  132. }
  133. real_t over_tolerance = p_over_tolerance_epsilon * (aabb.size.x + aabb.size.y + aabb.size.z);
  134. /* COMPUTE AVAILABLE VERTICES */
  135. for (int i = 0; i < p_points.size(); i++) {
  136. if (i == simplex[0]) {
  137. continue;
  138. }
  139. if (i == simplex[1]) {
  140. continue;
  141. }
  142. if (i == simplex[2]) {
  143. continue;
  144. }
  145. if (i == simplex[3]) {
  146. continue;
  147. }
  148. if (!valid_points[i]) {
  149. continue;
  150. }
  151. for (List<Face>::Element *E = faces.front(); E; E = E->next()) {
  152. if (E->get().plane.distance_to(p_points[i]) > over_tolerance) {
  153. E->get().points_over.push_back(i);
  154. break;
  155. }
  156. }
  157. }
  158. faces.sort(); // sort them, so the ones with points are in the back
  159. /* BUILD HULL */
  160. //poop face (while still remain)
  161. //find further away point
  162. //find lit faces
  163. //determine horizon edges
  164. //build new faces with horizon edges, them assign points side from all lit faces
  165. //remove lit faces
  166. uint32_t debug_stop = debug_stop_after;
  167. while (debug_stop > 0 && faces.back()->get().points_over.size()) {
  168. debug_stop--;
  169. Face &f = faces.back()->get();
  170. //find vertex most outside
  171. int next = -1;
  172. real_t next_d = 0;
  173. for (int i = 0; i < f.points_over.size(); i++) {
  174. real_t d = f.plane.distance_to(p_points[f.points_over[i]]);
  175. if (d > next_d) {
  176. next_d = d;
  177. next = i;
  178. }
  179. }
  180. ERR_FAIL_COND_V(next == -1, ERR_BUG);
  181. Vector3 v = p_points[f.points_over[next]];
  182. //find lit faces and lit edges
  183. List<List<Face>::Element *> lit_faces; //lit face is a death sentence
  184. Map<Edge, FaceConnect> lit_edges; //create this on the flight, should not be that bad for performance and simplifies code a lot
  185. for (List<Face>::Element *E = faces.front(); E; E = E->next()) {
  186. if (E->get().plane.distance_to(v) > 0) {
  187. lit_faces.push_back(E);
  188. for (int i = 0; i < 3; i++) {
  189. uint32_t a = E->get().vertices[i];
  190. uint32_t b = E->get().vertices[(i + 1) % 3];
  191. Edge e(a, b);
  192. Map<Edge, FaceConnect>::Element *F = lit_edges.find(e);
  193. if (!F) {
  194. F = lit_edges.insert(e, FaceConnect());
  195. }
  196. if (e.vertices[0] == a) {
  197. //left
  198. F->get().left = E;
  199. } else {
  200. F->get().right = E;
  201. }
  202. }
  203. }
  204. }
  205. //create new faces from horizon edges
  206. List<List<Face>::Element *> new_faces; //new faces
  207. for (Map<Edge, FaceConnect>::Element *E = lit_edges.front(); E; E = E->next()) {
  208. FaceConnect &fc = E->get();
  209. if (fc.left && fc.right) {
  210. continue; //edge is uninteresting, not on horizont
  211. }
  212. //create new face!
  213. Face face;
  214. face.vertices[0] = f.points_over[next];
  215. face.vertices[1] = E->key().vertices[0];
  216. face.vertices[2] = E->key().vertices[1];
  217. Plane p(p_points[face.vertices[0]], p_points[face.vertices[1]], p_points[face.vertices[2]]);
  218. if (p.is_point_over(center)) {
  219. //flip face to clockwise if facing inwards
  220. SWAP(face.vertices[0], face.vertices[1]);
  221. p = -p;
  222. }
  223. face.plane = p;
  224. new_faces.push_back(faces.push_back(face));
  225. }
  226. //distribute points into new faces
  227. for (List<List<Face>::Element *>::Element *F = lit_faces.front(); F; F = F->next()) {
  228. Face &lf = F->get()->get();
  229. for (int i = 0; i < lf.points_over.size(); i++) {
  230. if (lf.points_over[i] == f.points_over[next]) { //do not add current one
  231. continue;
  232. }
  233. Vector3 p = p_points[lf.points_over[i]];
  234. for (List<List<Face>::Element *>::Element *E = new_faces.front(); E; E = E->next()) {
  235. Face &f2 = E->get()->get();
  236. if (f2.plane.distance_to(p) > over_tolerance) {
  237. f2.points_over.push_back(lf.points_over[i]);
  238. break;
  239. }
  240. }
  241. }
  242. }
  243. //erase lit faces
  244. while (lit_faces.size()) {
  245. faces.erase(lit_faces.front()->get());
  246. lit_faces.pop_front();
  247. }
  248. //put faces that contain no points on the front
  249. for (List<List<Face>::Element *>::Element *E = new_faces.front(); E; E = E->next()) {
  250. Face &f2 = E->get()->get();
  251. if (f2.points_over.size() == 0) {
  252. faces.move_to_front(E->get());
  253. }
  254. }
  255. //whew, done with iteration, go next
  256. }
  257. /* CREATE MESHDATA */
  258. //make a map of edges again
  259. Map<Edge, RetFaceConnect> ret_edges;
  260. List<Geometry::MeshData::Face> ret_faces;
  261. for (List<Face>::Element *E = faces.front(); E; E = E->next()) {
  262. Geometry::MeshData::Face f;
  263. f.plane = E->get().plane;
  264. for (int i = 0; i < 3; i++) {
  265. f.indices.push_back(E->get().vertices[i]);
  266. }
  267. List<Geometry::MeshData::Face>::Element *F = ret_faces.push_back(f);
  268. for (int i = 0; i < 3; i++) {
  269. uint32_t a = E->get().vertices[i];
  270. uint32_t b = E->get().vertices[(i + 1) % 3];
  271. Edge e(a, b);
  272. Map<Edge, RetFaceConnect>::Element *G = ret_edges.find(e);
  273. if (!G) {
  274. G = ret_edges.insert(e, RetFaceConnect());
  275. }
  276. if (e.vertices[0] == a) {
  277. //left
  278. G->get().left = F;
  279. } else {
  280. G->get().right = F;
  281. }
  282. }
  283. }
  284. //fill faces
  285. bool warning_f = false;
  286. bool warning_o_equal_e = false;
  287. bool warning_o = false;
  288. for (List<Geometry::MeshData::Face>::Element *E = ret_faces.front(); E; E = E->next()) {
  289. Geometry::MeshData::Face &f = E->get();
  290. for (int i = 0; i < f.indices.size(); i++) {
  291. int a = E->get().indices[i];
  292. int b = E->get().indices[(i + 1) % f.indices.size()];
  293. Edge e(a, b);
  294. Map<Edge, RetFaceConnect>::Element *F = ret_edges.find(e);
  295. if (unlikely(!F)) {
  296. warning_f = true;
  297. continue;
  298. }
  299. List<Geometry::MeshData::Face>::Element *O = F->get().left == E ? F->get().right : F->get().left;
  300. if (unlikely(O == E)) {
  301. warning_o_equal_e = true;
  302. continue;
  303. }
  304. if (unlikely(!O)) {
  305. warning_o = true;
  306. continue;
  307. }
  308. if (O->get().plane.is_equal_approx(f.plane)) {
  309. //merge and delete edge and contiguous face, while repointing edges (uuugh!)
  310. int ois = O->get().indices.size();
  311. int merged = 0;
  312. for (int j = 0; j < ois; j++) {
  313. //search a
  314. if (O->get().indices[j] == a) {
  315. //append the rest
  316. for (int k = 0; k < ois; k++) {
  317. int idx = O->get().indices[(k + j) % ois];
  318. int idxn = O->get().indices[(k + j + 1) % ois];
  319. if (idx == b && idxn == a) { //already have b!
  320. break;
  321. }
  322. if (idx != a) {
  323. f.indices.insert(i + 1, idx);
  324. i++;
  325. merged++;
  326. }
  327. Edge e2(idx, idxn);
  328. Map<Edge, RetFaceConnect>::Element *F2 = ret_edges.find(e2);
  329. ERR_CONTINUE(!F2);
  330. //change faceconnect, point to this face instead
  331. if (F2->get().left == O) {
  332. F2->get().left = E;
  333. } else if (F2->get().right == O) {
  334. F2->get().right = E;
  335. }
  336. }
  337. break;
  338. }
  339. }
  340. // remove all edge connections to this face
  341. for (Map<Edge, RetFaceConnect>::Element *G = ret_edges.front(); G; G = G->next()) {
  342. if (G->get().left == O) {
  343. G->get().left = nullptr;
  344. }
  345. if (G->get().right == O) {
  346. G->get().right = nullptr;
  347. }
  348. }
  349. ret_edges.erase(F); //remove the edge
  350. ret_faces.erase(O); //remove the face
  351. }
  352. }
  353. }
  354. if (_flag_warnings) {
  355. if (warning_f) {
  356. WARN_PRINT("QuickHull : !F");
  357. }
  358. if (warning_o_equal_e) {
  359. WARN_PRINT("QuickHull : O == E");
  360. }
  361. if (warning_o) {
  362. WARN_PRINT("QuickHull : O == nullptr");
  363. }
  364. }
  365. //fill mesh
  366. r_mesh.faces.clear();
  367. r_mesh.faces.resize(ret_faces.size());
  368. int idx = 0;
  369. for (List<Geometry::MeshData::Face>::Element *E = ret_faces.front(); E; E = E->next()) {
  370. r_mesh.faces.write[idx++] = E->get();
  371. }
  372. r_mesh.edges.resize(ret_edges.size());
  373. idx = 0;
  374. for (Map<Edge, RetFaceConnect>::Element *E = ret_edges.front(); E; E = E->next()) {
  375. Geometry::MeshData::Edge e;
  376. e.a = E->key().vertices[0];
  377. e.b = E->key().vertices[1];
  378. r_mesh.edges.write[idx++] = e;
  379. }
  380. // we are only interested in outputting the points that are used
  381. Vector<int> out_indices;
  382. for (int n = 0; n < r_mesh.faces.size(); n++) {
  383. Geometry::MeshData::Face face = r_mesh.faces[n];
  384. for (int i = 0; i < face.indices.size(); i++) {
  385. face.indices.set(i, find_or_create_output_index(face.indices[i], out_indices));
  386. }
  387. r_mesh.faces.set(n, face);
  388. }
  389. for (int n = 0; n < r_mesh.edges.size(); n++) {
  390. Geometry::MeshData::Edge e = r_mesh.edges[n];
  391. e.a = find_or_create_output_index(e.a, out_indices);
  392. e.b = find_or_create_output_index(e.b, out_indices);
  393. r_mesh.edges.set(n, e);
  394. }
  395. // rejig the final vertices
  396. r_mesh.vertices.resize(out_indices.size());
  397. for (int n = 0; n < out_indices.size(); n++) {
  398. r_mesh.vertices.set(n, p_points[out_indices[n]]);
  399. }
  400. return OK;
  401. }