按需渲染帧

Render a frame on demand

我目前正在创建 NTSC 信号 decoder/simulator,基本上,我希望能够在渲染之前准备好帧,例如读取数组、处理数据、绘制一些像素相应地,然后渲染框架。我试过摆脱 glutMainLoop(); 的东西,只使用手工制作的循环:

for(;;) { 
    glClearColor(0.0f, 0.5f, 0.5f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    // Whatever I might have to do goes somewhere in here
    glFlush(); 
}

然而,这不起作用,glClearColorglClear,可能 glFlush 也被执行了,但只有一次,之后,程序就挂起,什么我可以做些什么来避免这种情况吗?

I've tried getting rid of the glutMainLoop(); thing, and just using a handmade loop
... after that, the program just hangs ...

这是个坏主意,因为一般来说,使用 GLUT 时获得事件处理的唯一方法是 glutMainLoop()

参见glutMainLoop:

glutMainLoop enters the GLUT event processing loop. This routine should be called at most once in a GLUT program. Once called, this routine will never return. It will call as necessary any callbacks that have been registered.

请注意,glutMainLoop()不仅会调用您在glutDisplayFunc中设置的回调函数,它还会接收和处理鼠标和键盘事件等IO事件。如果你不使用glutMainLoop(),那么你就没有事件处理,当然也没有IO事件处理。这导致程序似乎挂起并且对任何输入都没有反应。
您要么必须使用 glutMainLoop(),要么必须切换另一个 window API,例如 GLFW, where you can explicitly activate the event processing by glfwPollEvents()

较新的 GLUT 实现,如 freeglut 提供了一些额外的功能。 glutMainLoopEvent()glutMainLoop() 的作用相同,但只执行一次。它对事件循环进行一次迭代并立即交还控制权。因此,您可以实现自己的循环来处理您的应用程序。

例如

void display( void )
{
    glClearColor(0.0f, 0.5f, 0.5f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    // Whatever I might have to do goes somewhere in here
    glFlush();
}

int main()
{
    .....

    glutDisplayFunc(display);  

    .....

    for(;;)
    {
        glutMainLoopEvent(); // handle the main loop once
        glutPostRedisplay(); // cause `display` to be called in `glutMainLoopEvent`
    }

    .....
}

甚至可以设置一个dummy显示函数,它什么也不做,循环绘图:

例如

void dummyDisplay( void )
{
    // does nothing
}

int main()
{
    .....

    glutDisplayFunc(dummyDisplay);  

    .....

    for(;;)
    {
        glClearColor(0.0f, 0.5f, 0.5f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        // Whatever I might have to do goes somewhere in here
        glFlush();

        glutMainLoopEvent(); // does the event handling once
    }

    .....
}