SDL Programming

download SDL Programming

of 30

  • date post

  • Category


  • view

  • download


Embed Size (px)


SDL Programming. Introduction. Initialization. The first thing you must do is initialize SDL i nt SDL_Init ( SDL_INIT_EVERYTHING ) This will return -1 if it fails Various flags can be OR’ed together to enable various features In this case, we enable all features. Surfaces. - PowerPoint PPT Presentation

Transcript of SDL Programming

SDL Programming

SDL ProgrammingIntroductionInitialization2The first thing you must do is initialize SDLint SDL_Init( SDL_INIT_EVERYTHING )This will return -1 if it failsVarious flags can be ORed together to enable various featuresIn this case, we enable all featuresSurfaces3A surface is an area where you can drawThe screen is one such surfaceYou can create other surfaces to hold images or to draw onYou can copy one surface to anotherSurfaces have propertiesHeightWidthNumber of bits per pixelCreating the Screen4After initializing SDL, you create the screenSDL_Surface *screen;screen = SDL_SetVideoMode( winWidth, winHeight, screenDepth, SDL_HWSURFACE | SDL_DOUBLEBUF);The screen depth is usually 32If the screen cannot be created, NULL will be returnedWhen a surface is no longer needed it should be freedSDL_FreeSurface(surface);Setting a Window Title5You can set the title in the top of the windowSDL_WM_SetCaption( Title", NULL );

The title will be displayed in the window decoration area, usually at the top of the windowSDL Coordinates6(0, 0)(100, 0)(0, 100)(100, 100)The origin of a window is the top-left cornerY coordinates increase as we go downLoading Images7SDL can load images in the BMP formatThere are extensions which can load other formatsThese extensions must be downloaded and installed into your SDL directoriesLoaded images are stored on surfacesRemember, the screen itself is a surfaceYou can then copy them from one surface to another to make them appear on the screenLoading Images8To load an imageSDL_Surface *image = SDL_LoadBMP(file.bmp);This will either load the image or return NULL if it cannot be loaded

The trouble is that the image might not have the same format as the screen you want to display it onYou can convert it to the correct format as followsSDL_Surface *displayImage = SDL_DisplayFormat(image);Loading Images9These steps are done often enough to warrant creating a function or method for loading an image

SDL_Surface* loadImage(const char* fileName) {SDL_Surface *tmp = NULL, *image = NULL;tmp = SDL_LoadBMP(fileName);if(tmp) {image = SDL_DisplayFormat(tmp);SDL_FreeSurface(tmp);}return image;}Rendering Images10When you load an imageIt is stored on a surfaceThis does not make the image visibleThe image must be copied to the screen to be visibleWe move an image using bit blittingBit block image transferThis is done with the function SDL_BlitSurface

SDL_BlitSurface11int SDL_BlitSurface(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect)

Src source surfaceSrcrect rectangle delimiting areas to copy or NULL for entire imageDst the destination surfaceDstrect position to place on destination surface. If NULL image will be placed at top-left cornerReturns 0 on successSDL_Rect12This is a common structure used to indicate the size and position of rectangular areas

typedef struct{ Sint16 x, y; Uint16 w, h; } SDL_Rect; Event Handling13Many events happen while a program is runningKey pressesMouse movementWindow resizingWindow closingGames are interested in these events and need to be able to find out when they occurThis can be done usingSDL_PollEvent(& event)SDL_Event14typedef union{ Uint8 type; SDL_ActiveEvent active; SDL_KeyboardEvent key; SDL_MouseMotionEvent motion; SDL_MouseButtonEvent button; SDL_JoyAxisEvent jaxis; SDL_JoyBallEvent jball; SDL_JoyHatEvent jhat; SDL_JoyButtonEvent jbutton; SDL_ResizeEvent resize; SDL_ExposeEvent expose; SDL_QuitEvent quit; SDL_UserEvent user; SDL_SysWMEvent syswm; } SDL_Event; This is used for all event types Note that it is a union The type field indicates which member of the union is to be usedSDL Event Types & Structures15Event typeEvent StructureSDL_ACTIVEEVENTSDL_ActiveEventSDL_KEYDOWN/UPSDL_KeyboardEventSDL_MOUSEMOTIONSDL_MouseMotionEventSDL_MOUSEBUTTONDOWN/UPSDL_MouseButtonEventSDL_JOYAXISMOTIONSDL_JoyAxisEventSDL_JOYBALLMOTIONSDL_JoyBallEventSDL_JOYHATMOTIONSDL_JoyHatEventSDL_JOYBUTTONDOWN/UPSDL_JoyButtonEventSDL_VIDEORESIZESDL_ResizeEventSDL_VIDEOEXPOSESDL_ExposeEventSDL_QUITSDL_QuitEventSDL_USEREVENTSDL_UserEventSDL_SYSWMEVENTSDL_SysWMEventSDL_KeyboardEvent16typedef struct{ Uint8 type; Uint8 state; SDL_keysym keysym; } SDL_KeyboardEvent;FieldValuesDescriptiontypeSDL_KEYDOWNSDL_KEYUPType of key eventStateSDL_KEYPRESSEDSDL_KEYRELEASEDSame as typekeysymStructureThe key pressedSDL_keysym17typedef struct{ Uint8 scancode; SDLKey sym; SDLMod mod; Uint16 unicode; } SDL_keysym;FieldValuesDescriptionscancodeHardware scan codesymSee tableSDL virtual key codemodKey modifiersunicodeTranslated characterSDL Key Symbols18SDL keyASCIINameSDLK_BACKSPACE'\b'backspaceSDLK_TAB'\t'tabSDLK_CLEARclearSDLK_RETURN'\r'returnSDLK_PAUSEpauseSDLK_ESCAPE'^['escapeSDLK_SPACE''spaceSDLK_EXCLAIM'!'exclamationSDLK_QUOTEDBL'"'double quoteSDLK_HASH'#'hashSDLK_DOLLAR'$'dollarSDLK_AMPERSAND'&'ampersandSDL Key Symbols19SDL keyASCIINameSDLK_QUOTE'\''single quoteSDLK_LEFTPAREN'('left parenthesisSDLK_RIGHTPAREN')'right parenthesisSDLK_ASTERISK'*'asteriskSDLK_PLUS'+'plus signSDLK_COMMA','commaSDLK_MINUS'-'minus signSDLK_PERIOD'.'period / full stopSDLK_SLASH'/'forward slashSDLK_COLON':'colonSDLK_SEMICOLON';'semicolonSDLK_LESS''greater-than signSDLK_QUESTION'?'question markSDLK_AT'@'atSDLK_LEFTBRACKET'['left bracketSDLK_BACKSLASH'\\'backslashSDLK_RIGHTBRACKET']'right bracketSDLK_CARET'^'caretSDLK_UNDERSCORE'_'underscoreSDLK_DELETE'^?'deleteSDLK_UPup arrowSDLK_DOWNdown arrowSDL Key Symbols21SDL keyASCIINameSDLK_RIGHTright arrowSDLK_LEFTleft arrowSDLK_INSERTinsertSDLK_HOMEhomeSDLK_ENDendSDLK_PAGEUPpage upSDLK_PAGEDOWNpage downSDLK_F1 ...F1SDLK_F15F15SDLK_PRINTprint-screenSDLK_SYSREQSysRqSDLK_BREAKbreakSDL Key Symbols22SDL keyASCIINameSDLK_0'0'0SDLK_1'1'1SDLK_2'2'2SDLK_3'3'3SDLK_4'4'4SDLK_5'5'5SDLK_6'6'6SDLK_7'7'7SDLK_8'8'8SDLK_9'9'9SDL Key Symbols23SDL keyASCIISDLK_a'a'SDLK_b'b'SDLK_c'c'SDLK_d'd'SDLK_e'e'SDLK_f'f'SDLK_g'g'SDLK_h'h'SDLK_i'i'SDLK_j'j'SDLK_k'k'SDLK_l'l'SDLK_m'm'SDL keyASCIISDLK_n'n'SDLK_o'o'SDLK_p'p'SDLK_q'q'SDLK_r'r'SDLK_s's'SDLK_t't'SDLK_u'u'SDLK_v'v'SDLK_w'w'SDLK_x'x'SDLK_y'y'SDLK_z'z'Event Processing Loop24while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_KEYDOWN: if(event.key.keysym.sym==SDLK_LEFT) move_left(); break; . . . } }Poll for events and process each of the eventsThe Game Loop25bool quit = false;SDL_Event event;

