# Using index arrays with OpenGL VBOs

If, for example, I want to draw a cube using VBOs, can I use one VBO to hold the coordinates for the 8 vertices, and another one as an index array, to specify the order in which the vertices are drawn?

If it's possible I'd appreciate some help on the matter, or a link to good tutorial you may know on the subject.

Thanks.

You want to do something like:

glBindBuffer(GL_ARRAY_BUFFER, vertex_id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_id);
glDrawElements(GL_TRIANGLES, num_indices, index_type, 0 /*index_offset*/);


where index_type is something like GL_UNSIGNED_SHORT, depending on what kind of data your index buffer contains.

This asumes you have created your two buffers and filled them with data already, and are using the builtin glsl attributes or fixed function pipeline. If you have specified your own attribs in the vertex program you will need to call

glBindAttribLocation(program_id, 0 /*index*/, "position");


before linking the program to register position as attrib 0, and then call

glVertexAttribPointer(0 /*index*/, 3 /*num_elems*/, GL_FLOAT, GL_FALSE, 0, 0);


Filling is done with

glGenBuffers(1, &vertex_id);
glBindBuffer(GL_ARRAY_BUFFER, vertex_id);
glBufferData(GL_ARRAY_BUFFER, num_bytes, data, GL_STATIC_DRAW);


Same thing for index data, but with GL_ELEMENT_ARRAY_BUFFER as target instead. You can change GL_STATIC_DRAW to something else depending on your usage patterns.

From OpenGL.org :

Vertex data can be either vertex attributes and/or indices.'


So yes, you can store vertices and indices on your VBO's.

NeHe tutorials are generally a good resource, for tutorials, maybe you can find your joy here.

• Outdated, however. – The Communist Duck May 31 '11 at 16:45
• Indeed, the basics of actual OpenGL programming are rarely completely overhauled so even old Tuts can be useful. – Jonathan Connell Jun 1 '11 at 8:19