Wednesday, August 6, 2008

Hardware and Software SDL_Surfaces - Improving performance

Once again a very short tutorial, this time to insist on a point which often is the cause of performance issues on several SDL Applications. Indeed, most generated code samples and tutorials we see online handle SDL_Surfaces in an inapropriate way. If you look at the SDL application initialisation, it comes as follows:
screen = SDL_SetVideoMode (640, 480, 16, <b>SDL_SWSURFACE</b> | SDL_DOUBLEBUF);
What is abnormal here is that we are initialising the application focusing on system memory (RAM) instead of graphics card memory. This means every time you want to render your screen surface via a flip, you send all the screen surface data from your RAM over to your graphics card that will then draw it all on screen. On larger resolutions, this can cause a huge performance hit on your application

Other tutorials don't forget this switch in the application initialisation, and start it correctly, as follows:
screen = SDL_SetVideoMode (640, 480, 16, <b>SDL_HWSURFACE</b> | SDL_DOUBLEBUF);
Unfortunately, this is still not sufficient for optimal performance. It does help a lot because your screen buffer is now stored directly in your graphics card memory (your RAM should inflate MUCH less when you start your application). The remaining problem is that SDL_Surface pointers returned by the SDL and SDL_Image libraries return software surfaces, hence once again in system memory.
As a result, every time a surface is loaded, you have to load it to a temporary surface in your RAM (software surface), convert it to a surface in graphics card memory (hardware surface), and finally release your temporary surface in RAM. The piece of code below does it perfectly, using temp as the temporary system surface:
SDL_Surface* temp = SDL_LoadBMP("test.bmp");       //Load test.bmp to a software surface
surface = SDL_DisplayFormat(temp);                         //Convert software surface to hardware surface
SDL_FreeSurface(temp);                                           //Release software surface

No comments:

Post a Comment