I am having a problem getting my vertex array pointed to properly:
const float vertices[] = { /* position */ 0.75f, 0.75f, 0.0f, 1.0f, /* color */ 1.0f, 0.0f, 0.0f, 1.0f, /* position */ 0.75f, -0.75f, 0.0f, 1.0f, /* color */ 0.0f, 1.0f, 0.0f, 1.0f, /* position */ -0.75f, -0.75f, 0.0f, 1.0f, /* color */ 0.0f, 0.0f, 1.0f, 1.0f, }; ... glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, (void*)16); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1);
I do not understand how stride and offset work.
What is the correct way of going about using glVertexAttribPointer()
in my situation?
Stride and offset are specified in bytes. You are using an interleaved vertex array with position and color both as 4 floats. To get from th i-th element in a particular attribute array to the next one, there is the distance of 8 floats, so stride should be 8*sizeof(GLfloat). The offset is the byte position of the first element of each attribute array in the buffer, so in your example for position it is 0, and for color, it is 4*sizeof(GLfloat)
Since glVertexAttribPointer often make troubles, I try to further explain it here.
The formula to calculate the start pos of the i-th attribute in attributes array is :
startPos(i) = offset + i * stride
(From derhass' another answer)And explained in the graph below :
If you need code example, continue reading.
From Formatting VBO Data, we know we can manage our vertex data in three format. Make a example of drawing a triangle , with vert color and texture color mixed, here is the way to prepare vert attribute data:
#way1 Each attribute a VBO.
this format like : (xyzxyz...)(rgbrgb...)(stst....), and we can let both sride = 0 and offset = 0.
#way2: Each attribute is sequential, batched in a single VBO.
this format is like: (xyzxyzxyz... rgbrgb... ststst...), we can let stride=0 but offset should be specified.
#way3: Interleaved attribute in a single VBO
this format is like: (xyzrgbstxyzrgbst...),we have to manually specify the offset and stride .
And thanks for derhass's answer.