Tutorial 1: Introduction to SDL
In RTR, we will be using SDL, specifically SDL2, rather than glut from COSC1186/I3D last semester. SDL will handle creating a window, OpenGL context, keyboard/mouse input and other events. This tutorial will introduce the basics of the SDL API, by the end of which we’ll have some animating points in a 3D environment as shown in the following image.
Use this skeleton code to get started with an empty window.
The current code is missing the main loop. As discussed in the
lecture, unlike glut, SDL does not provide a main loop,
instead you must write your own. For now, just put the main
loop in main
. Use the following structure:
-
Process events such as keyboard/mouse input. The skeleton
code provides
handleEvents()
which returns true if the user wants to exit. - Allow the events to affect the world. This is commonly done in an update/idle function.
-
Display/draw/render the result of the updates and swap
buffers (using the
function
SDL_GL_SwapWindow(mainWindow)
).
Now to test the code:
- All we have is a blank window. Try setting a red clear colour to check OpenGL is set up and working properly.
- Without many objects in a scene it can be difficult to get your bearings. Add a set of red/green/blue world axes at the origin. Simple visual debugging techniques such as these are vital to graphics programming.
Now on to the points:
-
Draw points at random positions
(using
random()/(float)RAND_MAX
) using immediate mode for now, as you did last semester. Recall that without the initial projection the viewing volume is an orthographic -1 to 1 cube. So that the points don’t change each frame, save their coordinates in an array. -
Animate the points so they move downwards to the bottom of
the window, at which point they reset their position to the
top. Put the code to update their positions in
the
update()
(idle) function. To begin with use a hard coded per-frame increment, but remember this is a bad/wrong way to do it as different computers run at different speeds, or even the same computer depending on other processes, so to do this properly real time must be measured. - Create and store random velocities as well as positions.
-
Now use
SDL_GetTicks()
to time the animation, in the same wayglutGet(GLUT_ELAPSED_TIME)
was used in I3D. -
The robot arm example has a slightly different structure,
with a separate
mainLoop
function. Modify your program to do likewise, along with callingpostRedisplay
when appropriate and rendering/displaying only when necessary.
To add some user interaction to the application:
- When the user presses one of the arrow keys (or w/a/s/d), make the particles all move in that direction.
- Don't forget to reset the particles to the right spot after they fall out of view.