Search code examples
openglshaderopengl-3

OpenGL why deselect shader program?


Possible Duplicate:
Is glDisableClientState required?

In OpenGL I've seen this code which follows this pattern quite often:

glUseProgram(prog_id);
// ... do some stuff
glUseProgram(0);

I understand that glUseProgram(0) deselects any shader programs. Now my question is what does it mean to deselect a shader program?

For example, why should or shouldn't I do something like this in a render loop?

while(render_loop_condition)
{
    glUseProgram(prog_id);
    // do some stuff
}
// various cleanup code
glUseProgram(0);

What about in a render loop which uses multiple shader programs, can I do something like this:

while(render_loop_condition)
{
    glUseProgram(prog_id1);
    // do some stuff
    glUseProgram(prog_id2);
    // do some other stuff
}
// various cleanup code
glUseProgram(0);

Solution

  • It's used to avoid any unintended side effects on what's drawn afterwards. It's perfectly fine (and in my opinion, preferable) to switch between programs within a method, but to select the default program (0) at the end of the method. That way you won't encounter any strange side-effects after calling that method.

    There aren't a whole lot of side-effects that I can think of, but I guess if you're drawing something the fixed-function way, you would accidentally draw with the last program you bound.

    And just a note, with the second block of code you posted, you can move the first glUseProgram call outside of the while loop to prevent binding the same program multiple times.