glVertexAttribPointer的奇怪行为

时间:2012-02-10 12:03:10

标签: opengl opengl-3

我正在创建默认的VAO和一个VBO,并绑定它们。 我正在将模型数据加载到结构数组vertex_data_t

    glBufferData(GL_ARRAY_BUFFER, nvertices * sizeof(vertex_data_t), vertices, GL_STATIC_DRAW);

然后在绘制功能中我做:

    glBindVertexArray(vao);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_data_t), (const GLvoid *)offsetof(vertex_data_t, position));
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, sizeof(vertex_data_t), (const GLvoid *)offsetof(vertex_data_t, position));
    glBindVertexArray(0);
    glDrawArrays(GL_TRIANGLES, 0, nvertices);

我变得很好,阴影Suzanne:

http://i.stack.imgur.com/uRjpv.png

然而,这是错误的! glVertexAttribPointer对于普通属性的最后一个参数应该是12又名(const GLvoid *)offsetof(vertex_data_t,normal),但是当我这样做时,我的Suzanne被破坏了:

http://i.stack.imgur.com/zBjTS.png

怎么可能?着色器如何知道正常偏移?

顶点着色器:

     attribute vec3 vertex;
     attribute vec3 normal;

     uniform vec4 ambient_color;
     uniform vec4 diffuse_color;
     uniform vec3 light_position;
     uniform mat3 normal_matrix;
     uniform mat4 model_view_matrix;
     uniform mat4 model_view_projection_matrix;

     varying vec4 varying_color;

     void main(void) {
              vec4 vertex4 = vec4(vertex.x, vertex.y, vertex.z, 1.0);
              vec3 eye_normal = normal_matrix * normal;
              vec4 position4 = model_view_matrix * vertex4;
              vec3 position3 = position4.xyz / position4.w;
              vec3 light_direction = normalize(light_position - position3);
              float diffuse = max(0.0, dot(eye_normal, light_direction));
              varying_color.rgb = diffuse * diffuse_color.rgb;
              varying_color.a = diffuse_color.a;
              varying_color += ambient_color;
              gl_Position = model_view_projection_matrix * vertex4;
    }

1 个答案:

答案 0 :(得分:1)

我想你错过了:

glBindAttribLocation(progId, 0, "vertex");
glBindAttribLocation(progId, 1, "normal");