user1781626
user1781626

Reputation:

How does OpenGL know how to use the normal data with glDrawElements()?

I spent days to construct a working example of rendering a cube in OpenGL with simple lighting

I have:

vertices = {...};
normals = {...};
vertex_indices = {...};
normal_indices = {...};

(1) I setup my VBOs

glBufferSubData(GL_ARRAY_BUFFER, 0, vertSize, &vertices[0]); // vertices
glBufferSubData(GL_ARRAY_BUFFER, vertSize, normSize, &normals[0]); // normals

(2) I enable my vertex pointers

glEnableVertexAttribArray(0);
glVertexAttribPointer(0,..)

glEnableVertexAttribArray(1);
glVertexAttribPointer(1,..)

(3) I also setup my index buffer

 glBufferData(GL_ELEMENT_ARRAY_BUFFER, indcSize, & vertex_indices[0], GL_STATIC_DRAW);

and then call glDrawElements in my render method

glDrawElements(GL_TRIANGLES, (int)vertex_indices.size(), GL_UNSIGNED_INT, 0);

I don't pass the normal indices anywhere but everything seems to work fine.

I don't think I understand glDrawElements correctly. How did the lighting work without the normal indices? was glDrawElements suppose to only get the vertex indices?

Upvotes: 3

Views: 2744

Answers (1)

derhass
derhass

Reputation: 45342

I don't think I understand glDrawElements correctly. How did the lighting work without the normal indices? was glDrawElements suppose to only get the vertex indices?

In OpenGL, there are no separate indices per attribute. As far as OpenGL is concerned, a vertex is an n-tuple of all attributes, like position, color, normal vector, tex coords, whatever.

In the case of your cube, you will need at least 24 vertices. There are only 8 corner positions, but each corner is connected to 3 different faces, each with a different normal. This means, that you need 3 separate vertices at each corner, all at the same position, but all differing by their normal direction.

Consequently, glDrawElements works with only one index array, and this is the index into all enabled vertex attribute arrays at the same time. Your normal_indices array is not used at all. If it still works as intended, your normal data happens to be organized in the correct way.

Upvotes: 3

Related Questions