while( quit == false ) { if( SDL_PollEvent( &event ) ) { if( event.type == SDL_QUIT ) { quit = true; } if( SDL_Flip( screen ) == -1 ) {//return 1; } }}This processes eventsand keeps the windowon the screen untilthe X in the top rightof the window is clicked.Drawing Text26SDL does not support TTF fonts as distributedYou can download the extension from the fileSDL_ttf-devel-2.0.10-VC.zipOpen the zip file andCopy the file in include to the include directory for your SDLCopy the files in lib to the lib directory for your SDLYou will need to copy the new DLLs to any project that wants to use textPreparing to Use Text27Set the text colorSDL_Color textColor;textColor.r = textColor.g = textColor.b = 255;Initialize the TTF extensionif( TTF_Init() == -1 ) { return false; } Load the fontif( NULL == (font = TTF_OpenFont( "lazy.ttf", 28 )) ) { return false; }Rendering the Text28text is rendered to a newly created surfaceYou then copy this surface onto the surface where the text should appear

textSurface = TTF_RenderText_Solid( font, "A-Maze-ing", textColor );

This surface is then blitted onto the destination surfaceColors29Colors are specified asRGB with each value from 0 255There are two different structuresAn unsigned 32 bit intAn SDL_Color structureSDL_Color has membersr, g, bTo create the 32 bit intunsigned int color = SD_MapRGB(screen->format,255, 255, 255);Drawing Lines & Rectangles30int SDL_DrawLine(SDL_Surface* dst, int x1, int y1, int x2, int y2, Uint32 color)

int SDL_FillRect(SDL_Surface *dst, SDL_Rect *dstrect, Uint32 color)

Both functions return 0 on success