在子窗口中多线程OpenGL

时间:2011-04-02 04:22:19

标签: c++ windows visual-studio multithreading opengl

我正在尝试构建一个即使在调整主窗口大小或移动时也能响应的OpenGL应用程序。我找到的最合理的解决方案是在单独的线程中创建一个子窗口和一个消息泵,它呈现OpenGL。它可以根据需要在帧之间调整大小。主消息泵和窗口框架在主过程中运行。

它很有用。可以移动窗口,使用菜单和调整大小,而不会影响子窗口的帧速率。 SwapBuffers()就是崩溃的地方。

当以这种方式运行时,SwapBuffers()似乎在软件模式下运行。它不再保持在60 FPS以匹配我的显示器的VSync,当窗口大约100x100时它会跳到数百个,当最大化到1920x1080时它会降到20 FPS。当在单个线程中运行时,一切看起来都很正常。

我解决了一些问题。就像消息需要在父节点和子节点之间传递一样,它会停止整个应用程序。覆盖WM_SETCURSOR并设置WS_EX_NOPARENTNOTIFY解决了这些问题。点击时它偶尔会出现断断续续的情况。

我希望我只是不做正确的事情而且有经验的OpenGL可以帮助我。与我的初始化或清理有关的事情可能是关闭的,因为这会干扰我的PC上运行的其他OpenGL应用程序,即使我关闭它。

这是一个简化的测试用例,展示了我遇到的问题。它应该在任何现代Visual Studio中编译。

#include <windows.h>
#include <gl/gl.h>
#include <gl/glu.h>
#include <wchar.h>

#pragma comment(lib, "opengl32.lib")

typedef signed int s32;
typedef unsigned int u32;
typedef unsigned long long u64;
typedef float f32;
typedef double f64;

bool run = true;

// Window procedure for the main application window
LRESULT CALLBACK AppWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if (msg == WM_DESTROY && (GetWindowLong(hWnd, GWL_EXSTYLE) & WS_EX_APPWINDOW))
        PostQuitMessage(0);

    return DefWindowProc(hWnd, msg, wParam, lParam);
}

// Window procedure for the OpenGL rendering window
LRESULT CALLBACK RenderWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if (msg == WM_SETCURSOR)
    {
        SetCursor(LoadCursor(NULL, IDC_CROSS));
        return TRUE;
    }
    if (msg == WM_SIZE)
        glViewport(0, 0, LOWORD(lParam)-2, HIWORD(lParam)-2);

    return AppWindowProc(hWnd, msg, wParam, lParam);
}

