SelfIntersectMesh.h 29 KB

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