ray_mesh_intersect.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "ray_mesh_intersect.h"
  2. extern "C"
  3. {
  4. #include "raytri.c"
  5. }
  6. template <
  7. typename Derivedsource,
  8. typename Deriveddir,
  9. typename DerivedV,
  10. typename DerivedF>
  11. IGL_INLINE bool igl::ray_mesh_intersect(
  12. const Eigen::PlainObjectBase<Derivedsource> & s,
  13. const Eigen::PlainObjectBase<Deriveddir> & dir,
  14. const Eigen::PlainObjectBase<DerivedV> & V,
  15. const Eigen::PlainObjectBase<DerivedF> & F,
  16. std::vector<igl::Hit> & hits)
  17. {
  18. using namespace Eigen;
  19. using namespace igl;
  20. using namespace std;
  21. // Should be but can't be const
  22. Vector3d s_d = s.template cast<double>();
  23. Vector3d dir_d = dir.template cast<double>();
  24. hits.clear();
  25. // loop over all triangles
  26. for(int f = 0;f<F.rows();f++)
  27. {
  28. // Should be but can't be const
  29. RowVector3d v0 = V.row(F(f,0)).template cast<double>();
  30. RowVector3d v1 = V.row(F(f,1)).template cast<double>();
  31. RowVector3d v2 = V.row(F(f,2)).template cast<double>();
  32. // shoot ray, record hit
  33. double t,u,v;
  34. if(intersect_triangle1(
  35. s_d.data(), dir_d.data(), v0.data(), v1.data(), v2.data(), &t, &u, &v) &&
  36. t>0)
  37. {
  38. hits.push_back({(int)f,(int)-1,(float)u,(float)v,(float)t});
  39. }
  40. }
  41. // Sort hits based on distance
  42. std::sort(
  43. hits.begin(),
  44. hits.end(),
  45. [](const Hit & a, const Hit & b)->bool{ return a.t < b.t;});
  46. return hits.size() > 0;
  47. }
  48. template <
  49. typename Derivedsource,
  50. typename Deriveddir,
  51. typename DerivedV,
  52. typename DerivedF>
  53. IGL_INLINE bool igl::ray_mesh_intersect(
  54. const Eigen::PlainObjectBase<Derivedsource> & source,
  55. const Eigen::PlainObjectBase<Deriveddir> & dir,
  56. const Eigen::PlainObjectBase<DerivedV> & V,
  57. const Eigen::PlainObjectBase<DerivedF> & F,
  58. igl::Hit & hit)
  59. {
  60. std::vector<igl::Hit> hits;
  61. ray_mesh_intersect(source,dir,V,F,hits);
  62. if(hits.size() > 0)
  63. {
  64. hit = hits.front();
  65. return true;
  66. }else
  67. {
  68. return false;
  69. }
  70. }