Why a program can have more than one shader?

I recently added shader support for my little OpenGL engine.
I’m wondering why you can attach more than one shader of the same type (fragment or vertex) to a program?

I tried to code a function in a fragment shader and then use that function in the shader wich defines the main() method (both shaders are attached to same program, of course), but it gave me an error. How can I use a shader’s function from another? (sort of C #include)

Thanks

Each shader type can only have one shader with a main function. But you can use other shaders of the same type that contain other functions (helper functions for your main function). You have to declare the other functions in your main function. It works like this:


// main shader

// declare function
float my_calculation_function(vec4);

void main(void)
{
   // use your other function
   float result = my_calculation_function(vec4(1.0));
}

The code for the other shader looks like this:


float my_calculation_function(vec4 input)
{
   float result = 0;
   // do the magical calculation
   return result;
}

This should work. Its from the top of my head, so if it doesn’t, have a look in the glsl specification to see if anything was wrong (perhaps function declarion). But I think this is ok.

Ah, i see. You have to declare the function prototype in the main shader. Thanks!

I advice you to allow a program contain any number of shaders of any type:
-there can be no fragment attachment
-there usually no geometry attachment
-most of programs include your ‘toolkit’ shaders, that contain commony shared code (quaternion operations, perspective transforms, etc)

This topic was automatically closed 183 days after the last reply. New replies are no longer allowed.