glVertexAttribPointer第1个参数及着色器中的location的作用

本文详细解析了OpenGL中glVertexAttribPointer函数的使用方法及其与顶点着色器中属性值的对应关系。介绍了如何通过该函数指定顶点数据,并解释了如何使用glBindAttribLocation函数为顶点属性设置索引值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//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的关系

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值