AABB.h 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2015 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_AABB_H
  9. #define IGL_AABB_H
  10. #include "Hit.h"
  11. #include <Eigen/Core>
  12. #include <Eigen/Geometry>
  13. #include <vector>
  14. namespace igl
  15. {
  16. // Implementation of semi-general purpose axis-aligned bounding box hierarchy.
  17. // The mesh (V,Ele) is stored and managed by the caller and each routine here
  18. // simply takes it as references (it better not change between calls).
  19. //
  20. // It's a little annoying that the Dimension is a template parameter and not
  21. // picked up at run time from V. This leads to duplicated code for 2d/3d (up to
  22. // dim).
  23. template <typename DerivedV, int DIM>
  24. class AABB
  25. {
  26. public:
  27. typedef typename DerivedV::Scalar Scalar;
  28. typedef Eigen::Matrix<Scalar,1,DIM> RowVectorDIMS;
  29. typedef Eigen::Matrix<Scalar,DIM,1> VectorDIMS;
  30. typedef Eigen::Matrix<Scalar,Eigen::Dynamic,DIM> MatrixXDIMS;
  31. // Shared pointers are slower...
  32. AABB * m_left;
  33. AABB * m_right;
  34. Eigen::AlignedBox<Scalar,DIM> m_box;
  35. // -1 non-leaf
  36. int m_primitive;
  37. //Scalar m_max_sqr_d;
  38. //int m_depth;
  39. AABB():
  40. m_left(NULL), m_right(NULL),
  41. m_box(), m_primitive(-1)
  42. //m_max_sqr_d(std::numeric_limits<double>::infinity()),
  43. //m_depth(0)
  44. {}
  45. // http://stackoverflow.com/a/3279550/148668
  46. AABB(const AABB& other):
  47. m_left(other.m_left ? new AABB(*other.m_left) : NULL),
  48. m_right(other.m_right ? new AABB(*other.m_right) : NULL),
  49. m_box(other.m_box),
  50. m_primitive(other.m_primitive)
  51. //m_max_sqr_d(other.m_max_sqr_d),
  52. //m_depth(std::max(
  53. // m_left ? m_left->m_depth + 1 : 0,
  54. // m_right ? m_right->m_depth + 1 : 0))
  55. {
  56. }
  57. // copy-swap idiom
  58. friend void swap(AABB& first, AABB& second)
  59. {
  60. // Enable ADL
  61. using std::swap;
  62. swap(first.m_left,second.m_left);
  63. swap(first.m_right,second.m_right);
  64. swap(first.m_box,second.m_box);
  65. swap(first.m_primitive,second.m_primitive);
  66. //swap(first.m_max_sqr_d,second.m_max_sqr_d);
  67. //swap(first.m_depth,second.m_depth);
  68. }
  69. // Pass-by-value (aka copy)
  70. AABB& operator=(AABB other)
  71. {
  72. swap(*this,other);
  73. return *this;
  74. }
  75. AABB(AABB&& other):
  76. // initialize via default constructor
  77. AABB()
  78. {
  79. swap(*this,other);
  80. }
  81. // Seems like there should have been an elegant solution to this using
  82. // the copy-swap idiom above:
  83. inline void deinit()
  84. {
  85. m_primitive = -1;
  86. m_box = Eigen::AlignedBox<Scalar,DIM>();
  87. delete m_left;
  88. m_left = NULL;
  89. delete m_right;
  90. m_right = NULL;
  91. }
  92. ~AABB()
  93. {
  94. deinit();
  95. }
  96. // Build an Axis-Aligned Bounding Box tree for a given mesh and given
  97. // serialization of a previous AABB tree.
  98. //
  99. // Inputs:
  100. // V #V by dim list of mesh vertex positions.
  101. // Ele #Ele by dim+1 list of mesh indices into #V.
  102. // bb_mins max_tree by dim list of bounding box min corner positions
  103. // bb_maxs max_tree by dim list of bounding box max corner positions
  104. // elements max_tree list of element or (not leaf id) indices into Ele
  105. // i recursive call index {0}
  106. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  107. inline void init(
  108. const Eigen::PlainObjectBase<DerivedV> & V,
  109. const Eigen::MatrixXi & Ele,
  110. const Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  111. const Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  112. const Eigen::VectorXi & elements,
  113. const int i = 0);
  114. // Wrapper for root with empty serialization
  115. inline void init(
  116. const Eigen::PlainObjectBase<DerivedV> & V,
  117. const Eigen::MatrixXi & Ele);
  118. // Build an Axis-Aligned Bounding Box tree for a given mesh.
  119. //
  120. // Inputs:
  121. // V #V by dim list of mesh vertex positions.
  122. // Ele #Ele by dim+1 list of mesh indices into #V.
  123. // SI #Ele by dim list revealing for each coordinate where Ele's
  124. // barycenters would be sorted: SI(e,d) = i --> the dth coordinate of
  125. // the barycenter of the eth element would be placed at position i in a
  126. // sorted list.
  127. // I #I list of indices into Ele of elements to include (for recursive
  128. // calls)
  129. //
  130. inline void init(
  131. const Eigen::PlainObjectBase<DerivedV> & V,
  132. const Eigen::MatrixXi & Ele,
  133. const Eigen::MatrixXi & SI,
  134. const Eigen::VectorXi & I);
  135. // Return whether at leaf node
  136. inline bool is_leaf() const;
  137. // Find the indices of elements containing given point: this makes sense
  138. // when Ele is a co-dimension 0 simplex (tets in 3D, triangles in 2D).
  139. //
  140. // Inputs:
  141. // V #V by dim list of mesh vertex positions. **Should be same as used to
  142. // construct mesh.**
  143. // Ele #Ele by dim+1 list of mesh indices into #V. **Should be same as used to
  144. // construct mesh.**
  145. // q dim row-vector query position
  146. // first whether to only return first element containing q
  147. // Returns:
  148. // list of indices of elements containing q
  149. template <typename Derivedq>
  150. inline std::vector<int> find(
  151. const Eigen::PlainObjectBase<DerivedV> & V,
  152. const Eigen::MatrixXi & Ele,
  153. const Eigen::PlainObjectBase<Derivedq> & q,
  154. const bool first=false) const;
  155. // If number of elements m then total tree size should be 2*h where h is
  156. // the deepest depth 2^ceil(log(#Ele*2-1))
  157. inline int subtree_size() const;
  158. // Serialize this class into 3 arrays (so we can pass it pack to matlab)
  159. //
  160. // Outputs:
  161. // bb_mins max_tree by dim list of bounding box min corner positions
  162. // bb_maxs max_tree by dim list of bounding box max corner positions
  163. // elements max_tree list of element or (not leaf id) indices into Ele
  164. // i recursive call index into these arrays {0}
  165. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  166. inline void serialize(
  167. Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  168. Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  169. Eigen::VectorXi & elements,
  170. const int i = 0) const;
  171. // Compute squared distance to a query point
  172. //
  173. // Inputs:
  174. // V #V by dim list of vertex positions
  175. // Ele #Ele by dim list of simplex indices
  176. // P 3 list of query point coordinates
  177. // min_sqr_d current minimum squared distance (only find distances
  178. // less than this)
  179. // Outputs:
  180. // I #P list of facet indices corresponding to smallest distances
  181. // C #P by 3 list of closest points
  182. // Returns squared distance
  183. //
  184. // Known bugs: currently assumes Elements are triangles regardless of
  185. // dimension.
  186. inline Scalar squared_distance(
  187. const Eigen::PlainObjectBase<DerivedV> & V,
  188. const Eigen::MatrixXi & Ele,
  189. const RowVectorDIMS & p,
  190. int & i,
  191. RowVectorDIMS & c) const;
  192. //private:
  193. inline Scalar squared_distance(
  194. const Eigen::PlainObjectBase<DerivedV> & V,
  195. const Eigen::MatrixXi & Ele,
  196. const RowVectorDIMS & p,
  197. const Scalar min_sqr_d,
  198. int & i,
  199. RowVectorDIMS & c) const;
  200. // All hits
  201. inline bool intersect_ray(
  202. const Eigen::PlainObjectBase<DerivedV> & V,
  203. const Eigen::MatrixXi & Ele,
  204. const RowVectorDIMS & origin,
  205. const RowVectorDIMS & dir,
  206. std::vector<igl::Hit> & hits) const;
  207. // First hit
  208. inline bool intersect_ray(
  209. const Eigen::PlainObjectBase<DerivedV> & V,
  210. const Eigen::MatrixXi & Ele,
  211. const RowVectorDIMS & origin,
  212. const RowVectorDIMS & dir,
  213. igl::Hit & hit) const;
  214. //private:
  215. inline bool intersect_ray(
  216. const Eigen::PlainObjectBase<DerivedV> & V,
  217. const Eigen::MatrixXi & Ele,
  218. const RowVectorDIMS & origin,
  219. const RowVectorDIMS & dir,
  220. const Scalar min_t,
  221. igl::Hit & hit) const;
  222. public:
  223. template <
  224. typename DerivedP,
  225. typename DerivedsqrD,
  226. typename DerivedI,
  227. typename DerivedC>
  228. inline void squared_distance(
  229. const Eigen::PlainObjectBase<DerivedV> & V,
  230. const Eigen::MatrixXi & Ele,
  231. const Eigen::PlainObjectBase<DerivedP> & P,
  232. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  233. Eigen::PlainObjectBase<DerivedI> & I,
  234. Eigen::PlainObjectBase<DerivedC> & C) const;
  235. template <
  236. typename Derivedother_V,
  237. typename DerivedsqrD,
  238. typename DerivedI,
  239. typename DerivedC>
  240. inline void squared_distance(
  241. const Eigen::PlainObjectBase<DerivedV> & V,
  242. const Eigen::MatrixXi & Ele,
  243. const AABB<Derivedother_V,DIM> & other,
  244. const Eigen::PlainObjectBase<Derivedother_V> & other_V,
  245. const Eigen::MatrixXi & other_Ele,
  246. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  247. Eigen::PlainObjectBase<DerivedI> & I,
  248. Eigen::PlainObjectBase<DerivedC> & C) const;
  249. private:
  250. template <
  251. typename Derivedother_V,
  252. typename DerivedsqrD,
  253. typename DerivedI,
  254. typename DerivedC>
  255. inline Scalar squared_distance_helper(
  256. const Eigen::PlainObjectBase<DerivedV> & V,
  257. const Eigen::MatrixXi & Ele,
  258. const AABB<Derivedother_V,DIM> * other,
  259. const Eigen::PlainObjectBase<Derivedother_V> & other_V,
  260. const Eigen::MatrixXi & other_Ele,
  261. const Scalar min_sqr_d,
  262. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  263. Eigen::PlainObjectBase<DerivedI> & I,
  264. Eigen::PlainObjectBase<DerivedC> & C) const;
  265. // Helper function for leaves: works in-place on sqr_d
  266. inline void leaf_squared_distance(
  267. const Eigen::PlainObjectBase<DerivedV> & V,
  268. const Eigen::MatrixXi & Ele,
  269. const RowVectorDIMS & p,
  270. Scalar & sqr_d,
  271. int & i,
  272. RowVectorDIMS & c) const;
  273. inline void set_min(
  274. const RowVectorDIMS & p,
  275. const Scalar sqr_d_candidate,
  276. const int i_candidate,
  277. const RowVectorDIMS & c_candidate,
  278. Scalar & sqr_d,
  279. int & i,
  280. RowVectorDIMS & c) const;
  281. public:
  282. static
  283. inline void barycentric_coordinates(
  284. const RowVectorDIMS & p,
  285. const RowVectorDIMS & a,
  286. const RowVectorDIMS & b,
  287. const RowVectorDIMS & c,
  288. Eigen::Matrix<Scalar,1,3> & bary);
  289. public:
  290. EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  291. };
  292. }
  293. // Implementation
  294. #include "EPS.h"
  295. #include "barycenter.h"
  296. #include "colon.h"
  297. #include "colon.h"
  298. #include "doublearea.h"
  299. #include "matlab_format.h"
  300. #include "project_to_line_segment.h"
  301. #include "sort.h"
  302. #include "volume.h"
  303. #include "ray_box_intersect.h"
  304. #include "ray_mesh_intersect.h"
  305. #include <iostream>
  306. #include <iomanip>
  307. #include <limits>
  308. #include <list>
  309. template <typename DerivedV, int DIM>
  310. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  311. inline void igl::AABB<DerivedV,DIM>::init(
  312. const Eigen::PlainObjectBase<DerivedV> & V,
  313. const Eigen::MatrixXi & Ele,
  314. const Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  315. const Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  316. const Eigen::VectorXi & elements,
  317. const int i)
  318. {
  319. using namespace std;
  320. using namespace Eigen;
  321. if(bb_mins.size() > 0)
  322. {
  323. assert(bb_mins.rows() == bb_maxs.rows() && "Serial tree arrays must match");
  324. assert(bb_mins.cols() == V.cols() && "Serial tree array dim must match V");
  325. assert(bb_mins.cols() == bb_maxs.cols() && "Serial tree arrays must match");
  326. assert(bb_mins.rows() == elements.rows() &&
  327. "Serial tree arrays must match");
  328. // construct from serialization
  329. m_box.extend(bb_mins.row(i).transpose());
  330. m_box.extend(bb_maxs.row(i).transpose());
  331. m_primitive = elements(i);
  332. // Not leaf then recurse
  333. if(m_primitive == -1)
  334. {
  335. m_left = new AABB();
  336. m_left->init( V,Ele,bb_mins,bb_maxs,elements,2*i+1);
  337. m_right = new AABB();
  338. m_right->init( V,Ele,bb_mins,bb_maxs,elements,2*i+2);
  339. //m_depth = std::max( m_left->m_depth, m_right->m_depth)+1;
  340. }
  341. }else
  342. {
  343. VectorXi allI = colon<int>(0,Ele.rows()-1);
  344. MatrixXDIMS BC;
  345. if(Ele.cols() == 1)
  346. {
  347. // points
  348. BC = V;
  349. }else
  350. {
  351. // Simplices
  352. barycenter(V,Ele,BC);
  353. }
  354. MatrixXi SI(BC.rows(),BC.cols());
  355. {
  356. MatrixXDIMS _;
  357. MatrixXi IS;
  358. igl::sort(BC,1,true,_,IS);
  359. // Need SI(i) to tell which place i would be sorted into
  360. const int dim = IS.cols();
  361. for(int i = 0;i<IS.rows();i++)
  362. {
  363. for(int d = 0;d<dim;d++)
  364. {
  365. SI(IS(i,d),d) = i;
  366. }
  367. }
  368. }
  369. init(V,Ele,SI,allI);
  370. }
  371. }
  372. template <typename DerivedV, int DIM>
  373. inline void igl::AABB<DerivedV,DIM>::init(
  374. const Eigen::PlainObjectBase<DerivedV> & V,
  375. const Eigen::MatrixXi & Ele)
  376. {
  377. using namespace Eigen;
  378. return init(V,Ele,MatrixXDIMS(),MatrixXDIMS(),VectorXi(),0);
  379. }
  380. template <typename DerivedV, int DIM>
  381. inline void igl::AABB<DerivedV,DIM>::init(
  382. const Eigen::PlainObjectBase<DerivedV> & V,
  383. const Eigen::MatrixXi & Ele,
  384. const Eigen::MatrixXi & SI,
  385. const Eigen::VectorXi & I)
  386. {
  387. using namespace Eigen;
  388. using namespace std;
  389. assert(DIM == V.cols() && "V.cols() should matched declared dimension");
  390. //const Scalar inf = numeric_limits<Scalar>::infinity();
  391. m_box = AlignedBox<Scalar,DIM>();
  392. // Compute bounding box
  393. for(int i = 0;i<I.rows();i++)
  394. {
  395. for(int c = 0;c<Ele.cols();c++)
  396. {
  397. m_box.extend(V.row(Ele(I(i),c)).transpose());
  398. m_box.extend(V.row(Ele(I(i),c)).transpose());
  399. }
  400. }
  401. switch(I.size())
  402. {
  403. case 0:
  404. {
  405. assert(false);
  406. }
  407. case 1:
  408. {
  409. m_primitive = I(0);
  410. break;
  411. }
  412. default:
  413. {
  414. // Compute longest direction
  415. int max_d = -1;
  416. m_box.diagonal().maxCoeff(&max_d);
  417. // Can't use median on BC directly because many may have same value,
  418. // but can use median on sorted BC indices
  419. VectorXi SIdI(I.rows());
  420. for(int i = 0;i<I.rows();i++)
  421. {
  422. SIdI(i) = SI(I(i),max_d);
  423. }
  424. // Since later I use <= I think I don't need to worry about odd/even
  425. // Pass by copy to avoid changing input
  426. const auto median = [](VectorXi A)->Scalar
  427. {
  428. size_t n = A.size()/2;
  429. nth_element(A.data(),A.data()+n,A.data()+A.size());
  430. if(A.rows() % 2 == 1)
  431. {
  432. return A(n);
  433. }else
  434. {
  435. nth_element(A.data(),A.data()+n-1,A.data()+A.size());
  436. return 0.5*(A(n)+A(n-1));
  437. }
  438. };
  439. const Scalar med = median(SIdI);
  440. VectorXi LI((I.rows()+1)/2),RI(I.rows()/2);
  441. assert(LI.rows()+RI.rows() == I.rows());
  442. // Distribute left and right
  443. {
  444. int li = 0;
  445. int ri = 0;
  446. for(int i = 0;i<I.rows();i++)
  447. {
  448. if(SIdI(i)<=med)
  449. {
  450. LI(li++) = I(i);
  451. }else
  452. {
  453. RI(ri++) = I(i);
  454. }
  455. }
  456. }
  457. //m_depth = 0;
  458. if(LI.rows()>0)
  459. {
  460. m_left = new AABB();
  461. m_left->init(V,Ele,SI,LI);
  462. //m_depth = std::max(m_depth, m_left->m_depth+1);
  463. }
  464. if(RI.rows()>0)
  465. {
  466. m_right = new AABB();
  467. m_right->init(V,Ele,SI,RI);
  468. //m_depth = std::max(m_depth, m_right->m_depth+1);
  469. }
  470. }
  471. }
  472. }
  473. template <typename DerivedV, int DIM>
  474. inline bool igl::AABB<DerivedV,DIM>::is_leaf() const
  475. {
  476. return m_primitive != -1;
  477. }
  478. template <typename DerivedV, int DIM>
  479. template <typename Derivedq>
  480. inline std::vector<int> igl::AABB<DerivedV,DIM>::find(
  481. const Eigen::PlainObjectBase<DerivedV> & V,
  482. const Eigen::MatrixXi & Ele,
  483. const Eigen::PlainObjectBase<Derivedq> & q,
  484. const bool first) const
  485. {
  486. using namespace std;
  487. using namespace Eigen;
  488. assert(q.size() == DIM &&
  489. "Query dimension should match aabb dimension");
  490. assert(Ele.cols() == V.cols()+1 &&
  491. "AABB::find only makes sense for (d+1)-simplices");
  492. const Scalar epsilon = igl::EPS<Scalar>();
  493. // Check if outside bounding box
  494. bool inside = m_box.contains(q.transpose());
  495. if(!inside)
  496. {
  497. return std::vector<int>();
  498. }
  499. assert(m_primitive==-1 || (m_left == NULL && m_right == NULL));
  500. if(is_leaf())
  501. {
  502. // Initialize to some value > -epsilon
  503. Scalar a1=0,a2=0,a3=0,a4=0;
  504. switch(DIM)
  505. {
  506. case 3:
  507. {
  508. // Barycentric coordinates
  509. typedef Eigen::Matrix<Scalar,1,3> RowVector3S;
  510. const RowVector3S V1 = V.row(Ele(m_primitive,0));
  511. const RowVector3S V2 = V.row(Ele(m_primitive,1));
  512. const RowVector3S V3 = V.row(Ele(m_primitive,2));
  513. const RowVector3S V4 = V.row(Ele(m_primitive,3));
  514. a1 = volume_single(V2,V4,V3,(RowVector3S)q);
  515. a2 = volume_single(V1,V3,V4,(RowVector3S)q);
  516. a3 = volume_single(V1,V4,V2,(RowVector3S)q);
  517. a4 = volume_single(V1,V2,V3,(RowVector3S)q);
  518. break;
  519. }
  520. case 2:
  521. {
  522. // Barycentric coordinates
  523. typedef Eigen::Matrix<Scalar,2,1> Vector2S;
  524. const Vector2S V1 = V.row(Ele(m_primitive,0));
  525. const Vector2S V2 = V.row(Ele(m_primitive,1));
  526. const Vector2S V3 = V.row(Ele(m_primitive,2));
  527. // Hack for now to keep templates simple. If becomes bottleneck
  528. // consider using std::enable_if_t
  529. const Vector2S q2 = q.head(2);
  530. a1 = doublearea_single(V1,V2,q2);
  531. a2 = doublearea_single(V2,V3,q2);
  532. a3 = doublearea_single(V3,V1,q2);
  533. break;
  534. }
  535. default:assert(false);
  536. }
  537. // Normalization is important for correcting sign
  538. Scalar sum = a1+a2+a3+a4;
  539. a1 /= sum;
  540. a2 /= sum;
  541. a3 /= sum;
  542. a4 /= sum;
  543. if(
  544. a1>=-epsilon &&
  545. a2>=-epsilon &&
  546. a3>=-epsilon &&
  547. a4>=-epsilon)
  548. {
  549. return std::vector<int>(1,m_primitive);
  550. }else
  551. {
  552. return std::vector<int>();
  553. }
  554. }
  555. std::vector<int> left = m_left->find(V,Ele,q,first);
  556. if(first && !left.empty())
  557. {
  558. return left;
  559. }
  560. std::vector<int> right = m_right->find(V,Ele,q,first);
  561. if(first)
  562. {
  563. return right;
  564. }
  565. left.insert(left.end(),right.begin(),right.end());
  566. return left;
  567. }
  568. template <typename DerivedV, int DIM>
  569. inline int igl::AABB<DerivedV,DIM>::subtree_size() const
  570. {
  571. // 1 for self
  572. int n = 1;
  573. int n_left = 0,n_right = 0;
  574. if(m_left != NULL)
  575. {
  576. n_left = m_left->subtree_size();
  577. }
  578. if(m_right != NULL)
  579. {
  580. n_right = m_right->subtree_size();
  581. }
  582. n += 2*std::max(n_left,n_right);
  583. return n;
  584. }
  585. template <typename DerivedV, int DIM>
  586. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  587. inline void igl::AABB<DerivedV,DIM>::serialize(
  588. Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  589. Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  590. Eigen::VectorXi & elements,
  591. const int i) const
  592. {
  593. using namespace std;
  594. using namespace Eigen;
  595. // Calling for root then resize output
  596. if(i==0)
  597. {
  598. const int m = subtree_size();
  599. //cout<<"m: "<<m<<endl;
  600. bb_mins.resize(m,DIM);
  601. bb_maxs.resize(m,DIM);
  602. elements.resize(m,1);
  603. }
  604. //cout<<i<<" ";
  605. bb_mins.row(i) = m_box.min();
  606. bb_maxs.row(i) = m_box.max();
  607. elements(i) = m_primitive;
  608. if(m_left != NULL)
  609. {
  610. m_left->serialize(bb_mins,bb_maxs,elements,2*i+1);
  611. }
  612. if(m_right != NULL)
  613. {
  614. m_right->serialize(bb_mins,bb_maxs,elements,2*i+2);
  615. }
  616. }
  617. template <typename DerivedV, int DIM>
  618. inline typename igl::AABB<DerivedV,DIM>::Scalar
  619. igl::AABB<DerivedV,DIM>::squared_distance(
  620. const Eigen::PlainObjectBase<DerivedV> & V,
  621. const Eigen::MatrixXi & Ele,
  622. const RowVectorDIMS & p,
  623. int & i,
  624. RowVectorDIMS & c) const
  625. {
  626. return squared_distance(V,Ele,p,std::numeric_limits<Scalar>::infinity(),i,c);
  627. }
  628. template <typename DerivedV, int DIM>
  629. inline typename igl::AABB<DerivedV,DIM>::Scalar
  630. igl::AABB<DerivedV,DIM>::squared_distance(
  631. const Eigen::PlainObjectBase<DerivedV> & V,
  632. const Eigen::MatrixXi & Ele,
  633. const RowVectorDIMS & p,
  634. Scalar min_sqr_d,
  635. int & i,
  636. RowVectorDIMS & c) const
  637. {
  638. using namespace Eigen;
  639. using namespace std;
  640. using namespace igl;
  641. Scalar sqr_d = min_sqr_d;
  642. //assert(DIM == 3 && "Code has only been tested for DIM == 3");
  643. assert((Ele.cols() == 3 || Ele.cols() == 2 || Ele.cols() == 1)
  644. && "Code has only been tested for simplex sizes 3,2,1");
  645. assert(m_primitive==-1 || (m_left == NULL && m_right == NULL));
  646. if(is_leaf())
  647. {
  648. leaf_squared_distance(V,Ele,p,sqr_d,i,c);
  649. }else
  650. {
  651. bool looked_left = false;
  652. bool looked_right = false;
  653. const auto & look_left = [&]()
  654. {
  655. int i_left;
  656. RowVectorDIMS c_left = c;
  657. Scalar sqr_d_left = m_left->squared_distance(V,Ele,p,sqr_d,i_left,c_left);
  658. set_min(p,sqr_d_left,i_left,c_left,sqr_d,i,c);
  659. looked_left = true;
  660. };
  661. const auto & look_right = [&]()
  662. {
  663. int i_right;
  664. RowVectorDIMS c_right = c;
  665. Scalar sqr_d_right = m_right->squared_distance(V,Ele,p,sqr_d,i_right,c_right);
  666. set_min(p,sqr_d_right,i_right,c_right,sqr_d,i,c);
  667. looked_right = true;
  668. };
  669. // must look left or right if in box
  670. if(m_left->m_box.contains(p.transpose()))
  671. {
  672. look_left();
  673. }
  674. if(m_right->m_box.contains(p.transpose()))
  675. {
  676. look_right();
  677. }
  678. // if haven't looked left and could be less than current min, then look
  679. Scalar left_min_sqr_d = m_left->m_box.squaredExteriorDistance(p.transpose());
  680. Scalar right_min_sqr_d = m_right->m_box.squaredExteriorDistance(p.transpose());
  681. if(left_min_sqr_d < right_min_sqr_d)
  682. {
  683. if(!looked_left && left_min_sqr_d<sqr_d)
  684. {
  685. look_left();
  686. }
  687. if( !looked_right && right_min_sqr_d<sqr_d)
  688. {
  689. look_right();
  690. }
  691. }else
  692. {
  693. if( !looked_right && right_min_sqr_d<sqr_d)
  694. {
  695. look_right();
  696. }
  697. if(!looked_left && left_min_sqr_d<sqr_d)
  698. {
  699. look_left();
  700. }
  701. }
  702. }
  703. return sqr_d;
  704. }
  705. template <typename DerivedV, int DIM>
  706. template <
  707. typename DerivedP,
  708. typename DerivedsqrD,
  709. typename DerivedI,
  710. typename DerivedC>
  711. inline void igl::AABB<DerivedV,DIM>::squared_distance(
  712. const Eigen::PlainObjectBase<DerivedV> & V,
  713. const Eigen::MatrixXi & Ele,
  714. const Eigen::PlainObjectBase<DerivedP> & P,
  715. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  716. Eigen::PlainObjectBase<DerivedI> & I,
  717. Eigen::PlainObjectBase<DerivedC> & C) const
  718. {
  719. assert(P.cols() == V.cols() && "cols in P should match dim of cols in V");
  720. sqrD.resize(P.rows(),1);
  721. I.resize(P.rows(),1);
  722. C.resize(P.rows(),P.cols());
  723. for(int p = 0;p<P.rows();p++)
  724. {
  725. RowVectorDIMS Pp = P.row(p), c;
  726. int Ip;
  727. sqrD(p) = squared_distance(V,Ele,Pp,Ip,c);
  728. I(p) = Ip;
  729. C.row(p).head(DIM) = c;
  730. }
  731. }
  732. template <typename DerivedV, int DIM>
  733. template <
  734. typename Derivedother_V,
  735. typename DerivedsqrD,
  736. typename DerivedI,
  737. typename DerivedC>
  738. inline void igl::AABB<DerivedV,DIM>::squared_distance(
  739. const Eigen::PlainObjectBase<DerivedV> & V,
  740. const Eigen::MatrixXi & Ele,
  741. const AABB<Derivedother_V,DIM> & other,
  742. const Eigen::PlainObjectBase<Derivedother_V> & other_V,
  743. const Eigen::MatrixXi & other_Ele,
  744. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  745. Eigen::PlainObjectBase<DerivedI> & I,
  746. Eigen::PlainObjectBase<DerivedC> & C) const
  747. {
  748. assert(other_Ele.cols() == 1 &&
  749. "Only implemented for other as list of points");
  750. assert(other_V.cols() == V.cols() && "other must match this dimension");
  751. sqrD.setConstant(other_Ele.rows(),1,std::numeric_limits<double>::infinity());
  752. I.resize(other_Ele.rows(),1);
  753. C.resize(other_Ele.rows(),other_V.cols());
  754. // All points in other_V currently think they need to check against root of
  755. // this. The point of using another AABB is to quickly prune chunks of
  756. // other_V so that most points just check some subtree of this.
  757. // This holds a conservative estimate of max(sqr_D) where sqr_D is the
  758. // current best minimum squared distance for all points in this subtree
  759. double min_sqr_d = std::numeric_limits<double>::infinity();
  760. squared_distance_helper(
  761. V,Ele,&other,other_V,other_Ele,min_sqr_d,sqrD,I,C);
  762. }
  763. template <typename DerivedV, int DIM>
  764. template <
  765. typename Derivedother_V,
  766. typename DerivedsqrD,
  767. typename DerivedI,
  768. typename DerivedC>
  769. inline typename igl::AABB<DerivedV,DIM>::Scalar igl::AABB<DerivedV,DIM>::squared_distance_helper(
  770. const Eigen::PlainObjectBase<DerivedV> & V,
  771. const Eigen::MatrixXi & Ele,
  772. const AABB<Derivedother_V,DIM> * other,
  773. const Eigen::PlainObjectBase<Derivedother_V> & other_V,
  774. const Eigen::MatrixXi & other_Ele,
  775. const Scalar /*min_sqr_d*/,
  776. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  777. Eigen::PlainObjectBase<DerivedI> & I,
  778. Eigen::PlainObjectBase<DerivedC> & C) const
  779. {
  780. using namespace std;
  781. using namespace Eigen;
  782. // This implementation is a bit disappointing. There's no major speed up. Any
  783. // performance gains seem to come from accidental cache coherency and
  784. // diminish for larger "other" (the opposite of what was intended).
  785. // Base case
  786. if(other->is_leaf() && this->is_leaf())
  787. {
  788. Scalar sqr_d = sqrD(other->m_primitive);
  789. int i = I(other->m_primitive);
  790. RowVectorDIMS c = C.row( other->m_primitive);
  791. RowVectorDIMS p = other_V.row(other->m_primitive);
  792. leaf_squared_distance(V,Ele,p,sqr_d,i,c);
  793. sqrD( other->m_primitive) = sqr_d;
  794. I( other->m_primitive) = i;
  795. C.row(other->m_primitive) = c;
  796. //cout<<"leaf: "<<sqr_d<<endl;
  797. //other->m_max_sqr_d = sqr_d;
  798. return sqr_d;
  799. }
  800. if(other->is_leaf())
  801. {
  802. Scalar sqr_d = sqrD(other->m_primitive);
  803. int i = I(other->m_primitive);
  804. RowVectorDIMS c = C.row( other->m_primitive);
  805. RowVectorDIMS p = other_V.row(other->m_primitive);
  806. sqr_d = squared_distance(V,Ele,p,sqr_d,i,c);
  807. sqrD( other->m_primitive) = sqr_d;
  808. I( other->m_primitive) = i;
  809. C.row(other->m_primitive) = c;
  810. //other->m_max_sqr_d = sqr_d;
  811. return sqr_d;
  812. }
  813. //// Exact minimum squared distance between arbitary primitives inside this and
  814. //// othre's bounding boxes
  815. //const auto & min_squared_distance = [&](
  816. // const AABB<DerivedV,DIM> * A,
  817. // const AABB<Derivedother_V,DIM> * B)->Scalar
  818. //{
  819. // return A->m_box.squaredExteriorDistance(B->m_box);
  820. //};
  821. if(this->is_leaf())
  822. {
  823. //if(min_squared_distance(this,other) < other->m_max_sqr_d)
  824. if(true)
  825. {
  826. this->squared_distance_helper(
  827. V,Ele,other->m_left,other_V,other_Ele,0,sqrD,I,C);
  828. this->squared_distance_helper(
  829. V,Ele,other->m_right,other_V,other_Ele,0,sqrD,I,C);
  830. }else
  831. {
  832. // This is never reached...
  833. }
  834. //// we know other is not a leaf
  835. //other->m_max_sqr_d = std::max(other->m_left->m_max_sqr_d,other->m_right->m_max_sqr_d);
  836. return 0;
  837. }
  838. // FORCE DOWN TO OTHER LEAF EVAL
  839. //if(min_squared_distance(this,other) < other->m_max_sqr_d)
  840. if(true)
  841. {
  842. if(true)
  843. {
  844. this->squared_distance_helper(
  845. V,Ele,other->m_left,other_V,other_Ele,0,sqrD,I,C);
  846. this->squared_distance_helper(
  847. V,Ele,other->m_right,other_V,other_Ele,0,sqrD,I,C);
  848. }else // this direction never seems to be faster
  849. {
  850. this->m_left->squared_distance_helper(
  851. V,Ele,other,other_V,other_Ele,0,sqrD,I,C);
  852. this->m_right->squared_distance_helper(
  853. V,Ele,other,other_V,other_Ele,0,sqrD,I,C);
  854. }
  855. }else
  856. {
  857. // this is never reached ... :-(
  858. }
  859. //// we know other is not a leaf
  860. //other->m_max_sqr_d = std::max(other->m_left->m_max_sqr_d,other->m_right->m_max_sqr_d);
  861. return 0;
  862. #if 0 // False
  863. // _Very_ conservative approximation of maximum squared distance between
  864. // primitives inside this and other's bounding boxes
  865. const auto & max_squared_distance = [](
  866. const AABB<DerivedV,DIM> * A,
  867. const AABB<Derivedother_V,DIM> * B)->Scalar
  868. {
  869. AlignedBox<Scalar,DIM> combo = A->m_box;
  870. combo.extend(B->m_box);
  871. return combo.diagonal().squaredNorm();
  872. };
  873. //// other base-case
  874. //if(other->is_leaf())
  875. //{
  876. // double sqr_d = sqrD(other->m_primitive);
  877. // int i = I(other->m_primitive);
  878. // RowVectorDIMS c = C.row(m_primitive);
  879. // RowVectorDIMS p = other_V.row(m_primitive);
  880. // leaf_squared_distance(V,Ele,p,sqr_d,i,c);
  881. // sqrD(other->m_primitive) = sqr_d;
  882. // I(other->m_primitive) = i;
  883. // C.row(m_primitive) = c;
  884. // return;
  885. //}
  886. std::vector<const AABB<DerivedV,DIM> * > this_list;
  887. if(this->is_leaf())
  888. {
  889. this_list.push_back(this);
  890. }else
  891. {
  892. assert(this->m_left);
  893. this_list.push_back(this->m_left);
  894. assert(this->m_right);
  895. this_list.push_back(this->m_right);
  896. }
  897. std::vector<AABB<Derivedother_V,DIM> *> other_list;
  898. if(other->is_leaf())
  899. {
  900. other_list.push_back(other);
  901. }else
  902. {
  903. assert(other->m_left);
  904. other_list.push_back(other->m_left);
  905. assert(other->m_right);
  906. other_list.push_back(other->m_right);
  907. }
  908. //const std::function<Scalar(
  909. // const AABB<Derivedother_V,DIM> * other)
  910. // > max_sqr_d = [&sqrD,&max_sqr_d](const AABB<Derivedother_V,DIM> * other)->Scalar
  911. // {
  912. // if(other->is_leaf())
  913. // {
  914. // return sqrD(other->m_primitive);
  915. // }else
  916. // {
  917. // return std::max(max_sqr_d(other->m_left),max_sqr_d(other->m_right));
  918. // }
  919. // };
  920. //// Potentially recurse on all pairs, if minimum distance is less than running
  921. //// bound
  922. //Eigen::Matrix<Scalar,Eigen::Dynamic,1> other_max_sqr_d =
  923. // Eigen::Matrix<Scalar,Eigen::Dynamic,1>::Constant(other_list.size(),1,min_sqr_d);
  924. for(size_t child = 0;child<other_list.size();child++)
  925. {
  926. auto other_tree = other_list[child];
  927. Eigen::Matrix<Scalar,Eigen::Dynamic,1> this_max_sqr_d(this_list.size(),1);
  928. for(size_t t = 0;t<this_list.size();t++)
  929. {
  930. const auto this_tree = this_list[t];
  931. this_max_sqr_d(t) = max_squared_distance(this_tree,other_tree);
  932. }
  933. if(this_list.size() ==2 &&
  934. ( this_max_sqr_d(0) > this_max_sqr_d(1))
  935. )
  936. {
  937. std::swap(this_list[0],this_list[1]);
  938. //std::swap(this_max_sqr_d(0),this_max_sqr_d(1));
  939. }
  940. const Scalar sqr_d = this_max_sqr_d.minCoeff();
  941. for(size_t t = 0;t<this_list.size();t++)
  942. {
  943. const auto this_tree = this_list[t];
  944. //const auto mm = max_sqr_d(other_tree);
  945. //const Scalar mc = other_max_sqr_d(child);
  946. //assert(mc == mm);
  947. // Only look left/right in this_list if can possible decrease somebody's
  948. // distance in this_tree.
  949. const Scalar min_this_other = min_squared_distance(this_tree,other_tree);
  950. if(
  951. min_this_other < sqr_d &&
  952. min_this_other < other_tree->m_max_sqr_d)
  953. {
  954. //cout<<"before: "<<other_max_sqr_d(child)<<endl;
  955. //other_max_sqr_d(child) = std::min(
  956. // other_max_sqr_d(child),
  957. // this_tree->squared_distance_helper(
  958. // V,Ele,other_tree,other_V,other_Ele,other_max_sqr_d(child),sqrD,I,C));
  959. //cout<<"after: "<<other_max_sqr_d(child)<<endl;
  960. this_tree->squared_distance_helper(
  961. V,Ele,other_tree,other_V,other_Ele,0,sqrD,I,C);
  962. }
  963. }
  964. }
  965. //const Scalar ret = other_max_sqr_d.maxCoeff();
  966. //const auto mm = max_sqr_d(other);
  967. //assert(mm == ret);
  968. //cout<<"non-leaf: "<<ret<<endl;
  969. //return ret;
  970. if(!other->is_leaf())
  971. {
  972. other->m_max_sqr_d = std::max(other->m_left->m_max_sqr_d,other->m_right->m_max_sqr_d);
  973. }
  974. return 0;
  975. #endif
  976. }
  977. template <typename DerivedV, int DIM>
  978. inline void igl::AABB<DerivedV,DIM>::leaf_squared_distance(
  979. const Eigen::PlainObjectBase<DerivedV> & V,
  980. const Eigen::MatrixXi & Ele,
  981. const RowVectorDIMS & p,
  982. Scalar & sqr_d,
  983. int & i,
  984. RowVectorDIMS & c) const
  985. {
  986. using namespace Eigen;
  987. using namespace igl;
  988. using namespace std;
  989. // Simplex size
  990. const size_t ss = Ele.cols();
  991. // Only one element per node
  992. // plane unit normal
  993. bool inside_triangle = false;
  994. Scalar d_j = std::numeric_limits<Scalar>::infinity();
  995. RowVectorDIMS pp;
  996. // Only consider triangles, and non-degenerate triangles at that
  997. if(ss == 3 &&
  998. Ele(m_primitive,0) != Ele(m_primitive,1) &&
  999. Ele(m_primitive,1) != Ele(m_primitive,2) &&
  1000. Ele(m_primitive,2) != Ele(m_primitive,0))
  1001. {
  1002. assert(DIM == 3 && "Only implemented for 3D triangles");
  1003. typedef Eigen::Matrix<Scalar,1,3> RowVector3S;
  1004. // can't be const because of annoying DIM template
  1005. RowVector3S v10(0,0,0);
  1006. v10.head(DIM) = (V.row(Ele(m_primitive,1))- V.row(Ele(m_primitive,0)));
  1007. RowVector3S v20(0,0,0);
  1008. v20.head(DIM) = (V.row(Ele(m_primitive,2))- V.row(Ele(m_primitive,0)));
  1009. const RowVectorDIMS n = (v10.cross(v20)).head(DIM);
  1010. Scalar n_norm = n.norm();
  1011. if(n_norm > 0)
  1012. {
  1013. const RowVectorDIMS un = n/n.norm();
  1014. // vector to plane
  1015. const RowVectorDIMS bc =
  1016. 1./3.*
  1017. ( V.row(Ele(m_primitive,0))+
  1018. V.row(Ele(m_primitive,1))+
  1019. V.row(Ele(m_primitive,2)));
  1020. const auto & v = p-bc;
  1021. // projected point on plane
  1022. d_j = v.dot(un);
  1023. pp = p - d_j*un;
  1024. // determine if pp is inside triangle
  1025. Eigen::Matrix<Scalar,1,3> b;
  1026. barycentric_coordinates(
  1027. pp,
  1028. V.row(Ele(m_primitive,0)),
  1029. V.row(Ele(m_primitive,1)),
  1030. V.row(Ele(m_primitive,2)),
  1031. b);
  1032. inside_triangle = fabs(fabs(b(0)) + fabs(b(1)) + fabs(b(2)) - 1.) <= 1e-10;
  1033. }
  1034. }
  1035. const auto & point_point_squared_distance = [&](const RowVectorDIMS & s)
  1036. {
  1037. const Scalar sqr_d_s = (p-s).squaredNorm();
  1038. set_min(p,sqr_d_s,m_primitive,s,sqr_d,i,c);
  1039. };
  1040. if(inside_triangle)
  1041. {
  1042. // point-triangle squared distance
  1043. const Scalar sqr_d_j = d_j*d_j;
  1044. //cout<<"point-triangle..."<<endl;
  1045. set_min(p,sqr_d_j,m_primitive,pp,sqr_d,i,c);
  1046. }else
  1047. {
  1048. if(ss >= 2)
  1049. {
  1050. // point-segment distance
  1051. // number of edges
  1052. size_t ne = ss==3?3:1;
  1053. for(size_t x = 0;x<ne;x++)
  1054. {
  1055. const size_t e1 = Ele(m_primitive,(x+1)%ss);
  1056. const size_t e2 = Ele(m_primitive,(x+2)%ss);
  1057. const RowVectorDIMS & s = V.row(e1);
  1058. const RowVectorDIMS & d = V.row(e2);
  1059. // Degenerate edge
  1060. if(e1 == e2 || (s-d).squaredNorm()==0)
  1061. {
  1062. // only consider once
  1063. if(e1 < e2)
  1064. {
  1065. point_point_squared_distance(s);
  1066. }
  1067. continue;
  1068. }
  1069. Matrix<Scalar,1,1> sqr_d_j_x(1,1);
  1070. Matrix<Scalar,1,1> t(1,1);
  1071. project_to_line_segment(p,s,d,t,sqr_d_j_x);
  1072. const RowVectorDIMS q = s+t(0)*(d-s);
  1073. set_min(p,sqr_d_j_x(0),m_primitive,q,sqr_d,i,c);
  1074. }
  1075. }else
  1076. {
  1077. // So then Ele is just a list of points...
  1078. assert(ss == 1);
  1079. const RowVectorDIMS & s = V.row(Ele(m_primitive,0));
  1080. point_point_squared_distance(s);
  1081. }
  1082. }
  1083. }
  1084. template <typename DerivedV, int DIM>
  1085. inline void igl::AABB<DerivedV,DIM>::set_min(
  1086. const RowVectorDIMS &
  1087. #ifndef NDEBUG
  1088. p
  1089. #endif
  1090. ,
  1091. const Scalar sqr_d_candidate,
  1092. const int i_candidate,
  1093. const RowVectorDIMS & c_candidate,
  1094. Scalar & sqr_d,
  1095. int & i,
  1096. RowVectorDIMS & c) const
  1097. {
  1098. #ifndef NDEBUG
  1099. //std::cout<<matlab_format(c_candidate,"c_candidate")<<std::endl;
  1100. const Scalar pc_norm = (p-c_candidate).squaredNorm();
  1101. const Scalar diff = fabs(sqr_d_candidate - pc_norm);
  1102. assert(diff<=1e-10 && "distance should match norm of difference");
  1103. #endif
  1104. if(sqr_d_candidate < sqr_d)
  1105. {
  1106. i = i_candidate;
  1107. c = c_candidate;
  1108. sqr_d = sqr_d_candidate;
  1109. }
  1110. }
  1111. template <typename DerivedV, int DIM>
  1112. inline void
  1113. igl::AABB<DerivedV,DIM>::barycentric_coordinates(
  1114. const RowVectorDIMS & p,
  1115. const RowVectorDIMS & a,
  1116. const RowVectorDIMS & b,
  1117. const RowVectorDIMS & c,
  1118. Eigen::Matrix<Scalar,1,3> & bary)
  1119. {
  1120. // http://gamedev.stackexchange.com/a/23745
  1121. const RowVectorDIMS v0 = b - a;
  1122. const RowVectorDIMS v1 = c - a;
  1123. const RowVectorDIMS v2 = p - a;
  1124. Scalar d00 = v0.dot(v0);
  1125. Scalar d01 = v0.dot(v1);
  1126. Scalar d11 = v1.dot(v1);
  1127. Scalar d20 = v2.dot(v0);
  1128. Scalar d21 = v2.dot(v1);
  1129. Scalar denom = d00 * d11 - d01 * d01;
  1130. bary(1) = (d11 * d20 - d01 * d21) / denom;
  1131. bary(2) = (d00 * d21 - d01 * d20) / denom;
  1132. bary(0) = 1.0f - bary(1) - bary(2);
  1133. }
  1134. template <typename DerivedV, int DIM>
  1135. inline bool
  1136. igl::AABB<DerivedV,DIM>::intersect_ray(
  1137. const Eigen::PlainObjectBase<DerivedV> & V,
  1138. const Eigen::MatrixXi & Ele,
  1139. const RowVectorDIMS & origin,
  1140. const RowVectorDIMS & dir,
  1141. std::vector<igl::Hit> & hits) const
  1142. {
  1143. hits.clear();
  1144. const Scalar t0 = 0;
  1145. const Scalar t1 = std::numeric_limits<Scalar>::infinity();
  1146. if(!ray_box_intersect(origin,dir,m_box,t0,t1))
  1147. {
  1148. return false;
  1149. }
  1150. if(this->is_leaf())
  1151. {
  1152. // Actually process elements
  1153. assert((Ele.size() == 0 || Ele.cols() == 3) && "Elements should be triangles");
  1154. // Cheesecake way of hitting element
  1155. return ray_mesh_intersect(origin,dir,V,Ele.row(m_primitive).eval(),hits);
  1156. }
  1157. std::vector<igl::Hit> left_hits;
  1158. std::vector<igl::Hit> right_hits;
  1159. const bool left_ret = m_left->intersect_ray(V,Ele,origin,dir,left_hits);
  1160. const bool right_ret = m_right->intersect_ray(V,Ele,origin,dir,right_hits);
  1161. hits.insert(hits.end(),left_hits.begin(),left_hits.end());
  1162. hits.insert(hits.end(),right_hits.begin(),right_hits.end());
  1163. return left_ret || right_ret;
  1164. }
  1165. template <typename DerivedV, int DIM>
  1166. inline bool
  1167. igl::AABB<DerivedV,DIM>::intersect_ray(
  1168. const Eigen::PlainObjectBase<DerivedV> & V,
  1169. const Eigen::MatrixXi & Ele,
  1170. const RowVectorDIMS & origin,
  1171. const RowVectorDIMS & dir,
  1172. igl::Hit & hit) const
  1173. {
  1174. return intersect_ray(
  1175. V,Ele,origin,dir,std::numeric_limits<Scalar>::infinity(),hit);
  1176. }
  1177. template <typename DerivedV, int DIM>
  1178. inline bool
  1179. igl::AABB<DerivedV,DIM>::intersect_ray(
  1180. const Eigen::PlainObjectBase<DerivedV> & V,
  1181. const Eigen::MatrixXi & Ele,
  1182. const RowVectorDIMS & origin,
  1183. const RowVectorDIMS & dir,
  1184. const Scalar _min_t,
  1185. igl::Hit & hit) const
  1186. {
  1187. //// Naive, slow
  1188. //std::vector<igl::Hit> hits;
  1189. //intersect_ray(V,Ele,origin,dir,hits);
  1190. //if(hits.size() > 0)
  1191. //{
  1192. // hit = hits.front();
  1193. // return true;
  1194. //}else
  1195. //{
  1196. // return false;
  1197. //}
  1198. Scalar min_t = _min_t;
  1199. const Scalar t0 = 0;
  1200. if(!ray_box_intersect(origin,dir,m_box,t0,min_t))
  1201. {
  1202. return false;
  1203. }
  1204. if(this->is_leaf())
  1205. {
  1206. // Actually process elements
  1207. assert((Ele.size() == 0 || Ele.cols() == 3) && "Elements should be triangles");
  1208. // Cheesecake way of hitting element
  1209. return ray_mesh_intersect(origin,dir,V,Ele.row(m_primitive).eval(),hit);
  1210. }
  1211. igl::Hit left_hit;
  1212. igl::Hit right_hit;
  1213. bool left_ret = m_left->intersect_ray(V,Ele,origin,dir,min_t,left_hit);
  1214. if(left_ret && left_hit.t<min_t)
  1215. {
  1216. min_t = left_hit.t;
  1217. hit = left_hit;
  1218. left_ret = true;
  1219. }else
  1220. {
  1221. left_ret = false;
  1222. }
  1223. bool right_ret = m_right->intersect_ray(V,Ele,origin,dir,min_t,right_hit);
  1224. if(right_ret && right_hit.t<min_t)
  1225. {
  1226. min_t = right_hit.t;
  1227. hit = right_hit;
  1228. right_ret = true;
  1229. }else
  1230. {
  1231. right_ret = false;
  1232. }
  1233. return left_ret || right_ret;
  1234. }
  1235. #endif