问题
I've just read through a tutorial about Vertex Array Objects and Vertex Buffer Objects, and I can't work out from the following code how OpenGL knows the first VBO (vertexBufferObjID[0]
) represents vertex coordinates, and the second VBO (vertexBufferObjID[1]
) represents colour data?
glGenBuffers(2, vertexBufferObjID);
// VBO for vertex data
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjID[0]);
glBufferData(GL_ARRAY_BUFFER, 9*sizeof(GLfloat), vertices, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
// VBO for colour data
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjID[1]);
glBufferData(GL_ARRAY_BUFFER, 9*sizeof(GLfloat), colours, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
Edit: Thanks to Peter's answer, I found the following two lines of code which hook up each VBO with the shaders (indices 0 & 1 correlate to the VBO index):
glBindAttribLocation(programId, 0, "in_Position");
glBindAttribLocation(programId, 1, "in_Color");
回答1:
It doesn't, you have to tell it which is which in the shader.
layout(location = 0) in vec3 position;
layout(location = 1) in vec3 color;
void main()
{
/* ... */
}
回答2:
glVertexAttribPointer
is only meant to be used with shaders. Therefore you, as the shader writer, always know what each attribute index is supposed to do, as it maps to a certain variable in your vertex shader. You control the index to variable map with commands glBindAttribLocation
or glGetAttribLocation
, or from special keywords inside GLSL.
If you're just using the fixed function pipeline (default shader), then you don't want to use glVertexAttribPointer
. Instead for the fixed function pipe the equivalent commands are glVertexPointer
and glColorPointer
, etc. Note that these are deprecated commands.
Also note that for fixed function glEnableVertexAttribArray
is to be replaced with glEnableClientState
.
来源:https://stackoverflow.com/questions/12237652/how-does-opengl-know-what-type-each-vertex-buffer-object-is