Apollo503
Apollo503

Reputation: 13

How do I pass uniforms between different shader programs in OpenGL?

I'm wondering if there is a way to communicate data between two separate shader programs.

I have one geometry shader that uses a uniform float, and I would like to send the value of that float to a fragment shaders that is used by another program.

Is this possible? I know that OpenGL uses pre-defined global variables, but is there a way to create my own?

Geometry shader from program 1:

uniform float uTime;

Fragment shader from program 2:

if (uTime > 0.){
...
}

Upvotes: 0

Views: 1402

Answers (1)

httpdigest
httpdigest

Reputation: 5797

I would like to send the value of that float to a fragment shaders that is used by another program. Is this possible?

There is no "interface" between different shader programs.

If you want to use the same uniform in your second shader program, then you simply need to declare and upload that same uniform in your second shader program, just like you did it for your first shader program.

(I am not getting into uniform buffer objects for the rest of this answer, since you used top-level uniform variables in the unnamed block. But, you can use a uniform buffer object holding your uniform values, which you then bind to both shader programs.)

So: Declare the uniform in the fragment shader of your second shader program just like you did with the geometry shader of your first shader program:

uniform float uTime;

void main(void) {
  ...
  if (uTime > 0.){
    ...
  }
  ...
}

Then, as usual, compile and link that program and obtain the location of the uniform in that second shader program via glGetUniformLocation() once:

// do once:
GLint uTimeLocationInSecondShaderProgram = glGetUniformLocation(yourSecondShaderProgram, "uTime");

and then send a value to the uniform via e.g. glUniform1f() whenever the value changes (e.g. once per render loop iteration):

// do before drawing:
float time = ...; // <- whatever time you also used in your first shader program
glUseProgram(yourSecondShaderProgram);
glUniform1f(uTimeLocationInSecondShaderProgram, time);

Upvotes: 1

Related Questions