MSDN Documentation

Microsoft Developer Network

OpenGL API Reference

This documentation provides a comprehensive reference to the OpenGL API. OpenGL (Open Graphics Library) is a cross-language, cross-platform API for rendering 2D and 3D vector graphics.

Introduction to OpenGL

OpenGL is a powerful and widely used graphics API that allows developers to create stunning visual experiences in applications ranging from games and simulations to professional design tools and scientific visualization.

The API is designed to be hardware-independent, meaning that the same OpenGL code can run on various graphics hardware from different vendors. This is achieved through the OpenGL driver, which translates OpenGL commands into instructions specific to the underlying hardware.

Getting Started with OpenGL

Before you can start issuing OpenGL commands, you need to set up an OpenGL context and a rendering window. This typically involves using an auxiliary library like GLUT, GLFW, or SDL, or interacting directly with the windowing system (e.g., WGL on Windows, GLX on Linux).

A basic OpenGL application structure usually involves:

  • Initializing the window and OpenGL context.
  • Setting up the viewport and projection matrices.
  • Entering a render loop where drawing commands are issued.
  • Handling events (e.g., window resizing, user input).
  • Cleaning up resources upon exit.

Core API Functions

glBegin / glEnd

void glBegin(GLenum mode); void glEnd(void);

These functions delimit a primitive (like points, lines, or triangles) to be drawn. The mode parameter specifies the type of primitive. This immediate mode is largely deprecated in modern OpenGL in favor of Vertex Buffer Objects (VBOs) and vertex array objects (VAOs).

Parameters:

  • mode: Specifies the primitive type. Common values include:
    • GL_POINTS
    • GL_LINES
    • GL_LINE_STRIP
    • GL_TRIANGLES
    • GL_TRIANGLE_STRIP
    • GL_TRIANGLE_FAN

glVertex

void glVertex{2,3,4}{s,f,d}(TYPE x, TYPE y, ...);

Specifies a vertex for the current primitive. The suffix indicates the number of coordinates (2, 3, or 4) and their type (short, float, double).

Parameters:

  • x, y, z, w: Coordinate values.

glColor

void glColor{3,4}{s,f,d}(TYPE component1, ...);

Sets the current color. The color is applied to subsequent vertices.

Parameters:

  • r, g, b, a: Color components (Red, Green, Blue, Alpha). Values are typically in the range [0, 1] for float/double, or [-max, max] for integer types.

glNormal

void glNormal{3}{s,f,d}(TYPE x, TYPE y, TYPE z);

Sets the current normal vector. Normals are used for lighting calculations.

Parameters:

  • x, y, z: Components of the normal vector.

glTexCoord

void glTexCoord{1,2,3,4}{s,f,d}(TYPE coordinate1, ...);

Sets the current texture coordinates. These coordinates are used to map textures onto geometry.

Parameters:

  • s, t, r, q: Texture coordinate components.

glVertexPointer

void glVertexPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);

Defines an array of vertex data. This is a key function for using vertex arrays, a precursor to VBOs.

Parameters:

  • size: Number of coordinates per vertex (2, 3, or 4).
  • type: Data type of each coordinate (e.g., GL_FLOAT, GL_SHORT).
  • stride: Byte offset between consecutive vertices. If 0, vertices are tightly packed.
  • pointer: Pointer to the first vertex in the array.

glColorPointer

void glColorPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);

Defines an array of color indices or RGBA colors.

Parameters:

  • size: Number of components per color (3 for RGB, 4 for RGBA).
  • type: Data type of each color component (e.g., GL_FLOAT, GL_UNSIGNED_BYTE).
  • stride: Byte offset between consecutive colors.
  • pointer: Pointer to the first color in the array.

glNormalPointer

void glNormalPointer(GLenum type, GLsizei stride, const GLvoid *pointer);

Defines an array of normal vectors.

Parameters:

  • type: Data type of each component (e.g., GL_FLOAT, GL_BYTE).
  • stride: Byte offset between consecutive normals.
  • pointer: Pointer to the first normal in the array.

