Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic bind in OpenGL object wrapper

Tags:

c++

opengl

I tend to wrap OpenGL objects in their own classes. In OpenGL there is the concept of binding, where you bind your object, do something with it and then unbind it. For example, a texture:

 glBindTexture(GL_TEXTURE_2D, TextureColorbufferName);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1000);
 glBindTexture(GL_TEXTURE_2D, 0);

Wrapping this would be something like:

texture->bind();
    texture->setParameter(...);
    texture->setParameter(...);
texture->unBind();

The problem here, is that I want to avoid the bind() and unBind() functions, and instead just be able to call the set methods and the GLObject will be bound automaticly.

I could just do it in every method implementation:

public void Texture::setParameter(...)
{
    this.bind();
    // do something
    this.unBind();
}

Though then I have to do that for every added method! Is there a better way, so it is automatically done before and after every method added?

like image 933
Morgan Bengtsson Avatar asked Feb 22 '23 06:02

Morgan Bengtsson


1 Answers

Maybe a context object may help here. Consider this small object:

class TextureContext {
public:
    TextureContext(char* texname) {
        glBindTexture(GL_TEXTURE_2D, texname);
    }
    ~TextureContext() {
        glBindTexture(GL_TEXTURE_2D, 0);
    }
};

This object is now used within a scope:

{
    TextureContext mycont(textname);
    mytexture->setParameter(...);
    mytexture->setParameter(...);
    mytexture->setParameter(...);
}

the object mycont only lives in the scope and calls its destructor (ant the unbind method respectively) automatically once the scope is left.

EDIT:

Maybe you can adjust the TextureContext class to take your Texture instance instead in the constructor and retrieves the texture name itself before binding the texture.

like image 115
Constantinius Avatar answered Mar 05 '23 05:03

Constantinius