Index Buffers in OpenGL - hls333555/OpenGL GitHub Wiki
Consider drawing a square, you need to draw two triangles which make up a square. If we draw it like below, you will notice that there are two vertices actually being drawn twice which is a waste of memory.
We can use index buffer to solve this. An index buffer is something that allows to reuse existing vertices.
Here are the main steps:
-
Remove any duplicate vertices from the vertex array, now the array should look something like this:
float positions[] = { -0.5f, -0.5f, // 0 0.5f, -0.5f, // 1 0.5f, 0.5f, // 2 -0.5f, 0.5f // 3 };
-
Add an index array which contains index of vertex according to the above vertex array to draw each triangle:
unsigned int indices[] = { 0, 1, 2, 2, 3, 0 };
-
Replace
glBufferData(GL_ARRAY_BUFFER, 3 * 2 * sizeof(float), positions, GL_STATIC_DRAW);
with:
glBufferData(GL_ARRAY_BUFFER, 4 * 2 * sizeof(float), positions, GL_STATIC_DRAW);
-
Send the index buffer to the GPU, note there are several differences from vertex buffer version:
// Index buffer object unsigned int ibo; // Generate index buffer object names glGenBuffers(1, &ibo); // Bind a named index buffer object glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); // Create and initialize an index buffer object's data store. glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * sizeof(unsigned int), indices, GL_STATIC_DRAW);
-
Finally, replace
glDrawArrays(GL_TRIANGLES, 0, 3);
with:
// The count is actually the number of indices rather than vertices // Since index buffer is already bound to GL_ELEMENT_ARRAY_BUFFER, we do not need to specify the pointer to indices glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
That's it! Here is the final result: