OpenGL: storing index/vertex data together inside a single buffer

With modern OpenGL, it is possible to store index and vertex data together in a single buffer. Here is a short code snipped showing how to do this (Direct State Access for OpenGL 4.5+).

Lets assume our data is initially loaded in these two vectors.

vector<vec3> positions;
vector<unsigned int> indices;
...

First, let’s create a new buffer and upload everything into it.

const size_t sizeI = sizeof(unsigned int) * indices.size();
const size_t sizeV = sizeof(vec3) * positions.size();

GLuint buf;
glCreateBuffers(1, &buf);
glNamedBufferStorage(buf, sizeI + sizeV, nullptr, GL_DYNAMIC_STORAGE_BIT);
glNamedBufferSubData(buf, 0, sizeI, indices.data());
glNamedBufferSubData(buf, sizeI, sizeV, positions.data());

Create and set up a new VAO.

GLuint vao;
glCreateVertexArrays( 1, &VAO);

Now we can tell OpenGL that our indices should be read from the same buffer and the offset of our vertex data from the beginning of the buffer is equal to sizeI.

glVertexArrayElementBuffer(vao, buf);
glVertexArrayVertexBuffer(vao, 0, buf, sizeI, sizeof(vec3));
glEnableVertexArrayAttrib(vao, 0);
glVertexArrayAttribFormat(vao, 0, 3, GL_FLOAT, GL_FALSE, 0);
glVertexArrayAttribBinding(vao, 0, 0);

That’s it. Rendering with glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, nullptr); just works as expected.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.