Game programming/Basic SDL
Simple Directmedia Layer, SDL, is a wrapper library which abstracts away OS-specific code from the programmer.
Purpose
edit- Learn the structure, and how to make a simple SDL application
Requirements
edit- C knowledge
- Dependencies installed
Dependencies
edit- Go get SDL from here
- Install it in your environment, add include and lib directories
- Link with libSDLmain.a (SDLmain.lib) and libSDL.a (SDL.lib)
Basic SDL program structure
edit#include "SDL.h"
#define CAPTION "Application name"
#define RESOLUTION_WIDTH 640
#define RESOLUTION_HEIGHT 480
#define COLOR_DEPTH 0 /* Can be any value. 0 stands for whatever color depth is currently selected */
#define FLAGS 0
static int running = 0;
static void handleEvent(const SDL_Event sdl_event);
static void render(SDL_Surface* screen);
int main(int argc, char* argv[])
{
SDL_Surface *window = NULL;
if(SDL_Init(SDL_INIT_EVERYTHING) == -1) /* if SDL_Init fails */
{
return 1;
}
SDL_WM_SetCaption(CAPTION, NULL);
window = SDL_SetVideoMode(RESOLUTION_WIDTH, RESOLUTION_HEIGHT, COLOR_DEPTH, FLAGS);
if(window == NULL) /* SDL_SetVideoMode failed */
{
SDL_Quit();
return 1;
}
running = 1;
while(running)
{
SDL_Event sdl_event;
while(SDL_PollEvent(&sdl_event) > 0) /* Run as long as there are available events and fill sdl_event with their information */
{
handleEvent(sdl_event);
}
SDL_FillRect(screen, NULL, 0); /* Clears the screen */
render(screen);
SDL_Flip(screen); /* Draws the screen */
}
SDL_Quit();
return 0;
}
static void handleEvent(const SDL_Event sdl_event)
{
switch(sdl_event.type)
{
/* Event handling goes here */
case(SDL_QUIT):
running = 0;
break;
}
}
static void render(SDL_Surface* screen)
{
/* Rendering code goes here */
}
Rendering
editThe following code renders a blue rectangle, 128 pixels wide and 16 pixels high, 32 pixels from the left edge of the window, and 64 pixels from it's top.
static void render(SDL_Surface* screen)
{
SDL_Rect rectangle;
rectangle.x = 32; /* Location on X plane */
rectangle.y = 64; /* Location on Y plane */
rectangle.w = 128; /* Width */
rectangle.h = 16; /* Height */
SDL_FillRect(screen, &(rectangle), SDL_MapRGB(screen->format, 0, 0, 255)); /* Screen format, Red, Green, Blue */
}
Trivia
edit- SDL's co-ordinates system uses pixels, with the bird at the upper-left corner of the window. The positive X direction is right, and positive Y direction is down.
- SDL is a wrapper. This means that it uses the OSes own API for the work it does. When you're using SDL on windows, you're actually using Win32. On GNU+Linux, you use whatever desktop environment is currently running.