Search code examples
c++opengltextures

How do you "free" a texture unit?


In order to use a texture unit, we usually bind it to the current process more or less like this:

glUseProgram(program);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureID);

GLint loc = glGetUniformLocation(program, "uniform");
//error check

glUniform1i(loc,0);

How do you "free" the texture unit. In other words how do you detach the texture from the texture unit binding point in the current program?


Solution

  • How do you "free" the texture unit. In other words how do you detach the texture from the texture unit binding point in the current program?


    You can't "free" the texture unit, but you can bind the default texture object to the texture unit.

    See OpenGL 4.6 API Compatibility Profile Specification; 8.1 Texture Objects; page 178:

    Textures in GL are represented by named objects. The name space for texture objects is the unsigned integers, with zero reserved by the GL to represent the default texture object.

    ...

    The binding is effected by calling

    void BindTexture( enum target, uint texture );
    

    with target set to the desired texture target and texture set to the unused name.

    This means

    GLuint defaultTextureObjectID = 0;
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, defaultTextureObjectID);
    

    will bind the default texture object to texture unit 0.


    Since OpenGL 4.5 it can be used glBindTextureUnit

    The command

    void BindTextureUnit( uint unit, uint texture );
    

    binds an existing texture object to the texture unit numbered unit. texture must be zero or the name of an existing texture object. When texture is the name of an existing texture object, that object is bound to the target, in the corresponding texture unit, that was specified when the object was created.

    So you can use the following too:

    glBindTextureUnit( 0, 0 ); // texture unit 0, default texture object (0)