Opening a window with SDL for drawing with OpenGL

Teaching material for my class in OpenGL

Tags : 3D graphics

Save this article in PDF

This short document presents the C code for Linux, MS Windows or OSX of a program which initializes a window and calls a drawing function repeatedly until the window is closed or the ’Esc’ key is pressed.

This template does not draw anything but clears the window to black. Here is the description of each part of the code:


Like for any C library, one have to include the header files for OpenGL and SDL. Nothing fancy here, just put this at the top of the file.

The OpenGL Drawing function

This function will be called in the main program. It draws one frame of what you want to draw, starting by clearing the screen. It also uses the SDL functionality to swap of frame buffer.

The initialization function

This function will be called once at the start of the program. It sets OpenGL viewport and perspective to match with the window size. It also sets some OpenGL states to typical values, like the clearing color or the shading model.

An alternative to the perspective projection is the orthogonal projection. The latter is appropriate for 2D drawing. The gluPerspective line could be replaced by:

The core of the program

The program does three things: initializing, rendering repeatedly, and ending properly. Before calling the OpenGL initialization function above, we need to set the window environment up. This is done with SDL by the two functions SDL_Init and SDL_SetVideoMode. The program ends if one of those fails.

Then, we can call the drawing function. If only called once, the content of the window would never be redrawn (e.g. after hiding the window, or for animation). Therefore we call it in a while loop which ends when the proper SDL events are received. Every SDL events in the pool shall be treated: here we only care of QUIT and the ’Esc’ key.

Voila !

SPIP | template | | Site Map | Follow-up of the site's activity RSS 2.0