简体   繁体   中英

OpenGL and C++: Real-Time Handling and Binding Buffers?

I have been toying with OpenGL for about 2 weeks, creating hardcoded VBOs and making rotating triangles, but the question that has been lingering in my head is how the heck do I create more than one VBO/VAO in real-time so I can handle multiple objects? And how do I render multiple objects on the screen? The binding system seems limiting and restrictive. Eventually, I want to be able to create objects and draw them using a single Lua function. Sorry for the no-code post, but I have no code to begin with as I am trying to figure this out conceptually.

When you said that the OpenGL binding system is limiting and restrictive you where right, it is. However, it is easy to get used to. Your workflow when dealing with GL objects consists basically of:

  • Bind resource
  • Use (draw/modify/query)
  • Unbind resource

Now, going into specifics, how would you model a C++ class that encapsulate a VAO/VBO? One very simple way, with implicit binding, could be:

class MyVAO {
public:

    void Draw()
    {
        glBindVertexArray(vao);
        glDrawElements(...);
        // etc...
        glBindVertexArray(0);
    }

private:

    GLuint vb, ib, vao;
};

// Then in the client code:
MyVAO vao;
...
vao.Draw();

With explicit binding:

class MyVAO {
public:

    void Bind()
    {
        glBindVertexArray(vao);
    }

    void Unbind()
    {
        glBindVertexArray(0);
    }

    void Draw()
    {
        glDrawElements(...);
        // etc...
    }

private:

    GLuint vb, ib, vao;
};

// Then in the client code:
MyVAO vao;
...
vao.Bind();
vao.Draw();
vao.Unbind();

The choice of explicit or implicit binding is yours. Implicit binding automates the work a bit, but it can be wasteful when you are sharing resources in the code. It can also lead to some hard to track bugs if you forget to bind/unbind inside the class implementation. Explicit binding allows you to do things like leaving a resource bound for a long time and use it for a while, but it can be a nightmare to debug cases when you forget to bing/unbind the resource yourself.

I personally tend to prefer the explicit binding though. I dislike having things happening behind the curtains. I prefer to know when a resource is current. But ultimately, you should choose the best fit for your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM