I would like to have two pixel shaders; the first doing one thing, and then the next doing something else. Is this possible, or do I have to pack everything into the one shader?
3 Answers
You can do do this, e.g. by doing function calls from the main entrypoint to functions that are implemented in the various shader objects.
main() {
callToShaderObject1()
callToShaderObject2()
}
each of those callToShaderObject functions can live in different shader objects, but all objects have to be attached and linked in the same program before it can be used.

- 17,760
- 43
- 62
-
1Out of curioisity, why would you do this, as opposed to simply having all functions in the fragment shader in question? Is this so that code could be shared with other shader programs, without necessitating duplication? – Engineer Jul 15 '12 at 09:35
-
@Nick: I've not seen it used myself. I was surprised when I first read the spec at the idea to build shader programs out of shader objects - hence why I know you _can_ do it. It was built from the standard compile model... – Bahbar Jul 15 '12 at 18:39
-
3Update: I've seen this in use now, while studying modded MineCraft shaders. In that case, it was quite useful as each shader has a lot of options that may be turned on and off, with various effects operating in conjunction with various others. In a scenario like that, and where multiple authors are involved, it becomes a lot more useful to separate functions into separate files. – Engineer Oct 07 '12 at 10:53
-
1Note that you need to declare the function header in the shader were it is used. – wedesoft Jan 27 '22 at 22:12
They can't run at the same time, but you are free to use different shaders for different geometry, or to render in multiple passes using different shaders.

- 820
- 6
- 12
-
1So would that require a different program? So a different program for each pass? As in, I could have a vertex and fragment shader on one program (which is one pass?) and then have a vertex and fragment shader on another program (the second pass?)? Can I just change glUseProgram() when I feel like it? So I'm essentially rendering a scene twice...? – Harry Feb 26 '10 at 21:22
-
1Exactly right. Just like a multi-pass render in fixed pipeline, but instead of changing openGL settings between passes, you're loading different programs. – Michael Daum Mar 01 '10 at 14:20
The answer depends on the GL version, you need to check glAttachShader
documentation for the version you are using. GLES versions (including webgl) do not allow attaching multiple fragment shaders to a single program and will raise GL_INVALID_OPERATION error when attempted.
It is permissible to attach multiple shader objects of the same type because each may contain a portion of the complete shader.
glAttachShader - OpenGL ES 3.2:
It is not permissible to attach multiple shader objects of the same type.

- 1,064
- 1
- 11
- 20