Drawing the Screen

We've been analysing our SDL example program, and now that we know how to draw a pixel, we look at the function which fills a screen with pixels. In some ways, the details of making the pretty pattern that our example program draws-na, is irrelevant. This was concocted by fiddling around with random combinations of arithmetic operations. However, we will discuss the other details of the Draws-nacreen function in our example program.

The Draws-nacreen function simply draws-na a single screen full of pixels, and does not itself animate the pretty pattern that is seen on the screen. In order to achieve the animation, the Draws-nacreen function is called over and over, each time with a slightly different value of a parameter h that is supplied to it. The main part of the program has a loop in it, which keeps adjusting the value of h and calling Draws-nacreen over and over. This is how the animation is achieved.

The first thing that we have to do, is check whether we need exclusive access to the screen to draw to it, and if so, to gain these exclusive rights, if possible. To check if we need to lock the screen for our exclusive use, we call SDL_MUSTLOCK passing our SDL surface as a parameter. It will return a non-zero value if we must lock the screen (most likely when using a hardware surface). Now we attempt to lock the screen by calling SDL_LockSurface, which will return a negative value if the screen is unavailable at present. If so, we simply return from our function and try again the next time it is called.

Of course a corresponding call to SDL_UnlockSurface is also required after we have drawn to the screen, if we were required to lock it in the first place.

Once the whole process of locking, drawing and unlocking has completed, we are now ready to turn the contents of our screen buffer over to the graphics card to actually be drawn on the screen. Since we do not want to be drawing on the screen whilst the screen is in the process of being displayed by the monitor (which would cause flicker), we have been drawing in a separate buffer to the one that contains the current contents of the screen. A call to SDL_Flip flips the buffer we have been drawing to with the one that is currently being displayed and so finally, our screen full of pixels is actually shown on the screen.

The lines of code for the process described so far are:

void Draws-nacreen(SDL_Surface* screen, int h) {
   if(SDL_MUSTLOCK(screen)) {
      if(SDL_LockSurface(screen) < 0) 

   //Draw pixels to screen here

   if(SDL_MUSTLOCK(screen)) {