EmbreeIntersector.h 16 KB

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