Thursday, August 7, 2008

SDL with DevC++ - Handling Transparency

This very short tutorial's objective is to explain how transparency is handled with bitmaps in SDL. Indeed, the basic tutorials only let you handle Bitmap images, that hold Red, Blue and Green pixel 
information but no Alpha channel information. Games have gone around this problem via the colour key technique, which consists in indicating to SDL that a specific colour should NOT be rendered for each SDL_Surface you load. Therefore, you can now put your sprites on a specific background colour and tell SDL to ignore that colour... 
Here's a very simple example. Consider the ball and steel images below, and the 2 different rendering results we obtained:


Note that the ball is on a white background. Therefore, if you want to draw the ball in game, in front of the steel background, you will get the bad side effect of keeping the ball's white background. Using the transparency colour key on the ball image for the white colour (R = G = B = 255) will make all the white pixels of the image transparent and produce the correct effect you see on the 4th screenshot.
The switching of the transparent key colour is done in SDL by using the SDL_SetColorKey() function as follows
SDL_SetColorKey(surface,SDL_SRCCOLORKEY|SDL_RLEACCEL,colour);
surface = SDL_DisplayFormatAlpha(surface);
This will simply assign the colour you pass in parameter as being transparent for the surface you passed in first parameter. Note that we called the SDL_DisplayFormatAlpha() on our alpha switched surface. This enables a direct copy from the surface from your RAM to the graphics card RAM and therefore improves performance. This will be detailed a little more in the next tutorial.

As for the colour parameter, most people don't know how to code a colour on a Uint32 integer. You can easily get a conversion from [R G B] to [Uint32] with the following function:
Uint32 colour = SDL_MapRGB(screen->format, R, G, B);

No comments:

Post a Comment