EmbreeIntersector.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
  4. // 2014 Christian Schüller <schuellchr@gmail.com>
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla Public License
  7. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  8. // obtain one at http://mozilla.org/MPL/2.0/.
  9. // igl function interface for Embree2.2
  10. //
  11. // Necessary changes to switch from previous Embree versions:
  12. // * Use igl:Hit instead of embree:Hit (where id0 -> id)
  13. // * For Embree2.2
  14. // * Uncomment #define __USE_RAY_MASK__ in platform.h to enable masking
  15. //
  16. // TODO: Check for NANs in the input
  17. #ifndef IGL_EMBREE_INTERSECTOR_H
  18. #define IGL_EMBREE_INTERSECTOR_H
  19. #include <Eigen/Geometry>
  20. #include <Eigen/Core>
  21. #include <Eigen/Geometry>
  22. #include <vector>
  23. #include <embree2/rtcore.h>
  24. #include <embree2/rtcore_ray.h>
  25. #include <iostream>
  26. #include "Hit.h"
  27. #include <iostream>
  28. namespace igl
  29. {
  30. class EmbreeIntersector
  31. {
  32. public:
  33. // Initialize embree engine. This will be called on instance `init()`
  34. // calls. If already inited then this function does nothing: it is harmless
  35. // to call more than once.
  36. static inline void global_init();
  37. private:
  38. // Deinitialize the embree engine.
  39. static inline void global_deinit();
  40. public:
  41. typedef Eigen::Matrix<float,Eigen::Dynamic,3> PointMatrixType;
  42. typedef Eigen::Matrix<int,Eigen::Dynamic,3> FaceMatrixType;
  43. public:
  44. inline EmbreeIntersector();
  45. private:
  46. // Copying and assignment are not allowed.
  47. inline EmbreeIntersector(const EmbreeIntersector & that);
  48. inline EmbreeIntersector & operator=(const EmbreeIntersector &);
  49. public:
  50. virtual inline ~EmbreeIntersector();
  51. // Initialize with a given mesh.
  52. //
  53. // Inputs:
  54. // V #V by 3 list of vertex positions
  55. // F #F by 3 list of Oriented triangles
  56. // Side effects:
  57. // The first time this is ever called the embree engine is initialized.
  58. inline void init(
  59. const PointMatrixType& V,
  60. const FaceMatrixType& F);
  61. // Initialize with a given mesh.
  62. //
  63. // Inputs:
  64. // V vector of #V by 3 list of vertex positions for each geometry
  65. // F vector of #F by 3 list of Oriented triangles for each geometry
  66. // masks a 32 bit mask to identify active geometries.
  67. // Side effects:
  68. // The first time this is ever called the embree engine is initialized.
  69. inline void init(
  70. const std::vector<const PointMatrixType*>& V,
  71. const std::vector<const FaceMatrixType*>& F,
  72. const std::vector<int>& masks);
  73. // Deinitialize embree datasctructures for current mesh. Also called on
  74. // destruction: no need to call if you just want to init() once and
  75. // destroy.
  76. inline void deinit();
  77. // Given a ray find the first hit
  78. //
  79. // Inputs:
  80. // origin 3d origin point of ray
  81. // direction 3d (not necessarily normalized) direction vector of ray
  82. // tnear start of ray segment
  83. // tfar end of ray segment
  84. // masks a 32 bit mask to identify active geometries.
  85. // Output:
  86. // hit information about hit
  87. // Returns true if and only if there was a hit
  88. inline bool intersectRay(
  89. const Eigen::RowVector3f& origin,
  90. const Eigen::RowVector3f& direction,
  91. Hit& hit,
  92. float tnear = 0,
  93. float tfar = -1,
  94. int mask = 0xFFFFFFFF) const;
  95. // Given a ray find the first hit
  96. // This is a conservative hit test where multiple rays within a small radius
  97. // will be tested and only the closesest hit is returned.
  98. //
  99. // Inputs:
  100. // origin 3d origin point of ray
  101. // direction 3d (not necessarily normalized) direction vector of ray
  102. // tnear start of ray segment
  103. // tfar end of ray segment
  104. // masks a 32 bit mask to identify active geometries.
  105. // geoId id of geometry mask (default -1 if no: no masking)
  106. // closestHit true for gets closest hit, false for furthest hit
  107. // Output:
  108. // hit information about hit
  109. // Returns true if and only if there was a hit
  110. inline bool intersectBeam(
  111. const Eigen::RowVector3f& origin,
  112. const Eigen::RowVector3f& direction,
  113. Hit& hit,
  114. float tnear = 0,
  115. float tfar = -1,
  116. int mask = 0xFFFFFFFF,
  117. int geoId = -1,
  118. bool closestHit = true) const;
  119. // Given a ray find all hits in order
  120. //
  121. // Inputs:
  122. // origin 3d origin point of ray
  123. // direction 3d (not necessarily normalized) direction vector of ray
  124. // tnear start of ray segment
  125. // tfar end of ray segment
  126. // masks a 32 bit mask to identify active geometries.
  127. // Output:
  128. // hit information about hit
  129. // num_rays number of rays shot (at least one)
  130. // Returns true if and only if there was a hit
  131. inline bool intersectRay(
  132. const Eigen::RowVector3f& origin,
  133. const Eigen::RowVector3f& direction,
  134. std::vector<Hit > &hits,
  135. int& num_rays,
  136. float tnear = 0,
  137. float tfar = std::numeric_limits<float>::infinity(),
  138. int mask = 0xFFFFFFFF) const;
  139. // Given a ray find the first hit
  140. //
  141. // Inputs:
  142. // a 3d first end point of segment
  143. // ab 3d vector from a to other endpoint b
  144. // Output:
  145. // hit information about hit
  146. // Returns true if and only if there was a hit
  147. inline bool intersectSegment(
  148. const Eigen::RowVector3f& a,
  149. const Eigen::RowVector3f& ab,
  150. Hit &hit,
  151. int mask = 0xFFFFFFFF) const;
  152. private:
  153. struct Vertex {float x,y,z,a;};
  154. struct Triangle {int v0, v1, v2;};
  155. RTCScene scene;
  156. unsigned geomID;
  157. Vertex* vertices;
  158. Triangle* triangles;
  159. bool initialized;
  160. inline void createRay(
  161. RTCRay& ray,
  162. const Eigen::RowVector3f& origin,
  163. const Eigen::RowVector3f& direction,
  164. float tnear,
  165. float tfar,
  166. int mask) const;
  167. };
  168. }
  169. // Implementation
  170. #include <igl/EPS.h>
  171. // This unfortunately cannot be a static field of EmbreeIntersector because it
  172. // would depend on the template and then we might end up with initializing
  173. // embree twice. If only there was a way to ask embree if it's already
  174. // initialized...
  175. namespace igl
  176. {
  177. // Keeps track of whether the **Global** Embree intersector has been
  178. // initialized. This should never been done at the global scope.
  179. static bool EmbreeIntersector_inited = false;
  180. }
  181. inline void igl::EmbreeIntersector::global_init()
  182. {
  183. if(!EmbreeIntersector_inited)
  184. {
  185. rtcInit();
  186. if(rtcGetError() != RTC_NO_ERROR)
  187. std::cerr << "Embree: An error occured while initialiting embree core!" << std::endl;
  188. #ifdef IGL_VERBOSE
  189. else
  190. std::cerr << "Embree: core initialized." << std::endl;
  191. #endif
  192. EmbreeIntersector_inited = true;
  193. }
  194. }
  195. inline void igl::EmbreeIntersector::global_deinit()
  196. {
  197. EmbreeIntersector_inited = false;
  198. rtcExit();
  199. }
  200. inline igl::EmbreeIntersector::EmbreeIntersector()
  201. :
  202. //scene(NULL),
  203. geomID(0),
  204. triangles(NULL),
  205. vertices(NULL),
  206. initialized(false)
  207. {
  208. }
  209. inline igl::EmbreeIntersector::EmbreeIntersector(
  210. const EmbreeIntersector &)
  211. :// To make -Weffc++ happy
  212. //scene(NULL),
  213. geomID(0),
  214. triangles(NULL),
  215. vertices(NULL),
  216. initialized(false)
  217. {
  218. assert(false && "Embree: Copying EmbreeIntersector is not allowed");
  219. }
  220. inline igl::EmbreeIntersector & igl::EmbreeIntersector::operator=(
  221. const EmbreeIntersector &)
  222. {
  223. assert(false && "Embree: Assigning an EmbreeIntersector is not allowed");
  224. return *this;
  225. }
  226. inline void igl::EmbreeIntersector::init(
  227. const PointMatrixType& V,
  228. const FaceMatrixType& F)
  229. {
  230. std::vector<const PointMatrixType*> Vtemp;
  231. std::vector<const FaceMatrixType*> Ftemp;
  232. std::vector<int> masks;
  233. Vtemp.push_back(&V);
  234. Ftemp.push_back(&F);
  235. masks.push_back(0xFFFFFFFF);
  236. init(Vtemp,Ftemp,masks);
  237. }
  238. inline void igl::EmbreeIntersector::init(
  239. const std::vector<const PointMatrixType*>& V,
  240. const std::vector<const FaceMatrixType*>& F,
  241. const std::vector<int>& masks)
  242. {
  243. if(initialized)
  244. deinit();
  245. using namespace std;
  246. global_init();
  247. if(V.size() == 0 || F.size() == 0)
  248. {
  249. std::cerr << "Embree: No geometry specified!";
  250. return;
  251. }
  252. // create a scene
  253. scene = rtcNewScene(RTC_SCENE_ROBUST | RTC_SCENE_HIGH_QUALITY,RTC_INTERSECT1);
  254. for(int g=0;g<V.size();g++)
  255. {
  256. // create triangle mesh geometry in that scene
  257. geomID = rtcNewTriangleMesh(scene,RTC_GEOMETRY_STATIC,F[g]->rows(),V[g]->rows(),1);
  258. // fill vertex buffer
  259. vertices = (Vertex*)rtcMapBuffer(scene,geomID,RTC_VERTEX_BUFFER);
  260. for(int i=0;i<(int)V[g]->rows();i++)
  261. {
  262. vertices[i].x = (float)V[g]->coeff(i,0);
  263. vertices[i].y = (float)V[g]->coeff(i,1);
  264. vertices[i].z = (float)V[g]->coeff(i,2);
  265. }
  266. rtcUnmapBuffer(scene,geomID,RTC_VERTEX_BUFFER);
  267. // fill triangle buffer
  268. triangles = (Triangle*) rtcMapBuffer(scene,geomID,RTC_INDEX_BUFFER);
  269. for(int i=0;i<(int)F[g]->rows();i++)
  270. {
  271. triangles[i].v0 = (int)F[g]->coeff(i,0);
  272. triangles[i].v1 = (int)F[g]->coeff(i,1);
  273. triangles[i].v2 = (int)F[g]->coeff(i,2);
  274. }
  275. rtcUnmapBuffer(scene,geomID,RTC_INDEX_BUFFER);
  276. rtcSetMask(scene,geomID,masks[g]);
  277. }
  278. rtcCommit(scene);
  279. if(rtcGetError() != RTC_NO_ERROR)
  280. std::cerr << "Embree: An error occured while initializing the provided geometry!" << endl;
  281. #ifdef IGL_VERBOSE
  282. else
  283. std::cerr << "Embree: geometry added." << endl;
  284. #endif
  285. initialized = true;
  286. }
  287. igl::EmbreeIntersector
  288. ::~EmbreeIntersector()
  289. {
  290. if(initialized)
  291. deinit();
  292. }
  293. void igl::EmbreeIntersector::deinit()
  294. {
  295. rtcDeleteScene(scene);
  296. if(rtcGetError() != RTC_NO_ERROR)
  297. std::cerr << "Embree: An error occured while resetting!" << std::endl;
  298. #ifdef IGL_VERBOSE
  299. else
  300. std::cerr << "Embree: geometry removed." << std::endl;
  301. #endif
  302. }
  303. inline bool igl::EmbreeIntersector::intersectRay(
  304. const Eigen::RowVector3f& origin,
  305. const Eigen::RowVector3f& direction,
  306. Hit& hit,
  307. float tnear,
  308. float tfar,
  309. int mask) const
  310. {
  311. RTCRay ray;
  312. createRay(ray, origin,direction,tnear,std::numeric_limits<float>::infinity(),mask);
  313. // shot ray
  314. rtcIntersect(scene,ray);
  315. #ifdef IGL_VERBOSE
  316. if(rtcGetError() != RTC_NO_ERROR)
  317. std::cerr << "Embree: An error occured while resetting!" << std::endl;
  318. #endif
  319. if(ray.geomID != RTC_INVALID_GEOMETRY_ID)
  320. {
  321. hit.id = ray.primID;
  322. hit.gid = ray.geomID;
  323. hit.u = ray.u;
  324. hit.v = ray.v;
  325. hit.t = ray.tfar;
  326. return true;
  327. }
  328. return false;
  329. }
  330. inline bool igl::EmbreeIntersector::intersectBeam(
  331. const Eigen::RowVector3f& origin,
  332. const Eigen::RowVector3f& direction,
  333. Hit& hit,
  334. float tnear,
  335. float tfar,
  336. int mask,
  337. int geoId,
  338. bool closestHit) const
  339. {
  340. bool hasHit = false;
  341. Hit bestHit;
  342. if(closestHit)
  343. bestHit.t = std::numeric_limits<float>::max();
  344. else
  345. bestHit.t = 0;
  346. hasHit = (intersectRay(origin,direction,hit,tnear,tfar,mask) && (hit.gid == geoId || geoId == -1));
  347. if(hasHit)
  348. bestHit = hit;
  349. // sample points around actual ray (conservative hitcheck)
  350. float eps= 1e-5;
  351. int density = 4;
  352. Eigen::RowVector3f up; up.setRandom(1,3);
  353. while (fabs(direction.cross(up).norm()) < 1e-5)
  354. up.setRandom(1,3);
  355. Eigen::RowVector3f offset = direction.cross(up).normalized();
  356. Eigen::Matrix3f rot = Eigen::AngleAxis<float>(2*3.14159265358979/density,direction).toRotationMatrix();
  357. for(int r=0;r<density;r++)
  358. {
  359. if(intersectRay(origin+offset*eps,direction,hit,tnear,tfar,mask) && ((closestHit && (hit.t < bestHit.t)) || (!closestHit && (hit.t > bestHit.t))) && (hit.gid == geoId || geoId == -1))
  360. {
  361. bestHit = hit;
  362. hasHit = true;
  363. }
  364. offset = rot*offset.transpose();
  365. }
  366. hit = bestHit;
  367. return hasHit;
  368. }
  369. inline bool
  370. igl::EmbreeIntersector
  371. ::intersectRay(
  372. const Eigen::RowVector3f& origin,
  373. const Eigen::RowVector3f& direction,
  374. std::vector<Hit > &hits,
  375. int& num_rays,
  376. float tnear,
  377. float tfar,
  378. int mask) const
  379. {
  380. using namespace std;
  381. num_rays = 0;
  382. hits.clear();
  383. int last_id0 = -1;
  384. double self_hits = 0;
  385. // This epsilon is directly correleated to the number of missed hits, smaller
  386. // means more accurate and slower
  387. //const double eps = DOUBLE_EPS;
  388. const double eps = FLOAT_EPS;
  389. double min_t = tnear;
  390. bool large_hits_warned = false;
  391. RTCRay ray;
  392. createRay(ray,origin,direction,tnear,std::numeric_limits<float>::infinity(),mask);
  393. while(true)
  394. {
  395. ray.tnear = min_t;
  396. ray.tfar = tfar;
  397. ray.geomID = RTC_INVALID_GEOMETRY_ID;
  398. ray.primID = RTC_INVALID_GEOMETRY_ID;
  399. ray.instID = RTC_INVALID_GEOMETRY_ID;
  400. num_rays++;
  401. rtcIntersect(scene,ray);
  402. if(ray.geomID != RTC_INVALID_GEOMETRY_ID)
  403. {
  404. // Hit self again, progressively advance
  405. if(ray.primID == last_id0 || ray.tfar <= min_t)
  406. {
  407. // push min_t a bit more
  408. //double t_push = pow(2.0,self_hits-4)*(hit.t<eps?eps:hit.t);
  409. double t_push = pow(2.0,self_hits)*eps;
  410. #ifdef IGL_VERBOSE
  411. std::cerr<<" t_push: "<<t_push<<endl;
  412. #endif
  413. //o = o+t_push*d;
  414. min_t += t_push;
  415. self_hits++;
  416. }
  417. else
  418. {
  419. Hit hit;
  420. hit.id = ray.primID;
  421. hit.gid = ray.geomID;
  422. hit.u = ray.u;
  423. hit.v = ray.v;
  424. hit.t = ray.tfar;
  425. hits.push_back(hit);
  426. #ifdef IGL_VERBOSE
  427. std::cerr<<" t: "<<hit.t<<endl;
  428. #endif
  429. // Instead of moving origin, just change min_t. That way calculations
  430. // all use exactly same origin values
  431. min_t = ray.tfar;
  432. // reset t_scale
  433. self_hits = 0;
  434. }
  435. last_id0 = ray.primID;
  436. }
  437. else
  438. break; // no more hits
  439. if(hits.size()>1000 && !large_hits_warned)
  440. {
  441. std::cout<<"Warning: Large number of hits..."<<endl;
  442. std::cout<<"[ ";
  443. for(vector<Hit>::iterator hit = hits.begin(); hit != hits.end();hit++)
  444. {
  445. std::cout<<(hit->id+1)<<" ";
  446. }
  447. std::cout.precision(std::numeric_limits< double >::digits10);
  448. std::cout<<"[ ";
  449. for(vector<Hit>::iterator hit = hits.begin(); hit != hits.end(); hit++)
  450. {
  451. std::cout<<(hit->t)<<endl;;
  452. }
  453. std::cout<<"]"<<endl;
  454. large_hits_warned = true;
  455. return hits.empty();
  456. }
  457. }
  458. return hits.empty();
  459. }
  460. inline bool
  461. igl::EmbreeIntersector
  462. ::intersectSegment(const Eigen::RowVector3f& a, const Eigen::RowVector3f& ab, Hit &hit, int mask) const
  463. {
  464. RTCRay ray;
  465. createRay(ray,a,ab,0,1.0,mask);
  466. rtcIntersect(scene,ray);
  467. if(ray.geomID != RTC_INVALID_GEOMETRY_ID)
  468. {
  469. hit.id = ray.primID;
  470. hit.gid = ray.geomID;
  471. hit.u = ray.u;
  472. hit.v = ray.v;
  473. hit.t = ray.tfar;
  474. return true;
  475. }
  476. return false;
  477. }
  478. inline void
  479. igl::EmbreeIntersector
  480. ::createRay(RTCRay& ray, const Eigen::RowVector3f& origin, const Eigen::RowVector3f& direction, float tnear, float tfar, int mask) const
  481. {
  482. ray.org[0] = origin[0];
  483. ray.org[1] = origin[1];
  484. ray.org[2] = origin[2];
  485. ray.dir[0] = direction[0];
  486. ray.dir[1] = direction[1];
  487. ray.dir[2] = direction[2];
  488. ray.tnear = tnear;
  489. ray.tfar = tfar;
  490. ray.geomID = RTC_INVALID_GEOMETRY_ID;
  491. ray.primID = RTC_INVALID_GEOMETRY_ID;
  492. ray.instID = RTC_INVALID_GEOMETRY_ID;
  493. ray.mask = mask;
  494. ray.time = 0.0f;
  495. }
  496. #endif //EMBREE_INTERSECTOR_H