10

Short:

Can I define a function that every shader can use? Or I have to define it per shader?


The whole story:

So the ramps need to be defined ONCE per shader, and the function should be defined all at once that every shader can use safely.

I have the algorithms, the question is for sharing functions, and define constants in GLSL.

Is this possible? Or I have to copy the function into every shader? Is there some precompile option at least?

Geri Borbás
  • 15,810
  • 18
  • 109
  • 172

1 Answers1

16

You can do that similarly as in C - you declare functions in headers and define it in common C file.

In GLSL you'll need to do following:

  1. in some shader (string) you define function (lets call it COMMON):

    float getCommonValue() { return 42; }
    
  2. in all shaders you want to use this function you only declare it and use it (lets call it SHADER1):

    float getCommonValue();
    void main() { gl_Color = vec4(getCommonValue(), 0, 0, 0); }
    
  3. when compiling shaders with glCompileShader you compile COMMON shader only once and store shader GLuint somewhere

  4. when you link program with glLinkProgram for SHADER1 you attach to program with glAttachShader both shaders - COMMON and SHADER1. Thus you'll be able to call getCommonValue function from one shader to other.

  5. you can reuse COMMON shader GLuint value multiple times for different sahder programs (SHADER1, SHADER2, ...).

Mārtiņš Možeiko
  • 12,733
  • 2
  • 45
  • 45
  • Whoa, sounds nice, I'll try it. – Geri Borbás May 06 '12 at 00:18
  • 5
    What should the type of the `COMMON` shader be when we create the shader? – uucp Mar 19 '18 at 23:49
  • 1
    I have the same question as @UltimatePea. Should the shared shader be vertex, fragment, or does it not matter? – Chuck Oct 05 '18 at 04:21
  • I haven't tried this but the [ES 2.0 spec](https://www.khronos.org/registry/OpenGL/specs/es/2.0/es_full_spec_2.0.pdf) states `Multiple shader objects of the same type may not be attached to a single program object`. – LJᛃ Jul 26 '19 at 12:42