SelfIntersectMesh.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. #ifndef IGL_SELFINTERSECTMESH_H
  2. #define IGL_SELFINTERSECTMESH_H
  3. #include "CGAL_includes.hpp"
  4. #include "selfintersect.h"
  5. #include <Eigen/Dense>
  6. #include <list>
  7. #include <map>
  8. #include <vector>
  9. // The easiest way to keep track of everything is to use a class
  10. namespace igl
  11. {
  12. // Kernel is a CGAL kernel like:
  13. // CGAL::Exact_predicates_inexact_constructions_kernel
  14. // or
  15. // CGAL::Exact_predicates_exact_constructions_kernel
  16. template <typename Kernel>
  17. class SelfIntersectMesh
  18. {
  19. public:
  20. // 3D Primitives
  21. typedef CGAL::Point_3<Kernel> Point_3;
  22. typedef CGAL::Segment_3<Kernel> Segment_3;
  23. typedef CGAL::Triangle_3<Kernel> Triangle_3;
  24. typedef CGAL::Plane_3<Kernel> Plane_3;
  25. typedef CGAL::Tetrahedron_3<Kernel> Tetrahedron_3;
  26. typedef CGAL::Polyhedron_3<Kernel> Polyhedron_3;
  27. typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron_3;
  28. // 2D Primitives
  29. typedef CGAL::Point_2<Kernel> Point_2;
  30. typedef CGAL::Segment_2<Kernel> Segment_2;
  31. typedef CGAL::Triangle_2<Kernel> Triangle_2;
  32. // 2D Constrained Delaunay Triangulation types
  33. typedef CGAL::Triangulation_vertex_base_2<Kernel> TVB_2;
  34. typedef CGAL::Constrained_triangulation_face_base_2<Kernel> CTFB_2;
  35. typedef CGAL::Triangulation_data_structure_2<TVB_2,CTFB_2> TDS_2;
  36. typedef CGAL::Exact_intersections_tag Itag;
  37. typedef CGAL::Constrained_Delaunay_triangulation_2<Kernel,TDS_2,Itag>
  38. CDT_2;
  39. typedef CGAL::Constrained_triangulation_plus_2<CDT_2> CDT_plus_2;
  40. // Axis-align boxes for all-pairs self-intersection detection
  41. typedef std::vector<Triangle_3> Triangles;
  42. typedef typename Triangles::iterator TrianglesIterator;
  43. typedef typename Triangles::const_iterator TrianglesConstIterator;
  44. typedef
  45. CGAL::Box_intersection_d::Box_with_handle_d<double,3,TrianglesIterator>
  46. Box;
  47. // Axis-aligned bounding box tree
  48. typedef CGAL::AABB_triangle_primitive<Kernel,TrianglesIterator> Primitive;
  49. typedef CGAL::AABB_traits<Kernel, Primitive> Traits;
  50. typedef CGAL::AABB_tree<Traits> Tree;
  51. typedef typename Tree::Object_and_primitive_id Object_and_primitive_id;
  52. typedef typename Tree::Primitive_id Primitive_id;
  53. // 3D Delaunay Triangulation
  54. typedef CGAL::Delaunay_triangulation_3<Kernel> Delaunay_triangulation_3;
  55. typedef typename Delaunay_triangulation_3::Finite_cells_iterator
  56. Delaunay3CellIterator;
  57. // Input mesh
  58. const Eigen::MatrixXd & V;
  59. const Eigen::MatrixXi & F;
  60. // Number of self-intersecting triangle pairs
  61. int count;
  62. std::vector<std::list<CGAL::Object> > F_objects;
  63. Triangles T;
  64. std::list<int> lIF;
  65. std::vector<bool> offensive;
  66. std::vector<int> offending_index;
  67. std::vector<int> offending;
  68. // Make a short name for the edge map's key
  69. typedef std::pair<int,int> EMK;
  70. // Make a short name for the type stored at each edge, the edge map's
  71. // value
  72. typedef std::list<int> EMV;
  73. // Make a short name for the edge map
  74. typedef std::map<EMK,EMV> EdgeMap;
  75. EdgeMap edge2faces;
  76. public:
  77. SelfintersectParam params;
  78. public:
  79. // Constructs (VV,FF) a new mesh with self-intersections of (V,F)
  80. // subdivided
  81. inline SelfIntersectMesh(
  82. const Eigen::MatrixXd & V,
  83. const Eigen::MatrixXi & F,
  84. const SelfintersectParam & params,
  85. Eigen::MatrixXd & VV,
  86. Eigen::MatrixXi & FF,
  87. Eigen::MatrixXi & IF);
  88. private:
  89. // Helper function to mark a face as offensive
  90. //
  91. // Inputs:
  92. // f index of face in F
  93. inline void mark_offensive(const int f);
  94. // Helper function to count intersections between faces
  95. //
  96. // Input:
  97. // fa index of face A in F
  98. // fb index of face B in F
  99. inline void count_intersection(const int fa,const int fb);
  100. // Helper function for box_intersect. Intersect two triangles A and B,
  101. // append the intersection object (point,segment,triangle) to a running
  102. // list for A and B
  103. //
  104. // Inputs:
  105. // A triangle in 3D
  106. // B triangle in 3D
  107. // fa index of A in F (and F_objects)
  108. // fb index of A in F (and F_objects)
  109. // Returns true only if A intersects B
  110. //
  111. inline bool intersect(
  112. const Triangle_3 & A,
  113. const Triangle_3 & B,
  114. const int fa,
  115. const int fb);
  116. // Helper function for box_intersect. In the case where A and B have
  117. // already been identified to share a vertex, then we only want to add
  118. // possible segment intersections. Assumes truly duplicate triangles are
  119. // not given as input
  120. //
  121. // Inputs:
  122. // A triangle in 3D
  123. // B triangle in 3D
  124. // fa index of A in F (and F_objects)
  125. // fb index of B in F (and F_objects)
  126. // va index of shared vertex in A (and F_objects)
  127. // vb index of shared vertex in B (and F_objects)
  128. //// Returns object of intersection (should be Segment or point)
  129. // Returns true if intersection (besides shared point)
  130. //
  131. inline bool single_shared_vertex(
  132. const Triangle_3 & A,
  133. const Triangle_3 & B,
  134. const int fa,
  135. const int fb,
  136. const int va,
  137. const int vb);
  138. // Helper handling one direction
  139. inline bool single_shared_vertex(
  140. const Triangle_3 & A,
  141. const Triangle_3 & B,
  142. const int fa,
  143. const int fb,
  144. const int va);
  145. // Helper function for box_intersect. In the case where A and B have
  146. // already been identified to share two vertices, then we only want to add
  147. // a possible coplanar (Triangle) intersection. Assumes truly degenerate
  148. // facets are not givine as input.
  149. inline bool double_shared_vertex(
  150. const Triangle_3 & A,
  151. const Triangle_3 & B,
  152. const int fa,
  153. const int fb);
  154. public:
  155. // Callback function called during box self intersections test. Means
  156. // boxes a and b intersect. This method then checks if the triangles in
  157. // each box intersect and if so, then processes the intersections
  158. //
  159. // Inputs:
  160. // a box containing a triangle
  161. // b box containing a triangle
  162. inline void box_intersect(const Box& a, const Box& b);
  163. private:
  164. // Compute 2D delaunay triangulation of a given 3d triangle and a list of
  165. // intersection objects (points,segments,triangles). CGAL uses an affine
  166. // projection rather than an isometric projection, so we're not
  167. // guaranteed that the 2D delaunay triangulation here will be a delaunay
  168. // triangulation in 3D.
  169. //
  170. // Inputs:
  171. // A triangle in 3D
  172. // A_objects_3 updated list of intersection objects for A
  173. // Outputs:
  174. // cdt Contrained delaunay triangulation in projected 2D plane
  175. inline void projected_delaunay(
  176. const Triangle_3 & A,
  177. const std::list<CGAL::Object> & A_objects_3,
  178. CDT_plus_2 & cdt);
  179. // Getters:
  180. public:
  181. //const std::list<int>& get_lIF() const{ return lIF;}
  182. static inline void box_intersect(
  183. SelfIntersectMesh * SIM,
  184. const SelfIntersectMesh::Box &a,
  185. const SelfIntersectMesh::Box &b);
  186. };
  187. }
  188. // Implementation
  189. #include "mesh_to_cgal_triangle_list.h"
  190. #include <igl/REDRUM.h>
  191. #include <igl/C_STR.h>
  192. #include <boost/function.hpp>
  193. #include <boost/bind.hpp>
  194. #include <algorithm>
  195. #include <exception>
  196. #include <cassert>
  197. #include <iostream>
  198. // References:
  199. // http://minregret.googlecode.com/svn/trunk/skyline/src/extern/CGAL-3.3.1/examples/Polyhedron/polyhedron_self_intersection.cpp
  200. // http://www.cgal.org/Manual/3.9/examples/Boolean_set_operations_2/do_intersect.cpp
  201. // Q: Should we be using CGAL::Polyhedron_3?
  202. // A: No! Input is just a list of unoriented triangles. Polyhedron_3 requires
  203. // a 2-manifold.
  204. // A: But! It seems we could use CGAL::Triangulation_3. Though it won't be easy
  205. // to take advantage of functions like insert_in_facet because we want to
  206. // constrain segments. Hmmm. Actualy Triangulation_3 doesn't look right...
  207. //static void box_intersect(SelfIntersectMesh * SIM,const Box & A, const Box & B)
  208. //{
  209. // return SIM->box_intersect(A,B);
  210. //}
  211. // CGAL's box_self_intersection_d uses C-style function callbacks without
  212. // userdata. This is a leapfrog method for calling a member function. It should
  213. // be bound as if the prototype was:
  214. // static void box_intersect(const Box &a, const Box &b)
  215. // using boost:
  216. // boost::function<void(const Box &a,const Box &b)> cb
  217. // = boost::bind(&::box_intersect, this, _1,_2);
  218. //
  219. template <typename Kernel>
  220. inline void igl::SelfIntersectMesh<Kernel>::box_intersect(
  221. igl::SelfIntersectMesh<Kernel> * SIM,
  222. const typename igl::SelfIntersectMesh<Kernel>::Box &a,
  223. const typename igl::SelfIntersectMesh<Kernel>::Box &b)
  224. {
  225. SIM->box_intersect(a,b);
  226. }
  227. #define FIRST_HIT_EXCEPTION 10
  228. template <typename Kernel>
  229. inline igl::SelfIntersectMesh<Kernel>::SelfIntersectMesh(
  230. const Eigen::MatrixXd & V,
  231. const Eigen::MatrixXi & F,
  232. const SelfintersectParam & params,
  233. Eigen::MatrixXd & VV,
  234. Eigen::MatrixXi & FF,
  235. Eigen::MatrixXi & IF):
  236. V(V),
  237. F(F),
  238. count(0),
  239. F_objects(F.rows()),
  240. T(),
  241. lIF(),
  242. offensive(F.rows(),false),
  243. offending_index(F.rows(),-1),
  244. offending(),
  245. edge2faces(),
  246. params(params)
  247. {
  248. using namespace std;
  249. using namespace Eigen;
  250. // Compute and process self intersections
  251. mesh_to_cgal_triangle_list(V,F,T);
  252. // http://www.cgal.org/Manual/latest/doc_html/cgal_manual/Box_intersection_d/Chapter_main.html#Section_63.5
  253. // Create the corresponding vector of bounding boxes
  254. std::vector<Box> boxes;
  255. boxes.reserve(T.size());
  256. for (
  257. TrianglesIterator tit = T.begin();
  258. tit != T.end();
  259. ++tit)
  260. {
  261. boxes.push_back(Box(tit->bbox(), tit));
  262. }
  263. // Leapfrog callback
  264. boost::function<void(const Box &a,const Box &b)> cb
  265. = boost::bind(&box_intersect, this, _1,_2);
  266. // Run the self intersection algorithm with all defaults
  267. try{
  268. CGAL::box_self_intersection_d(boxes.begin(), boxes.end(),cb);
  269. }catch(int e)
  270. {
  271. // Rethrow if not FIRST_HIT_EXCEPTION
  272. if(e != FIRST_HIT_EXCEPTION)
  273. {
  274. throw e;
  275. }
  276. // Otherwise just fall through
  277. }
  278. // Convert lIF to Eigen matrix
  279. assert(lIF.size()%2 == 0);
  280. IF.resize(lIF.size()/2,2);
  281. {
  282. int i=0;
  283. for(
  284. typename list<int>::const_iterator ifit = lIF.begin();
  285. ifit!=lIF.end();
  286. )
  287. {
  288. IF(i,0) = (*ifit);
  289. ifit++;
  290. IF(i,1) = (*ifit);
  291. ifit++;
  292. i++;
  293. }
  294. }
  295. if(params.detect_only)
  296. {
  297. return;
  298. }
  299. int NF_count = 0;
  300. // list of new faces, we'll fix F later
  301. vector<MatrixXi> NF(offending.size());
  302. // list of new vertices
  303. list<Point_3> NV;
  304. int NV_count = 0;
  305. vector<CDT_plus_2> cdt(offending.size());
  306. vector<Plane_3> P(offending.size());
  307. // Use map for *all* faces
  308. map<typename CDT_plus_2::Vertex_handle,int> v2i;
  309. // Loop over offending triangles
  310. for(int o = 0;o<(int)offending.size();o++)
  311. {
  312. // index in F
  313. const int f = offending[o];
  314. projected_delaunay(T[f],F_objects[f],cdt[o]);
  315. // Q: Is this also delaunay in 3D?
  316. // A: No, because the projection is affine and delaunay is not affine
  317. // invariant.
  318. // Q: Then, can't we first get the 2D delaunay triangulation, then lift it
  319. // to 3D and flip any offending edges?
  320. // Plane of projection (also used by projected_delaunay)
  321. P[o] = Plane_3(T[f].vertex(0),T[f].vertex(1),T[f].vertex(2));
  322. // Build index map
  323. {
  324. int i=0;
  325. for(
  326. typename CDT_plus_2::Finite_vertices_iterator vit = cdt[o].finite_vertices_begin();
  327. vit != cdt[o].finite_vertices_end();
  328. ++vit)
  329. {
  330. if(i<3)
  331. {
  332. //cout<<T[f].vertex(i)<<
  333. // (T[f].vertex(i) == P[o].to_3d(vit->point())?" == ":" != ")<<
  334. // P[o].to_3d(vit->point())<<endl;
  335. #ifndef NDEBUG
  336. // I want to be sure that the original corners really show up as the
  337. // original corners of the CDT. I.e. I don't trust CGAL to maintain the
  338. // order
  339. assert(T[f].vertex(i) == P[o].to_3d(vit->point()));
  340. #endif
  341. // For first three, use original index in F
  342. v2i[vit] = F(f,i);
  343. }else
  344. {
  345. const Point_3 vit_point_3 = P[o].to_3d(vit->point());
  346. // First look up each edge's neighbors to see if exact point has
  347. // already been added (This makes everything a bit quadratic)
  348. bool found = false;
  349. for(int e = 0; e<3 && !found;e++)
  350. {
  351. // Index of F's eth edge in V
  352. int i = F(f,(e+1)%3);
  353. int j = F(f,(e+2)%3);
  354. // Be sure that i<j
  355. if(i>j)
  356. {
  357. swap(i,j);
  358. }
  359. assert(edge2faces.count(EMK(i,j))==1);
  360. // loop over neighbors
  361. for(
  362. list<int>::const_iterator nit = edge2faces[EMK(i,j)].begin();
  363. nit != edge2faces[EMK(i,j)].end() && !found;
  364. nit++)
  365. {
  366. // don't consider self
  367. if(*nit == f)
  368. {
  369. continue;
  370. }
  371. // index of neighbor in offending (to find its cdt)
  372. int no = offending_index[*nit];
  373. // Loop over vertices of that neighbor's cdt (might not have been
  374. // processed yet, but then it's OK because it'll just be empty)
  375. for(
  376. typename CDT_plus_2::Finite_vertices_iterator uit = cdt[no].finite_vertices_begin();
  377. uit != cdt[no].finite_vertices_end() && !found;
  378. ++uit)
  379. {
  380. if(vit_point_3 == P[no].to_3d(uit->point()))
  381. {
  382. assert(v2i.count(uit) == 1);
  383. v2i[vit] = v2i[uit];
  384. found = true;
  385. }
  386. }
  387. }
  388. }
  389. if(!found)
  390. {
  391. v2i[vit] = V.rows()+NV_count;
  392. NV.push_back(vit_point_3);
  393. NV_count++;
  394. }
  395. }
  396. i++;
  397. }
  398. }
  399. {
  400. int i = 0;
  401. // Resize to fit new number of triangles
  402. NF[o].resize(cdt[o].number_of_faces(),3);
  403. NF_count+=NF[o].rows();
  404. // Append new faces to NF
  405. for(
  406. typename CDT_plus_2::Finite_faces_iterator fit = cdt[o].finite_faces_begin();
  407. fit != cdt[o].finite_faces_end();
  408. ++fit)
  409. {
  410. NF[o](i,0) = v2i[fit->vertex(0)];
  411. NF[o](i,1) = v2i[fit->vertex(1)];
  412. NF[o](i,2) = v2i[fit->vertex(2)];
  413. i++;
  414. }
  415. }
  416. }
  417. assert(NV_count == (int)NV.size());
  418. // Build output
  419. #ifndef NDEBUG
  420. {
  421. int off_count = 0;
  422. for(int f = 0;f<F.rows();f++)
  423. {
  424. off_count+= (offensive[f]?1:0);
  425. }
  426. assert(off_count==(int)offending.size());
  427. }
  428. #endif
  429. // Append faces
  430. FF.resize(F.rows()-offending.size()+NF_count,3);
  431. // First append non-offending original faces
  432. // There's an Eigen way to do this in one line but I forget
  433. int off = 0;
  434. for(int f = 0;f<F.rows();f++)
  435. {
  436. if(!offensive[f])
  437. {
  438. FF.row(off++) = F.row(f);
  439. }
  440. }
  441. assert(off == (int)(F.rows()-offending.size()));
  442. // Now append replacement faces for offending faces
  443. for(int o = 0;o<(int)offending.size();o++)
  444. {
  445. FF.block(off,0,NF[o].rows(),3) = NF[o];
  446. off += NF[o].rows();
  447. }
  448. // Append vertices
  449. VV.resize(V.rows()+NV_count,3);
  450. VV.block(0,0,V.rows(),3) = V;
  451. {
  452. int i = 0;
  453. for(
  454. typename list<Point_3>::const_iterator nvit = NV.begin();
  455. nvit != NV.end();
  456. nvit++)
  457. {
  458. for(int d = 0;d<3;d++)
  459. {
  460. const Point_3 & p = *nvit;
  461. VV(V.rows()+i,d) = CGAL::to_double(p[d]);
  462. // This distinction does not seem necessary:
  463. //#ifdef INEXACT_CONSTRUCTION
  464. // VV(V.rows()+i,d) = CGAL::to_double(p[d]);
  465. //#else
  466. // VV(V.rows()+i,d) = CGAL::to_double(p[d].exact());
  467. //#endif
  468. }
  469. i++;
  470. }
  471. }
  472. // Q: Does this give the same result as TETGEN?
  473. // A: For the cow and beast, yes.
  474. // Q: Is tetgen faster than this CGAL implementation?
  475. // A: Well, yes. But Tetgen is only solving the detection (predicates)
  476. // problem. This is also appending the intersection objects (construction).
  477. // But maybe tetgen is still faster for the detection part. For example, this
  478. // CGAL implementation on the beast takes 98 seconds but tetgen detection
  479. // takes 14 seconds
  480. }
  481. template <typename Kernel>
  482. inline void igl::SelfIntersectMesh<Kernel>::mark_offensive(const int f)
  483. {
  484. using namespace std;
  485. lIF.push_back(f);
  486. if(!offensive[f])
  487. {
  488. offensive[f]=true;
  489. offending_index[f]=offending.size();
  490. offending.push_back(f);
  491. // Add to edge map
  492. for(int e = 0; e<3;e++)
  493. {
  494. // Index of F's eth edge in V
  495. int i = F(f,(e+1)%3);
  496. int j = F(f,(e+2)%3);
  497. // Be sure that i<j
  498. if(i>j)
  499. {
  500. swap(i,j);
  501. }
  502. // Create new list if there is no entry
  503. if(edge2faces.count(EMK(i,j))==0)
  504. {
  505. edge2faces[EMK(i,j)] = list<int>();
  506. }
  507. // append to list
  508. edge2faces[EMK(i,j)].push_back(f);
  509. }
  510. }
  511. }
  512. template <typename Kernel>
  513. inline void igl::SelfIntersectMesh<Kernel>::count_intersection(
  514. const int fa,
  515. const int fb)
  516. {
  517. mark_offensive(fa);
  518. mark_offensive(fb);
  519. this->count++;
  520. // We found the first intersection
  521. if(params.first_only && this->count >= 1)
  522. {
  523. throw FIRST_HIT_EXCEPTION;
  524. }
  525. }
  526. template <typename Kernel>
  527. inline bool igl::SelfIntersectMesh<Kernel>::intersect(
  528. const Triangle_3 & A,
  529. const Triangle_3 & B,
  530. const int fa,
  531. const int fb)
  532. {
  533. // Determine whether there is an intersection
  534. if(!CGAL::do_intersect(A,B))
  535. {
  536. return false;
  537. }
  538. if(!params.detect_only)
  539. {
  540. // Construct intersection
  541. CGAL::Object result = CGAL::intersection(A,B);
  542. F_objects[fa].push_back(result);
  543. F_objects[fb].push_back(result);
  544. }
  545. count_intersection(fa,fb);
  546. return true;
  547. }
  548. template <typename Kernel>
  549. inline bool igl::SelfIntersectMesh<Kernel>::single_shared_vertex(
  550. const Triangle_3 & A,
  551. const Triangle_3 & B,
  552. const int fa,
  553. const int fb,
  554. const int va,
  555. const int vb)
  556. {
  557. ////using namespace std;
  558. //CGAL::Object result = CGAL::intersection(A,B);
  559. //if(CGAL::object_cast<Segment_3 >(&result))
  560. //{
  561. // // Append to each triangle's running list
  562. // F_objects[fa].push_back(result);
  563. // F_objects[fb].push_back(result);
  564. // count_intersection(fa,fb);
  565. //}else
  566. //{
  567. // // Then intersection must be at point
  568. // // And point must be at shared vertex
  569. // assert(CGAL::object_cast<Point_3>(&result));
  570. //}
  571. if(single_shared_vertex(A,B,fa,fb,va))
  572. {
  573. return true;
  574. }
  575. return single_shared_vertex(B,A,fb,fa,vb);
  576. }
  577. template <typename Kernel>
  578. inline bool igl::SelfIntersectMesh<Kernel>::single_shared_vertex(
  579. const Triangle_3 & A,
  580. const Triangle_3 & B,
  581. const int fa,
  582. const int fb,
  583. const int va)
  584. {
  585. // This was not a good idea. It will not handle coplanar triangles well.
  586. using namespace std;
  587. Segment_3 sa(
  588. A.vertex((va+1)%3),
  589. A.vertex((va+2)%3));
  590. if(CGAL::do_intersect(sa,B))
  591. {
  592. CGAL::Object result = CGAL::intersection(sa,B);
  593. if(const Point_3 * p = CGAL::object_cast<Point_3 >(&result))
  594. {
  595. if(!params.detect_only)
  596. {
  597. // Single intersection --> segment from shared point to intersection
  598. CGAL::Object seg = CGAL::make_object(Segment_3(
  599. A.vertex(va),
  600. *p));
  601. F_objects[fa].push_back(seg);
  602. F_objects[fb].push_back(seg);
  603. }
  604. count_intersection(fa,fb);
  605. return true;
  606. }else if(CGAL::object_cast<Segment_3 >(&result))
  607. {
  608. //cerr<<REDRUM("Coplanar at: "<<fa<<" & "<<fb<<" (single shared).")<<endl;
  609. // Must be coplanar
  610. if(params.detect_only)
  611. {
  612. count_intersection(fa,fb);
  613. }else
  614. {
  615. // WRONG:
  616. //// Segment intersection --> triangle from shared point to intersection
  617. //CGAL::Object tri = CGAL::make_object(Triangle_3(
  618. // A.vertex(va),
  619. // s->vertex(0),
  620. // s->vertex(1)));
  621. //F_objects[fa].push_back(tri);
  622. //F_objects[fb].push_back(tri);
  623. //count_intersection(fa,fb);
  624. // Need to do full test. Intersection could be a general poly.
  625. bool test = intersect(A,B,fa,fb);
  626. ((void)test);
  627. assert(test);
  628. }
  629. return true;
  630. }else
  631. {
  632. cerr<<REDRUM("Segment ∩ triangle neither point nor segment?")<<endl;
  633. assert(false);
  634. }
  635. }
  636. return false;
  637. }
  638. template <typename Kernel>
  639. inline bool igl::SelfIntersectMesh<Kernel>::double_shared_vertex(
  640. const Triangle_3 & A,
  641. const Triangle_3 & B,
  642. const int fa,
  643. const int fb)
  644. {
  645. using namespace std;
  646. // Cheaper way to do this than calling do_intersect?
  647. if(
  648. // Can only have an intersection if co-planar
  649. (A.supporting_plane() == B.supporting_plane() ||
  650. A.supporting_plane() == B.supporting_plane().opposite()) &&
  651. CGAL::do_intersect(A,B))
  652. {
  653. // Construct intersection
  654. try
  655. {
  656. CGAL::Object result = CGAL::intersection(A,B);
  657. if(result)
  658. {
  659. if(CGAL::object_cast<Segment_3 >(&result))
  660. {
  661. // not coplanar
  662. return false;
  663. } else if(CGAL::object_cast<Point_3 >(&result))
  664. {
  665. // this "shouldn't" happen but does for inexact
  666. return false;
  667. } else
  668. {
  669. if(!params.detect_only)
  670. {
  671. // Triangle object
  672. F_objects[fa].push_back(result);
  673. F_objects[fb].push_back(result);
  674. }
  675. count_intersection(fa,fb);
  676. //cerr<<REDRUM("Coplanar at: "<<fa<<" & "<<fb<<" (double shared).")<<endl;
  677. return true;
  678. }
  679. }else
  680. {
  681. // CGAL::intersection is disagreeing with do_intersect
  682. return false;
  683. }
  684. }catch(...)
  685. {
  686. // This catches some cgal assertion:
  687. // CGAL error: assertion violation!
  688. // Expression : is_finite(d)
  689. // File : /opt/local/include/CGAL/GMP/Gmpq_type.h
  690. // Line : 132
  691. // Explanation:
  692. // But only if NDEBUG is not defined, otherwise there's an uncaught
  693. // "Floating point exception: 8" SIGFPE
  694. return false;
  695. }
  696. }
  697. // Shouldn't get here either
  698. assert(false);
  699. return false;
  700. }
  701. template <typename Kernel>
  702. inline void igl::SelfIntersectMesh<Kernel>::box_intersect(
  703. const Box& a,
  704. const Box& b)
  705. {
  706. using namespace std;
  707. // index in F and T
  708. int fa = a.handle()-T.begin();
  709. int fb = b.handle()-T.begin();
  710. const Triangle_3 & A = *a.handle();
  711. const Triangle_3 & B = *b.handle();
  712. // I'm not going to deal with degenerate triangles, though at some point we
  713. // should
  714. assert(!a.handle()->is_degenerate());
  715. assert(!b.handle()->is_degenerate());
  716. // Number of combinatorially shared vertices
  717. int comb_shared_vertices = 0;
  718. // Number of geometrically shared vertices (*not* including combinatorially
  719. // shared)
  720. int geo_shared_vertices = 0;
  721. // Keep track of shared vertex indices (we only handles single shared
  722. // vertices as a special case, so just need last/first/only ones)
  723. int va=-1,vb=-1;
  724. int ea,eb;
  725. for(ea=0;ea<3;ea++)
  726. {
  727. for(eb=0;eb<3;eb++)
  728. {
  729. if(F(fa,ea) == F(fb,eb))
  730. {
  731. comb_shared_vertices++;
  732. va = ea;
  733. vb = eb;
  734. }else if(A.vertex(ea) == B.vertex(eb))
  735. {
  736. geo_shared_vertices++;
  737. va = ea;
  738. vb = eb;
  739. }
  740. }
  741. }
  742. const int total_shared_vertices = comb_shared_vertices + geo_shared_vertices;
  743. if(comb_shared_vertices== 3)
  744. {
  745. // Combinatorially duplicate face, these should be removed by preprocessing
  746. cerr<<REDRUM("Facets "<<fa<<" and "<<fb<<" are combinatorial duplicates")<<endl;
  747. goto done;
  748. }
  749. if(total_shared_vertices== 3)
  750. {
  751. // Geometrically duplicate face, these should be removed by preprocessing
  752. cerr<<REDRUM("Facets "<<fa<<" and "<<fb<<" are geometrical duplicates")<<endl;
  753. goto done;
  754. }
  755. //// SPECIAL CASES ARE BROKEN FOR COPLANAR TRIANGLES
  756. //if(total_shared_vertices > 0)
  757. //{
  758. // bool coplanar =
  759. // CGAL::coplanar(A.vertex(0),A.vertex(1),A.vertex(2),B.vertex(0)) &&
  760. // CGAL::coplanar(A.vertex(0),A.vertex(1),A.vertex(2),B.vertex(1)) &&
  761. // CGAL::coplanar(A.vertex(0),A.vertex(1),A.vertex(2),B.vertex(2));
  762. // if(coplanar)
  763. // {
  764. // cerr<<MAGENTAGIN("Facets "<<fa<<" and "<<fb<<
  765. // " are coplanar and share vertices")<<endl;
  766. // goto full;
  767. // }
  768. //}
  769. if(total_shared_vertices == 2)
  770. {
  771. // Q: What about coplanar?
  772. //
  773. // o o
  774. // |\ /|
  775. // | \/ |
  776. // | /\ |
  777. // |/ \|
  778. // o----o
  779. double_shared_vertex(A,B,fa,fb);
  780. goto done;
  781. }
  782. assert(total_shared_vertices<=1);
  783. if(total_shared_vertices==1)
  784. {
  785. assert(va>=0 && va<3);
  786. assert(vb>=0 && vb<3);
  787. //#ifndef NDEBUG
  788. // CGAL::Object result =
  789. //#endif
  790. single_shared_vertex(A,B,fa,fb,va,vb);
  791. //#ifndef NDEBUG
  792. // if(!CGAL::object_cast<Segment_3 >(&result))
  793. // {
  794. // const Point_3 * p = CGAL::object_cast<Point_3 >(&result);
  795. // assert(p);
  796. // for(int ea=0;ea<3;ea++)
  797. // {
  798. // for(int eb=0;eb<3;eb++)
  799. // {
  800. // if(F(fa,ea) == F(fb,eb))
  801. // {
  802. // assert(*p==A.vertex(ea));
  803. // assert(*p==B.vertex(eb));
  804. // }
  805. // }
  806. // }
  807. // }
  808. //#endif
  809. }else
  810. {
  811. //full:
  812. // No geometrically shared vertices, do general intersect
  813. intersect(*a.handle(),*b.handle(),fa,fb);
  814. }
  815. done:
  816. return;
  817. }
  818. // Compute 2D delaunay triangulation of a given 3d triangle and a list of
  819. // intersection objects (points,segments,triangles). CGAL uses an affine
  820. // projection rather than an isometric projection, so we're not guaranteed
  821. // that the 2D delaunay triangulation here will be a delaunay triangulation
  822. // in 3D.
  823. //
  824. // Inputs:
  825. // A triangle in 3D
  826. // A_objects_3 updated list of intersection objects for A
  827. // Outputs:
  828. // cdt Contrained delaunay triangulation in projected 2D plane
  829. template <typename Kernel>
  830. inline void igl::SelfIntersectMesh<Kernel>::projected_delaunay(
  831. const Triangle_3 & A,
  832. const std::list<CGAL::Object> & A_objects_3,
  833. CDT_plus_2 & cdt)
  834. {
  835. using namespace std;
  836. // http://www.cgal.org/Manual/3.2/doc_html/cgal_manual/Triangulation_2/Chapter_main.html#Section_2D_Triangulations_Constrained_Plus
  837. // Plane of triangle A
  838. Plane_3 P(A.vertex(0),A.vertex(1),A.vertex(2));
  839. // Insert triangle into vertices
  840. typename CDT_plus_2::Vertex_handle corners[3];
  841. for(int i = 0;i<3;i++)
  842. {
  843. corners[i] = cdt.insert(P.to_2d(A.vertex(i)));
  844. }
  845. // Insert triangle edges as constraints
  846. for(int i = 0;i<3;i++)
  847. {
  848. cdt.insert_constraint( corners[(i+1)%3], corners[(i+2)%3]);
  849. }
  850. // Insert constraints for intersection objects
  851. for(
  852. typename list<CGAL::Object>::const_iterator lit = A_objects_3.begin();
  853. lit != A_objects_3.end();
  854. lit++)
  855. {
  856. CGAL::Object obj = *lit;
  857. if(const Point_3 *ipoint = CGAL::object_cast<Point_3 >(&obj))
  858. {
  859. // Add point
  860. cdt.insert(P.to_2d(*ipoint));
  861. } else if(const Segment_3 *iseg = CGAL::object_cast<Segment_3 >(&obj))
  862. {
  863. // Add segment constraint
  864. cdt.insert_constraint(P.to_2d(iseg->vertex(0)),P.to_2d(iseg->vertex(1)));
  865. } else if(const Triangle_3 *itri = CGAL::object_cast<Triangle_3 >(&obj))
  866. {
  867. // Add 3 segment constraints
  868. cdt.insert_constraint(P.to_2d(itri->vertex(0)),P.to_2d(itri->vertex(1)));
  869. cdt.insert_constraint(P.to_2d(itri->vertex(1)),P.to_2d(itri->vertex(2)));
  870. cdt.insert_constraint(P.to_2d(itri->vertex(2)),P.to_2d(itri->vertex(0)));
  871. } else if(const std::vector<Point_3 > *polyp =
  872. CGAL::object_cast< std::vector<Point_3 > >(&obj))
  873. {
  874. //cerr<<REDRUM("Poly...")<<endl;
  875. const std::vector<Point_3 > & poly = *polyp;
  876. const int m = poly.size();
  877. assert(m>=2);
  878. for(int p = 0;p<m;p++)
  879. {
  880. const int np = (p+1)%m;
  881. cdt.insert_constraint(P.to_2d(poly[p]),P.to_2d(poly[np]));
  882. }
  883. }else
  884. {
  885. cerr<<REDRUM("What is this object?!")<<endl;
  886. assert(false);
  887. }
  888. }
  889. }
  890. #endif