我编写了一个小程序,它从数据文件中读取3个double类型的顶点,并将它们显示为三角形(使用直线)。它编译,但当我运行它时窗口总是冻结。我试过调试它,但没有成功。我还创建了一个单独的程序,以相同的方式读取相同的数据,但不以图形方式显示它。有效。我想问题出在我的openGL命令中。
你可以指出我的错误吗?//to compile, use $ g++ -lGL -lglut Triangulation.cpp -o Triangulation
#include <iostream>
#include <GL/glut.h>
#include <fstream>//for operation on files
using namespace std;
double triangle_vertices[3][2];
void Draw_Triangulation() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.8, 0.8, 0.0);//color of the shape (Red,Green,Blue). red+green=yellow
int i=0;
ifstream myfile ("data.txt"); //read from file
if (myfile.is_open()) {
while (myfile.good()) {
for (i;i<3;i++) {
for (int j=0;j<2;j++) {
myfile >> triangle_vertices[i][j];
}
}
}
cout<<"file successfuly read."<<endl;
}
myfile.close();
i=0;
glBegin(GL_LINES); //display line with vertices 2&0
glVertex3f(triangle_vertices[i+2][0],triangle_vertices[i+2][1],0.0);
glVertex3f(triangle_vertices[i][0],triangle_vertices[i][1],0.0);
glEnd();
for (i;i<2;i++) { //display lines with vertices 0&1 and 1&2
glBegin(GL_LINES);
glVertex3f(triangle_vertices[i][0],triangle_vertices[i][1],0.0);
glVertex3f(triangle_vertices[i+1][0],triangle_vertices[i+1][1],0.0);
glEnd();
}
glFlush();
}
void Initialize() {
glClearColor(0.32, 0.49, 0.46, 0.0);//(Red,Green,Blue,Alpha) initializes background color.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}
int main(int iArgc, char** cppArgv) {
glutInit(&iArgc, cppArgv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(600, 600); //600*600 pixel window
glutInitWindowPosition(200, 200);
glutCreateWindow("Triangulation From Data File"); //Title of the window
Initialize();
glutDisplayFunc(Draw_Triangulation);
glutMainLoop();
return 0;
}
答案 0 :(得分:3)
从磁盘读取文件是一个非常慢的操作,现在肯定是你想要在Draw方法中做的事情(理想情况下,每秒调用30次以上)。您应该事先读取顶点数据(在main中)并将其存储在一个结构中,然后您可以从DrawTriangulation
方法访问该结构。