i’m having this issue with VBO’s that I don’t really understand. My problem is solved by accidentally changing the last parameter in the glVertexAttribPointer method call. So, I’m looking for an answer as to WHY this is suddenly working or why my previous code isn’t working anymore. (just to get a better understanding on opengl)
Struct:
typedef struct
{
float position[3];
float color[4];
} Vertex;
Without VBOs:
// Get pointers to the data
GLsizei stride = sizeof(Vertex);
const GLvoid *pCoords = &squareVertices[0].position[0];
const GLvoid *pColors = &squareVertices[0].color[0];
// Setup pointers to positions and colors
glVertexAttribPointer(positionSlot, 3, GL_FLOAT, GL_FALSE, stride, pCoords);
glVertexAttribPointer(colorSlot, 4, GL_FLOAT, GL_FALSE, stride, pColors);
// Draw
glDrawArrays(GL_TRIANGLES, 0, sizeof(squareVertices) / sizeof(Vertex));
With VBOs (this gives me an EXC_BAD_ACCESS)
// Stide
GLsizei stride = sizeof(Vertex);
// Setup pointers to positions and colors
glVertexAttribPointer(positionSlot, 3, GL_FLOAT, GL_FALSE, stride, 0);
glVertexAttribPointer(colorSlot, 4, GL_FLOAT, GL_FALSE, stride, (GLvoid*) (sizeof(float) * 3));
// Draw
glDrawElements(GL_TRIANGLES, sizeof(squareIndices) / sizeof(squareIndices[0]), GL_UNSIGNED_BYTE, 0);
So, the only thing that actually differs is the glVertexAttribPointer call which had a pointer to the data and now has fixed numbers. Can anyone elaborate on this? Thanks in advance.
When a VBO is active, the last parameter to
glVertexAttribPointeris not really a pointer, but the offset inside the vertex buffer object type-cast to a pointer. That’s how VBOs work: the data has been copied to some memory managed by the graphics driver, you don’t know its address. In fact, it might not even have a normal address when it’s stored somewhere on your graphics card.The rest is cheating around the C/C++ type system. The type system is nowhere near smart enough to understand that
glVertexAttribPointer‘s last argument should be a pointer-sized integer offset when a VBO is active, and a pointer otherwise. So to the C++ compiler, this has to look like a pointer all the time, because that is howglVertexAttribPointer(or rather, it’s predecessorsglVertexPointerand friends) where defined originally. When it is really just a number, we just use a type cast to cheat the compiler.