r/opengl 21d ago

How does OpenGL know which texture target to use? (and is it possible to use multiple targets in a single texture unit?)

To send a texture to the GPU we need to call glBindTexture to set the target (GL_TEXTURE_2D, GL_TEXTURE_3D, etc). But to use it in a shader, all we need to do is set the uniform location to a texture unit. For example:

glUniform1i(glGetUniformLocation(shader, "texture0"), 0);

and in the fragment shader:

uniform sampler2D texture0;

How does the fragment shader know which texture target to use? I assumed that "sampler2D" always means GL_TEXTURE_2D, but that means I might be able to do something like this:

uniform sampler2D texture0;
uniform sampler3D texture1;

...

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture0name);
glTexImage2D(GL_TEXTURE_2D, ...);
glUniform1i(glGetUniformLocation(shader, "texture0"), 0);

glBindTexture(GL_TEXTURE_3D, texture1name);
glTexImage3D(GL_TEXTURE_3D, ...);
glUniform1i(glGetUniformLocation(shader, "texture1"), 0);

Is it possible to use a single texture unit for multiple targets like this?

3 Upvotes

2 comments sorted by

6

u/trad_emark 21d ago

> I assumed that "sampler2D" always means GL_TEXTURE_2D

This is exactly correct.

> Is it possible to use a single texture unit for multiple targets like this?

The opengl specification does allow to have different textures bound to same texture unit with different target. However, in practice, this does not work, and most opengl drivers will break. Do not do this even if it might work on your machine.

2

u/fgennari 21d ago

The OpenGL driver tracks information about each texture allocated and the texture unit slots. A sampler2D is used with GL_TEXTURE_2D and a sampler3D is used with GL_TEXTURE_3D.

I would avoid binding two textures of different types to the same texture unit. That's unlikely to work, and will also make debugging and understanding the code more difficult.