mpri-graphics-project/util/ObjParser.cpp

58 lines
1.3 KiB
C++
Raw Permalink Normal View History

2018-01-28 23:03:57 +01:00
#include "ObjParser.hpp"
2018-02-06 19:08:17 +01:00
#include <sstream>
#include <cctype>
2018-01-28 23:03:57 +01:00
ObjParser::ObjParser(const std::string& path)
: path(path)
{}
Mesh ObjParser::parse() {
std::ifstream handle(path);
Mesh output;
if(!handle.is_open())
throw std::runtime_error(std::string("Cannot open the file ") + path);
2018-02-06 19:08:17 +01:00
for(std::string line; std::getline(handle, line); ) {
std::istringstream lineStream(strip(line));
2018-01-28 23:03:57 +01:00
char type;
2018-02-06 19:08:17 +01:00
lineStream >> type;
2018-01-28 23:03:57 +01:00
if(type == 'v') { // vertice
double x, y, z;
2018-02-06 19:08:17 +01:00
lineStream >> x >> y >> z;
2018-01-28 23:03:57 +01:00
output.add_vertice(Point(x, y, z));
}
2018-02-06 19:08:17 +01:00
else if(type == 'f') {
2018-01-28 23:03:57 +01:00
int v1, v2, v3;
2018-02-06 19:08:17 +01:00
lineStream >> v1 >> v2 >> v3;
output.add_face(Face(v1 - 1, v2 - 1, v3 - 1));
}
else {
throw BadObj(path);
2018-01-28 23:03:57 +01:00
}
}
2018-02-06 21:05:45 +01:00
output.normalize_center(false);
2018-01-28 23:03:57 +01:00
return output;
}
2018-02-06 19:08:17 +01:00
std::string ObjParser::strip(const std::string& str) {
size_t fPos, lPos;
for(fPos=0; fPos < str.size(); ++fPos) {
if(!isspace(str[fPos]))
break;
}
if(fPos == str.size())
return "";
for(lPos=str.size() - 1; lPos > 0; --lPos) {
if(!isspace(str[lPos]))
break;
}
return str.substr(fPos, lPos - fPos + 1);
}