One QOpenGLShaderProgram instance per model or per OpenGLContext?

  • So I'm quite new to OpenGL and Qt and I have set up most of the basics for my simple engine.

    One thing however bugs me. Is it supposed to be 1 QOpenGLShaderProgram per OpenGLContext or can I have multiple?
    Because I'm unsure how I can have different shaders for different models, as it seems that if I load the shaders, create multiple model objects and render them, they all get the same shaders. Mostly its no problem, but what if I want one model to have a specific shader? for example a pulsating color? Could anyone point me in the right direction? Can I simply add a QOpenGLShaderProgram variable to my model class?

    • TriNity

  • Moderators

    Hi, welcome to the forum.

    You can have as many shader programs as you need. If you were to have only one shader in your whole application it would either be very limited or gigantic and inefficient.
    A shader should not be tied directly to a model, because probably a lot of models will use the same shader and so having a ton of identical copies and switching between them would be terrible for performance.

    Switching a shader is relatively costly operation. You should avoid it when you can. Usually you have a list of shaders and a list of models. A model only holds some sort of id of the shader it uses. Then you group together models that use same shader and draw them like this (in pseudocode):

    foreach(shader in shader_list)
        foreach(model in models_using_that_shader)

  • Thank you very much! It works as expected :D I solved it with std::map and pointers to the shaderprograms. Works like a charm ^~^

  • Moderators

    Great. Just a hint: a map (as any other node-based structure) is not very performance friendly (traversal thrashes memory cache a lot). Try to structure your data so that it is accessed linearly whenever possible i.e. vector of models sorted by the shader is often better than a map.
    I recommend this excellent talk from CppCon2014: Efficiency with Algorithms, Performance with Data Structures. The author talks a lot about why structuring your program and managing access patterns is key to performance.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.