EmbreeIntersector.h 16 KB

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