可以使用OpenGL的glut库来绘制obj模型,具体实现可以参考以下代码:
#include <GL/glut.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<float> vertices;
vector<float> normals;
vector<int> indices;
void loadObj(string filename) {
ifstream file(filename);
if (!file.is_open()) {
cout << "Failed to open file: " << filename << endl;
return;
}
string line;
while (getline(file, line)) {
if (line.substr(0, 2) == "v ") {
float x, y, z;
sscanf(line.c_str(), "v %f %f %f", &x, &y, &z);
vertices.push_back(x);
vertices.push_back(y);
vertices.push_back(z);
} else if (line.substr(0, 2) == "vn") {
float x, y, z;
sscanf(line.c_str(), "vn %f %f %f", &x, &y, &z);
normals.push_back(x);
normals.push_back(y);
normals.push_back(z);
} else if (line.substr(0, 2) == "f ") {
int v1, v2, v3, n1, n2, n3;
sscanf(line.c_str(), "f %d//%d %d//%d %d//%d", &v1, &n1, &v2, &n2, &v3, &n3);
indices.push_back(v1 - 1);
indices.push_back(v2 - 1);
indices.push_back(v3 - 1);
}
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
glNormalPointer(GL_FLOAT, 0, &normals[0]);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, &indices[0]);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glutSwapBuffers();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL obj viewer");
glEnable(GL_DEPTH_TEST);
loadObj("model.obj");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}