opengl绘制obj模型
时间: 2023-05-12 14:03:57 浏览: 104
可以使用OpenGL的glut库来绘制obj模型,具体实现可以参考以下代码:
#include <GL/glut.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
struct Vertex {
float x, y, z;
};
struct Face {
int v1, v2, v3;
};
vector<Vertex> vertices;
vector<Face> faces;
void loadObj(string filename) {
ifstream file(filename);
if (!file) {
cout << "Error: Cannot open file " << filename << endl;
exit(1);
}
string line;
while (getline(file, line)) {
istringstream iss(line);
string type;
iss >> type;
if (type == "v") {
Vertex v;
iss >> v.x >> v.y >> v.z;
vertices.push_back(v);
} else if (type == "f") {
Face f;
iss >> f.v1 >> f.v2 >> f.v3;
faces.push_back(f);
}
}
}
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);
glColor3f(1, 1, 1);
glBegin(GL_TRIANGLES);
for (Face f : faces) {
glVertex3f(vertices[f.v1 - 1].x, vertices[f.v1 - 1].y, vertices[f.v1 - 1].z);
glVertex3f(vertices[f.v2 - 1].x, vertices[f.v2 - 1].y, vertices[f.v2 - 1].z);
glVertex3f(vertices[f.v3 - 1].x, vertices[f.v3 - 1].y, vertices[f.v3 - 1].z);
}
glEnd();
glutSwapBuffers();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("OBJ Viewer");
glEnable(GL_DEPTH_TEST);
loadObj("model.obj");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
阅读全文