c++ - 为什么我的 OpenGL 代码不工作

标签 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;
}

但是,当我编译程序时,它只显示一个完全充满白色的窗口,没有其他内容。为什么上面的代码没有按应有的方式工作?

最佳答案

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()

关于c++ - 为什么我的 OpenGL 代码不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27577474/

相关文章:

c++ - OpenGL C++ 围绕场景中心旋转对象

objective-c - 我的 NSOpenGLView 无法工作。我什么都试过了

c++ - 是使用ping命令查找服务器在cpp上的网络状态吗?

c++ - 共享库中的类和静态变量

用于存储对象指针的 C++ vector 类

c++ - 如何使用 vector 来存储形状?

java - java中的3D运动图

c++ - 如何在 map c++中使用复数

c++ - OpenGL 立方体贴图 : Writing to mipmap

opengl - 创建阴影体积时如何在 GLSL 中转换背面顶点