Added .obj loader
This commit is contained in:
parent
a97fa446b4
commit
363779f809
3 changed files with 55 additions and 6 deletions
50
obj.cpp
50
obj.cpp
|
@ -3,6 +3,7 @@
|
|||
#include <vector>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
#include <regex>
|
||||
|
||||
void ObjectLoader::load_mtl(string filename) {
|
||||
string tmp;
|
||||
|
@ -43,6 +44,51 @@ void ObjectLoader::load_obj(string filename) {
|
|||
string tmp;
|
||||
ifstream f(filename);
|
||||
while (getline(f, tmp)) {
|
||||
Material* mtl_ptr;
|
||||
if (tmp[0] == 'v') {
|
||||
float* target_list;
|
||||
switch (tmp[1]) {
|
||||
case ' ':
|
||||
vertices.push_back(*(new Vertex));
|
||||
target_list = vertices.back().pos;
|
||||
break;
|
||||
case 'n':
|
||||
normals.push_back(*(new Normal));
|
||||
target_list = normals.back().dir;
|
||||
break;
|
||||
default:
|
||||
continue;
|
||||
};
|
||||
char delim = ' ';
|
||||
char *token = strtok(const_cast<char*>(tmp.c_str()), &delim);
|
||||
for (int i = 0; i < 3; i++) {
|
||||
token = strtok(NULL, &delim);
|
||||
target_list[i] = atof(token);
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
} else if (tmp.rfind("usemtl", 0) == 0) {
|
||||
mtl_ptr = get_mtl_ptr(tmp.substr(tmp.find(' ') + 1));
|
||||
} else if (tmp[0] == 'f') {
|
||||
faces.push_back(*(new Face));
|
||||
faces.back().mtl = mtl_ptr;
|
||||
regex re("f (\\d*)//(\\d*) (\\d*)//(\\d*) (\\d*)//(\\d*)");
|
||||
smatch match;
|
||||
regex_search(tmp, match, re);
|
||||
for (int i = 1; i < 7; i++) {
|
||||
if (i % 2 == 0) {
|
||||
faces.back().normals.push_back(&(normals[stoi(match.str(i))]));
|
||||
} else {
|
||||
faces.back().vertices.push_back(&(vertices[stoi(match.str(i))]));
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
Material* ObjectLoader::get_mtl_ptr(string mtl_name) {
|
||||
for (int i = 0; i < mtls.size(); i++) {
|
||||
if (mtls[i].name == mtl_name) {
|
||||
return &(mtls[i]);
|
||||
};
|
||||
};
|
||||
};
|
||||
|
|
10
obj.h
10
obj.h
|
@ -6,7 +6,7 @@ struct Vertex {
|
|||
};
|
||||
|
||||
struct Normal {
|
||||
float pos[3];
|
||||
float dir[3];
|
||||
};
|
||||
|
||||
struct Material {
|
||||
|
@ -18,9 +18,9 @@ struct Material {
|
|||
};
|
||||
|
||||
struct Face {
|
||||
vector<Vertex> vertices;
|
||||
Normal normal;
|
||||
Material mtl;
|
||||
vector<Vertex*> vertices;
|
||||
vector<Normal*> normals;
|
||||
Material* mtl;
|
||||
};
|
||||
|
||||
class ObjectLoader
|
||||
|
@ -32,6 +32,8 @@ public:
|
|||
vector<Face> faces;
|
||||
|
||||
protected:
|
||||
Material* get_mtl_ptr(string mtl_name);
|
||||
|
||||
vector<Vertex> vertices;
|
||||
vector<Normal> normals;
|
||||
vector<Material> mtls;
|
||||
|
|
|
@ -24,6 +24,7 @@ void OPGLWidget::initializeGL() {
|
|||
|
||||
ObjectLoader obj;
|
||||
obj.load_mtl("untitled.mtl");
|
||||
obj.load_obj("untitled.obj");
|
||||
}
|
||||
|
||||
void OPGLWidget::paintGL() {
|
||||
|
|
Loading…
Reference in a new issue