'Drawing 3D objects using Indices and Normals
I would like to understand how to optimize the 3D objects drawing using also normals.
For example I have a cube: it has 8 vertices, and 6 faces that could be rapresented as 12 triangles.
(I've used the cube in order to simplify the question, but in general if you have triangles that represent plane surfaces the question is still valid)
If so, I have a VertexBuffer with 8 vertices, and an IndexBuffer of 36 items (12t*3v each).
If I use the OpenGL function DrawElements in my code. This works!
The next step is introducing the normals, because I want the lights effects.
In this example I thought to use a NormalsBuffer with a normal for each triangle.
In order to get the right normal, I thought to use VertexShader and retrive the value just dividing the gl_VertexID by 3.
int triangleIndex = (gl_VertexID/3)
the triangleIndex is the Normals index to use to retrive normal in NormalsBuffer.
I didn't find any example or document that explains how to optimize the normal's vectors usage.
Is it my idea valid?
And if Yes how can I get the normal vector from Vertex Shader?
I have found this Post inspiring "Rendering meshes with multiple indices", but not useful because it miss usable code.
Solution 1:[1]
Your method will not work. Not unless you're indirectly accessing the positions too.
gl_VertexID is the vertex's index within the rendering stream. When doing array rendering, each vertex has a unique index (since the indices go from start to end in the array). For indexed rendering, each vertex's index is... its index. From the index array. That's the point of indexing.
So if you have 8 vertices, your gl_VertexID value will be on the range [0, 7].
Furthermore, vertex shaders explicitly require the user to not do anything that would cause a particular VS for a specific vertex index (and instance) to produce a different value for a given draw call. That is, if gl_VertexID is 3, your code is required to produce binary identical outputs no matter when that index is 3.
The only way to get around this is to not use indexed rendering at all. To manually do all vertex reading from buffers, positions and normals alike. With such rendering, gl_VertexID will just be a sequentially increasing value.
Since you know that your object is a cube, you can synthesize both the normal and position indices in the VS itself without having to read memory.
Solution 2:[2]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicol Bolas |
| Solution 2 |


