Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GLSL reusable/shared functions, shared constants (OpenGL ES 2.0)?

Short:

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


The whole story:

  • I want to create numerous shaders intended to colorize the input fragments with predefined gradient ramps (something like this - http://www.thinkboxsoftware.com/storage/krakatoa-support-images/krakatoa15_kcm_densitybyage_gradientrampmap.png).

  • I want to define a gradient ramp constant for each shader (an array of vec4 color samples, where the alpha value holds the gradient position, see Pos in the picture above)

  • And I need a function that can return a color sample from the given gradient ramp for a particular texture coordinate position.

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?

like image 500
Geri Borbás Avatar asked May 05 '12 16:05

Geri Borbás


1 Answers

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, ...).

like image 71
Mārtiņš Možeiko Avatar answered Oct 19 '22 20:10

Mārtiņš Možeiko