int WINAPI ThreadMain(HWND parent)
{
    HINSTANCE hInstance = GetModuleHandle(0);

    // Depending on if this is running as a child or a overlap window, set up the window styles
    UINT ClassStyle, Style, ExStyle;
    if (parent)
    {
        ClassStyle = 0;
        Style = WS_CHILD;
        ExStyle = WS_EX_NOPARENTNOTIFY;
    } else {
        ClassStyle = 0 | CS_VREDRAW | CS_HREDRAW;
        Style = WS_OVERLAPPEDWINDOW;
        ExStyle = WS_EX_APPWINDOW;
    }

    // Create the child window class
    WNDCLASSEX wc = {0};
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = ClassStyle;
    wc.hInstance = hInstance;
    wc.lpfnWndProc = RenderWindowProc;
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.hIcon = LoadIcon(0, IDI_APPLICATION);
    wc.hCursor = LoadCursor(0, IDC_ARROW);
    wc.lpszClassName = L"OGLChild";
    ATOM ClassAtom = RegisterClassEx(&wc);

    // Create the child window
    RECT r = {0, 0, 640, 480};
    if (parent)
        GetClientRect(parent, &r);
    HWND WindowHandle = CreateWindowExW(ExStyle, (LPCTSTR)MAKELONG(ClassAtom, 0), 0, Style, 
                                        0, 0, r.right, r.bottom, parent, 0, hInstance, 0);

    // Initialize OpenGL render context
    PIXELFORMATDESCRIPTOR pfd = {0};
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 16;
    pfd.iLayerType = PFD_MAIN_PLANE;
    HDC DeviceContext = GetDC(WindowHandle);
    int format = ChoosePixelFormat(DeviceContext, &pfd);
    SetPixelFormat(DeviceContext, format, &pfd);
    HGLRC RenderContext = wglCreateContext(DeviceContext);
    wglMakeCurrent(DeviceContext, RenderContext);

    ShowWindow(WindowHandle, SW_SHOW);

    GetClientRect(WindowHandle, &r);
    glViewport(0, 0, r.right, r.bottom);

    // Set up an accurate clock
    u64 start, now, last, frequency;
    QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);
    QueryPerformanceCounter((LARGE_INTEGER*)&now);
    start = last = now;

    u32 frames = 0; // total frames this second
    f64 nextFrameCount = 0; // next FPS update
    f32 left = 0; // line position

    MSG msg;
    while (run)
    {
        while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            if (msg.message == WM_QUIT || msg.message == WM_DESTROY)
                run = false;
        }

        // Update the clock
        QueryPerformanceCounter((LARGE_INTEGER*)&now);
        f64 clock = (f64)(now - start) / frequency;
        f64 delta = (f64)(now - last) / frequency;
        last = now;

        // Render a line moving
        glOrtho(0, 640, 480, 0, -1, 1);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();   
        glColor3f(1.0f, 1.0f, 0.0f);
        left += (f32)(delta * 320.0f);
        if (left > 640.0f)
            left = 0;
        glBegin(GL_LINES);
            glVertex2f(0.0f, 0.0f);
            glVertex2f(left, 480.0f);
        glEnd();
        SwapBuffers(DeviceContext);

        // Resize as necessary
        if (parent)
        {
            RECT pr, cr;
            GetClientRect(parent, &pr);
            GetClientRect(WindowHandle, &cr);
            if (pr.right != cr.right || pr.bottom != cr.bottom)
                MoveWindow(WindowHandle, 0, 0, pr.right, pr.bottom, FALSE);
        }

        // Update FPS counter
        frames++;
        if (clock > nextFrameCount)
        {
            WCHAR title[16] = {0};
            _snwprintf_s(title, 16, 16, L"FPS: %u", frames);
            SetWindowText(parent ? parent : WindowHandle, title);
            nextFrameCount = clock + 1;
            frames = 0;
        }

        Sleep(1);

    }

    // Cleanup OpenGL context
    wglDeleteContext(RenderContext);
    wglMakeCurrent(0,0);
    ReleaseDC(WindowHandle, DeviceContext);

    DestroyWindow(WindowHandle);

    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    int result = MessageBox(0, L"Would you like to run in threaded child mode?", 
                            L"Threaded OpenGL Demo", MB_YESNOCANCEL | MB_ICONQUESTION);
    if (result == IDNO)
        return ThreadMain(0);
    else if (result != IDYES)
        return 0;

    // Create the parent window class
    WNDCLASSEX wc = {0};
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = 0;
    wc.hInstance = hInstance;
    wc.lpfnWndProc = (WNDPROC)AppWindowProc;
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.hIcon = LoadIcon(0, IDI_APPLICATION);
    wc.hCursor = LoadCursor(0, IDC_ARROW);
    wc.lpszClassName = L"OGLFrame";
    ATOM ClassAtom = RegisterClassEx(&wc);

    // Create the parent window
    HWND WindowHandle = CreateWindowExW(WS_EX_APPWINDOW, (LPCTSTR)MAKELONG(ClassAtom, 0), 
                                        0, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, 
                                        0, 0, 640, 480, 0, 0, hInstance, 0);

    ShowWindow(WindowHandle, SW_SHOW);

    // Start the child thread
    HANDLE thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadMain, (LPVOID)WindowHandle, 0, 0);

    MSG msg;
    while (run)
    {
        while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            if (msg.message == WM_QUIT)
                run = false;
        }

        Sleep(100);
    }

    DestroyWindow(WindowHandle);

    // Wait for the child thread to finish
    WaitForSingleObject(thread, INFINITE);

    ExitProcess(0);
    return 0;
}

我一直在NVIDIA GeForce 8800 GTX上运行它,但我希望任何解决方案都适用于任何现代卡。

我尝试了其他方法,例如在主进程中将线程渲染到窗口中,但在调整大小期间我得到了伪像,甚至还有几个蓝屏。我的应用程序将是跨平台的,因此DirectX不是一个选项。

1 个答案:

答案 0 :(得分:2)

问题是,在Visual Studio中对OpenGL应用程序进行长时间调试会导致OpenGL无法创建上下文。由于我没有捕获任何错误,我从未意识到它在没有硬件加速的情况下运行。它需要完全重启才能恢复,现在工作正常。

此外,用这个替换泵WinMain修复了调整大小的任何问题:

MSG msg;
while (GetMessage(&msg, 0, 0, 0) != 0)
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
run = false;