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/Geometry>
  18. #include <Eigen/Core>
  19. #include <vector>
  20. #include <embree2/rtcore.h>
  21. #include <embree2/rtcore_ray.h>
  22. #include <iostream>
  23. #include "Hit.h"
  24. namespace igl
  25. {
  26. class EmbreeIntersector
  27. {
  28. public:
  29. // Initialize embree engine. This will be called on instance `init()`
  30. // calls. If already inited then this function does nothing: it is harmless
  31. // to call more than once.
  32. static inline void global_init();
  33. private:
  34. // Deinitialize the embree engine.
  35. static inline void global_deinit();
  36. public:
  37. typedef Eigen::Matrix<float,Eigen::Dynamic,3> PointMatrixType;
  38. typedef Eigen::Matrix<int,Eigen::Dynamic,3> FaceMatrixType;
  39. public:
  40. inline EmbreeIntersector();
  41. private:
  42. // Copying and assignment are not allowed.
  43. inline EmbreeIntersector(const EmbreeIntersector & that);
  44. inline EmbreeIntersector & operator=(const EmbreeIntersector &);
  45. public:
  46. virtual inline ~EmbreeIntersector();
  47. // Initialize with a given mesh.
  48. //
  49. // Inputs:
  50. // V #V by 3 list of vertex positions
  51. // F #F by 3 list of Oriented triangles
  52. // Side effects:
  53. // The first time this is ever called the embree engine is initialized.
  54. inline void init(
  55. const PointMatrixType& V,
  56. const FaceMatrixType& F);
  57. // Initialize with a given mesh.
  58. //
  59. // Inputs:
  60. // V vector of #V by 3 list of vertex positions for each geometry
  61. // F vector of #F by 3 list of Oriented triangles for each geometry
  62. // masks a 32 bit mask to identify active geometries.
  63. // Side effects:
  64. // The first time this is ever called the embree engine is initialized.
  65. inline void init(
  66. const std::vector<const PointMatrixType*>& V,
  67. const std::vector<const FaceMatrixType*>& F,
  68. const std::vector<int>& masks);
  69. // Deinitialize embree datasctructures for current mesh. Also called on
  70. // destruction: no need to call if you just want to init() once and
  71. // destroy.
  72. inline void deinit();
  73. // Given a ray find the first hit
  74. //
  75. // Inputs:
  76. // origin 3d origin point of ray
  77. // direction 3d (not necessarily normalized) direction vector of ray
  78. // tnear start of ray segment
  79. // tfar end of ray segment
  80. // masks a 32 bit mask to identify active geometries.
  81. // Output:
  82. // hit information about hit
  83. // Returns true if and only if there was a hit
  84. inline bool intersectRay(
  85. const Eigen::RowVector3f& origin,
  86. const Eigen::RowVector3f& direction,
  87. Hit& hit,
  88. float tnear = 0,
  89. float tfar = -1,
  90. int mask = 0xFFFFFFFF) const;
  91. // Given a ray find the first hit
  92. // This is a conservative hit test where multiple rays within a small radius
  93. // will be tested and only the closesest hit is returned.
  94. //
  95. // Inputs:
  96. // origin 3d origin point of ray
  97. // direction 3d (not necessarily normalized) direction vector of ray
  98. // tnear start of ray segment
  99. // tfar end of ray segment
  100. // masks a 32 bit mask to identify active geometries.
  101. // geoId id of geometry mask (default -1 if no: no masking)
  102. // closestHit true for gets closest hit, false for furthest hit
  103. // Output:
  104. // hit information about hit
  105. // Returns true if and only if there was a hit
  106. inline bool intersectBeam(
  107. const Eigen::RowVector3f& origin,
  108. const Eigen::RowVector3f& direction,
  109. Hit& hit,
  110. float tnear = 0,
  111. float tfar = -1,
  112. int mask = 0xFFFFFFFF,
  113. int geoId = -1,
  114. bool closestHit = true) const;
  115. // Given a ray find all hits in order
  116. //
  117. // Inputs:
  118. // origin 3d origin point of ray
  119. // direction 3d (not necessarily normalized) direction vector of ray
  120. // tnear start of ray segment
  121. // tfar end of ray segment
  122. // masks a 32 bit mask to identify active geometries.
  123. // Output:
  124. // hit information about hit
  125. // num_rays number of rays shot (at least one)
  126. // Returns true if and only if there was a hit
  127. inline bool intersectRay(
  128. const Eigen::RowVector3f& origin,
  129. const Eigen::RowVector3f& direction,
  130. std::vector<Hit > &hits,
  131. int& num_rays,
  132. float tnear = 0,
  133. float tfar = std::numeric_limits<float>::infinity(),
  134. int mask = 0xFFFFFFFF) const;
  135. // Given a ray find the first hit
  136. //
  137. // Inputs:
  138. // a 3d first end point of segment
  139. // ab 3d vector from a to other endpoint b
  140. // Output:
  141. // hit information about hit
  142. // Returns true if and only if there was a hit
  143. inline bool intersectSegment(
  144. const Eigen::RowVector3f& a,
  145. const Eigen::RowVector3f& ab,
  146. Hit &hit,
  147. int mask = 0xFFFFFFFF) const;
  148. private:
  149. struct Vertex {float x,y,z,a;};
  150. struct Triangle {int v0, v1, v2;};
  151. RTCScene scene;
  152. unsigned geomID;
  153. Vertex* vertices;
  154. Triangle* triangles;
  155. bool initialized;
  156. inline void createRay(
  157. RTCRay& ray,
  158. const Eigen::RowVector3f& origin,
  159. const Eigen::RowVector3f& direction,
  160. float tnear,
  161. float tfar,
  162. int mask) const;
  163. };
  164. }
  165. // Implementation
  166. #include <igl/EPS.h>
  167. // This unfortunately cannot be a static field of EmbreeIntersector because it
  168. // would depend on the template and then we might end up with initializing
  169. // embree twice. If only there was a way to ask embree if it's already
  170. // initialized...
  171. namespace igl
  172. {
  173. // Keeps track of whether the **Global** Embree intersector has been
  174. // initialized. This should never been done at the global scope.
  175. static bool EmbreeIntersector_inited = false;
  176. }
  177. inline void igl::EmbreeIntersector::global_init()
  178. {
  179. if(!EmbreeIntersector_inited)
  180. {
  181. rtcInit();
  182. if(rtcGetError() != RTC_NO_ERROR)
  183. std::cerr << "Embree: An error occured while initialiting embree core!" << std::endl;
  184. #ifdef IGL_VERBOSE
  185. else
  186. std::cerr << "Embree: core initialized." << std::endl;
  187. #endif
  188. EmbreeIntersector_inited = true;
  189. }
  190. }
  191. inline void igl::EmbreeIntersector::global_deinit()
  192. {
  193. EmbreeIntersector_inited = false;
  194. rtcExit();
  195. }
  196. inline igl::EmbreeIntersector::EmbreeIntersector()
  197. :
  198. //scene(NULL),
  199. geomID(0),
  200. triangles(NULL),
  201. vertices(NULL),
  202. initialized(false)
  203. {
  204. }
  205. inline igl::EmbreeIntersector::EmbreeIntersector(
  206. const EmbreeIntersector &)
  207. :// To make -Weffc++ happy
  208. //scene(NULL),
  209. geomID(0),
  210. triangles(NULL),
  211. vertices(NULL),
  212. initialized(false)
  213. {
  214. assert(false && "Embree: Copying EmbreeIntersector is not allowed");
  215. }
  216. inline igl::EmbreeIntersector & igl::EmbreeIntersector::operator=(
  217. const EmbreeIntersector &)
  218. {
  219. assert(false && "Embree: Assigning an EmbreeIntersector is not allowed");
  220. return *this;
  221. }
  222. inline void igl::EmbreeIntersector::init(
  223. const PointMatrixType& V,
  224. const FaceMatrixType& F)
  225. {
  226. std::vector<const PointMatrixType*> Vtemp;
  227. std::vector<const FaceMatrixType*> Ftemp;
  228. std::vector<int> masks;
  229. Vtemp.push_back(&V);
  230. Ftemp.push_back(&F);
  231. masks.push_back(0xFFFFFFFF);
  232. init(Vtemp,Ftemp,masks);
  233. }
  234. inline void igl::EmbreeIntersector::init(
  235. const std::vector<const PointMatrixType*>& V,
  236. const std::vector<const FaceMatrixType*>& F,
  237. const std::vector<int>& masks)
  238. {
  239. if(initialized)
  240. deinit();
  241. using namespace std;
  242. global_init();
  243. if(V.size() == 0 || F.size() == 0)
  244. {
  245. std::cerr << "Embree: No geometry specified!";
  246. return;
  247. }
  248. // create a scene
  249. scene = rtcNewScene(RTC_SCENE_ROBUST | RTC_SCENE_HIGH_QUALITY,RTC_INTERSECT1);
  250. for(int g=0;g<V.size();g++)
  251. {
  252. // create triangle mesh geometry in that scene
  253. geomID = rtcNewTriangleMesh(scene,RTC_GEOMETRY_STATIC,F[g]->rows(),V[g]->rows(),1);
  254. // fill vertex buffer
  255. vertices = (Vertex*)rtcMapBuffer(scene,geomID,RTC_VERTEX_BUFFER);
  256. for(int i=0;i<(int)V[g]->rows();i++)
  257. {
  258. vertices[i].x = (float)V[g]->coeff(i,0);
  259. vertices[i].y = (float)V[g]->coeff(i,1);
  260. vertices[i].z = (float)V[g]->coeff(i,2);
  261. }
  262. rtcUnmapBuffer(scene,geomID,RTC_VERTEX_BUFFER);
  263. // fill triangle buffer
  264. triangles = (Triangle*) rtcMapBuffer(scene,geomID,RTC_INDEX_BUFFER);
  265. for(int i=0;i<(int)F[g]->rows();i++)
  266. {
  267. triangles[i].v0 = (int)F[g]->coeff(i,0);
  268. triangles[i].v1 = (int)F[g]->coeff(i,1);
  269. triangles[i].v2 = (int)F[g]->coeff(i,2);
  270. }
  271. rtcUnmapBuffer(scene,geomID,RTC_INDEX_BUFFER);
  272. rtcSetMask(scene,geomID,masks[g]);
  273. }
  274. rtcCommit(scene);
  275. if(rtcGetError() != RTC_NO_ERROR)
  276. std::cerr << "Embree: An error occured while initializing the provided geometry!" << endl;
  277. #ifdef IGL_VERBOSE
  278. else
  279. std::cerr << "Embree: geometry added." << endl;
  280. #endif
  281. initialized = true;
  282. }
  283. igl::EmbreeIntersector
  284. ::~EmbreeIntersector()
  285. {
  286. if(initialized)
  287. deinit();
  288. }
  289. void igl::EmbreeIntersector::deinit()
  290. {
  291. rtcDeleteScene(scene);
  292. if(rtcGetError() != RTC_NO_ERROR)
  293. std::cerr << "Embree: An error occured while resetting!" << std::endl;
  294. #ifdef IGL_VERBOSE
  295. else
  296. std::cerr << "Embree: geometry removed." << std::endl;
  297. #endif
  298. }
  299. inline bool igl::EmbreeIntersector::intersectRay(
  300. const Eigen::RowVector3f& origin,
  301. const Eigen::RowVector3f& direction,
  302. Hit& hit,
  303. float tnear,
  304. float tfar,
  305. int mask) const
  306. {
  307. RTCRay ray;
  308. createRay(ray, origin,direction,tnear,std::numeric_limits<float>::infinity(),mask);
  309. // shot ray
  310. rtcIntersect(scene,ray);
  311. #ifdef IGL_VERBOSE
  312. if(rtcGetError() != RTC_NO_ERROR)
  313. std::cerr << "Embree: An error occured while resetting!" << std::endl;
  314. #endif
  315. if(ray.geomID != RTC_INVALID_GEOMETRY_ID)
  316. {
  317. hit.id = ray.primID;
  318. hit.gid = ray.geomID;
  319. hit.u = ray.u;
  320. hit.v = ray.v;
  321. hit.t = ray.tfar;
  322. return true;
  323. }
  324. return false;
  325. }
  326. inline bool igl::EmbreeIntersector::intersectBeam(
  327. const Eigen::RowVector3f& origin,
  328. const Eigen::RowVector3f& direction,
  329. Hit& hit,
  330. float tnear,
  331. float tfar,
  332. int mask,
  333. int geoId,
  334. bool closestHit) 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. if(hasHit = (intersectRay(origin,direction,hit,tnear,tfar,mask) && (hit.gid == geoId || geoId == -1)))
  343. bestHit = hit;
  344. // sample points around actual ray (conservative hitcheck)
  345. float eps= 1e-5;
  346. int density = 4;
  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/density,direction).toRotationMatrix();
  350. for(int r=0;r<density;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