EmbreeIntersector.h 15 KB

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