Okay I have the following code that works correctly. It loads a vertex array, a normal array and a vertex index array then draws them with some simple light shading.
To load the buffers:
//Load Buffers
//vertices
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(verts), &verts[0], GL_STATIC_DRAW); //verts is std::vector<float>
//normals
glGenBuffers(1, &normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(normals), &normals[0], GL_STATIC_DRAW); //normals is std::vector<float>
//indices
glGenBuffers(1, &elementbuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLushort), &indices[0] , GL_STATIC_DRAW);
//indices is std::vector<unsigned short> and in this working example only
//contains indices into the vertex array (I will add interleaved normal indices)
To draw the buffers:
//Draw Object
glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_NORMAL_ARRAY );
//vertices
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);
//Indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
//Normals
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glNormalPointer(GL_FLOAT, 0, (void*)0 );
//Draw the mesh
glDrawElements( GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, (void*)0);
//Clean up
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
In this code, normals are not indexed. I would like to change it so that the normals are based on the the index in indices[]
(same as vertices are now). indices[]
is interleaved (not in the above code) as such: {vertex index,normal index,vertex index,normal index...}.
I've been trying to get this to work for some time without success and every example I've found online seems to use a different approach to VBOs making it very difficult to combine multiple examples into one that does what I need.
Help would be greatly appreciated. And if I'm doing anything in a less than ideal way, I'm open to suggestions.