From 363779f80918fabcdbc09ca4b4b0ee417de1a453 Mon Sep 17 00:00:00 2001 From: Muaz Ahmad Date: Wed, 3 May 2023 14:39:35 +0500 Subject: [PATCH] Added .obj loader --- obj.cpp | 50 ++++++++++++++++++++++++++++++++++++++++++++++++-- obj.h | 10 ++++++---- opglwidget.cpp | 1 + 3 files changed, 55 insertions(+), 6 deletions(-) diff --git a/obj.cpp b/obj.cpp index 14cd47e..e449a7d 100644 --- a/obj.cpp +++ b/obj.cpp @@ -3,6 +3,7 @@ #include #include #include +#include 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(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]); + }; + }; +}; diff --git a/obj.h b/obj.h index f2a3ac9..2a8e0c9 100644 --- a/obj.h +++ b/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 vertices; - Normal normal; - Material mtl; + vector vertices; + vector normals; + Material* mtl; }; class ObjectLoader @@ -32,6 +32,8 @@ public: vector faces; protected: + Material* get_mtl_ptr(string mtl_name); + vector vertices; vector normals; vector mtls; diff --git a/opglwidget.cpp b/opglwidget.cpp index 9e137bd..f62c61f 100644 --- a/opglwidget.cpp +++ b/opglwidget.cpp @@ -24,6 +24,7 @@ void OPGLWidget::initializeGL() { ObjectLoader obj; obj.load_mtl("untitled.mtl"); + obj.load_obj("untitled.obj"); } void OPGLWidget::paintGL() {