我正在创建默认 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);
我越来越好,阴影苏珊娜:
http://i.stack.imgur.com/uRjpv.png
然而,这是错误的!正常属性的 glVertexAttribPointer 的最后一个参数应该是 12 aka (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;
}