readOBJ.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. //
  2. // IGL Lib - Simple C++ mesh library
  3. //
  4. // Copyright 2011, Daniele Panozzo. All rights reserved.
  5. // History:
  6. // return type changed from void to bool Alec 18 Sept 2011
  7. #ifndef IGL_READOBJ_H
  8. #define IGL_READOBJ_H
  9. #include <Eigen/Core>
  10. #include <string>
  11. #include <iostream>
  12. #include <fstream>
  13. #include <vector>
  14. namespace igl
  15. {
  16. //! Read a mesh from an ascii obj file
  17. // Inputs:
  18. // str path to .obj file
  19. // Outputs:
  20. // V eigen double matrix #V by 3
  21. // F eigen int matrix #F by 3
  22. //
  23. // KNOWN BUG: This only knows how to read *triangle* meshes. It will probably
  24. // crash or give garbage on anything else.
  25. //
  26. // KNOWN BUG: This only knows how to face lines without normal or texture
  27. // indices. It will probably crash or give garbage on anything else.
  28. bool readOBJ(const std::string str, Eigen::MatrixXd& V, Eigen::MatrixXi& F);
  29. }
  30. // Implementation
  31. bool igl::readOBJ(const std::string str, Eigen::MatrixXd& V, Eigen::MatrixXi& F)
  32. {
  33. std::ifstream s(str.c_str());
  34. if (s.is_open() == false)
  35. {
  36. fprintf (stderr, "readOBJ(): could not open file %s", str.c_str());
  37. return false;
  38. }
  39. std::vector<Eigen::Vector3d> Vtemp;
  40. std::vector<Eigen::Vector3i> Ftemp;
  41. char buf[1000];
  42. while(!s.eof())
  43. {
  44. s.getline(buf, 1000);
  45. if (buf[0] == 'v') // vertex coordinates found
  46. {
  47. char v;
  48. double v1,v2,v3;
  49. sscanf(buf, "%c %lf %lf %lf",&v,&v1,&v2,&v3);
  50. Vtemp.push_back(Eigen::Vector3d(v1,v2,v3));
  51. }
  52. else if (buf[0] == 'f') // face description found
  53. {
  54. char v;
  55. int v1,v2,v3;
  56. sscanf(buf, "%c %d %d %d",&v,&v1,&v2,&v3);
  57. Ftemp.push_back(Eigen::Vector3i(v1-1,v2-1,v3-1));
  58. }
  59. }
  60. s.close();
  61. V = Eigen::MatrixXd(Vtemp.size(),3);
  62. for(int i=0;i<V.rows();++i)
  63. V.row(i) = Vtemp[i];
  64. F = Eigen::MatrixXi(Ftemp.size(),3);
  65. for(int i=0;i<F.rows();++i)
  66. F.row(i) = Ftemp[i];
  67. return true;
  68. }
  69. #endif