OpenGL ES 2.0 Multiple Programs or Multiple Shaders or what? How does it work?

Robert Massaioli picture Robert Massaioli · Feb 9, 2012 · Viewed 14.6k times · Source

The Problem (TL;DR)

My problem, fundamentally, is that I do not know how OpenGL ES 2.0 expects me to write and use multiple shaders; or if it is even advisable/expected that a person will do so.

The fundamental question here is: if I have an apple, a glowing rock and a fuzzy mesh, all in the same 3D world, all best drawn with different shader programs but using the same mvpMatrix then how would I go about using all of them in the same OpenGL render such that they all use their most appropriate shaders that I have written?

What Have I done

So I have written a basic OpenGL ES 2.0 program for my Android Game that works perfectly in that it can draw the outline of the objects to the screen. But it does nothing else; pretty much because the shaders look like this:

Vertex Shader

uniform mat4 uMVPMatrix;
attribute vec4 aPosition;

void main() {
    gl_Position = uMVPMatrix * aPosition;
}

Fragment Shader

void main() {
    gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}

Now they are pretty basic. The reason that I have not gone further is because I cannot figure out if I am supposed to write one shader to apply to all of my different objects or if I am supposed to use multiple shaders. And if I am supposed to use multiple shaders to draw multiple different objects then how do I go about doing that in an efficient way?

I get the feeling that this must be basic knowledge to anybody that does OpenGL ES 2.0 day in and day out so I am hoping that somebody can answer my question or point me in the right direction.

I have:

  • Looked at multiple tutorials; none of which use anything but the most basic shaders.
  • Read the entire OpenGL ES 2.0 GLSL Spec (none of which mentioned how it was intended to be used; it was just about what everything did rather than how it fits together).
  • Tried to modify my shaders a bit.

So I'm hoping that I am close to understanding the OpenGL workflow but I don't seem to be there yet.

Edit: I found this well afterwards:

If your application is written for OpenGL ES 2.0, do not create a single shader with lots of switches and conditionals that performs every task your application needs to render the scene. Instead, compile multiple shader programs that each perform a specific, focused task.

That is from the iOS OpenGL ES 2.0 guidelines.

Answer

Jave picture Jave · Feb 9, 2012

You can use multiple shaders, but to switch between them can be quite costly so the recommended practise is to draw every object of a shader, then switch to the next shader and draw all the objects using that one and so on.
To switch between shaders, you call glUseProgram().