c++ - FreeGLUT 窗口在启动时消失

标签 c++ opengl glew freeglut

我今天刚开始使用 OpenGL 并关注 a tutorial用于在 Visual Studio 2010 中设置 OpenGL 项目。 但是当我运行代码时,我看到一个窗口打开得非常快,闪烁然后消失。这正常吗?

#include <GL\glew.h>
#include <GL\freeglut.h>
#include <iostream>

using namespace std;

//Window Resized, this function get called "glutReshapedFunc" in main
void changeViewport(int w, int h) {
      glViewport(0, 0, w, h);
}

//Here s a function that gets Called time Windows need to the redraw.
//Its the "paint" method for our program, and its setup from the glutDisplayFunc in main
void render() {

     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
     glutSwapBuffers();
}

int main(int argc, char** argv) {
    //Initialize GLUT
    glutInit(&argc, argv);

    //Setup some Memory Buffer for our Display
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA|GLUT_DEPTH);

    //Setup Window Size
    glutInitWindowSize(800,600);

    //Create Window with Title
    glutCreateWindow("GL_HelloWorld");

    //Bind two functions (above) respond when necessary
    glutReshapeFunc(changeViewport);
    glutDisplayFunc(render);

    //Very important! this initialize the entry points in the OpenGL driver so we can
    //Call all the functions in the API
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "GLEW error");
        return 1;
    }

}

最佳答案

您错过了 glutMainLoop 进入 GLUT 事件处理循环的机会:

int main(int argc, char** argv) {

    // [...]

    glutDisplayFunc(render);

    //Very important! this initialize the entry points in the OpenGL driver so we can
    //Call all the functions in the API
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "GLEW error");
        return 1;
    }

    // start event processing loop - causes 1st call of "render"
    glutMainLoop();

    return 0;
}

此函数从不返回,处理事件并执行回调,如显示回调 (render)。该函数处理主应用程序循环。 如果不调用此函数,则程序会在窗口创建后立即终止。

如果您希望您的应用程序不断重绘场景,那么您必须调用 glutPostRedisplay()render 中。这将当前窗口标记为需要重新显示,并导致在事件处理循环中再次调用显示回调(render):

void render() {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // draw the scene
    // [...]

    glutSwapBuffers();

    // mark to be redisplayed - causes continuously calls to "render"
    glutPostRedisplay()
}

关于c++ - FreeGLUT 窗口在启动时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57936608/

相关文章:

c++ - Visual C++ 2012 似乎不尊重 lambda 中的默认捕获

java - Opengl Quads 不渲染

c++ - 沿opengl中的路径旋转

c++ - Glew 问题, Unresolved external 问题

c++ - 尝试在 C++ 中使用 glDrawArrays 时出错

c++ - 使用 boost::function 和 boost::bind

c++ - gmtime 同时改变两个指针

c++ - 什么是 friend ostream

c++ - 将数据从后台缓冲区复制到前台缓冲区

c++ - OpenGL 3.30/GLSL 3.30 - MRT 输出黑色纹理