delaunay_triangulation.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2016 Qingnan Zhou <qnzhou@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "delaunay_triangulation.h"
  9. #include "flip_edge.h"
  10. #include "lexicographic_triangulation.h"
  11. #include "unique_edge_map.h"
  12. #include <vector>
  13. #include <sstream>
  14. template<
  15. typename DerivedV,
  16. typename Orient2D,
  17. typename InCircle,
  18. typename DerivedF>
  19. IGL_INLINE void igl::delaunay_triangulation(
  20. const Eigen::PlainObjectBase<DerivedV>& V,
  21. Orient2D orient2D,
  22. InCircle incircle,
  23. Eigen::PlainObjectBase<DerivedF>& F)
  24. {
  25. assert(V.cols() == 2);
  26. typedef typename DerivedF::Scalar Index;
  27. typedef typename DerivedV::Scalar Scalar;
  28. igl::lexicographic_triangulation(V, orient2D, F);
  29. const size_t num_faces = F.rows();
  30. if (num_faces == 0) {
  31. // Input points are degenerate. No faces will be generated.
  32. return;
  33. }
  34. assert(F.cols() == 3);
  35. Eigen::MatrixXi E;
  36. Eigen::MatrixXi uE;
  37. Eigen::VectorXi EMAP;
  38. std::vector<std::vector<Index> > uE2E;
  39. igl::unique_edge_map(F, E, uE, EMAP, uE2E);
  40. auto is_delaunay = [&V,&F,&uE2E,num_faces,&incircle](size_t uei) {
  41. auto& half_edges = uE2E[uei];
  42. if (half_edges.size() != 2) {
  43. throw "Cannot flip non-manifold or boundary edge";
  44. }
  45. const size_t f1 = half_edges[0] % num_faces;
  46. const size_t f2 = half_edges[1] % num_faces;
  47. const size_t c1 = half_edges[0] / num_faces;
  48. const size_t c2 = half_edges[1] / num_faces;
  49. assert(c1 < 3);
  50. assert(c2 < 3);
  51. assert(f1 != f2);
  52. const size_t v1 = F(f1, (c1+1)%3);
  53. const size_t v2 = F(f1, (c1+2)%3);
  54. const size_t v4 = F(f1, c1);
  55. const size_t v3 = F(f2, c2);
  56. const Scalar p1[] = {V(v1, 0), V(v1, 1)};
  57. const Scalar p2[] = {V(v2, 0), V(v2, 1)};
  58. const Scalar p3[] = {V(v3, 0), V(v3, 1)};
  59. const Scalar p4[] = {V(v4, 0), V(v4, 1)};
  60. auto orientation = incircle(p1, p2, p4, p3);
  61. return orientation <= 0;
  62. };
  63. bool all_delaunay = false;
  64. while(!all_delaunay) {
  65. all_delaunay = true;
  66. for (size_t i=0; i<uE2E.size(); i++) {
  67. if (uE2E[i].size() == 2) {
  68. if (!is_delaunay(i)) {
  69. all_delaunay = false;
  70. flip_edge(F, E, uE, EMAP, uE2E, i);
  71. }
  72. }
  73. }
  74. }
  75. }