Hari's Corner

Humour, comics, tech, law, software, reviews, essays, articles and HOWTOs intermingled with random philosophy now and then

A (very simple) SDL Program

Filed under: Tutorials and HOWTOs by Hari
Posted on Sat, Jul 29, 2006 at 18:10 IST (last updated: Wed, Jul 16, 2008 @ 20:43 IST)

Simple DirectMedia Layer (libSDL) is a cross-platform low-level graphics API that can be used to develop games on Linux. At present I find that it's one of the easiest among all the low-level APIs I've encountered to get a hang of and start programming.

Mind you, my first SDL program is very basic (as can be expected), but I guess many programmers will find that this is actually what is required to get you started on more involved graphics and game programming using SDL. I'm still playing with it a bit, but once I get around to creating a few simple programs with SDL it would be easy to build upon it.

Compared to the monstrosity that is DirectX (and which takes ages for you to understand something just to display a blank screen) SDL is a cakewalk. Python programmers will be interested in pygame.

Here's a very basic C++ program I wrote which just loads a PNG image (requires libsdl_image library as well as libsdl) and displays it in a window until the user presses the button 'Q'. It takes a while to poke around the documentation to understand the first few steps, but once you do that it's really easy. Those who've gone through any DirectX tutorial will realize that a similar program to display a bitmap or image using DirectX would require much more code.

For what it's worth, here it is:
#include <SDL/SDL.h>
#include <SDL/SDL_keyboard.h>
#include <SDL/SDL_keysym.h>
#include <SDL/SDL_image.h>
#include <iostream>

SDL_Surface* screen;

int main () { if ( SDL_Init (SDL_INIT_VIDEO) != 0) { std::cerr << "Cannot initialize SDL"; return -1; } atexit (SDL_Quit); screen = SDL_SetVideoMode (640, 480, 16, SDL_HWSURFACE); if (screen == NULL) { std::cerr << "Unable to set video mode"; return -1; } SDL_Surface* img = IMG_Load ("sdl_test.png"); SDL_Surface* img_format = SDL_DisplayFormat (img); SDL_FreeSurface (img); SDL_BlitSurface (img_format, NULL, screen, NULL); SDL_Flip (screen); SDL_FreeSurface(img_format); SDL_Event event;

while (1) { while (SDL_PollEvent (&event)) { switch (event.type) { case SDL_KEYUP: if (event.key.keysym.sym == 'q') exit (0); break; case SDL_QUIT: exit (0); } } } }

No comments yet

There are no comments for this article yet.

Comments closed

The blog owner has closed further commenting on this entry.