Home > OS >  Is it okay to bind the same OpenGL object twice?
Is it okay to bind the same OpenGL object twice?

Time:08-03

I've been writing some code to check if a texture, buffer, or shader is currently bound, and avoid binding it twice if it is.

if (lastShaderBound != shaderName) {
    lastShaderBound = shaderName);
    glUseProgram(shaderName);
}

However, there's a potential pitfall; if any of these objects are deleted while bound, OpenGL will implicitly unbind them and allow their GLuint name to be reused. This could result in my "state" of what's bound diverging from OpenGL's, (unless I try to duplicate this behavior, which is fairly complex).

I'm wondering if any of this is even necessary? If OpenGL is smart enough to unbind deleted buffers, perhaps it's already doing what I'm trying to do, or perhaps it's not the binding calls that are expensive in the first place?

Should I just freely bind things without worrying about the same thing being bound multiple times in a row?

CodePudding user response:

It is technically legal to bind the same shader or texture again.

There would be costs associated with either binding overheads or branching.

Consider following code

QElapsedTimer elapsetimer;
    elapsetimer.start();
    ResourceManager::GetShader("Screen").Use();  // glUseProgram(this->ID);
    for (int i = 0; i < 1000; i  ) {
        if (ResourceManager::GetShader("Screen").ID != id)
            ResourceManager::GetShader("Screen").Use();
    }

    qDebug() << elapsetimer.nsecsElapsed(); 

If i use branching condition than i have about 2000 - 3000 nanoSeconds lesser than binding the shader(very basic shader program) again and again.

But this will vary based from shader to shader.

On my platform branching is cheaper than binding the shader again , but for this difference i have to have atleast 1000 iterations.

  • Related