Using a single texture image unit with multiple sampler uniforms

Posted by bcrist on Stack Overflow See other posts from Stack Overflow or by bcrist
Published on 2013-10-20T02:11:26Z Indexed on 2013/10/20 3:54 UTC
Read the original article Hit count: 148

Filed under:
|
|

I am writing a batching system which tracks currently bound textures in order to avoid unnecessary glBindTexture() calls. I'm not sure if I need to keep track of which textures have already been used by a particular batch so that if a texture is used twice, it will be bound to a different TIU for the second sampler which requires it.

Is it acceptable for an OpenGL application to use the same texture image unit for multiple samplers within the same shader stage? What about samplers in different shader stages? For example:

Fragment shader:

...
uniform sampler2D samp1;
uniform sampler2D samp2;

void main() { ... }

Main program:

...
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_id);
glUniform1i(samp1_location, 0);
glUniform1i(samp2_location, 0);
...

I don't see any reason why this shouldn't work, but what about if the shader program also included a vertex shader like this:

Vertex shader:

...
uniform sampler2D samp1;

void main() { ... }

In this case, OpenGL is supposed to treat both instances of samp1 as the same variable, and exposes a single location for them. Therefore, the same texture unit is being used in the vertex and fragment shaders. I have read that using the same texture in two different shader stages counts doubly against GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS but this would seem to contradict that.

In a quick test on my hardware (HD 6870), all of the following scenarios worked as expected:

  • 1 TIU used for 2 sampler uniforms in same shader stage
  • 1 TIU used for 1 sampler uniform which is used in 2 shader stages
  • 1 TIU used for 2 sampler uniforms, each occurring in a different stage.

However, I don't know if this is behavior that I should expect on all hardware/drivers, or if there are performance implications.

© Stack Overflow or respective owner

Related posts about opengl

Related posts about glsl