glTexCoordPointer

void glTexCoordPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);

Defines an array of texture coordinates.

Parameters:

  • size: Number of coordinates per texture coordinate set (1, 2, 3, or 4).
  • type: Data type of each coordinate (e.g., GL_FLOAT).
  • stride: Byte offset between consecutive texture coordinate sets.
  • pointer: Pointer to the first texture coordinate in the array.

glEnable / glDisable

void glEnable(GLenum cap); void glDisable(GLenum cap);

Enables or disables various OpenGL capabilities, such as lighting, texturing, or depth testing.

Parameters:

  • cap: The capability to enable or disable. Examples:
    • GL_LIGHTING
    • GL_TEXTURE_2D
    • GL_DEPTH_TEST
    • GL_CULL_FACE

glClear

void glClear(GLbitfield mask);

Clears the specified buffer bits.

Parameters:

  • mask: Bitwise OR of buffers to clear. Common values:
    • GL_COLOR_BUFFER_BIT
    • GL_DEPTH_BUFFER_BIT
    • GL_STENCIL_BUFFER_BIT

glClearColor

void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);

Sets the clear color used when the color buffer is cleared.

Parameters:

  • red, green, blue, alpha: The red, green, blue, and alpha values. Range is [0.0, 1.0].

glViewport

void glViewport(GLint x, GLint y, GLsizei width, GLsizei height);

Sets the viewport, which defines the rectangular region of the window into which OpenGL will render.

Parameters:

  • x, y: The lower-left corner of the viewport in window coordinates.
  • width, height: The width and height of the viewport in pixels.

glMatrixMode

void glMatrixMode(GLenum mode);

Specifies which matrix is the current target for subsequent matrix operations.

Parameters:

  • mode: The matrix mode to set. Common values:
    • GL_MODELVIEW
    • GL_PROJECTION
    • GL_TEXTURE

glLoadIdentity

void glLoadIdentity(void);

Replaces the current matrix with the identity matrix.

glTranslatef

void glTranslatef(GLfloat x, GLfloat y, GLfloat z);

Multiplies the current matrix by a translation matrix.

Parameters:

  • x, y, z: The amounts to translate along the X, Y, and Z axes.

glRotatef

void glRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);

Multiplies the current matrix by a rotation matrix.

Parameters:

  • angle: The angle of rotation, in degrees.
  • x, y, z: The axis around which to rotate.

glScalef

void glScalef(GLfloat x, GLfloat y, GLfloat z);

Multiplies the current matrix by a uniform scaling matrix.

Parameters:

  • x, y, z: The scale factors along the X, Y, and Z axes.

glFrustum

void glFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble nearVal, GLdouble farVal);

Applies a perspective projection defined by a frustum.

Parameters:

  • left, right, bottom, top: Define the clipping planes for the left, right, bottom, and top edges of the frustum.
  • nearVal, farVal: Define the clipping planes for the near and far edges of the frustum. Both must be positive.

glPerspective

void glPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);

Sets up a perspective projection matrix.

Parameters:

  • fovy: The field of view angle, in degrees, in the Y direction.
  • aspect: The aspect ratio (width divided by height).
  • zNear, zFar: Specify the clipping planes for the near and far faces of the view volume. Both must be positive.

glDrawArrays

void glDrawArrays(GLenum mode, GLint first, GLsizei count);

Renders primitives from the currently bound vertex array.

Parameters:

  • mode: Primitive type (e.g., GL_TRIANGLES).
  • first: Index of the first vertex to be rendered.
  • count: Number of vertices to be rendered.

glDrawElements

void glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);

Renders primitives by indexing into a bound vertex array. This is more efficient for reusing vertices.

Parameters:

  • mode: Primitive type (e.g., GL_TRIANGLES).
  • count: Number of indices to be rendered.
  • type: Data type of the indices (e.g., GL_UNSIGNED_INT).
  • indices: Pointer to the array of indices.

State Management

glPushMatrix / glPopMatrix

void glPushMatrix(void); void glPopMatrix(void);

