Wednesday, July 17, 2019

c++ - Where to store OpenGL object id:s


When working with OpenGL, you often recieve integer id:s to keep track of OpenGL objects.


For example, representing a simple mesh, you may have a number of references to objects like so:



GLuint arrayBuffer;
GLuint elementArrayBuffer;
GLuint texture;

Having many meshes, the id:s add up quickly. Therefore my problem is, where it is most logical and efficient to store them?


Alternative 1


My first thaught was to hand out the id:s to corresponding game entities. Something along the lines:


class Entity {
public:
GLuint arrayBuffer;

GLuint elementArrayBuffer;
GLuint texture;
// Other methods...
}

Then having a render class:


// Create the buffers and textures and pass id:s to entity.
renderer.init(entity);
// Render with corresponding buffer/texture id:s stored in entity
renderer.render(projection, view, entity);


Where it then is easy enough, in the implementation of the render method, just picking id:s and render with them.


Some disadvantages is that this is a leaky abstraction, where OpenGL concepts are "leaked" to game entities. Which does not feel quite right. An advantage might be that the method supposedly is efficient. You do not have to find id:s, you know them for each rendering pass.


Alternative 2


Another alternative would be to store the id:s internally in the renderer. For example, an internal data struct:


struct RenderData {
GLuint arrayBuffer;
GLuint elementArrayBuffer;
GLuint texture;
}


Then having an unordered map with references to each entity and corresponding RenderData:


std::unordered_map render_data;

Then in the rendering method, the correct render data is fetched from the map only by a unique id that is stored in each entity.


Advantages of this approach, is that it is less "leaky", where only the entity id is passed to the renderer, to know what data to use. Disadvantages may be slightly less efficiency, because of lookups in the unordered map?


I would greatly appreciate inputs on this, what approach to prefer, or if there are any other approaches out there?




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...