Reputation: 1695
I am just learning OpenGL, and I'm realizing that for more complex shader effects, there are basically two stategies that you can use to implement them. The first is to write one complicated vertex and fragment shader that accepts a number of different uniform variables from the main program, and decides what to do in the shader. Ex. if I want to make pixels in one context blue and in another context green, I might do in GLSL:
uniform int whichColor;
int main() {
if (whichColor == 1) {
gl_FragColor = vec4(0,1.0,0,1.0);
}
else {
gl_FragColor = vec4(0,0,1.0,1.0);
}
}
and pass different ints to whichColor in my C++ drawing loop. Alternatively, I could just define two separate shader programs, one of which sets gl_FragColor to blue and the other to green, and simply load one or the other when it is time for me to draw a particular object in my OpenGL scene.
I can't seem find any information on which one of these strategies is better, though. I might expect the first strategy, putting all the complexity of what to render on the graphics card, to be more performant, but in the sorts of cases I'm thinking of deciding what to draw isn't a per-pixel calculation and doesn't benefit from parallelization. I don't really understand how the shader programs run on the graphics card and what the costs of linking and passing variables are, so I'm not sure that my intuition is actually correct here.
Upvotes: 4
Views: 1231
Reputation: 1452
I've looked for answers on this topic a while ago, too. What I've gathered from a few different games and books is that you'd generally use different shaders.
You can compile all needed shader programs once and make every object-to-be-drawn switch to the required shader program:
void Draw(){
glUseProgram(yourShaderProgram);
glUniformX(yourUniformVariables);
glDrawArrays(yourVAO);
}
What you do NOT want to do is load and link the shader program everytime you need it.
Rather, keep a list of all shader programs somewhere, or pass the program's id to each objects so they can make use of it.
Upvotes: 2