objParser.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "objParser.h"
  2. Mesh& OBJ::buildMeshFromFile(Mesh &mesh, std::string &path){
  3. //Open file containing vertex data
  4. std::ifstream file;
  5. file.open(path.c_str());
  6. //Get vertices and normal data &
  7. //Get face, normal and texture indices
  8. loadFileData(mesh, file);
  9. file.close();
  10. }
  11. bool OBJ::fileExists(std::string &path){
  12. std::ifstream file(path.c_str());
  13. return file.good();
  14. }
  15. void OBJ::loadFileData(Mesh &mesh, std::ifstream &file){
  16. std::string line, key, x ,y ,z;
  17. Vector3 indices[3];
  18. char delimeter = '/';
  19. while(!file.eof()){
  20. std::getline(file,line);
  21. std::istringstream iss(line);
  22. iss >> key;
  23. if(key == "v"){ //Vertex data
  24. iss >> x >> y >> z;
  25. Vector3 vertex(std::stof(x),std::stof(y),std::stof(z));
  26. mesh.vertices.push_back(vertex);
  27. }
  28. else if(key == "vn"){ //Normal data
  29. iss >> x >> y >> z;
  30. Vector3 normal(std::stof(x),std::stof(y),std::stof(z));
  31. mesh.normals.push_back(normal);
  32. }
  33. else if(key == "f"){ //
  34. iss >> x >> y >> z;
  35. std::vector<std::string> splitX = split(x,delimeter);
  36. std::vector<std::string> splitY = split(y,delimeter);
  37. std::vector<std::string> splitZ = split(z,delimeter);
  38. for(int i = 0; i < splitX.size(); ++i){
  39. indices[i] = Vector3(std::stof(splitX[i])-1,std::stof(splitY[i])-1,std::stof(splitZ[i])-1);
  40. }
  41. mesh.vertexIndices.push_back(indices[0]);
  42. mesh.textureIndices.push_back(indices[1]);
  43. mesh.normalsIndices.push_back(indices[2]);
  44. }
  45. }
  46. mesh.numVertices = mesh.vertices.size();
  47. mesh.numFaces = mesh.vertexIndices.size();
  48. file.clear();
  49. file.seekg(0, file.beg);
  50. }
  51. std::vector<std::string> OBJ::split(std::string &str, char delim){
  52. std::stringstream ss(str);
  53. std::string token;
  54. std::vector<std::string> splitString;
  55. while(std::getline(ss,token,delim)){
  56. if(token == ""){
  57. //If token is empty just write -1
  58. //Since you cannot have an idnex of that size anyway
  59. splitString.push_back("-1");
  60. }
  61. else{
  62. splitString.push_back(token);
  63. }
  64. }
  65. return splitString;
  66. }