Using SDL Video (TGO-02-D)To start with, recall the example we ended with last time (or at least something very close): #include "SDL.h" enum { SCREENWIDTH = 512, SCREENHEIGHT = 384, SCREENBPP = 0, SCREENFLAGS = SDL_ANYFORMAT } ; int main( int argc, char* argv[] ) { //initialize systems SDL_Init ( SDL_INIT_VIDEO ) ; //set our at exit function atexit ( SDL_Quit ) ; //create a window SDL_Surface* pSurface = SDL_SetVideoMode ( SCREENWIDTH , SCREENHEIGHT , SCREENBPP , SCREENFLAGS ) ; //declare event variable SDL_Event event ; //message pump for ( ; ; ) { //look for an event if ( SDL_PollEvent ( &event ) ) { //an event was found if ( event.type == SDL_QUIT ) break ; } }//end of message pump //done return ( 0 ) ; } This is our basic shell application for SDL, and during this TGO, we will build on it. As you can see, I already have initialized SDL's video subsystem with my call to SDL_Init, and I have already set the video mode (it is currently set up for windowed mode and uses the current display format). This application doesn't do a whole lot, other than give you a blank, black window with a border around it. You can't resize the window, but you can move it around. This program simply waits for you to quit. However, I will point out that the equivalent application in GDI or DirectDraw would be about five times as many lines as we have here. Now we've got to make the application actually DO something. Let's get to work. Rectangular FillsOften, you will need a large rectangular area of a surface cleared out to a particular color. The rectangular area can be as small as a single pixel, or as large as the entire screen. The function for doing this is SDL_FillRect. int SDL_FillRect(SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color); This function takes three parameters: a pointer to the destination surface, a pointer to an SDL_Rect that describes the rectangle you wish to fill, and a color (in the native pixel format of the surface). If you want to clear out the entire surface, you can use NULL for the dstrect parameter. The surface we've got, and an SDL_Rect is easy enough to fill out. One thing we need before we can use this function is the ability to convert from a device independent color (i.e. an SDL_Color variable) into the native pixel format (and I don't want to use the code we looked at for this purpose earlier). Luckily, SDL has such a function. It is called SDL_MapRGB. Uint32 SDL_MapRGB(SDL_PixelFormat *fmt, Uint8 r, Uint8 g, Uint8 b); This function takes a pointer to an SDL_PixelFormat structure, and a red, green, and blue component from 0-255, and it figures out what value works for a native pixel of that same color (or the nearest equivalent). So, let us say we want to fill the screen with pure red. This is how we'd go about it: SDL_FillRect ( pSurface , NULL , SDL_MapRGB ( pSurface->format , 255 , 0 , 0 ) ) ; But we're still not done. SDL's video system doesn't automatically display any of the changes to the surface. In order to make the new data visible, we have to update the rectangle. The function for doing this is SDL_UpdateRect. void SDL_UpdateRect(SDL_Surface *screen, Sint32 x, Sint32 y, Sint32 w, Sint32 h); This function takes four parameters: the pointer to the surface, and an x , y, w, and h values describing the rectangle to update. If you wish to update the entire surface, you can place 0 into each of x, y, w, and h, like so: SDL_UpdateRect ( pSurface , 0 , 0 , 0 , 0 ) ; So, let's do a quick example. Start a new project named SDLRandomFillRect (or whatever you want to call it), set it up for SDL, and put the following code into main.cpp: #include "SDL.h" #include <stdlib.h> enum { SCREENWIDTH = 512, SCREENHEIGHT = 384, SCREENBPP = 0, SCREENFLAGS = SDL_ANYFORMAT } ; int main( int argc, char* argv[] ) { //initialize systems SDL_Init ( SDL_INIT_VIDEO ) ; //set our at exit function atexit ( SDL_Quit ) ; //create a window SDL_Surface* pSurface = SDL_SetVideoMode ( SCREENWIDTH , SCREENHEIGHT , SCREENBPP , SCREENFLAGS ) ; //declare event variable SDL_Event event ; //message pump for ( ; ; ) { //look for an event if ( SDL_PollEvent ( &event ) ) { //an event was found if ( event.type == SDL_QUIT ) break ; } //set up random rectangle SDL_Rect rect ; rect.x = rand ( ) % ( SCREENWIDTH ) ; rect.y = rand ( ) % ( SCREENHEIGHT ) ; rect.w = rand ( ) % ( SCREENWIDTH - rect.x ) ; rect.h = rand ( ) % ( SCREENHEIGHT - rect.y ) ; //fill the rectangle SDL_FillRect ( pSurface , &rect , SDL_MapRGB ( pSurface->format , rand ( ) % 256 , rand ( ) % 256 , rand ( ) % 256 ) ) ; //update the screen SDL_UpdateRect ( pSurface , 0 , 0 , 0 , 0 ) ; }//end of message pump //done return ( 0 ) ; } The lines in bold are new to this example (as opposed to the base shell code), if you just want to add those. Most of the lines are fairly obvious. Five of them deal with setting up the SDL_Rect variable, another does the filled rectangle, and yet another updates the display. On my display, this example runs really fast, but I've got a good video card and that's to be expected. Its output looks something like Figure 1.
Filling rectangular areas in SDL is a lot simpler than the equivalent GDI or DirectDraw code (no HBRUSH to make, no DDBLTFX structure to fill out). Just give it a rectangle, a format, and color, and you've drawn yourself a rectangle. Pixel PlottingIn theory, you could draw pixels using SDL_FillRect, and just use a w and h of 1. That, of course, is not how the SDL_FillRect function is intended to be used, but the SDL Police won't come and stop you, and it *IS* a completely cross platform method of drawing pixels, whereas doing pixel plotting with direct memory access can have portability issues, as we shall see in a moment. In DirectDraw, in order to start writing to the memory of a surface itself, you need to Lock the surface and Unlock it when you are done. The same is true for SDL, in general. Some surfaces never need to be locked, typically those that dwell in system memory. How do you tell? SDL provides a macro for you called SDL_MUSTLOCK. To test a surface, you do the following: if ( SDL_MUSTLOCK ( pSurface ) ) { //surface must be locked for access } else { //no need to lock surface } If you don't need to lock a surface, you will typically do nothing special, and so the entire else clause above won't be there. In order to lock a surface, you call SDL_LockSurface. In order to unlock a surface, you call SDL_UnlockSurface. I doubt either function name comes as a big surprise to you. The same sort of caveats exist for SDL locks as for DirectDraw locks. Don't lock a surface longer than you have to, and don't call any system functions while a surface is locked. Treat the locked surface time as a critical section of your code's execution. Here are the prototypes for SDL_LockSurface and SDL_UnlockSurface. int SDL_LockSurface(SDL_Surface *surface); void SDL_UnlockSurface(SDL_Surface *surface); Each of these have only one parameter... the pointer to the surface you intend to lock. In the case of SDL_LockSurface, there is a return value. If all goes well, this return value will be 0. If there is some sort of problem, you will get -1 instead. Something important to point out here. You can lock a surface more than once prior to unlocking it. If you do this, you need to have as many unlock calls as you have lock calls, like so: SDL_LockSurface ( pSurface ) ; //first lock SDL_LockSurface ( pSurface ) ; //second lock SDL_UnlockSurface ( pSurface ) ; //first unlock... surface is still locked SDL_UnlockSurface ( pSurface ) ; //second unlock... surface is now unlocked This is just something to be aware of. Generally speaking, if you have a large operation that requires some sort of direct access to the pixels of a surface, do a lock, do the operation, and do the unlock. If you have an even larger operation that relies on other operations that lock and unlock the surface, that's ok, because locking and unlocking is recursive. Once the surface is locked, you can begin to directly access the pixel data through the SDL_Surface's pixels member. This includes working with the pixel format of the surface as well as the pitch member of the surface. When setting pixels, I personally like to work with a pixel format independent representation of the color, i.e the SDL_Color structure, or something very much like it. I like having red, green, and blue all represented by numbers between 0 and 255. Unfortunately, an SDL_Surface can have a variety of different formats, and so we'll need to convert from an SDL_Color structure into the native format using SDL_MapRGB. No big deal. From there, next need to know where exactly to write to. The pixels member of SDL_Surface is a void*. I personally like to convert it to a char*, and work the on the surface as though it were like a character buffer. The offset from the beginning of the pixels pointer depends on the x and y coordinates of the pixel you wish to set. For every value in y, you increase by the contents of the SDL_Surface's pitch member. For every value in x, you increase by the contents of the SDL_Surface's pixel format's BytesPerPixel member. Calculating the position looks something like the following. //point to beginning of buffer char* pPosition = ( char * ) pSurface->pixels ; //increment y pPosition += ( y * pSurface->pitch ) ; //increment x pPosition += ( x * pSurface->format->BytesPerPixel ) ; //pPosition now points to the proper pixel We've got the proper position, and we've got the proper color. The only thing left is to copy the data from the color over into the buffer. This is where we meet a very small portability issue. On WIN32 ( and many other operating systems), we can simply do the following code to copy the pixel data from the color variable into the buffer: memcpy ( pPosition , &color , pSurface->format->BytesPerPixel ) ; And this will work, no problem, on most of the machines that the program is likely ever to be compiled for. But then there are the oddballs. The code above relies on the fact that the target machine is little endian. On a big endian system, unless using a 32 bpp surface, you are going to get garbled colors, or black. The solution? Well, I have one in mind, but I haven't had a chance to test it out yet ( since I don't have a machine that supports SDL but has a big endian). The basic idea is that you want to reverse the order of the bytes in the color variable if the machine is big endian, and then do the writing. There are a few macros and functions in SDL that can assist with this. So, here's a basic putpixel function. This function assumes that the surface has already been locked, or does not need locking. void SetPixel ( SDL_Surface* pSurface , int x , int y , SDL_Color color ) { //convert color Uint32 col = SDL_MapRGB ( pSurface->format , color.r , color.g , color.b ) ; //determine position char* pPosition = ( char* ) pSurface->pixels ; //offset by y pPosition += ( pSurface->pitch * y ) ; //offset by x pPosition += ( pSurface->format->BytesPerPixel * x ) ; //copy pixel data memcpy ( pPosition , &col , pSurface->format->BytesPerPixel ) ; } To retrieve a pixel, we can recycle much of our pixel setting code, because the task is simply reversed. We determine the position in the exact same way, we memcpy it into a Uint32 variable (with the same minor caveat about big endians), and then convert it to an SDL_Color variable. The function for doing that is SDL_GetRGB. void SDL_GetRGB(Uint32 pixel, SDL_PixelFormat *fmt, Uint8 *r, Uint8 *g, Uint8 *b); This function is much the same as SDL_MapRGB, except that this time, we send pointers to Uint8s into which are placed the various color components corresponding to the native pixel color. So, if we have a Uint32 variable called col, and an SDL_Color variable called color, this is how we would convert it. SDL_GetRGB ( col , pSurface->format , &color.r , &color.g , &color.b ) ; And with that, we can make a GetPixel function. SDL_Color GetPixel ( SDL_Surface* pSurface , int x , int y ) { SDL_Color color ; Uint32 col = 0 ; //determine position char* pPosition = ( char* ) pSurface->pixels ; //offset by y pPosition += ( pSurface->pitch * y ) ; //offset by x pPosition += ( pSurface->format->BytesPerPixel * x ) ; //copy pixel data memcpy ( &col , pPosition , pSurface->format->BytesPerPixel ) ; //convert color SDL_GetRGB ( col , pSurface->format , &color.r , &color.g , &color.b ) ; return ( color ) ; } And now time for another example. Create a project, and call it something like SDLRandomPixels. Place the following code into main.cpp. #include "SDL.h" #include <stdlib.h> #include <memory.h> enum { SCREENWIDTH = 512, SCREENHEIGHT = 384, SCREENBPP = 0, SCREENFLAGS = SDL_ANYFORMAT } ; void SetPixel ( SDL_Surface* pSurface , int x , int y , SDL_Color color ) ; SDL_Color GetPixel ( SDL_Surface* pSurface , int x , int y ) ; int main( int argc, char* argv[] ) { //initialize systems SDL_Init ( SDL_INIT_VIDEO ) ; //set our at exit function atexit ( SDL_Quit ) ; //create a window SDL_Surface* pSurface = SDL_SetVideoMode ( SCREENWIDTH , SCREENHEIGHT , SCREENBPP , SCREENFLAGS ) ; //declare event variable SDL_Event event ; //message pump for ( ; ; ) { //look for an event if ( SDL_PollEvent ( &event ) ) { //an event was found if ( event.type == SDL_QUIT ) break ; } //pick a random color SDL_Color color ; color.r = rand ( ) % 256 ; color.g = rand ( ) % 256 ; color.b = rand ( ) % 256 ; //lock the surface SDL_LockSurface ( pSurface ) ; //plot pixel at random location SetPixel ( pSurface , rand ( ) % SCREENWIDTH , rand ( ) % SCREENHEIGHT , color ) ; //unlock surface SDL_UnlockSurface ( pSurface ) ; //update surface SDL_UpdateRect ( pSurface , 0 , 0 , 0 , 0 ) ; }//end of message pump //done return ( 0 ) ; } void SetPixel ( SDL_Surface* pSurface , int x , int y , SDL_Color color ) { //convert color Uint32 col = SDL_MapRGB ( pSurface->format , color.r , color.g , color.b ) ; //determine position char* pPosition = ( char* ) pSurface->pixels ; //offset by y pPosition += ( pSurface->pitch * y ) ; //offset by x pPosition += ( pSurface->format->BytesPerPixel * x ) ; //copy pixel data memcpy ( pPosition , &col , pSurface->format->BytesPerPixel ) ; } SDL_Color GetPixel ( SDL_Surface* pSurface , int x , int y ) { SDL_Color color ; Uint32 col = 0 ; //determine position char* pPosition = ( char* ) pSurface->pixels ; //offset by y pPosition += ( pSurface->pitch * y ) ; //offset by x pPosition += ( pSurface->format->BytesPerPixel * x ) ; //copy pixel data memcpy ( &col , pPosition , pSurface->format->BytesPerPixel ) ; //convert color SDL_GetRGB ( col , pSurface->format , &color.r , &color.g , &color.b ) ; return ( color ) ; } Again, the code in bold is the code that has been added to the basic shell application. This example starts placing dots of random colors onto the window. When it runs, it looks somewhat like figure 2.
Once you can plot a pixel, you can do just about anything, including drawing lines, circles, rectangular frames, and so on. Doing all of that stuff is naturally beyond the scope of this article. I get you as far as plotting pixels. BlittingThe primary use of SDL_Surfaces is not to fill rectangles nor to plot pixels. The main task is to copy rectangular sections from one surface to another, much like GDI's BitBlt function and DirectDraw's Blt or BltFast function. The function for doing that is SDL_BlitSurface. int SDL_BlitSurface(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect); This function takes four parameters, the source surface, a source rectangle, a destination surface, and a destination rectangle. It returns 0 if everything is OK, and -1 if there was a problem. If the pointers to either rectangle are NULL, then the entire surface is assumed to be the source or destination area. Naturally, you need two surfaces in order to perform a blit, although you can use the same for both source and destination, at least in theory. The documentation warns that you should not call SDL_BlitSurface on a surface that is locked. So, time (already) for another quick example: the Amazing Bouncing Ball Demo of Death(tm)! Start yourself a new project, name it SDLBouncingBall or something just as clever, and place the following code into main.cpp. Also, make a small bitmap that is 32x32 pixels in size, draw a circle in it, and save it as ball.bmp. #include "SDL.h" enum { SCREENWIDTH = 512, SCREENHEIGHT = 384, SCREENBPP = 0, SCREENFLAGS = SDL_ANYFORMAT } ; int main( int argc, char* argv[] ) { //initialize systems SDL_Init ( SDL_INIT_VIDEO ) ; //set our at exit function atexit ( SDL_Quit ) ; //create a window SDL_Surface* pSurface = SDL_SetVideoMode ( SCREENWIDTH , SCREENHEIGHT , SCREENBPP , SCREENFLAGS ) ; //load bitmap SDL_Surface* pBitmap = SDL_LoadBMP ( "ball.bmp" ) ; //source and destination rectangles SDL_Rect rcSrc , rcDst ; rcSrc.w = pBitmap->w ; rcSrc.h = pBitmap->h ; rcSrc.x = 0 ; rcSrc.y = 0 ; rcDst = rcSrc ; //movement rate int dx = 2 , dy = 2 ; //declare event variable SDL_Event event ; //message pump for ( ; ; ) { //look for an event if ( SDL_PollEvent ( &event ) ) { //an event was found if ( event.type == SDL_QUIT ) break ; } //clear the screen SDL_FillRect ( pSurface , NULL , 0 ) ; //place the ball SDL_BlitSurface ( pBitmap , &rcSrc , pSurface , &rcDst ) ; //move the ball rcDst.x += dx ; rcDst.y += dy ; //check for bounces if ( rcDst.x == 0 || rcDst.x == SCREENWIDTH - rcDst.w ) dx = -dx ; if ( rcDst.y == 0 || rcDst.y == SCREENHEIGHT - rcDst.h ) dy = -dy ; //update the screen SDL_UpdateRect ( pSurface , 0 , 0 , 0 , 0 ) ; }//end of message pump //done return ( 0 ) ; } And if you run the application, you'll see whatever image you made for your ball bounce slowly around the window. Its not a particularly mind-boggling example, but it does adequately demonstrate SDL_BlitSurface. Plus it's hypnotic.... you are getting sleepy... sleeeeeepy.... Anyway. That's the simple blit demo. As we go along, this stuff just keeps getting easier. Figure 3 shows what this program looks like.
Just a quick note before we move on. When using the SDL_BlitSurface function, the contents of the SDL_Rect pointed to by dstrect can change if the destination rectangle is clipped, so often it is a good idea to make a copy of the destination rectangle prior to blitting, unless you absolutely know that the destination rectangle lies entirely withing the destination surface. Color KeysAnd now we come to the issue of transparency. In GDI, in order to make transparency work, you either need to use bitmasks, or else use the TransparentBlt function, which doesn't work on all versions of Windows. In DirectDraw, you have to set up a DDCOLORKEY for a surface that uses one, and you have to pass particular flags when using the Blt or BltFast function. In SDL, setting up a transparent color is really easy. Unlike DirectDraw, you can only have one (1) transparent color for an SDL surface (of course, it's not like DirectDraw had widespread support for transparent color spaces, but I digress). In any case, a single color is usually enough for transparency anyway. Once a color key has been set for a surface, it is used whenever that surface is the source surface in a blit operation (which is nice, because then you don't have to remember which surfaces have color keys). The function for setting the color key of a surface is called SDL_SetColorKey. int SDL_SetColorKey(SDL_Surface *surface, Uint32 flag, Uint32 key); This function takes three parameters: a pointer to a surface, a flag, and a key (the color, in the surfaces native pixel format). It returns an int, 0 if successful, and -1 if there is an error. If flag contiains SDL_SRCCOLORKEY, then the value in key becomes the new transparent color key. If flag contains 0, any color key is cleared. You can retrieve the color key from the surface's pixel format, e.g. pSurface->format->colorkey. Remember that key is in the native pixel format of the surface, and so if working with SDL_Color variables, you'll need to convert it with SDL_MapRGB. No example for color keys, as their use is fairly obvious. Clipping RectanglesAs a final topic, I'm going to show you how to set up a clipping rectangle for a surface. A clipping rectangle is the equivalent of an HRGN selected into an HDC in GDI, or an IDirectDrawClipper object attached to an IDirectDrawSurface object with SetClipper. Compared to their GDI or DirectDraw counterparts, the SDL clipping rectangle is not nearly as powerful or flexible. You can only have a single clipping rectangle at a time. For most purposes, that's enough. For times when it is not, you'll just have to get creative. A clipping rectangle is just that: a rectangular area ( as described by an SDL_Rect variable) to which all destination blits are confined. Pixel plotting is unaffected by the clipping rectangle, as it directly accesses the pixel data of the surface. To set up a clipping rectangle for a surface, the function is SDL_SetClipRect. void SDL_SetClipRect(SDL_Surface *surface, SDL_Rect *rect); This function returns no value. It takes two parameters, a pointer to a surface (for which you are setting the clipping rectangle), and a pointer to an SDL_Rect structure (which contains the new clipping rectangle). If you pass NULL for rect, you will set the clipping area to the size of the entire surface. To examine the contents of the clipping rectangle, you can either look at the clip_rect member of the SDL_Surface structure, or you can use SDL_GetClipRect, which has the same parameter list as SDL_SetClipRect, except that the current clipping rectangle is instead read into the variable pointed to by rect. No example for clipping rectangles, as their use is fairly obvious. SummaryWe haven't totally exhausted the video system of SDL yet. There is still quite a bit more, but you've now been exposed to the basics. The functions shown in this article will be the ones most oft-used, although there are certainly some interesting aspects of some of the other functions, and later in the series, we shall return once again to the video subsystem. For now, this shall suffice. Next Time: Events Ernest S. Pazera Sources: SDL Documentation |