example.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <igl/marching_cubes.h>
  2. typedef float ScalarType;
  3. typedef unsigned IndexType;
  4. int main(int argc, char * argv[])
  5. {
  6. Eigen::Matrix<ScalarType, 1, 3> bb_min, bb_max;
  7. bb_min<<0.,0.,0.;
  8. bb_max<<1.,1.,1.;
  9. //diagonal
  10. Eigen::Matrix<ScalarType, 1, 3> diff = bb_max - bb_min;
  11. //center of the sphere
  12. Eigen::Matrix<ScalarType, 1, 3> center = 0.5 * (bb_min + bb_max);
  13. IndexType xres, yres, zres;
  14. xres = yres = zres = 10;
  15. ScalarType radius = 0.42;
  16. //steps in x,y,z direction
  17. ScalarType dx = diff[0] / (ScalarType)(xres-1);
  18. ScalarType dy = diff[1] / (ScalarType)(yres-1);
  19. ScalarType dz = diff[2] / (ScalarType)(zres-1);
  20. Eigen::Matrix<ScalarType, Eigen::Dynamic, 3> points(xres*yres*zres,3);
  21. Eigen::Matrix<ScalarType, Eigen::Dynamic, 1> values(xres*yres*zres,1);
  22. Eigen::Matrix<ScalarType, Eigen::Dynamic, 3> vertices;
  23. Eigen::Matrix<IndexType, Eigen::Dynamic, 3> faces;
  24. std::cerr<<"Sphere -- construct grid"<<std::endl;
  25. for (unsigned int x=0; x<xres; ++x)
  26. for (unsigned int y=0; y<yres; ++y)
  27. for (unsigned int z=0; z<zres; ++z)
  28. {
  29. int index = x + y*xres + z*xres*yres;
  30. points.row(index) = bb_min +
  31. ScalarType(x)*Eigen::Matrix<ScalarType, 1, 3>(dx,0.,0.) +
  32. ScalarType(y)*Eigen::Matrix<ScalarType, 1, 3>(0.,dy,0.) +
  33. ScalarType(z)*Eigen::Matrix<ScalarType, 1, 3>(0.,0.,dz);
  34. values[index] = (points.row(index) - center).squaredNorm() - radius*radius;
  35. }
  36. std::cerr<<"Sphere -- marching cubes"<<std::endl;
  37. igl::marching_cubes(values,
  38. points,
  39. xres,
  40. yres,
  41. zres,
  42. vertices,
  43. faces);
  44. std::cerr<<"Sphere -- saving"<<std::endl;
  45. FILE * fid = fopen("sphere.obj","w");
  46. for (unsigned i = 0; i<vertices.rows(); ++i)
  47. fprintf(fid,"v %.10g %.10g %.10g\n",vertices(i,0),vertices(i,1),vertices(i,2));
  48. for (unsigned i = 0; i<faces.rows(); ++i)
  49. fprintf(fid,"f %d %d %d\n",faces(i,0)+1,faces(i,1)+1,faces(i,2)+1);
  50. fclose(fid);
  51. std::cerr<<"Sphere -- done."<<std::endl;
  52. return 0;
  53. }