I am trying to make a mesh class using a vao and a vbo.
First I create vectors to hold the data to be buffered:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texCoords;
std::vector<GLushort> indices;
I store data from a file and then I create the buffers:
// Vertex array
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// Vertex buffer
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
// Index buffer
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
I try to fill the buffers like this:
// Reserve space on the GPU (3 GLfloats per vertex, 3 per normal and 2 per texCoord)
glBufferData(GL_ARRAY_BUFFER, vertices.size() * 8 * sizeof(GLfloat), NULL, GL_STATIC_DRAW);
// Load data to the GPU
// Insert vertices at the beginning of the buffer
glBufferSubData(GL_ARRAY_BUFFER, NULL, vertices.size()*3*sizeof(GLfloat), &vertices);
// Insert normals behind vertices
glBufferSubData(GL_ARRAY_BUFFER, vertices.size()*3*sizeof(GLfloat), normals.size()*3*sizeof(GLfloat), &normals);
// Insert texCoords behind normals
glBufferSubData(GL_ARRAY_BUFFER, (vertices.size() + normals.size())*3*sizeof(GLfloat), texCoords.size()*2*sizeof(GLfloat), &texCoords);
// Load the index buffer
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size()*3*sizeof(GLushort), &indices, GL_STATIC_DRAW);
It breaks when I try to buffer the normal data:
glBufferSubData(GL_ARRAY_BUFFER, vertices.size()*3*sizeof(GLfloat), normals.size()*3*sizeof(GLfloat), &normals);
I get this error:
Unhandled exception at 0x699CEF38 (nvoglv32.dll) in Engine.exe: 0xC0000005: Access violation reading location 0x05C34000.
I have been searching for a while now but I still haven't found a solution. Any information regarding any mistakes I have made are very welcome.
Thanks in advance, Me
The glaring mistake is this:
glBufferSubData(GL_ARRAY_BUFFER, NULL, vertices.size()*3*sizeof(GLfloat), &vertices);
To get the data within the vector, you pass the address of the first element, not a pointer to the vector:
glBufferSubData(GL_ARRAY_BUFFER, NULL, vertices.size()*3*sizeof(GLfloat), &vertices[0]);
You make the same error in the other lines that call glBufferSubData
, including the line where it finally breaks down where you are using the normals
vector.
Also, the vector has to be non-empty before using &vertices[0]
, or if using C++11, you can use the vertices.data()
function instead of &vertices[0]
.