如何使用GLFW轮询libdispatch块中的事件?

时间:2012-09-24 18:03:48

标签: macos opengl glfw libdispatch

跟进How to use GLUT with libdispatch?的答案,我现在正在使用GLFW -

以下代码设置一个窗口,设置一个计时器来轮询事件,并随着时间的推移将渲染更新排队:

#include <dispatch/dispatch.h>
#include <GL/glfw.h>

float t=0;

int main(void)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        glfwInit();
        glfwDisable(GLFW_AUTO_POLL_EVENTS);
        glfwOpenWindow(320,200,8,8,8,8,8,0,GLFW_WINDOW);
    });

    // Periodically process window events --- this isn't working.
    dispatch_source_t windowEventTimer;
    windowEventTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    uint64_t nanoseconds = 100 * NSEC_PER_MSEC;
    dispatch_source_set_timer(windowEventTimer, dispatch_time(DISPATCH_TIME_NOW, nanoseconds), nanoseconds, 0);
    dispatch_source_set_event_handler(windowEventTimer, ^{
        glfwPollEvents();
    });
    dispatch_resume(windowEventTimer);

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for(int i=0;i<200;++i)
        {
            // Enqueue a rendering update.
            dispatch_async(dispatch_get_main_queue(), ^{
                glClearColor (0.2f, 0.2f, 0.4f, 1.0f);
                glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

                glColor3f (1.0, 0.7, 0.7); 
                glBegin( GL_LINES );
                    glVertex3f(0,0,0);
                    glVertex3f(t+=0.02,.1,0);
                glEnd();

                glfwSwapBuffers();
            });
            // Wait a bit, to simulate complex calculations.
            sleep(1);
        }
    });

    dispatch_main();
}

动画按预期更新,但窗口框架未绘制,窗口不响应事件。

1 个答案:

答案 0 :(得分:3)

通过GLFW源代码,我想我发现了问题:GLFW创建的Cocoa窗口的runloop需要从Thread 0执行,但GLFW不能确保{0}在Thread 0上发生。(相同)症状在this question about executing a Cocoa GUI on a thread other than 0报告。)

解决方法是使用CoreFoundation用于处理_glfwPlatformPollEvents()内的主libdispatch队列的相同私有接口。

如果我用以下代码替换上述代码中的CFRunLoop来电:

dispatch_main()

...它按预期工作 - 窗口框架绘制,窗口处理事件。


试图改善这种hacky情况,我: