line_mesh_intersection.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2013 Daniele Panozzo <daniele.panozzo@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #include "line_mesh_intersection.h"
  9. #include "../Hit.h"
  10. // For error printing
  11. #include <cstdio>
  12. #include <vector>
  13. #include <igl/per_vertex_normals.h>
  14. #include <igl/embree/EmbreeIntersector.h>
  15. template <typename ScalarMatrix, typename IndexMatrix>
  16. IGL_INLINE ScalarMatrix igl::embree::line_mesh_intersection
  17. (
  18. const ScalarMatrix & V_source,
  19. const ScalarMatrix & N_source,
  20. const ScalarMatrix & V_target,
  21. const IndexMatrix & F_target
  22. )
  23. {
  24. double tol = 0.00001;
  25. Eigen::MatrixXd ray_pos = V_source;
  26. Eigen::MatrixXd ray_dir = N_source;
  27. // Allocate matrix for the result
  28. ScalarMatrix R;
  29. R.resize(V_source.rows(), 3);
  30. // Initialize embree
  31. EmbreeIntersector embree;
  32. embree.init(V_target.template cast<float>(),F_target.template cast<int>());
  33. // Shoot rays from the source to the target
  34. for (unsigned i=0; i<ray_pos.rows(); ++i)
  35. {
  36. igl::Hit A,B;
  37. // Shoot ray A
  38. Eigen::RowVector3d A_pos = ray_pos.row(i) + tol * ray_dir.row(i);
  39. Eigen::RowVector3d A_dir = -ray_dir.row(i);
  40. bool A_hit = embree.intersectBeam(A_pos.cast<float>(), A_dir.cast<float>(),A);
  41. Eigen::RowVector3d B_pos = ray_pos.row(i) - tol * ray_dir.row(i);
  42. Eigen::RowVector3d B_dir = ray_dir.row(i);
  43. bool B_hit = embree.intersectBeam(B_pos.cast<float>(), B_dir.cast<float>(),B);
  44. int choice = -1;
  45. if (A_hit && ! B_hit)
  46. choice = 0;
  47. else if (!A_hit && B_hit)
  48. choice = 1;
  49. else if (A_hit && B_hit)
  50. choice = A.t > B.t;
  51. Eigen::RowVector3d temp;
  52. if (choice == -1)
  53. temp << -1, 0, 0;
  54. else if (choice == 0)
  55. temp << A.id, A.u, A.v;
  56. else if (choice == 1)
  57. temp << B.id, B.u, B.v;
  58. R.row(i) = temp;
  59. }
  60. return R;
  61. }
  62. #ifdef IGL_STATIC_LIBRARY
  63. template Eigen::Matrix<double, -1, -1, 0, -1, -1> igl::embree::line_mesh_intersection<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::Matrix<double, -1, -1, 0, -1, -1> const&, Eigen::Matrix<double, -1, -1, 0, -1, -1> const&, Eigen::Matrix<double, -1, -1, 0, -1, -1> const&, Eigen::Matrix<int, -1, -1, 0, -1, -1> const&);
  64. #endif