ray_mesh_intersect.cpp 1.8 KB

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