This tutorial guides you through rendering triangles using OpenGL with GLEW and GLFW. We start by drawing a single triangle, then expand to a triangle soup, and finally construct a small indexed triangle mesh.
Prerequisites
C++ development environment (e.g., Visual Studio, Code::Blocks, or GCC)
OpenGL, GLEW, and GLFW installed
OpenGL Evolution
(1997) : addition of vertex arrays, which allows for the number of GL calls to specify a point, line or polygon, which could easily get into double figures, to drop to one (not including some setup calls).
(2003) : addition of vertex buffer objects, which builts on the vertex array specification and which allowed for data that didn't need to change to be kept in GPU memory.
glDrawArrays: raw triangles with a fixed indexing pattern, one of GL_TRIANGLES, GL_TRIANGLE_STRIP or GL_TRIANGLE_FAN.
glDrawElements: using index buffer. With glDrawElements you can specify a mixed indexing pattern within the single draw call. However, you have to generate, store and load that index buffer onto the GPU, which adds extra time and takes extra space.
Now each vertex has its own colour attribute. We use glVertexAttribPointer to tell the shader program this data layout.
For glVertexAttribPointer, its second parameter specifies the size of the attribute, its 5th parameter specifies the stride (number of floats for each vertex), and its last parameter specifies the pointer to the first element.
void glVertexAttribPointer(GLuint index, GLint size, GLenum type,
GLboolean normalized, GLsizei stride, const void * offset);
/*
index: attribute index, corresponds to location in the vertex shader,
e.g. vertex location normally comes with 0
size: number of components, e.g. 3 for a 3d vertex
type: data type, e.g. GL_FLOAT
normalized: false
stride: size of each vertex data, in byte.
e.g. for a 3d vertex with (r, g, b) value, is 6 * sizeof(float)
offset: start offset of the attribute in each row, in bytes.
This is sometimes confusing.
*/
For our data, the stride is 6 * sizeof(float). The offset is 0 for vertex position attribute, 3 * sizeof(float) for the colour attribute . The following code sets the vertex location and vertex colour attributes using index retrieved from the vertex shader.
This tutorial demonstrated how to render a single triangle, multiple triangles, and an indexed triangle mesh using OpenGL with GLEW and GLFW. Next steps could involve adding colors, textures, or interactivity.