project_mesh.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 "project_mesh.h"
  9. // For error printing
  10. #include <cstdio>
  11. #include <vector>
  12. #include <igl/per_vertex_normals.h>
  13. #include <igl/embree/EmbreeIntersector.h>
  14. template <typename ScalarMatrix, typename IndexMatrix>
  15. IGL_INLINE ScalarMatrix igl::project_mesh(
  16. const ScalarMatrix & V_source,
  17. const IndexMatrix & F_source,
  18. const ScalarMatrix & V_target,
  19. const IndexMatrix & F_target
  20. )
  21. {
  22. // Compute normals for the tri
  23. Eigen::MatrixXd ray_dir;
  24. igl::per_vertex_normals(V_source, F_source, ray_dir);
  25. return project_points_on_mesh(V_source,ray_dir,V_target,F_target);
  26. }
  27. template <typename ScalarMatrix, typename IndexMatrix>
  28. IGL_INLINE ScalarMatrix igl::project_points_on_mesh
  29. (
  30. const ScalarMatrix & V_source,
  31. const ScalarMatrix & N_source,
  32. const ScalarMatrix & V_target,
  33. const IndexMatrix & F_target
  34. )
  35. {
  36. double tol = 0.00001;
  37. Eigen::MatrixXd ray_pos = V_source;
  38. Eigen::MatrixXd ray_dir = N_source;
  39. // Allocate matrix for the result
  40. ScalarMatrix R;
  41. R.resize(V_source.rows(), 3);
  42. // Initialize embree
  43. igl::EmbreeIntersector embree;
  44. embree.init(V_target.template cast<float>(),F_target.template cast<int>());
  45. // Shoot rays from the source to the target
  46. for (unsigned i=0; i<ray_pos.rows(); ++i)
  47. {
  48. igl::Hit A,B;
  49. // Shoot ray A
  50. Eigen::RowVector3d A_pos = ray_pos.row(i) + tol * ray_dir.row(i);
  51. Eigen::RowVector3d A_dir = -ray_dir.row(i);
  52. bool A_hit = embree.intersectRay(A_pos.cast<float>(), A_dir.cast<float>(),A);
  53. Eigen::RowVector3d B_pos = ray_pos.row(i) - tol * ray_dir.row(i);
  54. Eigen::RowVector3d B_dir = ray_dir.row(i);
  55. bool B_hit = embree.intersectRay(B_pos.cast<float>(), B_dir.cast<float>(),B);
  56. int choice = -1;
  57. if (A_hit && ! B_hit)
  58. choice = 0;
  59. else if (!A_hit && B_hit)
  60. choice = 1;
  61. else if (A_hit && B_hit)
  62. choice = A.t > B.t;
  63. Eigen::RowVector3d temp;
  64. if (choice == -1)
  65. temp << -1, 0, 0;
  66. else if (choice == 0)
  67. temp << A.id, A.u, A.v;
  68. else if (choice == 1)
  69. temp << B.id, B.u, B.v;
  70. R.row(i) = temp;
  71. }
  72. return R;
  73. }