如何关闭 openGL window

How to close an openGL window

在这里,我有两个循环。第一个循环处理图形几秒钟,然后代码进入第二个循环。我在第一个循环中通过 glutMainLoopEvent 处理图形事件。在第二个循环开始之前,我想关闭图形 window。似乎命令 glutLeaveMainLoop 无法关闭 window。我应该使用什么其他功能来强制 window 在第一个循环后立即关闭?

#include <stdio.h>
#include <GL/freeglut.h>
#include <boost/thread/thread.hpp> // for sleep

void cback_render()
{
    if(!glutGetWindow())
        return ;
    static float rotations = 0;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glLoadIdentity();
    glRotatef(rotations, 0, 0, 1);

    glBegin(GL_TRIANGLES);
        glVertex3f(0,0,0);
        glVertex3f(1,0,0);
        glVertex3f(0,1,0);
    glEnd();

    glutSwapBuffers();

    if (++rotations > 360) rotations -= 360;
}

void timer(int )
{
    if(!glutGetWindow())
        return ;
    glutPostRedisplay();
    glutMainLoopEvent();
    glutTimerFunc(30, timer, 1);
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(512, 512);
    glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);

    glutCreateWindow("freegluttest");
    glutDisplayFunc (cback_render);
    glutTimerFunc(30, timer, 1);

    long i=0;
    while(glutGetWindow() && i< 30)
    {
        printf("[%ld]\n",i);
        i++;
        glutMainLoopEvent();
        boost::this_thread::sleep( boost::posix_time::milliseconds(100) );
    }
    glutMainLoopEvent();

    glutLeaveMainLoop(); // does not work
    glutMainLoopEvent();

    // do something else ....
    while(1)
    {
        // other calculations
        boost::this_thread::sleep( boost::posix_time::milliseconds(100) );
    }

    return 0;
}

好的,来自 http://freeglut.sourceforge.net/docs/api.php#EventProcessing

的 freeglut 文档

您正在使用的功能 glutLeaveMainLoop() 是简单地停止 glut 的主循环,如果它是由 glutMainLoop() 而不是 glutMainLoopEvent() 启动的。

由于您在示例中自己控制循环,因此 glutLeaveMainLoop() 不会执行任何操作。

It is intended to leave glut's main loop IF glut is controlling it not you.

由于您在结束时有一个 while(1) 休眠 100 毫秒,因此当所有帧都已呈现后,应用程序将不会执行任何其他操作。如果你想破坏 window 使用一些 window 函数,比如 glutDestroyWindow().