用 OpenGL 读数据画点和线,大神帮忙看下程序哪里出了问题
在VC++用OpenGL读txt里的数据画点和线这是txt里的数据:
5 3 //这里是点的个数和线的个数
0, -1 1 0 //这是第0个点,后面三个数字是x,y,z的坐标
1, 1 1 0
2, -0.5 -0.5 0
3, -1 -1 0
4, 0.5 0.5 0 //这是第4个点
0, 1 //这里画线,是第0个点和第1个点连成线
0, 2
1, 3
我的程序是这样的:
#include "stdlib.h"
#include <stdio.h>
#include "glut.h"
void Display();
void Load();
//定义点和线的数据结构
struct vertex
{
float id;
float x;
float y;
float z;
};
struct tri
{
vertex a;
};
struct lin
{
float p;
float q;
};
struct line
{
lin b;
};
struct model
{
tri* tris;
line* lines;
int tris_num;
int lines_num;
};
model test;
//读数据
void Load()
{
FILE* file = fopen("model.txt", "r");
int i = 0;
if (!file)
return;
fscanf(file, "%d%d", &test.tris_num, &test.lines_num);
test.tris = (tri*)malloc(sizeof(tri) * test.tris_num);
test.lines = (line*)malloc(sizeof(line) * test.lines_num);
while (i < test.tris_num+test.lines_num)
{
while (i < test.tris_num)//先读点的数据
{
fscanf(file, "%f,%f%f%f", &test.tris[i].a.id, &test.tris[i].a.x, &test.tris[i].a.y, &test.tris[i].a.z);
++i;
}
fscanf(file, "%f,%f", &test.lines[i].b.p, &test.lines[i].b.q);//再读线的数据
++i;
}
fclose(file);
}
//画图
void Display()
{
gluPerspective(45.f, 1.f, 0.f, 100.f);
glMatrixMode(GL_MODELVIEW);
gluLookAt(0.f, 0.f, 5.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f);
glPointSize(5.0f);
glColor3f(0.f, 1.f, 1.f);
int i = test.tris_num+1;
glBegin(GL_LINES);
while (i < test.tris_num+test.lines_num)
{
int p=test.lines[i].b.p;
int q=test.lines[i].b.q;
glVertex3f(test.tris[p].a.x, test.tris[p].a.y, test.tris[p].a.z);
glVertex3f(test.tris[q].a.x, test.tris[q].a.y, test.tris[q].a.z);
++i;
}
glEnd();
glFinish();
glutSwapBuffers();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(500, 500);
glutCreateWindow("demo");
Load();
glutDisplayFunc(&Display);
glutMainLoop();
return 0;
}