MeshBoolean.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <libslic3r/TriangleMesh.hpp>
  2. #undef PI
  3. #include <igl/readOFF.h>
  4. //#undef IGL_STATIC_LIBRARY
  5. #include <igl/copyleft/cgal/mesh_boolean.h>
  6. #include <Eigen/Core>
  7. #include <iostream>
  8. #include <admesh/stl.h>
  9. #include <boost/nowide/cstdio.hpp>
  10. #include <boost/log/trivial.hpp>
  11. namespace Slic3r {
  12. bool its_write_obj(const Eigen::MatrixXd &V, Eigen::MatrixXi &F, const char *file)
  13. {
  14. FILE *fp = boost::nowide::fopen(file, "w");
  15. if (fp == nullptr) {
  16. BOOST_LOG_TRIVIAL(error) << "stl_write_obj: Couldn't open " << file << " for writing";
  17. return false;
  18. }
  19. for (size_t i = 0; i < V.rows(); ++ i)
  20. fprintf(fp, "v %lf %lf %lf\n", V(i, 0), V(i, 1), V(i, 2));
  21. for (size_t i = 0; i < F.rows(); ++ i)
  22. fprintf(fp, "f %d %d %d\n", F(i, 0) + 1, F(i, 1) + 1, F(i, 2) + 1);
  23. fclose(fp);
  24. return true;
  25. }
  26. void mesh_boolean_test(const std::string &fname)
  27. {
  28. using namespace Eigen;
  29. using namespace std;
  30. // igl::readOFF(TUTORIAL_SHARED_PATH "/cheburashka.off",VA,FA);
  31. // igl::readOFF(TUTORIAL_SHARED_PATH "/decimated-knight.off",VB,FB);
  32. // Plot the mesh with pseudocolors
  33. // igl::opengl::glfw::Viewer viewer;
  34. // Initialize
  35. // update(viewer);
  36. //igl::copyleft::cgal::mesh_boolean(VA,FA,VB,FB,boolean_type,VC,FC,J);
  37. std::cout << fname.c_str() << std::endl;
  38. TriangleMesh mesh;
  39. mesh.ReadSTLFile(fname.c_str());
  40. mesh.repair(true);
  41. its_write_obj(mesh.its, (fname + "-imported0.obj").c_str());
  42. Eigen::MatrixXd VA,VB,VC;
  43. Eigen::VectorXi J,I;
  44. Eigen::MatrixXi FA,FB,FC;
  45. igl::MeshBooleanType boolean_type(igl::MESH_BOOLEAN_TYPE_UNION);
  46. typedef Eigen::Map<const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor | Eigen::DontAlign>> MapMatrixXfUnaligned;
  47. typedef Eigen::Map<const Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor | Eigen::DontAlign>> MapMatrixXiUnaligned;
  48. Eigen::MatrixXd V = MapMatrixXfUnaligned(mesh.its.vertices.front().data(), mesh.its.vertices.size(), 3).cast<double>();
  49. Eigen::MatrixXi F = MapMatrixXiUnaligned(mesh.its.indices.front().data(), mesh.its.indices.size(), 3);
  50. its_write_obj(V, F, (fname + "-imported.obj").c_str());
  51. // Self-union to clean up
  52. igl::copyleft::cgal::mesh_boolean(V, F, Eigen::MatrixXd(), Eigen::MatrixXi(), boolean_type, VC, FC);
  53. its_write_obj(VC, FC, (fname + "-fixed.obj").c_str());
  54. }
  55. } // namespace Slic3r
  56. int main(const int argc, const char * argv[])
  57. {
  58. if (argc < 1) return -1;
  59. Slic3r::mesh_boolean_test(argv[1]);
  60. return 0;
  61. }