57 lines
1.3 KiB
C++
57 lines
1.3 KiB
C++
#include "ObjParser.hpp"
|
|
|
|
#include <sstream>
|
|
#include <cctype>
|
|
|
|
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);
|
|
|
|
for(std::string line; std::getline(handle, line); ) {
|
|
std::istringstream lineStream(strip(line));
|
|
char type;
|
|
lineStream >> type;
|
|
|
|
if(type == 'v') { // vertice
|
|
double x, y, z;
|
|
lineStream >> x >> y >> z;
|
|
output.add_vertice(Point(x, y, z));
|
|
}
|
|
else if(type == 'f') {
|
|
int v1, v2, v3;
|
|
lineStream >> v1 >> v2 >> v3;
|
|
output.add_face(Face(v1 - 1, v2 - 1, v3 - 1));
|
|
}
|
|
else {
|
|
throw BadObj(path);
|
|
}
|
|
}
|
|
|
|
output.normalize_center(false);
|
|
|
|
return output;
|
|
}
|
|
|
|
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);
|
|
}
|