Search code examples
c++sdl-2bgfx

Having trouble initializing bgfx (with an sdl2 window)


I'm attempting to create a window using SDL2 and initialize BGFX to use it. My current test is just to set the window to purple using a clear color.

I tried creating a window using CreateWindowEx as well, and was also unable to update the window with the clear color I specified in my call to bgfx::setViewClear. I've been scouring open source projects as well as the docs and samples, and I can't figure out what step of bgfx initialization/update I could be missing. Please help! I've attached my current approach as a small test main.

int main(int, char**) {
    SDL_InitSubSystem(SDL_INIT_VIDEO);

    const int width = 800;
    const int height = 600;

    SDL_Window* window = nullptr;
    HWND nativeWindow;

    // sdl2
    {
        window = SDL_CreateWindow(
            "test_window",
            SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
            width, height,
            0
        );

        SDL_SysWMinfo windowManInfo;
        SDL_VERSION(&windowManInfo.version);
        if (SDL_GetWindowWMInfo(window, &windowManInfo)) {
            nativeWindow = windowManInfo.info.win.window;
        }
    }

    // bgfx
    {
        bgfx::PlatformData platformData;
        platformData.ndt = nullptr;
        platformData.nwh = nativeWindow;
        bgfx::setPlatformData(platformData);

        // prevent creation of a renderer thread
        bgfx::renderFrame();

        bgfx::Init init;
        init.type = bgfx::RendererType::Count;
        init.resolution.width = width;
        init.resolution.height = height;
        init.resolution.reset = BGFX_RESET_VSYNC;
        bgfx::init(init);

        bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x443355FF /*purple*/, 1.f, 0);
    }

    while (1) {
        // sdl events
        {
            SDL_Event _event;
            while (SDL_PollEvent(&_event) > 0);
        }

        bgfx::frame();
    }

    bgfx::shutdown();
    SDL_Quit();

    return 0;
}

Solution

  • After asking around work/etc.. I finally got a solution, and there were actually a couple of things that I was missing.

    1. Because I wasn't adding any render work to the frame, bgfx is 'smart' and doesn't actually do anything. Adding a call to bgfx::touch will add an empty primitve for rendering. After I added this I could see a small dot in the top-left of my window, which leads to the other call I was missing.

    2. I never set my view! I was also only rendering to one pixel of my window. By adding a call to bgfx::setViewRect I was able to set a size for my window view and the clear color finally took.