//VAO[0]
glGenVertexArrays(2, vertex_array);
glBindVertexArray(vertex_array[0]);
//顶点数据
GLuint vbo_vertex = 0;
glGenBuffers(1, &vbo_vertex);
assert(vbo_vertex != 0);
glBindBuffer(GL_ARRAY_BUFFER, vbo_vertex);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*3*8, vertexs, GL_STATIC_DRAW);
/*Bind VAO and VBO 索引0是通过glBindAttribLocation函数或在顶点着色器中通过layout设置的索引值。将顶点数据中的位置属性输入到VAO,用来建立VAO和VBO的数据传递,上传数据完成之后可以删除*/
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0); //leave out this sentence
//顶点颜色
GLuint vbo_color = 0;
glGenBuffers(1, &vbo_color);
assert(vbo_color);
glBindBuffer(GL_ARRAY_BUFFER, vbo_color);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*24, color, GL_STATIC_DRAW);
/*索引1是通过glBindAttribLocation函数或在顶点着色器中通过layout设置的索引值。将顶点数据的颜色属性输入到VAO*/
glVertexAttribPointer(1,3,GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
如上代码用到了glVertexAttribPointer函数,该函数功能参见:《glVertexAttribPointer函数用法说明》
一直没搞明白这个函数的第1个参数怎么使用,近来知道了,记录下:
glVertexAttribPointer第一个参数对应vertexshader里那个in attribute,即外部程序传给着色器程序的有关顶点的属性值,如:顶点的位置、顶点颜色等,是vertexshader中attribute的索引。如下为顶点着色器代码:
// vertex shader,position的location设定为0,对应glVertexAttribPointer的第1个参数
layout(location = 0) in vec3 position;
// vertex shader,顶点颜色的location设定为1,对应glVertexAttribPointer的第1个参数
layout(location = 1) in vec4 color;
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*3*8, vertexs, GL_STATIC_DRAW);
则:
// 第1个参数就是上面的着色器layout(location = 0) in vec3 position的location的值,表示对顶点位置进行操作;
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
........ // 其它代码
// 第1个参数就是上面的着色器layout(location = 1) in vec4 color的location的值,表示对顶点颜色进行操作;
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);
如果着色器中没有指定location,也可以通过如下函数指定顶点属性的索引值:
void glBindAttribLocation( GLuint program,
GLuint index,
const GLchar *name);
关于该函数具体用法及含义,参见:glBindAttribLocation用法及含义
对于上例,不用着色器的location,而用glBindAttribLocation实现同样功能,代码如下:
glBindAttribLocation(program, 0, "position");
glBindAttribLocation(program, 1, "color");
其中program表示着色器程序的句柄,"position"、"color"为着色器中的如下输入变量:
in vec3 position;
in vec4 color;
如果在着色器中对顶点属性设置了location,同时也用glBindAttribLocation对顶点属性设置了location,则以着色器的为主,即着色器对顶点属性设置location比对glBindAttribLocation对顶点属性设置location优先级高。
另外,glVertexAttribPointer、glEnableVertexAttribArray、VAO、VBO之间的关系,请参见理解glVertexAttribPointer、glEnableVertexAttribArray、VAO、VBO的关系