Open GL errors in multithread setup

Hi! I am working on a game engine that currently uses OpenGL 4.5 core for rendering.

Everything worked fine until I added a separate render thread. All the OpenGL functions along with glfwMakeContextCurrent are called inside that render thread but still glBindTexture generates an GL_INVALID_OPERATION and glUseProgram generates an GL_INVALID_VALUE.

I tried to run the program under gdb which was not very helpful.

Thanks in advance.

Are you issuing OpenGL calls from multiple threads, or did you just move all of the calls from the main thread? If you’re using multiple threads, you need one context per thread. For GLFW, that means you need to create another window (which can be hidden), because you can’t create contexts other than by creating a window. You also need to ensure that the contexts share data (the last argument to glfwCreateWindow should be an existing window with which to share data), otherwise buffers, textures etc[1] only exist in the context with which they were created. If you’re using a single thread, ensure that you aren’t inadvertently issuing OpenGL calls from the main thread (e.g. from callbacks).

[1] Specifically, buffers, shaders, programs, textures, samplers, renderbuffers and sync objects can be shared. Container objects (program pipelines, FBOs, VAOs, transform feedback objects and query objects) are never shared. For programs, bear in mind that the default uniform block is part of the program object, so if you want to use a single program object in multiple threads concurrently with different uniform values, you need to use UBOs.

1 Like

I am doing all the OpenGL calls from the render thread. Can’t I make current context on a different thread and use it instead of creating multiple windows?

Edit: The clear colors are working fine.
Edit2: I have Dear ImGui setup that’s also rendering on the render thread and it works as well.

If you never use OpenGL from more than one thread, then you only need one context. But then you need to ensure that you don’t call any OpenGL functions implicitly or explicitly from the main thread (e.g. glfwSwapBuffers must be called from the rendering thread, not the main thread). Also, you need to call glfwMakeContextCurrent(NULL) from the main thread before making the context current in the rendering thread.

Sorry, it seems the error is somewhere in my asset pipeline. I added a log statement for the shader id and it outputs 1652124499, which is why the GL_INVALID_VALUE occurs.