closest_facet.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2015 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. //
  9. #include "closest_facet.h"
  10. #include <vector>
  11. #include <stdexcept>
  12. #include <unordered_map>
  13. #include <CGAL/AABB_tree.h>
  14. #include <CGAL/AABB_traits.h>
  15. #include <CGAL/AABB_triangle_primitive.h>
  16. #include <CGAL/intersections.h>
  17. #include <CGAL/Exact_predicates_exact_constructions_kernel.h>
  18. #include "order_facets_around_edge.h"
  19. #include "../../vertex_triangle_adjacency.h"
  20. #include "../../writePLY.h"
  21. template<
  22. typename DerivedV,
  23. typename DerivedF,
  24. typename DerivedI,
  25. typename DerivedP,
  26. typename uE2EType,
  27. typename DerivedEMAP,
  28. typename DerivedR,
  29. typename DerivedS >
  30. IGL_INLINE void igl::copyleft::cgal::closest_facet(
  31. const Eigen::PlainObjectBase<DerivedV>& V,
  32. const Eigen::PlainObjectBase<DerivedF>& F,
  33. const Eigen::PlainObjectBase<DerivedI>& I,
  34. const Eigen::PlainObjectBase<DerivedP>& P,
  35. const std::vector<std::vector<uE2EType> >& uE2E,
  36. const Eigen::PlainObjectBase<DerivedEMAP>& EMAP,
  37. Eigen::PlainObjectBase<DerivedR>& R,
  38. Eigen::PlainObjectBase<DerivedS>& S) {
  39. typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;
  40. typedef Kernel::Point_3 Point_3;
  41. typedef Kernel::Plane_3 Plane_3;
  42. typedef Kernel::Segment_3 Segment_3;
  43. typedef Kernel::Triangle_3 Triangle;
  44. typedef std::vector<Triangle>::iterator Iterator;
  45. typedef CGAL::AABB_triangle_primitive<Kernel, Iterator> Primitive;
  46. typedef CGAL::AABB_traits<Kernel, Primitive> AABB_triangle_traits;
  47. typedef CGAL::AABB_tree<AABB_triangle_traits> Tree;
  48. if (F.rows() <= 0 || I.rows() <= 0) {
  49. throw std::runtime_error(
  50. "Closest facet cannot be computed on empty mesh.");
  51. }
  52. std::vector<std::vector<size_t> > VF;
  53. std::vector<std::vector<size_t> > VFi;
  54. igl::vertex_triangle_adjacency(V.rows(), F, VF, VFi);
  55. std::vector<bool> in_I(F.rows(), false);
  56. const size_t num_faces = I.rows();
  57. std::vector<Triangle> triangles;
  58. for (size_t i=0; i<num_faces; i++) {
  59. const Eigen::Vector3i f = F.row(I(i, 0));
  60. in_I[I(i,0)] = true;
  61. triangles.emplace_back(
  62. Point_3(V(f[0], 0), V(f[0], 1), V(f[0], 2)),
  63. Point_3(V(f[1], 0), V(f[1], 1), V(f[1], 2)),
  64. Point_3(V(f[2], 0), V(f[2], 1), V(f[2], 2)));
  65. if (triangles.back().is_degenerate()) {
  66. throw std::runtime_error(
  67. "Input facet components contains degenerated triangles");
  68. }
  69. }
  70. Tree tree(triangles.begin(), triangles.end());
  71. tree.accelerate_distance_queries();
  72. auto on_the_positive_side = [&](size_t fid, const Point_3& p) {
  73. const auto& f = F.row(fid).eval();
  74. Point_3 v0(V(f[0], 0), V(f[0], 1), V(f[0], 2));
  75. Point_3 v1(V(f[1], 0), V(f[1], 1), V(f[1], 2));
  76. Point_3 v2(V(f[2], 0), V(f[2], 1), V(f[2], 2));
  77. auto ori = CGAL::orientation(v0, v1, v2, p);
  78. switch (ori) {
  79. case CGAL::POSITIVE:
  80. return true;
  81. case CGAL::NEGATIVE:
  82. return false;
  83. case CGAL::COPLANAR:
  84. // Warning:
  85. // This can only happen if fid contains a boundary edge.
  86. // Catergorized this ambiguous case as negative side.
  87. return false;
  88. default:
  89. throw std::runtime_error("Unknown CGAL state.");
  90. }
  91. return false;
  92. };
  93. auto get_orientation = [&](size_t fid, size_t s, size_t d) -> bool {
  94. const auto& f = F.row(fid);
  95. if ((size_t)f[0] == s && (size_t)f[1] == d) return false;
  96. else if ((size_t)f[1] == s && (size_t)f[2] == d) return false;
  97. else if ((size_t)f[2] == s && (size_t)f[0] == d) return false;
  98. else if ((size_t)f[0] == d && (size_t)f[1] == s) return true;
  99. else if ((size_t)f[1] == d && (size_t)f[2] == s) return true;
  100. else if ((size_t)f[2] == d && (size_t)f[0] == s) return true;
  101. else {
  102. throw std::runtime_error(
  103. "Cannot compute orientation due to incorrect connectivity");
  104. return false;
  105. }
  106. };
  107. auto index_to_signed_index = [&](size_t index, bool ori) -> int{
  108. return (index+1) * (ori? 1:-1);
  109. };
  110. //auto signed_index_to_index = [&](int signed_index) -> size_t {
  111. // return abs(signed_index) - 1;
  112. //};
  113. enum ElementType { VERTEX, EDGE, FACE };
  114. auto determine_element_type = [&](const Point_3& p, const size_t fid,
  115. size_t& element_index) {
  116. const auto& tri = triangles[fid];
  117. const Point_3 p0 = tri[0];
  118. const Point_3 p1 = tri[1];
  119. const Point_3 p2 = tri[2];
  120. if (p == p0) { element_index = 0; return VERTEX; }
  121. if (p == p1) { element_index = 1; return VERTEX; }
  122. if (p == p2) { element_index = 2; return VERTEX; }
  123. if (CGAL::collinear(p0, p1, p)) { element_index = 2; return EDGE; }
  124. if (CGAL::collinear(p1, p2, p)) { element_index = 0; return EDGE; }
  125. if (CGAL::collinear(p2, p0, p)) { element_index = 1; return EDGE; }
  126. element_index = 0;
  127. return FACE;
  128. };
  129. auto process_edge_case = [&](
  130. size_t query_idx,
  131. const size_t s, const size_t d,
  132. size_t preferred_facet,
  133. bool& orientation) {
  134. Point_3 query_point(
  135. P(query_idx, 0),
  136. P(query_idx, 1),
  137. P(query_idx, 2));
  138. size_t corner_idx = std::numeric_limits<size_t>::max();
  139. if ((s == F(preferred_facet, 0) && d == F(preferred_facet, 1)) ||
  140. (s == F(preferred_facet, 1) && d == F(preferred_facet, 0))) {
  141. corner_idx = 2;
  142. } else if ((s == F(preferred_facet, 0) && d == F(preferred_facet, 2)) ||
  143. (s == F(preferred_facet, 2) && d == F(preferred_facet, 0))) {
  144. corner_idx = 1;
  145. } else if ((s == F(preferred_facet, 1) && d == F(preferred_facet, 2)) ||
  146. (s == F(preferred_facet, 2) && d == F(preferred_facet, 1))) {
  147. corner_idx = 0;
  148. } else {
  149. std::cerr << "s: " << s << "\t d:" << d << std::endl;
  150. std::cerr << F.row(preferred_facet) << std::endl;
  151. throw std::runtime_error(
  152. "Invalid connectivity, edge does not belong to facet");
  153. }
  154. auto ueid = EMAP(preferred_facet + corner_idx * F.rows());
  155. auto eids = uE2E[ueid];
  156. std::vector<size_t> intersected_face_indices;
  157. for (auto eid : eids) {
  158. const size_t fid = eid % F.rows();
  159. if (in_I[fid]) {
  160. intersected_face_indices.push_back(fid);
  161. }
  162. }
  163. const size_t num_intersected_faces = intersected_face_indices.size();
  164. std::vector<int> intersected_face_signed_indices(num_intersected_faces);
  165. std::transform(
  166. intersected_face_indices.begin(),
  167. intersected_face_indices.end(),
  168. intersected_face_signed_indices.begin(),
  169. [&](size_t index) {
  170. return index_to_signed_index(
  171. index, get_orientation(index, s,d));
  172. });
  173. assert(num_intersected_faces >= 1);
  174. if (num_intersected_faces == 1) {
  175. // The edge must be a boundary edge. Thus, the orientation can be
  176. // simply determined by checking if the query point is on the
  177. // positive side of the facet.
  178. const size_t fid = intersected_face_indices[0];
  179. orientation = on_the_positive_side(fid, query_point);
  180. return fid;
  181. }
  182. Eigen::VectorXi order;
  183. DerivedP pivot = P.row(query_idx).eval();
  184. igl::copyleft::cgal::order_facets_around_edge(V, F, s, d,
  185. intersected_face_signed_indices,
  186. pivot, order);
  187. // Although first and last are equivalent, make the choice based on
  188. // preferred_facet.
  189. const size_t first = order[0];
  190. const size_t last = order[num_intersected_faces-1];
  191. if (intersected_face_indices[first] == preferred_facet) {
  192. orientation = intersected_face_signed_indices[first] < 0;
  193. return intersected_face_indices[first];
  194. } else if (intersected_face_indices[last] == preferred_facet) {
  195. orientation = intersected_face_signed_indices[last] > 0;
  196. return intersected_face_indices[last];
  197. } else {
  198. orientation = intersected_face_signed_indices[order[0]] < 0;
  199. return intersected_face_indices[order[0]];
  200. }
  201. };
  202. auto process_face_case = [&](
  203. const size_t query_idx, const Point_3& closest_point,
  204. const size_t fid, bool& orientation) {
  205. const auto& f = F.row(I(fid, 0));
  206. return process_edge_case(query_idx, f[0], f[1], I(fid, 0), orientation);
  207. };
  208. // Given that the closest point to query point P(query_idx,:) on (V,F(I,:))
  209. // is the vertex at V(s,:) which is incident at least on triangle
  210. // F(preferred_facet,:), determine a facet incident on V(s,:) that is
  211. // _exposed_ to the query point and determine whether that facet is facing
  212. // _toward_ or _away_ from the query point.
  213. //
  214. // Inputs:
  215. // query_idx index into P of query point
  216. // s index into V of closest point at vertex
  217. // preferred_facet facet incident on s
  218. // Outputs:
  219. // orientation whether returned face is facing toward or away from
  220. // query (parity unclear)
  221. // Returns face guaranteed to be "exposed" to P(query_idx,:)
  222. auto process_vertex_case = [&](
  223. const size_t query_idx,
  224. size_t s,
  225. size_t preferred_facet,
  226. bool& orientation)
  227. {
  228. const Point_3 query_point(
  229. P(query_idx, 0), P(query_idx, 1), P(query_idx, 2));
  230. const Point_3 closest_point(V(s, 0), V(s, 1), V(s, 2));
  231. std::vector<size_t> adj_faces;
  232. std::vector<size_t> adj_face_corners;
  233. {
  234. // Gather adj faces to s within I.
  235. const auto& all_adj_faces = VF[s];
  236. const auto& all_adj_face_corners = VFi[s];
  237. const size_t num_all_adj_faces = all_adj_faces.size();
  238. for (size_t i=0; i<num_all_adj_faces; i++)
  239. {
  240. const size_t fid = all_adj_faces[i];
  241. // Shouldn't this always be true if I is a full connected component?
  242. if (in_I[fid])
  243. {
  244. adj_faces.push_back(fid);
  245. adj_face_corners.push_back(all_adj_face_corners[i]);
  246. }
  247. }
  248. }
  249. const size_t num_adj_faces = adj_faces.size();
  250. assert(num_adj_faces > 0);
  251. std::set<size_t> adj_vertices_set;
  252. std::unordered_multimap<size_t, size_t> v2f;
  253. for (size_t i=0; i<num_adj_faces; i++)
  254. {
  255. const size_t fid = adj_faces[i];
  256. const size_t cid = adj_face_corners[i];
  257. const auto& f = F.row(adj_faces[i]);
  258. const size_t next = f[(cid+1)%3];
  259. const size_t prev = f[(cid+2)%3];
  260. adj_vertices_set.insert(next);
  261. adj_vertices_set.insert(prev);
  262. v2f.insert({{next, fid}, {prev, fid}});
  263. }
  264. const size_t num_adj_vertices = adj_vertices_set.size();
  265. std::vector<size_t> adj_vertices(num_adj_vertices);
  266. std::copy(adj_vertices_set.begin(), adj_vertices_set.end(),
  267. adj_vertices.begin());
  268. std::vector<Point_3> adj_points;
  269. for (size_t vid : adj_vertices)
  270. {
  271. adj_points.emplace_back(V(vid,0), V(vid,1), V(vid,2));
  272. }
  273. // A plane is on the exterior if all adj_points lies on or to
  274. // one side of the plane.
  275. auto is_on_exterior = [&](const Plane_3& separator) {
  276. size_t positive=0;
  277. size_t negative=0;
  278. size_t coplanar=0;
  279. for (const auto& point : adj_points) {
  280. switch(separator.oriented_side(point)) {
  281. case CGAL::ON_POSITIVE_SIDE:
  282. positive++;
  283. break;
  284. case CGAL::ON_NEGATIVE_SIDE:
  285. negative++;
  286. break;
  287. case CGAL::ON_ORIENTED_BOUNDARY:
  288. coplanar++;
  289. break;
  290. default:
  291. throw "Unknown plane-point orientation";
  292. }
  293. }
  294. auto query_orientation = separator.oriented_side(query_point);
  295. if (query_orientation == CGAL::ON_ORIENTED_BOUNDARY &&
  296. (positive == 0 && negative == 0)) {
  297. // All adj vertices and query point are coplanar.
  298. // In this case, all separators are equally valid.
  299. return true;
  300. } else {
  301. bool r = (positive == 0 && query_orientation == CGAL::POSITIVE)
  302. || (negative == 0 && query_orientation == CGAL::NEGATIVE);
  303. return r;
  304. }
  305. };
  306. size_t d = std::numeric_limits<size_t>::max();
  307. for (size_t i=0; i<num_adj_vertices; i++) {
  308. const size_t vi = adj_vertices[i];
  309. for (size_t j=i+1; j<num_adj_vertices; j++) {
  310. Plane_3 separator(closest_point, adj_points[i], adj_points[j]);
  311. if (separator.is_degenerate()) {
  312. continue;
  313. }
  314. if (is_on_exterior(separator)) {
  315. if (!CGAL::collinear(
  316. query_point, adj_points[i], closest_point)) {
  317. d = vi;
  318. break;
  319. } else {
  320. d = adj_vertices[j];
  321. assert(!CGAL::collinear(
  322. query_point, adj_points[j], closest_point));
  323. break;
  324. }
  325. }
  326. }
  327. }
  328. if (d == std::numeric_limits<size_t>::max()) {
  329. Eigen::MatrixXd tmp_vertices(V.rows(), V.cols());
  330. for (size_t i=0; i<V.rows(); i++) {
  331. for (size_t j=0; j<V.cols(); j++) {
  332. tmp_vertices(i,j) = CGAL::to_double(V(i,j));
  333. }
  334. }
  335. Eigen::MatrixXi tmp_faces(adj_faces.size(), 3);
  336. for (size_t i=0; i<adj_faces.size(); i++) {
  337. tmp_faces.row(i) = F.row(adj_faces[i]);
  338. }
  339. igl::writePLY("debug.ply", tmp_vertices, tmp_faces, false);
  340. throw std::runtime_error("Invalid vertex neighborhood");
  341. }
  342. const auto itr = v2f.equal_range(d);
  343. assert(itr.first != itr.second);
  344. return process_edge_case(query_idx, s, d, itr.first->second, orientation);
  345. };
  346. const size_t num_queries = P.rows();
  347. R.resize(num_queries, 1);
  348. S.resize(num_queries, 1);
  349. for (size_t i=0; i<num_queries; i++) {
  350. const Point_3 query(P(i,0), P(i,1), P(i,2));
  351. auto projection = tree.closest_point_and_primitive(query);
  352. const Point_3 closest_point = projection.first;
  353. size_t fid = projection.second - triangles.begin();
  354. bool fid_ori = false;
  355. // Gether all facets sharing the closest point.
  356. std::vector<Tree::Primitive_id> intersected_faces;
  357. tree.all_intersected_primitives(Segment_3(closest_point, query),
  358. std::back_inserter(intersected_faces));
  359. const size_t num_intersected_faces = intersected_faces.size();
  360. std::vector<size_t> intersected_face_indices(num_intersected_faces);
  361. std::transform(intersected_faces.begin(),
  362. intersected_faces.end(),
  363. intersected_face_indices.begin(),
  364. [&](const Tree::Primitive_id& itr) -> size_t
  365. { return I(itr-triangles.begin(), 0); });
  366. size_t element_index;
  367. auto element_type = determine_element_type(closest_point, fid,
  368. element_index);
  369. switch(element_type) {
  370. case VERTEX:
  371. {
  372. const auto& f = F.row(I(fid, 0));
  373. const size_t s = f[element_index];
  374. fid = process_vertex_case(i, s, I(fid, 0), fid_ori);
  375. }
  376. break;
  377. case EDGE:
  378. {
  379. const auto& f = F.row(I(fid, 0));
  380. const size_t s = f[(element_index+1)%3];
  381. const size_t d = f[(element_index+2)%3];
  382. fid = process_edge_case(i, s, d, I(fid, 0), fid_ori);
  383. }
  384. break;
  385. case FACE:
  386. {
  387. fid = process_face_case(i, closest_point, fid, fid_ori);
  388. }
  389. break;
  390. default:
  391. throw std::runtime_error("Unknown element type.");
  392. }
  393. R(i,0) = fid;
  394. S(i,0) = fid_ori;
  395. }
  396. }
  397. template<
  398. typename DerivedV,
  399. typename DerivedF,
  400. typename DerivedP,
  401. typename uE2EType,
  402. typename DerivedEMAP,
  403. typename DerivedR,
  404. typename DerivedS >
  405. IGL_INLINE void igl::copyleft::cgal::closest_facet(
  406. const Eigen::PlainObjectBase<DerivedV>& V,
  407. const Eigen::PlainObjectBase<DerivedF>& F,
  408. const Eigen::PlainObjectBase<DerivedP>& P,
  409. const std::vector<std::vector<uE2EType> >& uE2E,
  410. const Eigen::PlainObjectBase<DerivedEMAP>& EMAP,
  411. Eigen::PlainObjectBase<DerivedR>& R,
  412. Eigen::PlainObjectBase<DerivedS>& S) {
  413. const size_t num_faces = F.rows();
  414. Eigen::VectorXi I(num_faces);
  415. I.setLinSpaced(num_faces, 0, num_faces-1);
  416. igl::copyleft::cgal::closest_facet(V, F, I, P, uE2E, EMAP, R, S);
  417. }
  418. #ifdef IGL_STATIC_LIBRARY
  419. template void igl::copyleft::cgal::closest_facet<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, unsigned long, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> > const&, std::vector<std::vector<unsigned long, std::allocator<unsigned long> >, std::allocator<std::vector<unsigned long, std::allocator<unsigned long> > > > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
  420. #endif