EmbreeIntersector.h 15 KB

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