EmbreeIntersector.h 15 KB

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