在我的代码的开头,我已经初始化了 vbo:
GLuint VBO;
然后我的顶点和颜色数组:
GL float vertandcol[]={x1,y1, z1, r1,g1,b1, ...........,x3, y3, z3, r3,g3,b3};
现在我创建并绑定 vbo 并分配空间:
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertandcol),vertandcol, GL_STATIC_DRAW);
最后是渲染函数:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 6* sizeof(GLfloat), 0);
glColorPointer(3, GL_FLOAT, 6* sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));
glDrawArrays(GL_TRIANGLES, 0,3);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
这应该画一个三角形,但我看不到任何东西。也许 glVertexPointer 和 glColorPointer 的参数不正确。我已阅读 opengl.or 上有关 VBO 的文档,并且遵循了几个教程,如下所示:https ://www.youtube.com/watch?v=KIeExgOcmv0
我的代码和 youtube 链接上的代码相似,但第一个不起作用。我不明白为什么。你能帮助我吗?
这是整个代码:
GLuint vbo;
GLfloat vertandcolor[] = {175.0, 25.0, 0.0, 1.0, 0.0, 0.0,
100.0, 325.0, 0.0, 0.0,1.0,0.0, 250.0, 25.0, 0.0, 0.0, 0.0, 1.0};
void init()
{
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertandcolor),vertandcolor, GL_STATIC_DRAW);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 6* sizeof(GLfloat), 0);
glEnableClientState(GL_COLOR_ARRAY);
glColorPointer(3, GL_FLOAT, 6* sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));
glDrawArrays(GL_TRIANGLES, 0,3);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glutSwapBuffers();
glFlush();
}
void reshape(int w, int h){
glClearColor(0.5,0.2,0.5,1);
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, (GLsizei) w, 0, (GLsizei) h, -1,1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();}
int main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(350, 350);
glutInitWindowPosition(100, 100);
glutCreateWindow("VBO");
init();
glutDisplayFunc(&display);
glutReshapeFunc(reshape);
glutMainLoop();
}