Search code examples
opengltexturesshader

OpenGL reading from unbound texture unit


Does the OpenGL standard mandate what the result of a texture2d operation should be given a uniform sampler2D that the program hasn't bound to a texture unit?

For example in the pixel shader:

layout(binding=0) uniform sampler2D Map_Diffuse;
...
texture2D(Map_Diffuse, attrib_Fragment_Texture)

Where in the program:

::glActiveTexture(GL_TEXTURE0); 
::glBindTexture(GL_TEXTURE_2D, 0);

For context I'm wondering whether I can use the same shader for textured and non-textured entities, where (hopefully) I only need to make sure nothing is bound to GL_TEXTURE_2D for texture2d() to return 0, 0, 0, 1. Otherwise I'll need one shader for each permutation.


Solution

  • The way I read the spec, it's guaranteed to return black. The following quotes are copied from the 3.3 spec.

    In section 2.11.7 "Shader Execution" under "Vertex Shaders", on page 81:

    Using a sampler in a vertex or geometry shader will return (R,G,B,A) = (0,0,0,1) if the sampler’s associated texture is not complete, as defined in section 3.8.14.

    and equivalent in section 3.9.2 "Shader Execution" under "Fragment Shaders", on page 188:

    Using a sampler in a fragment shader will return (R,G,B,A) = (0,0,0,1) if the sampler’s associated texture is not complete, as defined in section 3.8.14.

    In section 3.8.14 "Texture Completeness", it says:

    A texture is said to be complete if all the image arrays and texture parameters required to utilize the texture for texture application are consistently defined.

    Now, it doesn't explicitly say anything about texture objects that don't even exist. But since texture names that don't reference a texture object (which includes 0) certainly don't have "all the image arrays and texture parameters consistently defined", I would argue that they fall under "not complete" in the definitions above.