为什么我的OpenGL代码不起作用

时间:2014-12-20 05:56:33

标签: c++ opengl

我是OpenGL的新手,并开始关注这个主题的书。他们展示的第一个项目是Sierpinski Gasket计划。这是代码在本书中的样子:

#include<GL/glut.h>
#include<stdlib.h>
void myinit()
{
    //attributes
    glClearColor(1.0,1.0,1.0,1.0);
    glColor3f(1.0,0.0,0.0); //draw in red

    //set up viewing
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0,50.0,0.0,50.0);
    glMatrixMode(GL_MODELVIEW);
}
void display()
{
    GLfloat vertices[3][2]={{0.0,0.0},{25.0,50.0},{50.0,0.0}};  //triangle
    GLfloat p[2]={7.5,5.0};     //arbitrary point
    glClear(GL_COLOR_BUFFER_BIT);   //clear the window
    glBegin(GL_POINTS);
    //Gasket Program
    for(int i=0;i<5000;i++){
        int j=rand()%3;
        //compute points halfway between random vertex and arbitrary point
        p[0]=(vertices[j][0]+p[0])/2;
        p[1]=(vertices[j][1]+p[1])/2;
        //plot the point
        glVertex2fv(p);
    }
    glEnd();
    glFlush();
}
int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowSize(500,500);
    glutInitWindowPosition(0,0);
    glutCreateWindow("Sierpinski Gasket");
    glutDisplayFunc(display);
    myinit();
    glutMainLoop();
    return 0;
}

然而,当我编译程序时,它只显示一个完全用白色填充的窗口,而不是其他任何东西。为什么以上代码不应该以它应该的方式工作?

1 个答案:

答案 0 :(得分:1)

glFlush()交换glutSwapBuffers()

#include<GL/glut.h>

void display()
{
    glClearColor(1.0,1.0,1.0,1.0);
    glClear(GL_COLOR_BUFFER_BIT);   //clear the window

    //set up viewing
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0,50.0,0.0,50.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    GLfloat vertices[3][2]={{0.0,0.0},{25.0,50.0},{50.0,0.0}};  //triangle
    GLfloat p[2]={7.5,5.0};     //arbitrary point
    glColor3f(1.0,0.0,0.0); //draw in red
    glBegin(GL_POINTS);
    //Gasket Program
    for(int i=0;i<5000;i++)
    {
        int j=rand()%3;
        //compute points halfway between random vertex and arbitrary point
        p[0]=(vertices[j][0]+p[0])/2;
        p[1]=(vertices[j][1]+p[1])/2;
        //plot the point
        glVertex2fv(p);
    }
    glEnd();

    glutSwapBuffers();
}

int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
    glutInitWindowSize(500,500);
    glutCreateWindow("Sierpinski Gasket");
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}

glFlush()实际上没有交换GLUT_DOUBLE请求的后台/前台缓冲区。你需要glutSwapBuffers()