Pushes the current matrix stack onto the stack or pops the matrix stack. This is crucial for hierarchical transformations (e.g., animating a robot arm).

glPushAttrib / glPopAttrib

void glPushAttrib(GLbitfield mask); void glPopAttrib(void);

Saves and restores groups of current attribute sets (e.g., lighting, polygon, texture attributes).

Parameters:

  • mask: Bitwise OR of attribute masks to save.

Shaders (Modern OpenGL - GLSL)

Modern OpenGL relies heavily on programmable shaders written in GL Shading Language (GLSL). These shaders run on the GPU and provide much more flexibility than the fixed-function pipeline.

glCreateShader

GLuint glCreateShader(GLenum type);

Creates an empty shader object of the specified type.

Parameters:

  • type: The type of shader to create. Common values:
    • GL_VERTEX_SHADER
    • GL_FRAGMENT_SHADER

Return Value:

A non-zero value identifying the new shader object.

glShaderSource

void glShaderSource(GLuint shader, GLsizei count, const GLchar **string, const GLint *length);

Sets the source code for a shader object.

Parameters:

  • shader: The shader object to modify.
  • count: The number of strings in the array `string`.
  • string: An array of pointers to character arrays containing the source code.
  • length: An array of integers, where each integer is the length of the corresponding string in `string`. If NULL, lengths are assumed to be null-terminated.

glCompileShader

void glCompileShader(GLuint shader);

Compiles a shader object. Errors can be queried using glGetShaderiv and glGetShaderInfoLog.

Parameters:

  • shader: The shader object to compile.

glCreateProgram

GLuint glCreateProgram(void);

Creates an empty program object. A program object is a container for shader objects that are linked together.

Return Value:

A non-zero value identifying the new program object.

glAttachShader

void glAttachShader(GLuint program, GLuint shader);

Attaches a shader object to a program object.

Parameters:

  • program: The program object.
  • shader: The shader object to attach.
void glLinkProgram(GLuint program);

Links a program object. This process combines the compiled shaders into an executable that can run on the GPU. Errors can be queried using glGetProgramiv and glGetProgramInfoLog.

Parameters:

  • program: The program object to link.

glUseProgram

void glUseProgram(GLuint program);

Installs a program object as part of the current OpenGL state.

Parameters:

  • program: The program object to use. If 0, the current program is disabled.

Error Handling

OpenGL provides a mechanism for querying runtime errors. It's crucial to check for errors, especially during development.

glGetError

GLenum glGetError(void);

Returns an error flag. If no errors have occurred, GL_NO_ERROR is returned. Otherwise, one of the following error codes is returned (and subsequent calls to glGetError will also return GL_NO_ERROR until the errors are cleared):

Possible Error Codes:

  • GL_INVALID_ENUM: An invalid enum parameter was passed to a function.
  • GL_INVALID_VALUE: An invalid value parameter was passed to a function.
  • GL_INVALID_OPERATION: The operation is not allowed in the current state.
  • GL_STACK_OVERFLOW: An attempt to push on an empty stack occurred.
  • GL_STACK_UNDERFLOW: An attempt to pop from an empty stack occurred.
  • GL_OUT_OF_MEMORY: An operation could not be completed due to lack of memory.

Example Usage:


GLenum error;
while ((error = glGetError()) != GL_NO_ERROR) {
    fprintf(stderr, "OpenGL Error: %d\n", error);
}
                    

Best Practices

  • Use Modern OpenGL: Prefer using Vertex Buffer Objects (VBOs), Vertex Array Objects (VAOs), and shaders over immediate mode and fixed-function pipeline functions.
  • Check Errors: Regularly use glGetError to diagnose issues.
  • Manage State Efficiently: Use glPushAttrib and glPopAttrib sparingly and understand which attributes are being saved/restored.
  • Optimize Rendering: Batch draw calls, use indexed rendering, and leverage shaders effectively.
  • Understand Transformations: Master the matrix stack for camera and object transformations.
  • Resource Management: Properly create, bind, and delete OpenGL objects (shaders, textures, buffers) to avoid memory leaks.