table of contents · sdl_cdresume — resumes a cdrom sdl_cdstop — stops a cdrom sdl_cdeject —...

Post on 11-Jun-2020

16 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

TableofContentsI.SDLGuide

PrefaceAboutSDLAboutSDLdocCredits

1.TheBasicsIntroductionInitializingSDL

2.GraphicsandVideoIntroductiontoSDLVideoUsingOpenGLWithSDL

3.InputhandlingHandlingJoysticksHandlingtheKeyboard

4.ExamplesIntroductionEventExamplesAudioExamplesCDROMExamplesTimeExamples

II.SDLReference5.General

SDL_Init—InitializesSDLSDL_InitSubSystem—InitializesubsystemsSDL_QuitSubSystem—ShutdownasubsystemSDL_Quit—ShutdownSDLSDL_WasInit—CheckwhichsubsystemsareinitializedSDL_GetError—GetSDLerrorstring

6.VideoSDL_GetVideoSurface—returnsapointertothecurrentdisplaysurfaceSDL_GetVideoInfo—returnsapointertoinformationaboutthevideohardwareSDL_VideoDriverName—ObtainthenameofthevideodriverSDL_ListModes—ReturnsapointertoanarrayofavailablescreendimensionsforthegivenformatandvideoflagsSDL_VideoModeOK—Checktoseeifaparticularvideomodeis

supported.SDL_SetVideoMode—Setupavideomodewiththespecifiedwidth,heightandbits-per-pixel.SDL_UpdateRect—Makessurethegivenareaisupdatedonthegivenscreen.SDL_UpdateRects—Makessurethegivenlistofrectanglesisupdatedonthegivenscreen.SDL_Flip—SwapsscreenbuffersSDL_SetColors—Setsaportionofthecolormapforthegiven8-bitsurface.SDL_SetPalette—Setsthecolorsinthepaletteofan8-bitsurface.SDL_SetGamma—SetsthecolorgammafunctionforthedisplaySDL_GetGammaRamp—GetsthecolorgammalookuptablesforthedisplaySDL_SetGammaRamp—SetsthecolorgammalookuptablesforthedisplaySDL_MapRGB—MapaRGBcolorvaluetoapixelformat.SDL_MapRGBA—MapaRGBAcolorvaluetoapixelformat.SDL_GetRGB—GetRGBvaluesfromapixelinthespecifiedpixelformat.SDL_GetRGBA—GetRGBAvaluesfromapixelinthespecifiedpixelformat.SDL_CreateRGBSurface—CreateanemptySDL_SurfaceSDL_CreateRGBSurfaceFrom—CreateanSDL_SurfacefrompixeldataSDL_FreeSurface—Frees(deletes)aSDL_SurfaceSDL_LockSurface—Lockasurfacefordirectlyaccess.SDL_UnlockSurface—Unlocksapreviouslylockedsurface.SDL_LoadBMP—LoadaWindowsBMPfileintoanSDL_Surface.SDL_SaveBMP—SaveanSDL_SurfaceasaWindowsBMPfile.SDL_SetColorKey—Setsthecolorkey(transparentpixel)inablittablesurfaceandRLEacceleration.SDL_SetAlpha—AdjustthealphapropertiesofasurfaceSDL_SetClipRect—Setstheclippingrectangleforasurface.SDL_GetClipRect—Getstheclippingrectangleforasurface.SDL_ConvertSurface—Convertsasurfacetothesameformatasanothersurface.SDL_BlitSurface—Thisperformsafastblitfromthesourcesurfacetothedestinationsurface.

SDL_FillRect—ThisfunctionperformsafastfillofthegivenrectanglewithsomecolorSDL_DisplayFormat—ConvertasurfacetothedisplayformatSDL_DisplayFormatAlpha—ConvertasurfacetothedisplayformatSDL_WarpMouse—Setthepositionofthemousecursor.SDL_CreateCursor—Createsanewmousecursor.SDL_FreeCursor—FreesacursorcreatedwithSDL_CreateCursor.SDL_SetCursor—Setthecurrentlyactivemousecursor.SDL_GetCursor—Getthecurrentlyactivemousecursor.SDL_ShowCursor—Togglewhetherornotthecursorisshownonthescreen.SDL_GL_LoadLibrary—SpecifyanOpenGLlibrarySDL_GL_GetProcAddress—GettheaddressofaGLfunctionSDL_GL_GetAttribute—GetthevalueofaspecialSDL/OpenGLattributeSDL_GL_SetAttribute—SetaspecialSDL/OpenGLattributeSDL_GL_SwapBuffers—SwapOpenGLframebuffers/UpdateDisplaySDL_CreateYUVOverlay—CreateaYUVvideooverlaySDL_LockYUVOverlay—LockanoverlaySDL_UnlockYUVOverlay—UnlockanoverlaySDL_DisplayYUVOverlay—BlittheoverlaytothedisplaySDL_FreeYUVOverlay—FreeaYUVvideooverlaySDL_GLattr—SDLGLAttributesSDL_Rect—DefinesarectangularareaSDL_Color—FormatindependentcolordescriptionSDL_Palette—Colorpalettefor8-bitpixelformatsSDL_PixelFormat—StoressurfaceformatinformationSDL_Surface—GraphicalSurfaceStructureSDL_VideoInfo—VideoTargetinformationSDL_Overlay—YUVvideooverlay

7.WindowManagementSDL_WM_SetCaption—Setsthewindowtileandiconname.SDL_WM_GetCaption—Getsthewindowtitleandiconname.SDL_WM_SetIcon—Setstheiconforthedisplaywindow.SDL_WM_IconifyWindow—Iconify/MinimisethewindowSDL_WM_ToggleFullScreen—TogglesfullscreenmodeSDL_WM_GrabInput—Grabsmouseandkeyboardinput.

8.Events

IntroductionSDLEventStructures.EventFunctions.

9.JoystickSDL_NumJoysticks—Countavailablejoysticks.SDL_JoystickName—Getjoystickname.SDL_JoystickOpen—Opensajoystickforuse.SDL_JoystickOpened—DetermineifajoystickhasbeenopenedSDL_JoystickIndex—GettheindexofanSDL_Joystick.SDL_JoystickNumAxes—GetthenumberofjoystickaxesSDL_JoystickNumBalls—GetthenumberofjoysticktrackballsSDL_JoystickNumHats—GetthenumberofjoystickhatsSDL_JoystickNumButtons—GetthenumberofjoysitckbuttonsSDL_JoystickUpdate—UpdatesthestateofalljoysticksSDL_JoystickGetAxis—GetthecurrentstateofanaxisSDL_JoystickGetHat—GetthecurrentstateofajoystickhatSDL_JoystickGetButton—GetthecurrentstateofagivenbuttononagivenjoystickSDL_JoystickGetBall—GetrelativetrackballmotionSDL_JoystickClose—Closesapreviouslyopenedjoystick

10.AudioSDL_AudioSpec—AudioSpecificationStructureSDL_OpenAudio—Openstheaudiodevicewiththedesiredparameters.SDL_PauseAudio—PausesandunpausestheaudiocallbackprocessingSDL_GetAudioStatus—GetthecurrentaudiostateSDL_LoadWAV—LoadaWAVEfileSDL_FreeWAV—FreespreviouslyopenedWAVdataSDL_AudioCVT—AudioConversionStructureSDL_BuildAudioCVT—InitializesaSDL_AudioCVTstructureforconversionSDL_ConvertAudio—Convertaudiodatatoadesiredaudioformat.SDL_MixAudio—MixaudiodataSDL_LockAudio—LockoutthecallbackfunctionSDL_UnlockAudio—UnlockthecallbackfunctionSDL_CloseAudio—Shutsdownaudioprocessingandclosestheaudiodevice.

11.CD-ROM

SDL_CDNumDrives—ReturnsthenumberofCD-ROMdrivesonthesystem.SDL_CDName—Returnsahuman-readable,system-dependentidentifierfortheCD-ROM.SDL_CDOpen—OpensaCD-ROMdriveforaccess.SDL_CDStatus—Returnsthecurrentstatusofthegivendrive.SDL_CDPlay—PlayaCDSDL_CDPlayTracks—PlaythegivenCDtrack(s)SDL_CDPause—PausesaCDROMSDL_CDResume—ResumesaCDROMSDL_CDStop—StopsaCDROMSDL_CDEject—EjectsaCDROMSDL_CDClose—ClosesaSDL_CDhandleSDL_CD—CDROMDriveInformationSDL_CDtrack—CDTrackInformationStructure

12.Multi-threadedProgrammingSDL_CreateThread—Createsanewthreadofexecutionthatsharesitsparent'sproperties.SDL_ThreadID—Getthe32-bitthreadidentifierforthecurrentthread.SDL_GetThreadID—GettheSDLthreadIDofaSDL_ThreadSDL_WaitThread—Waitforathreadtofinish.SDL_KillThread—Gracelesslyterminatesthethread.SDL_CreateMutex—CreateamutexSDL_DestroyMutex—DestroyamutexSDL_mutexP—LockamutexSDL_mutexV—UnlockamutexSDL_CreateSemaphore—Createsanewsemaphoreandassignsaninitialvaluetoit.SDL_DestroySemaphore—DestroysasemaphorethatwascreatedbySDL_CreateSemaphore.SDL_SemWait—Lockasemaphoreandsuspendthethreadifthesemaphorevalueiszero.SDL_SemTryWait—Attempttolockasemaphorebutdon'tsuspendthethread.SDL_SemWaitTimeout—Lockasemaphore,butonlywaituptoaspecifiedmaximumtime.SDL_SemPost—Unlockasemaphore.SDL_SemValue—Returnthecurrentvalueofasemaphore.

SDL_CreateCond—CreateaconditionvariableSDL_DestroyCond—DestroyaconditionvariableSDL_CondSignal—RestartathreadwaitonaconditionvariableSDL_CondBroadcast—RestartallthreadswaitingonaconditionvariableSDL_CondWait—WaitonaconditionvariableSDL_CondWaitTimeout—Waitonaconditionvariable,withtimeout

13.TimeSDL_GetTicks—GetthenumberofmillisecondssincetheSDLlibraryinitialization.SDL_Delay—Waitaspecifiednumberofmillisecondsbeforereturning.SDL_AddTimer—Addatimerwhichwillcallacallbackafterthespecifiednumberofmillisecondshaselapsed.SDL_RemoveTimer—RemoveatimerwhichwasaddedwithSDL_AddTimer.SDL_SetTimer—Setacallbacktorunafterthespecifiednumberofmillisecondshaselapsed.

ListofTables8-1.SDLKeysymdefinitions8-2.SDLmodifierdefinitions

ListofExamples1-1.InitializingSDL2-1.InitializingtheVideoDisplay2-2.InitializingtheBestVideoMode2-3.LoadingandDisplayingaBMPFile2-4.getpixel()2-5.putpixel()2-6.Usingputpixel()2-7.InitializingSDLwithOpenGL2-8.SDLandOpenGL3-1.InitializingSDLwithJoystickSupport3-2.QueryingtheNumberofAvailableJoysticks3-3.OpeningaJoystick3-4.JoystickAxisEvents3-5.MoreJoystickAxisEvents3-6.JoystickButtonEvents

3-7.JoystickBallEvents3-8.JoystickHatEvents3-9.QueryingJoystickCharacteristics3-10.ReadingKeyboardEvents3-11.InterpretingKeyEventInformation3-12.ProperGameMovement

Next SDLGuide

SDLLibraryDocumentationPrev Next

I.SDLGuideTableofContentsPreface1.TheBasics2.GraphicsandVideo3.Inputhandling4.Examples

Prev Home NextSDLLibraryDocumentation Preface

SDLLibraryDocumentationPrev Next

PrefaceTableofContentsAboutSDLAboutSDLdocCredits

AboutSDLTheSDLlibraryisdesignedtomakeiteasytowritegamesthatrunonLinux,*BSD,MacOS,Win32andBeOSusingthevariousnativehigh-performancemediainterfaces,(forvideo,audio,etc)andpresentingasinglesource-codelevelAPItoyourapplication.SDLisafairlylowlevelAPI,butusingit,completelyportableapplicationscanbewrittenwithagreatdealofflexibility.

Prev Home NextSDLGuide Up AboutSDLdoc

SDLLibraryDocumentationPrev Preface Next

AboutSDLdocSDLdoc(TheSDLDocumentationProject)wasformedtocompletelyrewritetheSDLdocumentationandtokeepitcontinuallyuptodate.TheteamconsistscompletelyofvolunteersrangingfrompeopleworkingwithSDLintheirsparetimetopeoplewhouseSDLintheireverydayworkinglives.

Thelatestversionofthisdocumentationcanalwaysbefoundhere:http://sdldoc.csn.ul.ieDownloadablePS,manpagesandhtmltarballsareavailableathttp://sdldoc.csn.ul.ie/pub/

Prev Home NextPreface Up Credits

SDLLibraryDocumentationPrev Preface Next

CreditsSamLantinga,slouken@libsdl.orgMartinDonlon,akawaka@skynet.ieMattiasEngdegårdJulianPetersonKenJordanMaximSobolevWesleyPooleMichaelVanceAndreasUmbachAndreasHofmeister

Prev Home NextAboutSDLdoc Up TheBasics

SDLLibraryDocumentationPrev Next

Chapter1.TheBasicsTableofContentsIntroductionInitializingSDL

IntroductionTheSDLGuidesectionisprettyincomplete.Ifyoufeelyouhaveanythingtoaddmailakawaka@skynet.ieorvisithttp://akawaka.csn.ul.ie/tne/.

Prev Home NextCredits Up InitializingSDL

SDLLibraryDocumentationPrev Chapter1.TheBasics Next

InitializingSDLSDLiscomposedofeightsubsystems-Audio,CDROM,EventHandling,FileI/O,JoystickHandling,Threading,TimersandVideo.BeforeyoucanuseanyofthesesubsystemstheymustbeinitializedbycallingSDL_Init(orSDL_InitSubSystem).SDL_InitmustbecalledbeforeanyotherSDLfunction.ItautomaticallyinitializestheEventHandling,FileI/OandThreadingsubsystemsandittakesaparameterspecifyingwhichothersubsystemstoinitialize.So,toinitializethedefaultsubsystemsandtheVideosubsystemsyouwouldcall:

SDL_Init(SDL_INIT_VIDEO);

Toinitializethedefaultsubsystems,theVideosubsystemandtheTimerssubsystemyouwouldcall:

SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER);

SDL_InitiscomplementedbySDL_Quit(andSDL_QuitSubSystem).SDL_Quitshutsdownallsubsystems,includingthedefaultones.ItshouldalwaysbecalledbeforeaSDLapplicationexits.

WithSDL_InitandSDL_QuitfirmlyembeddedinyourprogrammerstoolkityoucanwriteyourfirstandmostbasicSDLapplication.However,wemustbepreparetohandleerrors.ManySDLfunctionsreturnavalueandindicateswhetherthefunctionhassucceededorfailed,SDL_Init,forinstance,returns-1ifitcouldnotinitializeasubsystem.SDLprovidesausefulfacilitythatallowsyoutodetermineexactlywhattheproblemwas,everytimeanerroroccurswithinSDLanerrormessageisstoredwhichcanberetrievedusingSDL_GetError.Usethisoften,youcanneverknowtoomuchaboutanerror.

Example1-1.InitializingSDL

#include"SDL.h"/*AllSDLApp'sneedthis*/

#include<stdio.h>

intmain(){

printf("InitializingSDL.\n");

/*Initializedefaults,VideoandAudio*/

if((SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO)==-1)){

printf("CouldnotinitializeSDL:%s.\n",SDL_GetError());

exit(-1);

}

printf("SDLinitialized.\n");

printf("QuitingSDL.\n");

/*Shutdownallsubsystems*/

SDL_Quit();

printf("Quiting....\n");

exit(0);

}

Prev Home NextTheBasics Up GraphicsandVideo

SDLLibraryDocumentationPrev Next

Chapter2.GraphicsandVideoTableofContentsIntroductiontoSDLVideoUsingOpenGLWithSDL

IntroductiontoSDLVideoVideoisprobablythemostcommonthingthatSDLisusedfor,andsoithasthemostcompletesubsystem.Hereareafewexamplestodemonstratethebasics.

InitializingtheVideoDisplay

ThisiswhatalmostallSDLprogramshavetodoinonewayoranother.

Example2-1.InitializingtheVideoDisplay

SDL_Surface*screen;

/*InitializetheSDLlibrary*/

if(SDL_Init(SDL_INIT_VIDEO)<0){

fprintf(stderr,

"Couldn'tinitializeSDL:%s\n",SDL_GetError());

exit(1);

}

/*Cleanuponexit*/

atexit(SDL_Quit);

/*

*Initializethedisplayina640x4808-bitpalettizedmode,

*requestingasoftwaresurface

*/

screen=SDL_SetVideoMode(640,480,8,SDL_SWSURFACE);

if(screen==NULL){

fprintf(stderr,"Couldn'tset640x480x8videomode:%s\n",

SDL_GetError());

exit(1);

}

InitializingtheBestVideoMode

Ifyouhaveapreferenceforacertainpixeldepthbutwillacceptanyother,useSDL_SetVideoModewithSDL_ANYFORMATasbelow.YoucanalsouseSDL_VideoModeOK()tofindthenativevideomodethatisclosesttothemodeyourequest.

Example2-2.InitializingtheBestVideoMode

/*Haveapreferencefor8-bit,butacceptanydepth*/

screen=SDL_SetVideoMode(640,480,8,SDL_SWSURFACE|SDL_ANYFORMAT);

if(screen==NULL){

fprintf(stderr,"Couldn'tset640x480x8videomode:%s\n",

SDL_GetError());

exit(1);

}

printf("Set640x480at%dbits-per-pixelmode\n",

screen->format->BitsPerPixel);

LoadingandDisplayingaBMPFile

ThefollowingfunctionloadsanddisplaysaBMPfilegivenasargument,onceSDLisinitialisedandavideomodehasbeenset.

Example2-3.LoadingandDisplayingaBMPFile

voiddisplay_bmp(char*file_name)

{

SDL_Surface*image;

/*LoadtheBMPfileintoasurface*/

image=SDL_LoadBMP(file_name);

if(image==NULL){

fprintf(stderr,"Couldn'tload%s:%s\n",file_name,SDL_GetError());

return;

}

/*

*Palettizedscreenmodeswillhaveadefaultpalette(astandard

*8*8*4colourcube),butiftheimageispalettizedaswellwecan

*usethatpaletteforanicercolourmatching

*/

if(image->format->palette&&screen->format->palette){

SDL_SetColors(screen,image->format->palette->colors,0,

image->format->palette->ncolors);

}

/*Blitontothescreensurface*/

if(SDL_BlitSurface(image,NULL,screen,NULL)<0)

fprintf(stderr,"BlitSurfaceerror:%s\n",SDL_GetError());

SDL_UpdateRect(screen,0,0,image->w,image->h);

/*FreetheallocatedBMPsurface*/

SDL_FreeSurface(image);

}

DrawingDirectlytotheDisplay

Thefollowingtwofunctionscanbeusedtogetandsetsinglepixelsofasurface.TheyarecarefullywrittentoworkwithanydepthcurrentlysupportedbySDL.Remembertolockthesurfacebeforecallingthem,andtounlockitbeforecallinganyotherSDLfunctions.

Toconvertbetweenpixelvaluesandtheirred,green,bluecomponents,useSDL_GetRGB()andSDL_MapRGB().

Example2-4.getpixel()

/*

*Returnthepixelvalueat(x,y)

*NOTE:Thesurfacemustbelockedbeforecallingthis!

*/

Uint32getpixel(SDL_Surface*surface,intx,inty)

{

intbpp=surface->format->BytesPerPixel;

/*Herepistheaddresstothepixelwewanttoretrieve*/

Uint8*p=(Uint8*)surface->pixels+y*surface->pitch+x*bpp;

switch(bpp){

case1:

return*p;

case2:

return*(Uint16*)p;

case3:

if(SDL_BYTEORDER==SDL_BIG_ENDIAN)

returnp[0]<<16|p[1]<<8|p[2];

else

returnp[0]|p[1]<<8|p[2]<<16;

case4:

return*(Uint32*)p;

default:

return0;/*shouldn'thappen,butavoidswarnings*/

}

}

Example2-5.putpixel()

/*

*Setthepixelat(x,y)tothegivenvalue

*NOTE:Thesurfacemustbelockedbeforecallingthis!

*/

voidputpixel(SDL_Surface*surface,intx,inty,Uint32pixel)

{

intbpp=surface->format->BytesPerPixel;

/*Herepistheaddresstothepixelwewanttoset*/

Uint8*p=(Uint8*)surface->pixels+y*surface->pitch+x*bpp;

switch(bpp){

case1:

*p=pixel;

break;

case2:

*(Uint16*)p=pixel;

break;

case3:

if(SDL_BYTEORDER==SDL_BIG_ENDIAN){

p[0]=(pixel>>16)&0xff;

p[1]=(pixel>>8)&0xff;

p[2]=pixel&0xff;

}else{

p[0]=pixel&0xff;

p[1]=(pixel>>8)&0xff;

p[2]=(pixel>>16)&0xff;

}

break;

case4:

*(Uint32*)p=pixel;

break;

}

}

Thefollowingcodeusestheputpixel()functionabovetosetayellowpixelinthemiddleofthescreen.

Example2-6.Usingputpixel()

/*Codetosetayellowpixelatthecenterofthescreen*/

intx,y;

Uint32yellow;

/*Mapthecoloryellowtothisdisplay(R=0xff,G=0xFF,B=0x00)

Note:Ifthedisplayispalettized,youmustsetthepalettefirst.

*/

yellow=SDL_MapRGB(screen->format,0xff,0xff,0x00);

x=screen->w/2;

y=screen->h/2;

/*Lockthescreenfordirectaccesstothepixels*/

if(SDL_MUSTLOCK(screen)){

if(SDL_LockSurface(screen)<0){

fprintf(stderr,"Can'tlockscreen:%s\n",SDL_GetError());

return;

}

}

putpixel(screen,x,y,yellow);

if(SDL_MUSTLOCK(screen)){

SDL_UnlockSurface(screen);

}

/*Updatejustthepartofthedisplaythatwe'vechanged*/

SDL_UpdateRect(screen,x,y,1,1);

return;

Prev Home NextInitializingSDL Up UsingOpenGLWithSDL

SDLLibraryDocumentationPrev Chapter2.GraphicsandVideo Next

UsingOpenGLWithSDLSDLhastheabilitytocreateanduseOpenGLcontextsonseveralplatforms(Linux/X11,Win32,BeOS,MacOSClassic/Toolbox,MacOSX,FreeBSD/X11andSolaris/X11).ThisallowsyoutouseSDL'saudio,eventhandling,threadsandtimesinyourOpenGLapplications(afunctionoftenperformedbyGLUT).

Initialisation

InitialisingSDLtouseOpenGLisnotverydifferenttoinitialisingSDLnormally.Therearethreedifferences;youmustpassSDL_OPENGLtoSDL_SetVideoMode,youmustspecifyseveralGLattributes(depthbuffersize,framebuffersizes)usingSDL_GL_SetAttributeandfinally,ifyouwishtousedoublebufferingyoumustspecifyitasaGLattribute,notbypassingtheSDL_DOUBLEBUFflagtoSDL_SetVideoMode.

Example2-7.InitializingSDLwithOpenGL

/*Informationaboutthecurrentvideosettings.*/

constSDL_VideoInfo*info=NULL;

/*Dimensionsofourwindow.*/

intwidth=0;

intheight=0;

/*Colordepthinbitsofourwindow.*/

intbpp=0;

/*FlagswewillpassintoSDL_SetVideoMode.*/

intflags=0;

/*First,initializeSDL'svideosubsystem.*/

if(SDL_Init(SDL_INIT_VIDEO)<0){

/*Failed,exit.*/

fprintf(stderr,"Videoinitializationfailed:%s\n",

SDL_GetError());

quit_tutorial(1);

}

/*Let'sgetsomevideoinformation.*/

info=SDL_GetVideoInfo();

if(!info){

/*Thisshouldprobablyneverhappen.*/

fprintf(stderr,"Videoqueryfailed:%s\n",

SDL_GetError());

quit_tutorial(1);

}

/*

*Setourwidth/heightto640/480(youwould

*ofcourselettheuserdecidethisinanormal

*app).Wegetthebppwewillrequestfrom

*thedisplay.OnX11,VidModecan'tchange

*resolution,sothisisprobablybeingoverly

*safe.UnderWin32,ChangeDisplaySettings

*canchangethebpp.

*/

width=640;

height=480;

bpp=info->vfmt->BitsPerPixel;

/*

*Now,wewanttosetupourrequested

*windowattributesforourOpenGLwindow.

*Wewant*atleast*5bitsofred,green

*andblue.Wealsowantatleasta16-bit

*depthbuffer.

*

*Thelastthingwedoisrequestadouble

*bufferedwindow.'1'turnsondouble

*buffering,'0'turnsitoff.

*

*NotethatwedonotuseSDL_DOUBLEBUFin

*theflagstoSDL_SetVideoMode.Thatdoes

*notaffecttheGLattributestate,only

*thestandard2Dblittingsetup.

*/

SDL_GL_SetAttribute(SDL_GL_RED_SIZE,5);

SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,5);

SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,5);

SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);

SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);

/*

*WewanttorequestthatSDLprovideus

*withanOpenGLwindow,inafullscreen

*videomode.

*

*EXERCISE:

*Makestartingwindowedanoption,and

*handletheresizeeventsproperlywith

*glViewport.

*/

flags=SDL_OPENGL|SDL_FULLSCREEN;

/*

*Setthevideomode

*/

if(SDL_SetVideoMode(width,height,bpp,flags)==0){

/*

*Thiscouldhappenforavarietyofreasons,

*includingDISPLAYnotbeingset,thespecified

*resolutionnotbeingavailable,etc.

*/

fprintf(stderr,"Videomodesetfailed:%s\n",

SDL_GetError());

quit_tutorial(1);

}

Drawing

Apartfrominitialisation,usingOpenGLwithinSDListhesameasusingOpenGLwithanyotherAPI,e.g.GLUT.Youstilluseallthesamefunctioncallsanddatatypes.Howeverifyouareusingadouble-buffereddisplay,thenyoumustuseSDL_GL_SwapBuffers()toswapthebuffersandupdatethedisplay.Torequestdouble-bufferingwithOpenGL,useSDL_GL_SetAttributewithSDL_GL_DOUBLEBUFFER,anduseSDL_GL_GetAttributetoseeifyouactuallygotit.

Afullexamplecodelistingisnowpresentedbelow.

Example2-8.SDLandOpenGL

/*

*SDLOpenGLTutorial.

*(c)MichaelVance,2000

*briareos@lokigames.com

*

*DistributedundertermsoftheLGPL.

*/

#include<SDL/SDL.h>

#include<GL/gl.h>

#include<GL/glu.h>

#include<stdio.h>

#include<stdlib.h>

staticGLbooleanshould_rotate=GL_TRUE;

staticvoidquit_tutorial(intcode)

{

/*

*QuitSDLsowecanreleasethefullscreen

*modeandrestorethepreviousvideosettings,

*etc.

*/

SDL_Quit();

/*Exitprogram.*/

exit(code);

}

staticvoidhandle_key_down(SDL_keysym*keysym)

{

/*

*We'reonlyinterestedif'Esc'has

*beenpresssed.

*

*EXERCISE:

*Handlethearrowkeysandhavethatchangethe

*viewingposition/angle.

*/

switch(keysym->sym){

caseSDLK_ESCAPE:

quit_tutorial(0);

break;

caseSDLK_SPACE:

should_rotate=!should_rotate;

break;

default:

break;

}

}

staticvoidprocess_events(void)

{

/*OurSDLeventplaceholder.*/

SDL_Eventevent;

/*Graballtheeventsoffthequeue.*/

while(SDL_PollEvent(&event)){

switch(event.type){

caseSDL_KEYDOWN:

/*Handlekeypresses.*/

handle_key_down(&event.key.keysym);

break;

caseSDL_QUIT:

/*Handlequitrequests(likeCtrl-c).*/

quit_tutorial(0);

break;

}

}

}

staticvoiddraw_screen(void)

{

/*Ourangleofrotation.*/

staticfloatangle=0.0f;

/*

*EXERCISE:

*Replacethisawfulmesswithvertex

*arraysandacalltoglDrawElements.

*

*EXERCISE:

*Aftercompletingtheabove,change

*ittousecompiledvertexarrays.

*

*EXERCISE:

*Verifymywindingsarecorrecthere;).

*/

staticGLfloatv0[]={-1.0f,-1.0f,1.0f};

staticGLfloatv1[]={1.0f,-1.0f,1.0f};

staticGLfloatv2[]={1.0f,1.0f,1.0f};

staticGLfloatv3[]={-1.0f,1.0f,1.0f};

staticGLfloatv4[]={-1.0f,-1.0f,-1.0f};

staticGLfloatv5[]={1.0f,-1.0f,-1.0f};

staticGLfloatv6[]={1.0f,1.0f,-1.0f};

staticGLfloatv7[]={-1.0f,1.0f,-1.0f};

staticGLubytered[]={255,0,0,255};

staticGLubytegreen[]={0,255,0,255};

staticGLubyteblue[]={0,0,255,255};

staticGLubytewhite[]={255,255,255,255};

staticGLubyteyellow[]={0,255,255,255};

staticGLubyteblack[]={0,0,0,255};

staticGLubyteorange[]={255,255,0,255};

staticGLubytepurple[]={255,0,255,0};

/*Clearthecoloranddepthbuffers.*/

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

/*Wedon'twanttomodifytheprojectionmatrix.*/

glMatrixMode(GL_MODELVIEW);

glLoadIdentity();

/*Movedownthez-axis.*/

glTranslatef(0.0,0.0,-5.0);

/*Rotate.*/

glRotatef(angle,0.0,1.0,0.0);

if(should_rotate){

if(++angle>360.0f){

angle=0.0f;

}

}

/*Sendourtriangledatatothepipeline.*/

glBegin(GL_TRIANGLES);

glColor4ubv(red);

glVertex3fv(v0);

glColor4ubv(green);

glVertex3fv(v1);

glColor4ubv(blue);

glVertex3fv(v2);

glColor4ubv(red);

glVertex3fv(v0);

glColor4ubv(blue);

glVertex3fv(v2);

glColor4ubv(white);

glVertex3fv(v3);

glColor4ubv(green);

glVertex3fv(v1);

glColor4ubv(black);

glVertex3fv(v5);

glColor4ubv(orange);

glVertex3fv(v6);

glColor4ubv(green);

glVertex3fv(v1);

glColor4ubv(orange);

glVertex3fv(v6);

glColor4ubv(blue);

glVertex3fv(v2);

glColor4ubv(black);

glVertex3fv(v5);

glColor4ubv(yellow);

glVertex3fv(v4);

glColor4ubv(purple);

glVertex3fv(v7);

glColor4ubv(black);

glVertex3fv(v5);

glColor4ubv(purple);

glVertex3fv(v7);

glColor4ubv(orange);

glVertex3fv(v6);

glColor4ubv(yellow);

glVertex3fv(v4);

glColor4ubv(red);

glVertex3fv(v0);

glColor4ubv(white);

glVertex3fv(v3);

glColor4ubv(yellow);

glVertex3fv(v4);

glColor4ubv(white);

glVertex3fv(v3);

glColor4ubv(purple);

glVertex3fv(v7);

glColor4ubv(white);

glVertex3fv(v3);

glColor4ubv(blue);

glVertex3fv(v2);

glColor4ubv(orange);

glVertex3fv(v6);

glColor4ubv(white);

glVertex3fv(v3);

glColor4ubv(orange);

glVertex3fv(v6);

glColor4ubv(purple);

glVertex3fv(v7);

glColor4ubv(green);

glVertex3fv(v1);

glColor4ubv(red);

glVertex3fv(v0);

glColor4ubv(yellow);

glVertex3fv(v4);

glColor4ubv(green);

glVertex3fv(v1);

glColor4ubv(yellow);

glVertex3fv(v4);

glColor4ubv(black);

glVertex3fv(v5);

glEnd();

/*

*EXERCISE:

*Drawtexttellingtheuserthat'Spc'

*pausestherotationand'Esc'quits.

*Doitusingvetorsandtexturedquads.

*/

/*

*Swapthebuffers.Thisthistellsthedriverto

*renderthenextframefromthecontentsofthe

*back-buffer,andtosetallrenderingoperations

*tooccuronwhatwasthefront-buffer.

*

*Doublebufferingpreventsnastyvisualtearing

*fromtheapplicationdrawingonareasofthe

*screenthatarebeingupdatedatthesametime.

*/

SDL_GL_SwapBuffers();

}

staticvoidsetup_opengl(intwidth,intheight)

{

floatratio=(float)width/(float)height;

/*Ourshadingmodel--Gouraud(smooth).*/

glShadeModel(GL_SMOOTH);

/*Culling.*/

glCullFace(GL_BACK);

glFrontFace(GL_CCW);

glEnable(GL_CULL_FACE);

/*Settheclearcolor.*/

glClearColor(0,0,0,0);

/*Setupourviewport.*/

glViewport(0,0,width,height);

/*

*Changetotheprojectionmatrixandset

*ourviewingvolume.

*/

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

/*

*EXERCISE:

*ReplacethiswithacalltoglFrustum.

*/

gluPerspective(60.0,ratio,1.0,1024.0);

}

intmain(intargc,char*argv[])

{

/*Informationaboutthecurrentvideosettings.*/

constSDL_VideoInfo*info=NULL;

/*Dimensionsofourwindow.*/

intwidth=0;

intheight=0;

/*Colordepthinbitsofourwindow.*/

intbpp=0;

/*FlagswewillpassintoSDL_SetVideoMode.*/

intflags=0;

/*First,initializeSDL'svideosubsystem.*/

if(SDL_Init(SDL_INIT_VIDEO)<0){

/*Failed,exit.*/

fprintf(stderr,"Videoinitializationfailed:%s\n",

SDL_GetError());

quit_tutorial(1);

}

/*Let'sgetsomevideoinformation.*/

info=SDL_GetVideoInfo();

if(!info){

/*Thisshouldprobablyneverhappen.*/

fprintf(stderr,"Videoqueryfailed:%s\n",

SDL_GetError());

quit_tutorial(1);

}

/*

*Setourwidth/heightto640/480(youwould

*ofcourselettheuserdecidethisinanormal

*app).Wegetthebppwewillrequestfrom

*thedisplay.OnX11,VidModecan'tchange

*resolution,sothisisprobablybeingoverly

*safe.UnderWin32,ChangeDisplaySettings

*canchangethebpp.

*/

width=640;

height=480;

bpp=info->vfmt->BitsPerPixel;

/*

*Now,wewanttosetupourrequested

*windowattributesforourOpenGLwindow.

*Wewant*atleast*5bitsofred,green

*andblue.Wealsowantatleasta16-bit

*depthbuffer.

*

*Thelastthingwedoisrequestadouble

*bufferedwindow.'1'turnsondouble

*buffering,'0'turnsitoff.

*

*NotethatwedonotuseSDL_DOUBLEBUFin

*theflagstoSDL_SetVideoMode.Thatdoes

*notaffecttheGLattributestate,only

*thestandard2Dblittingsetup.

*/

SDL_GL_SetAttribute(SDL_GL_RED_SIZE,5);

SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,5);

SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,5);

SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);

SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);

/*

*WewanttorequestthatSDLprovideus

*withanOpenGLwindow,inafullscreen

*videomode.

*

*EXERCISE:

*Makestartingwindowedanoption,and

*handletheresizeeventsproperlywith

*glViewport.

*/

flags=SDL_OPENGL|SDL_FULLSCREEN;

/*

*Setthevideomode

*/

if(SDL_SetVideoMode(width,height,bpp,flags)==0){

/*

*Thiscouldhappenforavarietyofreasons,

*includingDISPLAYnotbeingset,thespecified

*resolutionnotbeingavailable,etc.

*/

fprintf(stderr,"Videomodesetfailed:%s\n",

SDL_GetError());

quit_tutorial(1);

}

/*

*Atthispoint,weshouldhaveaproperlysetup

*double-bufferedwindowforusewithOpenGL.

*/

setup_opengl(width,height);

/*

*Nowwewanttobeginournormalappprocess--

*aneventloopwithalotofredrawing.

*/

while(1){

/*Processincomingevents.*/

process_events();

/*Drawthescreen.*/

draw_screen();

}

/*

*EXERCISE:

*RecordtimingsusingSDL_GetTicks()and

*andprintoutframespersecondatprogram

*end.

*/

/*Neverreached.*/

return0;

}

Prev Home NextGraphicsandVideo Up Inputhandling

SDLLibraryDocumentationPrev Next

Chapter3.InputhandlingTableofContentsHandlingJoysticksHandlingtheKeyboard

HandlingJoysticks

Initialization

ThefirststepinusingajoystickinaSDLprogramistoinitializetheJoysticksubsystemsofSDL.ThisdonebypassingtheSDL_INIT_JOYSTICKflagtoSDL_Init.Thejoystickflagwillusuallybeusedinconjunctionwithotherflags(likethevideoflag)becausethejoystickisusuallyusedtocontrolsomething.

Example3-1.InitializingSDLwithJoystickSupport

if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK)<0)

{

fprintf(stderr,"Couldn'tinitializeSDL:%s\n",SDL_GetError());

exit(1);

}

ThiswillattempttostartSDLwithboththevideoandthejoysticksubsystemsactivated.

Querying

IfwehavereachedthispointthenwecansafelyassumethattheSDLlibraryhasbeeninitializedandthattheJoysticksubsystemisactive.Wecannowcallsomevideoand/orsoundfunctionstogetthingsgoingbeforeweneedthejoystick.Eventuallywehavetomakesurethatthereisactuallyajoysticktoworkwith.It'swisetoalwayscheckevenifyouknowajoystickwillbepresentonthesystembecauseitcanalsohelpdetectwhenthejoystickisunplugged.ThefunctionusedtocheckforjoysticksisSDL_NumJoysticks.

Thisfunctionsimplyreturnsthenumberofjoysticksavailableonthesystem.Ifitisatleastonethenweareingoodshape.Thenextstepistodeterminewhichjoysticktheuserwantstouse.Ifthenumberofjoysticksavailableisonlyonethenitissafetoassumethatonejoystickistheonetheuserwantstouse.SDLhasafunctiontogetthenameofthejoysticksasassignedbytheoperationssystemandthatfunctionisSDL_JoystickName.Thejoystickisspecifiedbyanindexwhere0isthefirstjoystickandthelastjoystickisthenumberreturnedbySDL_NumJoysticks-1.Inthedemonstrationalistofallavailablejoysticksisprintedtostdout.

Example3-2.QueryingtheNumberofAvailableJoysticks

printf("%ijoystickswerefound.\n\n",SDL_NumJoysticks());

printf("Thenamesofthejoysticksare:\n");

for(i=0;i<SDL_NumJoysticks();i++)

{

printf("%s\n",SDL_JoystickName(i));

}

OpeningaJoystickandReceivingJoystickEvents

SDL'seventdrivenarchitecturemakesworkingwithjoysticksasnap.Joystickscantrigger4differenttypesofevents:

SDL_JoyAxisEvent OccurswhenanaxischangesSDL_JoyBallEvent Occurswhenajoysticktrackball'spositionchangesSDL_JoyHatEvent Occurswhenahat'spositionchangesSDL_JoyButtonEvent Occurswhenabuttonispressedorreleased

Eventsarereceivedfromalljoysticksopened.ThefirstthingthatneedstobedoneinordertoreceivejoystickeventsistocallSDL_JoystickEventStatewiththeSDL_ENABLEflag.Nextyoumustopenthejoysticksthatyouwanttoreceiveenventsfrom.ThisisdonewiththeSDL_JoystickOpenfunction.Fortheexampleweareonlyinterestedineventsfromthefirstjoystickonthesystem,regardlessofwhatitmaybe.Toreceiveeventsfromitwewoulddothis:

Example3-3.OpeningaJoystick

SDL_Joystick*joystick;

SDL_JoystickEventState(SDL_ENABLE);

joystick=SDL_JoystickOpen(0);

IfwewantedtoreceiveeventsforotherjoystickswewouldopenthemwithcallstoSDL_JoystickOpenjustlikeweopenedjoystick0,exceptwewouldstoretheSDL_Joystickstructuretheyreturninadifferentpointer.Weonlyneedthejoystickpointerwhenwearequeryingthejoysticksorwhenweareclosingthejoystick.

Uptothispointallthecodewehaveisusedjusttoinitializethejoysticksinordertoreadvaluesatruntime.Allweneednowisaneventloop,whichissomethingthatallSDLprogramsshouldhaveanywaytoreceivethesystemsquitevents.Wemustnowaddcodetochecktheeventloopforatleastsomeoftheabovementionedevents.Let'sassumeoureventlooplookslikethis:

SDL_Eventevent;

/*Otherinitializtioncodegoeshere*/

/*Startmaingameloophere*/

while(SDL_PollEvent(&event))

{

switch(event.type)

{

caseSDL_KEYDOWN:

/*handlekeyboardstuffhere*/

break;

caseSDL_QUIT:

/*Setwhateverflagsarenecessaryto*/

/*endthemaingameloophere*/

break;

}

}

/*Endloophere*/

TohandleJoystickeventswemerelyaddcasesforthem,firstwe'lladdaxishandlingcode.Axischeckscangetkindaoftrickybecausealotofthejoystickeventsreceivedarejunk.Joystickaxishaveatendencytovaryjustalittlebetweenpollingduetothewaytheyaredesigned.Tocompensateforthisyouhavetosetathresholdforchangesandignoretheeventsthathave'ntexceededthethreshold.10%isusuallyagoodthresholdvalue.Thissoundsalotmorecomplicatedthanitis.HereistheAxiseventhandler:

Example3-4.JoystickAxisEvents

caseSDL_JOYAXISMOTION:/*HandleJoystickMotion*/

if((event.jaxis.value<-3200)||(event.jaxis.value>3200))

{

/*codegoeshere*/

}

break;

Anothertrickwithaxiseventsisthatup-downandleft-rightmovementaretwodifferentsetsofaxes.Themostimportantaxisisaxis0(left-right)andaxis1(up-down).Tohandlethemseperatlyinthecodewedothefollowing:

Example3-5.MoreJoystickAxisEvents

caseSDL_JOYAXISMOTION:/*HandleJoystickMotion*/

if((event.jaxis.value<-3200)||(event.jaxis.value>3200))

{

if(event.jaxis.axis==0)

{

/*Left-rightmovementcodegoeshere*/

}

if(event.jaxis.axis==1)

{

/*Up-Downmovementcodegoeshere*/

}

}

break;

Ideallythecodehereshoulduseevent.jaxis.valuetoscalesomething.Forexampleletsassumeyouareusingthejoysticktocontrolthemovementofaspaceship.Iftheuserisusingananalogjoystickandtheypushthestickalittlebittheyexpecttomovelessthaniftheypusheditalot.Designingyourcodeforthissituationispreferredbecauseitmakestheexperienceforusersofanalogcontrolsbetterandremainsthesameforusersofdigitalcontrols.

Ifyourjoystickhasanyadditionalaxisthentheymaybeusedforothersticksorthrottlecontrolsandthoseaxisreturnvaluestoojustwithdifferentevent.jaxis.axisvalues.

Buttonhandlingissimplecomparedtotheaxischecking.

Example3-6.JoystickButtonEvents

caseSDL_JOYBUTTONDOWN:/*HandleJoystickButtonPresses*/

if(event.jbutton.button==0)

{

/*codegoeshere*/

}

break;

Buttonchecksaresimplerthanaxischecksbecauseabuttoncanonlybepressedornotpressed.TheSDL_JOYBUTTONDOWNeventistriggeredwhenabuttonispressedandtheSDL_JOYBUTTONUPeventisfiredwhenabuttonisreleased.Wedohavetoknowwhatbuttonwaspressedthough,thatisdonebyreadingtheevent.jbutton.buttonfield.

LastlywhenwearethroughusingourjoysticksweshouldclosethemwithacalltoSDL_JoystickClose.Tocloseouropenedjoystick0wewoulddothisattheendofourprogram:

SDL_JoystickClose(joystick);

AdvancedJoystickFunctions

Thattakescareofthecontrolsthatyoucancountonbeingoneveryjoystickunderthesun,butthereareafewextrathingsthatSDLcansupport.Joyballsarenextonourlist,theyarealotlikeaxiswithafewminordifferences.Joyballsstorerelativechangesunlikethetheabsolutepostionstoredinaaxisevent.Alsoonetrackballeventcontainsboththechangeinxandtheychangeiny.Ourcaseforitisasfollows:

Example3-7.JoystickBallEvents

caseSDL_JOYBALLMOTION:/*HandleJoyballMotion*/

if(event.jball.ball==0)

{

/*ballhandling*/

}

break;

Theabovechecksthefirstjoyballonthejoystick.Thechangeinpositionwillbestoredinevent.jball.xrelandevent.jball.yrel.

Finallywehavethehatevent.Hatsreportonlythedirectiontheyarepushedin.Wecheckhat'spositionwiththebitmasks:

SDL_HAT_CENTERED

SDL_HAT_UP

SDL_HAT_RIGHT

SDL_HAT_DOWN

SDL_HAT_LEFT

Alsotherearesomepredefinedcombinationsoftheabove:

SDL_HAT_RIGHTUP

SDL_HAT_RIGHTDOWN

SDL_HAT_LEFTUP

SDL_HAT_LEFTDOWN

Ourcaseforthehatmayresemblethefollowing:

Example3-8.JoystickHatEvents

caseSDL_JOYHATMOTION:/*HandleHatMotion*/

if(event.jhat.hat&SDL_HAT_UP)

{

/*Doupstuffhere*/

}

if(event.jhat.hat&SDL_HAT_LEFT)

{

/*Doleftstuffhere*/

}

if(event.jhat.hat&SDL_HAT_RIGHTDOWN)

{

/*Dorightanddowntogetherstuffhere*/

}

break;

Inadditiontothequeriesfornumberofjoysticksonthesystemandtheirnamesthereareadditionalfunctionstoquerythecapabilitiesofattachedjoysticks:

SDL_JoystickNumAxes ReturnsthenumberofjoysitckaxesSDL_JoystickNumButtons ReturnsthenumberofjoysitckbuttonsSDL_JoystickNumBalls ReturnsthenumberofjoysitckballsSDL_JoystickNumHats Returnsthenumberofjoysitckhats

Tousethesefunctionswejusthavetopassinthejoystickstructurewegotwhenweopenedthejoystick.ForExample:

Example3-9.QueryingJoystickCharacteristics

intnumber_of_buttons;

SDL_Joystick*joystick;

joystick=SDL_JoystickOpen(0);

number_of_buttons=SDL_JoystickNumButtons(joystick);

Thisblockofcodewouldgetthenumberofbuttonsonthefirstjoystickinthesystem.

Prev Home NextUsingOpenGLWithSDL Up HandlingtheKeyboard

SDLLibraryDocumentationPrev Chapter3.Inputhandling Next

HandlingtheKeyboard

KeyboardRelatedStructures

Itshouldmakeitaloteasiertounderstandthistutorialisyouarefamiliarwiththedatatypesinvolvedinkeyboardaccess,soI'llexplainthemfirst.

SDLKey

SDLKeyisanenumeratedtypedefinedinSDL/include/SDL_keysym.handdetailedhere.EachSDLKeysymbolrepresentsakey,SDLK_acorrespondstothe'a'keyonakeyboard,SDLK_SPACEcorrespondstothespacebar,andsoon.

SDLMod

SDLModisanenumeratedtype,similartoSDLKey,howeveritenumerateskeyboardmodifiers(Control,Alt,Shift).Thefulllistofmodifiersymbolsishere.SDLModvaluescanbeAND'dtogethertorepresentseveralmodifiers.

SDL_keysym

typedefstruct{

Uint8scancode;

SDLKeysym;

SDLModmod;

Uint16unicode;

}SDL_keysym;

TheSDL_keysymstructuredescribesakeypressorakeyrelease.Thescancodefieldishardwarespecificandshouldbeignoredunlessyouknowwhatyourdoing.ThesymfieldistheSDLKeyvalueofthekeybeingpressedorreleased.Themodfielddescribesthestateofthekeyboardmodifiersatthetimethekeypressorreleaseoccurred.SoavalueofKMOD_NUM|KMOD_CAPS|KMOD_LSHIFTwouldmeanthatNumlock,Capslockandtheleftshiftkeywereallpress(orenabledinthecaseofthelockkeys).Finally,theunicodefieldstoresthe16-bitunicodevalueofthekey.

Note:ItshouldbenotedandunderstoodthatthisfieldisonlyvalidwhentheSDL_keysymisdescribingakeypress,notakeyrelease.Unicodevaluesonlymakesenseonakeypressbecausetheunicodevaluedescribes

aninternationalcharacterandonlykeypressesproducecharacters.MoreinformationonUnicodecanbefoundatwww.unicode.org

Note:UnicodetranslationmustbeenabledusingtheSDL_EnableUNICODEfunction.

SDL_KeyboardEvent

typedefstruct{

Uint8type;

Uint8state;

SDL_keysymkeysym;

}SDL_KeyboardEvent;

TheSDL_KeyboardEventdescribesakeyboardevent(obviously).ThekeymemberoftheSDL_EventunionisaSDL_KeyboardEventstructure.Thetypefieldspecifieswhethertheeventisakeyrelease(SDL_KEYUP)orakeypress(SDL_KEYDOWN)event.Thestateislargelyredundant,itreportsthesameinformationasthetypefieldbutusesdifferentvalues(SDL_RELEASEDandSDL_PRESSED).Thekeysymcontainsinformationofthekeypressorreleasethatthiseventrepresents(seeabove).

ReadingKeyboardEvents

Readingkeybaordeventsfromtheeventqueueisquitesimple(theeventqueueandusingitisdescribedhere).WereadeventsusingSDL_PollEventinawhile()loopandcheckforSDL_KEYUPandSDL_KEYDOWNeventsusingaswitchstatement,likeso:

Example3-10.ReadingKeyboardEvents

SDL_Eventevent;

.

.

/*Pollforevents.SDL_PollEvent()returns0whenthereareno*/

/*moreeventsontheeventqueue,ourwhileloopwillexitwhen*/

/*thatoccurs.*/

while(SDL_PollEvent(&event)){

/*WeareonlyworriedaboutSDL_KEYDOWNandSDL_KEYUPevents*/

switch(event.type){

caseSDL_KEYDOWN:

printf("Keypressdetected\n");

break;

caseSDL_KEYUP:

printf("Keyreleasedetected\n");

break;

default:

break;

}

}

.

.

Thisisaverybasicexample.Noinformationaboutthekeypressorreleaseisinterpreted.Wewillexploretheotherextremeoutourfirstfullexamplebelow-reportingallavailableinformationaboutakeyboardevent.

AMoreDetailedLook

BeforewecanreadeventsSDLmustbeinitialisedwithSDL_InitandavideomodemustbesetusingSDL_SetVideoMode.Thereare,however,twootherfunctionswemustusetoobtainalltheinformationrequired.WemustenableunicodetranslationbycallingSDL_EnableUNICODE(1)andwemustconvertSDLKeyvaluesintosomethingprintable,usingSDL_GetKeyName

Note:Itisusefultonotethatunicodevalues<0x80translatedirectlyacharactersASCIIvalue.THisisusedintheexamplebelow

Example3-11.InterpretingKeyEventInformation

#include"SDL.h"

/*FunctionPrototypes*/

voidPrintKeyInfo(SDL_KeyboardEvent*key);

voidPrintModifiers(SDLModmod);

/*main*/

intmain(intargc,char*argv[]){

SDL_Eventevent;

intquit=0;

/*InitialiseSDL*/

if(SDL_Init(SDL_INIT_VIDEO)<0){

fprintf(stderr,"CouldnotinitialiseSDL:%s\n",SDL_GetError());

exit(-1);

}

/*Setavideomode*/

if(!SDL_SetVideoMode(320,200,0,0)){

fprintf(stderr,"Couldnotsetvideomode:%s\n",SDL_GetError());

SDL_Quit();

exit(-1);

}

/*EnableUnicodetranslation*/

SDL_EnableUNICODE(1);

/*LoopuntilanSDL_QUITeventisfound*/

while(!quit){

/*Pollforevents*/

while(SDL_PollEvent(&event)){

switch(event.type){

/*Keyboardevent*/

/*PasstheeventdataontoPrintKeyInfo()*/

caseSDL_KEYDOWN:

caseSDL_KEYUP:

PrintKeyInfo(&event.key);

break;

/*SDL_QUITevent(windowclose)*/

caseSDL_QUIT:

quit=1;

break;

default:

break;

}

}

}

/*Cleanup*/

SDL_Quit();

exit(0);

}

/*Printallinformationaboutakeyevent*/

voidPrintKeyInfo(SDL_KeyboardEvent*key){

/*Isitareleaseorapress?*/

if(key->type==SDL_KEYUP)

printf("Release:-");

else

printf("Press:-");

/*Printthehardwarescancodefirst*/

printf("Scancode:0x%02X",key->keysym.scancode);

/*Printthenameofthekey*/

printf(",Name:%s",SDL_GetKeyName(key->keysym.sym));

/*Wewanttoprinttheunicodeinfo,butweneedtomake*/

/*sureitsapresseventfirst(remember,releaseevents*/

/*don'thaveunicodeinfo*/

if(key->type==SDL_KEYDOWN){

/*IftheUnicodevalueislessthan0x80thenthe*/

/*unicodevaluecanbeusedtogetaprintable*/

/*representationofthekey,using(char)unicode.*/

printf(",Unicode:");

if(key->keysym.unicode<0x80&&key->keysym.unicode>0){

printf("%c(0x%04X)",(char)key->keysym.unicode,

key->keysym.unicode);

}

else{

printf("?(0x%04X)",key->keysym.unicode);

}

}

printf("\n");

/*Printmodifierinfo*/

PrintModifiers(key->keysym.mod);

}

/*Printmodifierinfo*/

voidPrintModifiers(SDLModmod){

printf("Modifers:");

/*Iftherearenonethensaysoandreturn*/

if(mod==KMOD_NONE){

printf("None\n");

return;

}

/*CheckforthepresenceofeachSDLModvalue*/

/*Thislooksmessy,buttherereallyisn't*/

/*aclearerway.*/

if(mod&KMOD_NUM)printf("NUMLOCK");

if(mod&KMOD_CAPS)printf("CAPSLOCK");

if(mod&KMOD_LCTRL)printf("LCTRL");

if(mod&KMOD_RCTRL)printf("RCTRL");

if(mod&KMOD_RSHIFT)printf("RSHIFT");

if(mod&KMOD_LSHIFT)printf("LSHIFT");

if(mod&KMOD_RALT)printf("RALT");

if(mod&KMOD_LALT)printf("LALT");

if(mod&KMOD_CTRL)printf("CTRL");

if(mod&KMOD_SHIFT)printf("SHIFT");

if(mod&KMOD_ALT)printf("ALT");

printf("\n");

}

Game-typeInput

Ihavefoundthatpeopleusingkeyboardeventsforgamesandotherinteractiveapplicationsdon'talwaysunderstandonefundementalpoint.

Keyboardeventsonlytakeplacewhenakeysstatechangesfrombeingunpressedtopressed,andviceversa.

Imagineyouhaveanimageofanalienthatyouwishtomovearoundusingthecursorkeys-whenyoupressedtheleftarrowkeyyouwanthimtoslideovertotheleft,whenyoupressthedownkeyyouwanthimtoslidedownthescreen.Examinethefollowingcode,ithighlightsanderrorthatmanypeoplehavemade.

/*Alienscreencoordinates*/

intalien_x=0,alien_y=0;

.

.

/*InitialiseSDLandvideomodesandallthat*/

.

/*Maingameloop*/

/*Checkforevents*/

while(SDL_PollEvent(&event)){

switch(event.type){

/*Lookforakeypress*/

caseSDL_KEYDOWN:

/*ChecktheSDLKeyvaluesandmovechangethecoords*/

switch(event.key.keysym.sym){

caseSDLK_LEFT:

alien_x-=1;

break;

caseSDLK_RIGHT:

alien_x+=1;

break;

caseSDLK_UP:

alien_y-=1;

break;

caseSDLK_DOWN:

alien_y+=1;

break;

default:

break;

}

}

}

}

.

.

Atfirstglanceyoumaythinkthisisaperfectlyreasonablepieceofcodeforthetask,butitisn't.LikeIsaidkeyboardeventsonlyoccurwhenakeychangesstate,sotheuserwouldhavetopressandreleasetheleftcursorkey100timestomovethealien100pixelstotheleft.

Togetaroundthisproblemwemustnotusetheeventstochangethepositionofthealien,weusetheeventstosetflagswhicharethenusedinaseperatesectionofcodetomovethealien.Somethinglikethis:

Example3-12.ProperGameMovement

/*Alienscreencoordinates*/

intalien_x=0,alien_y=0;

intalien_xvel=0,alien_yvel=0;

.

.

/*InitialiseSDLandvideomodesandallthat*/

.

/*Maingameloop*/

/*Checkforevents*/

while(SDL_PollEvent(&event)){

switch(event.type){

/*Lookforakeypress*/

caseSDL_KEYDOWN:

/*ChecktheSDLKeyvaluesandmovechangethecoords*/

switch(event.key.keysym.sym){

caseSDLK_LEFT:

alien_xvel=-1;

break;

caseSDLK_RIGHT:

alien_xvel=1;

break;

caseSDLK_UP:

alien_yvel=-1;

break;

caseSDLK_DOWN:

alien_yvel=1;

break;

default:

break;

}

break;

/*WemustalsousetheSDL_KEYUPeventstozerothex*/

/*andyvelocityvariables.Butwemustalsobe*/

/*carefulnottozerothevelocitieswhenweshouldn't*/

caseSDL_KEYUP:

switch(event.key.keysym.sym){

caseSDLK_LEFT:

/*Wechecktomakesurethealienismoving*/

/*totheleft.Ifitisthenwezerothe*/

/*velocity.Ifthealienismovingtothe*/

/*rightthentherightkeyisstillpress*/

/*sowedon'ttocuhthevelocity*/

if(alien_xvel<0)

alien_xvel=0;

break;

caseSDLK_RIGHT:

if(alien_xvel>0)

alien_xvel=0;

break;

caseSDLK_UP:

if(alien_yvel<0)

alien_yvel=0;

break;

caseSDLK_DOWN:

if(alien_yvel>0)

alien_yvel=0;

break;

default:

break;

}

break;

default:

break;

}

}

.

.

/*Updatethealienposition*/

alien_x+=alien_xvel;

alien_y+=alien_yvel;

Ascanbeseen,weusetwoextravariables,alien_xvelandalien_yvel,whichrepresentthemotionoftheship,itisthesevariablesthatweupdatewhenwedetectkeypressesandreleases.

Prev Home NextInputhandling Up Examples

SDLLibraryDocumentationPrev Next

Chapter4.ExamplesTableofContentsIntroductionEventExamplesAudioExamplesCDROMExamplesTimeExamples

IntroductionForthemomenttheseexamplesaretakendirectlyfromtheoldSDLdocumentation.Bythe1.2releasetheseexamplesshouldhopefullydealwithmostcommonSDLprogrammingproblems.

Prev Home NextHandlingtheKeyboard Up EventExamples

SDLLibraryDocumentationPrev Chapter4.Examples Next

EventExamples

FilteringandHandlingEvents#include<stdio.h>

#include<stdlib.h>

#include"SDL.h"

/*Thisfunctionmayruninaseparateeventthread*/

intFilterEvents(constSDL_Event*event){

staticintboycott=1;

/*Thisquiteventsignalstheclosingofthewindow*/

if((event->type==SDL_QUIT)&&boycott){

printf("Quiteventfilteredout--tryagain.\n");

boycott=0;

return(0);

}

if(event->type==SDL_MOUSEMOTION){

printf("Mousemovedto(%d,%d)\n",

event->motion.x,event->motion.y);

return(0);/*Dropit,we'vehandledit*/

}

return(1);

}

intmain(intargc,char*argv[])

{

SDL_Eventevent;

/*InitializetheSDLlibrary(startstheeventloop)*/

if(SDL_Init(SDL_INIT_VIDEO)<0){

fprintf(stderr,

"Couldn'tinitializeSDL:%s\n",SDL_GetError());

exit(1);

}

/*Cleanuponexit,exitonwindowcloseandinterrupt*/

atexit(SDL_Quit);

/*Ignorekeyevents*/

SDL_EventState(SDL_KEYDOWN,SDL_IGNORE);

SDL_EventState(SDL_KEYUP,SDL_IGNORE);

/*Filterquitandmousemotionevents*/

SDL_SetEventFilter(FilterEvents);

/*Themouseisn'tmuchuseunlesswehaveadisplayforreference*/

if(SDL_SetVideoMode(640,480,8,0)==NULL){

fprintf(stderr,"Couldn'tset640x480x8videomode:%s\n",

SDL_GetError());

exit(1);

}

/*LoopwaitingforESC+Mouse_Button*/

while(SDL_WaitEvent(&event)>=0){

switch(event.type){

caseSDL_ACTIVEEVENT:{

if(event.active.state&SDL_APPACTIVE){

if(event.active.gain){

printf("Appactivated\n");

}else{

printf("Appiconified\n");

}

}

}

break;

caseSDL_MOUSEBUTTONDOWN:{

Uint8*keys;

keys=SDL_GetKeyState(NULL);

if(keys[SDLK_ESCAPE]==SDL_PRESSED){

printf("Byebye...\n");

exit(0);

}

printf("Mousebuttonpressed\n");

}

break;

caseSDL_QUIT:{

printf("Quitrequested,quitting.\n");

exit(0);

}

break;

}

}

/*Thisshouldneverhappen*/

printf("SDL_WaitEventerror:%s\n",SDL_GetError());

exit(1);

}

Prev Home NextExamples Up AudioExamples

SDLLibraryDocumentationPrev Chapter4.Examples Next

AudioExamples

OpeningtheaudiodeviceSDL_AudioSpecwanted;

externvoidfill_audio(void*udata,Uint8*stream,intlen);

/*Settheaudioformat*/

wanted.freq=22050;

wanted.format=AUDIO_S16;

wanted.channels=2;/*1=mono,2=stereo*/

wanted.samples=1024;/*Goodlow-latencyvalueforcallback*/

wanted.callback=fill_audio;

wanted.userdata=NULL;

/*Opentheaudiodevice,forcingthedesiredformat*/

if(SDL_OpenAudio(&wanted,NULL)<0){

fprintf(stderr,"Couldn'topenaudio:%s\n",SDL_GetError());

return(-1);

}

return(0);

PlayingaudiostaticUint8*audio_chunk;

staticUint32audio_len;

staticUint8*audio_pos;

/*Theaudiofunctioncallbacktakesthefollowingparameters:

stream:Apointertotheaudiobuffertobefilled

len:Thelength(inbytes)oftheaudiobuffer

*/

voidfill_audio(void*udata,Uint8*stream,intlen)

{

/*Onlyplayifwehavedataleft*/

if(audio_len==0)

return;

/*Mixasmuchdataaspossible*/

len=(len>audio_len?audio_len:len);

SDL_MixAudio(stream,audio_pos,len,SDL_MIX_MAXVOLUME);

audio_pos+=len;

audio_len-=len;

}

/*Loadtheaudiodata...*/

;;;;;

audio_pos=audio_chunk;

/*Letthecallbackfunctionplaytheaudiochunk*/

SDL_PauseAudio(0);

/*Dosomeprocessing*/

;;;;;

/*Waitforsoundtocomplete*/

while(audio_len>0){

SDL_Delay(100);/*Sleep1/10second*/

}

SDL_CloseAudio();

Prev Home NextEventExamples Up CDROMExamples

SDLLibraryDocumentationPrev Chapter4.Examples Next

CDROMExamples

ListingCD-ROMdrives#include"SDL.h"

/*InitializeSDLfirst*/

if(SDL_Init(SDL_INIT_CDROM)<0){

fprintf(stderr,"Couldn'tinitializeSDL:%s\n",SDL_GetError());

exit(1);

}

atexit(SDL_Quit);

/*FindouthowmanyCD-ROMdrivesareconnectedtothesystem*/

printf("Drivesavailable:%d\n",SDL_CDNumDrives());

for(i=0;i<SDL_CDNumDrives();++i){

printf("Drive%d:\"%s\"\n",i,SDL_CDName(i));

}

OpeningthedefaultdriveSDL_CD*cdrom;

CDstatusstatus;

char*status_str;

cdrom=SDL_CDOpen(0);

if(cdrom==NULL){

fprintf(stderr,"Couldn'topendefaultCD-ROMdrive:%s\n",

SDL_GetError());

exit(2);

}

status=SDL_CDStatus(cdrom);

switch(status){

caseCD_TRAYEMPTY:

status_str="trayempty";

break;

caseCD_STOPPED:

status_str="stopped";

break;

caseCD_PLAYING:

status_str="playing";

break;

caseCD_PAUSED:

status_str="paused";

break;

caseCD_ERROR:

status_str="errorstate";

break;

}

printf("Drivestatus:%s\n",status_str);

if(status>=CD_PLAYING){

intm,s,f;

FRAMES_TO_MSF(cdrom->cur_frame,&m,&s,&f);

printf("Currentlyplayingtrack%d,%d:%2.2d\n",

cdrom->track[cdrom->cur_track].id,m,s);

}

ListingthetracksonaCDSDL_CD*cdrom;/*Assumingthishasalreadybeenset..*/

inti;

intm,s,f;

SDL_CDStatus(cdrom);

printf("Drivetracks:%d\n",cdrom->numtracks);

for(i=0;i<cdrom->numtracks;++i){

FRAMES_TO_MSF(cdrom->track[i].length,&m,&s,&f);

if(f>0)

++s;

printf("\tTrack(index%d)%d:%d:%2.2d\n",i,

cdrom->track[i].id,m,s);

}

PlayanentireCDSDL_CD*cdrom;/*Assumingthishasalreadybeenset..*/

//PlayentireCD:

if(CD_INDRIVE(SDL_CDStatus(cdrom)))

SDL_CDPlayTracks(cdrom,0,0,0,0);

//Playlasttrack:

if(CD_INDRIVE(SDL_CDStatus(cdrom))){

SDL_CDPlayTracks(cdrom,cdrom->numtracks-1,0,0,0);

}

//Playfirstandsecondtrackand10secondsofthirdtrack:

if(CD_INDRIVE(SDL_CDStatus(cdrom)))

SDL_CDPlayTracks(cdrom,0,0,2,CD_FPS*10);

Prev Home NextAudioExamples Up TimeExamples

SDLLibraryDocumentationPrev Chapter4.Examples Next

TimeExamples

Timebasedgameloop#defineTICK_INTERVAL30

staticUint32next_time;

Uint32time_left(void)

{

Uint32now;

now=SDL_GetTicks();

if(next_time<=now)

return0;

else

returnnext_time-now;

}

/*maingameloop*/

next_time=SDL_GetTicks()+TICK_INTERVAL;

while(game_running){

update_game_state();

SDL_Delay(time_left());

next_time+=TICK_INTERVAL;

}

Prev Home NextCDROMExamples Up SDLReference

SDLLibraryDocumentationPrev Chapter4.Examples Next

VideoExamples

InitializingthevideodisplaySDL_Surface*screen;

/*InitializetheSDLlibrary*/

if(SDL_Init(SDL_INIT_VIDEO)<0){

fprintf(stderr,

"Couldn'tinitializeSDL:%s\n",SDL_GetError());

exit(1);

}

/*Cleanuponexit*/

atexit(SDL_Quit);

/*Initializethedisplayina640x4808-bitpalettizedmode*/

screen=SDL_SetVideoMode(640,480,8,SDL_SWSURFACE);

if(screen==NULL){

fprintf(stderr,"Couldn'tset640x480x8videomode:%s\n",

SDL_GetError());

exit(1);

}

Initializingthebestvideomode/*Haveapreferencefor8-bit,butacceptanydepth*/

screen=SDL_SetVideoMode(640,480,8,SDL_SWSURFACE|SDL_ANYFORMAT);

if(screen==NULL){

fprintf(stderr,"Couldn'tset640x480x8videomode:%s\n",

SDL_GetError());

exit(1);

}

printf("Set640x480at%dbits-per-pixelmode\n",

screen->format->BitsPerPixel);

LoadinganddisplayingaBMPfileSDL_Surface*image;

SDL_Rectdest;

intncolors,i;

SDL_Color*colors;

/*LoadtheBMPfileintoasurface*/

image=SDL_LoadBMP("sample.bmp");

if(image==NULL){

fprintf(stderr,"Couldn'tloadsample.bmp:%s\n",

SDL_GetError());

return;

}

/*Setthedisplaycolors--SDL_SetColors()onlydoessomethingon

palettizeddisplays,butitdoesn'thurtanythingonHiColoror

TrueColordisplays.

Ifthedisplaycolorshavealreadybeenset,thisstepcanbe

skipped,andthelibrarywillautomaticallymaptheimageto

thecurrentdisplaycolors.

*/

if(image->format->palette){

ncolors=image->format->palette->ncolors;

colors=(SDL_Color*)malloc(ncolors*sizeof(SDL_Color));

memcpy(colors,image->format->palette->colors,ncolors);

}

else{

intr,g,b;

/*Allocate256colorpalette*/

ncolors=256;

colors=(SDL_Color*)malloc(ncolors*sizeof(SDL_Color));

/*Seta3,3,2colorcube*/

for(r=0;r<8;++r){

for(g=0;g<8;++g){

for(b=0;b<4;++b){

i=((r<<5)|(g<<2)|b);

colors[i].r=r<<5;

colors[i].g=g<<5;

colors[i].b=b<<6;

}

}

}

/*Note:Abetterwayofallocatingthepalettemightbe

tocalculatethefrequencyofcolorsintheimage

andcreateapalettebasedonthatinformation.

*/

}

/*Setcolormap,tryforallthecolors,butdon'tworryaboutit*/

SDL_SetColors(screen,colors,0,ncolors);

free(colors);

/*Blitontothescreensurface*/

dest.x=0;

dest.y=0;

dest.w=image->w;

dest.h=image->h;

SDL_BlitSurface(image,NULL,screen,&dest);

SDL_UpdateRects(screen,1,&dest);

/*FreetheallocatedBMPsurface*/

SDL_FreeSurface(image);

return;

Drawingdirectlytothedisplay/*Codetosetayellowpixelatthecenterofthescreen*/

Sint32X,Y;

Uint32pixel;

Uint8*bits,bpp;

/*Mapthecoloryellowtothisdisplay(R=0xFF,G=0xFF,B=0x00)

Note:Ifthedisplayispalettized,youmustsetthepalettefirst.

*/

pixel=SDL_MapRGB(screen->format,0xFF,0xFF,0x00);

/*Calculatetheframebufferoffsetofthecenterofthescreen*/

if(SDL_MUSTLOCK(screen)){

if(SDL_LockSurface(screen)<0)

return;

}

bpp=screen->format->BytesPerPixel;

X=screen->w/2;

Y=screen->h/2;

bits=((Uint8*)screen->pixels)+Y*screen->pitch+X*bpp;

/*Setthepixel*/

switch(bpp){

case1:

*((Uint8*)(bits))=(Uint8)pixel;

break;

case2:

*((Uint16*)(bits))=(Uint16)pixel;

break;

case3:{/*Format/endianindependent*/

Uint8r,g,b;

r=(pixel>>screen->format->Rshift)&0xFF;

g=(pixel>>screen->format->Gshift)&0xFF;

b=(pixel>>screen->format->Bshift)&0xFF;

*((bits)+screen->format->Rshift/8)=r;

*((bits)+screen->format->Gshift/8)=g;

*((bits)+screen->format->Bshift/8)=b;

}

break;

case4:

*((Uint32*)(bits))=(Uint32)pixel;

break;

}

/*Updatethedisplay*/

if(SDL_MUSTLOCK(screen)){

SDL_UnlockSurface(screen);

}

SDL_UpdateRect(screen,X,Y,1,1);

return;

Fastestpossiblesurfaceblit

Therearethreedifferentwaysyoucandrawanimagetothescreen:

1.CreateasurfaceanduseSDL_BlitSurfacetoblitittothescreen2.CreatethevideosurfaceinsystemmemoryandcallSDL_UpdateRect3.CreatethevideosurfaceinvideomemoryandcallSDL_LockSurface

Thebestwaytodothisistocombinemethods:

#include<stdio.h>

#include<stdlib.h>

#include"SDL.h"

#include"SDL_timer.h"

voidComplainAndExit(void)

{

fprintf(stderr,"Problem:%s\n",SDL_GetError());

exit(1);

}

intmain(intargc,char*argv[])

{

SDL_PixelFormatfmt;

SDL_Surface*screen,*locked;

SDL_Surface*imagebmp,*image;

SDL_Rectdstrect;

inti;

Uint8*buffer;

/*InitializeSDL*/

if(SDL_Init(SDL_INIT_VIDEO)<0){

ComplainAndExit();

}

atexit(SDL_Quit);

/*LoadaBMPimageintoasurface*/

imagebmp=SDL_LoadBMP("image.bmp");

if(imagebmp==NULL){

ComplainAndExit();

}

/*Setthevideomode(640x480atnativedepth)*/

screen=SDL_SetVideoMode(640,480,0,SDL_HWSURFACE|SDL_FULLSCREEN);

if(screen==NULL){

ComplainAndExit();

}

/*Setthevideocolormap*/

if(imagebmp->format->palette!=NULL){

SDL_SetColors(screen,

imagebmp->format->palette->colors,0,

imagebmp->format->palette->ncolors);

}

/*Converttheimagetothevideoformat(mapscolors)*/

image=SDL_DisplayFormat(imagebmp);

SDL_FreeSurface(imagebmp);

if(image==NULL){

ComplainAndExit();

}

/*Drawbandsofcolorontherawsurface*/

if(SDL_MUSTLOCK(screen)){

if(SDL_LockSurface(screen)<0)

ComplainAndExit();

}

buffer=(Uint8*)screen->pixels;

for(i=0;i<screen->h;++i){

memset(buffer,(i*255)/screen->h,

screen->w*screen->format->BytesPerPixel);

buffer+=screen->pitch;

}

if(SDL_MUSTLOCK(screen)){

SDL_UnlockSurface(screen);

}

/*Blittheimagetothecenterofthescreen*/

dstrect.x=(screen->w-image->w)/2;

dstrect.y=(screen->h-image->h)/2;

dstrect.w=image->w;

dstrect.h=image->h;

if(SDL_BlitSurface(image,NULL,screen,&dstrect)<0){

SDL_FreeSurface(image);

ComplainAndExit();

}

SDL_FreeSurface(image);

/*Updatethescreen*/

SDL_UpdateRects(screen,1,&dstrect);

SDL_Delay(5000);/*Wait5seconds*/

exit(0);

}

Prev Home NextExamples Up EventExamples

SDLLibraryDocumentationPrev Next

II.SDLReferenceTableofContents5.General6.Video7.WindowManagement8.Events9.Joystick10.Audio11.CD-ROM12.Multi-threadedProgramming13.Time

Prev Home NextTimeExamples General

SDLLibraryDocumentationPrev Next

Chapter5.GeneralTableofContentsSDL_Init—InitializesSDLSDL_InitSubSystem—InitializesubsystemsSDL_QuitSubSystem—ShutdownasubsystemSDL_Quit—ShutdownSDLSDL_WasInit—CheckwhichsubsystemsareinitializedSDL_GetError—GetSDLerrorstring

BeforeSDLcanbeusedinaprogramitmustbeinitializedwithSDL_Init.SDL_Initinitializesallthesubsystemsthattheuserrequests(video,audio,joystick,timersand/orcdrom).OnceSDLisinitializedwithSDL_InitsubsystemscanbeshutdownandinitializedasneededusingSDL_InitSubSystemandSDL_QuitSubSystem.

SDLmustalsobeshutdownbeforetheprogramexitstomakesureitcleansupcorrectly.CallingSDL_QuitshutsdownallsubsystemsandfreesanyresourcesallocatedtoSDL.

Prev Home NextSDLReference Up SDL_Init

SDLLibraryDocumentationPrev Next

SDL_Init

Name

SDL_Init--InitializesSDL

Synopsis#include"SDL.h"

intSDL_Init(Uint32flags);

Description

InitializesSDL.ThisshouldbecalledbeforeallotherSDLfunctions.Theflagsparameterspecifieswhatpart(s)ofSDLtoinitialize.

SDL_INIT_TIMER Initializesthetimersubsystem.SDL_INIT_AUDIO Initializestheaudiosubsystem.SDL_INIT_VIDEO Initializesthevideosubsystem.SDL_INIT_CDROM Initializesthecdromsubsystem.SDL_INIT_JOYSTICK Initializesthejoysticksubsystem.SDL_INIT_EVERYTHING Initializealloftheabove.SDL_INIT_NOPARACHUTE PreventsSDLfromcatchingfatalsignals.SDL_INIT_EVENTTHREAD

ReturnValue

Returns-1onanerroror0onsuccess.

SeeAlso

SDL_Quit,SDL_InitSubSystem

Prev Home NextGeneral Up SDL_InitSubSystem

SDLLibraryDocumentationPrev Next

SDL_InitSubSystem

Name

SDL_InitSubSystem--Initializesubsystems

Synopsis#include"SDL.h"

intSDL_InitSubSystem(Uint32flags);

Description

AfterSDLhasbeeninitializedwithSDL_InityoumayinitializeuninitializedsubsystemswithSDL_InitSubSystem.TheflagsparameteristhesameasthatusedinSDL_Init.

Examples/*SeperatingJoystickandVideoinitialization.*/

SDL_Init(SDL_INIT_VIDEO);

.

.

SDL_SetVideoMode(640,480,16,SDL_DOUBLEBUF|SDL_FULLSCREEN);

.

/*DoSomeVideostuff*/

.

.

/*Initializethejoysticksubsystem*/

SDL_InitSubSystem(SDL_INIT_JOYSTICK);

/*Dosomestuffwithvideoandjoystick*/

.

.

.

/*Shutthembothdown*/

SDL_Quit();

ReturnValue

Returns-1onanerroror0onsuccess.

SeeAlso

SDL_Init,SDL_Quit,SDL_QuitSubSystem

Prev Home NextSDL_Init Up SDL_QuitSubSystem

SDLLibraryDocumentationPrev Next

SDL_QuitSubSystem

Name

SDL_QuitSubSystem--Shutdownasubsystem

Synopsis#include"SDL.h"

voidSDL_QuitSubSystem(Uint32flags);

Description

SDL_QuitSubSystemallowsyoutoshutdownasubsystemthathasbeenpreviouslyinitializedbySDL_InitorSDL_InitSubSystem.TheflagstellsSDL_QuitSubSystemwhichsubsystemstoshutdown,itusesthesamevaluesthatarepassedtoSDL_Init.

SeeAlso

SDL_Quit,SDL_Init,SDL_InitSubSystem

Prev Home NextSDL_InitSubSystem Up SDL_Quit

SDLLibraryDocumentationPrev Next

SDL_Quit

Name

SDL_Quit--ShutdownSDL

Synopsis#include"SDL.h"

voidSDL_Quit(void);

Description

SDL_QuitshutsdownallSDLsubsystemsandfreestheresourcesallocatedtothem.Thisshouldalwaysbecalledbeforeyouexit.ForthesakeofsimplicityyoucansetSDL_Quitasyouratexitcall,like:

SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO);

atexit(SDL_Quit);

.

.

Note:Whileusingatexitmaybebefineforsmallprograms,moreadvancedusersshouldshutdownSDLintheirowncleanupcode.Plus,usingatexitinalibraryisasurewaytocrashdynamicallyloadedcode

SeeAlso

SDL_QuitSubsystem,SDL_Init

Prev Home NextSDL_QuitSubSystem Up SDL_WasInit

SDLLibraryDocumentationPrev Next

SDL_WasInit

Name

SDL_WasInit--Checkwhichsubsystemsareinitialized

Synopsis#include"SDL.h"

Uint32SDL_WasInit(Uint32flags);

Description

SDL_WasInitallowsyoutoseewhichSDLsubsytemshavebeeninitialized.flagsisabitwiseOR'dcombinationofthesubsystemsyouwishtocheck(seeSDL_Initforalistofsubsystemflags).

ReturnValue

SDL_WasInitreturnsabitwisedOR'dcombinationoftheinitializedsubsystems.

Examples/*HereareseveralwaysyoucanuseSDL_WasInit()*/

/*Getinitdataonallthesubsystems*/

Uint32subsystem_init;

subsystem_init=SDL_WasInit(SDL_INIT_EVERYTHING);

if(subsystem_init&SDL_INIT_VIDEO)

printf("Videoisinitialized.\n");

else

printf("Videoisnotinitialized.\n");

/*Justcheckforonespecficsubsystem*/

if(SDL_WasInit(SDL_INIT_VIDEO)!=0)

printf("Videoisinitialized.\n");

else

printf("Videoisnotinitialized.\n");

/*Checkfortwosubsystems*/

Uint32subsystem_mask=SDL_INIT_VIDEO|SDL_INIT_AUDIO;

if(SDL_WasInit(subsystem_mask)==subsystem_mask)

printf("VideoandAudioinitialized.\n");

else

printf("VideoandAudionotinitialized.\n");

SeeAlso

SDL_Init,SDL_Subsystem

Prev Home NextSDL_Quit Up SDL_GetError

SDLLibraryDocumentationPrev Next

SDL_GetError

Name

SDL_GetError--GetSDLerrorstring

Synopsis#include"SDL/SDL.h"

char*SDL_GetError(void);

Description

SDL_GetErrorreturnsaNULLterminatedstringcontaininginformationaboutthelastinternalSDLerror.

ReturnValue

SDL_GetErrorreturnsastringcontainingthelasterror.

Prev Home NextSDL_WasInit Up Video

SDLLibraryDocumentationPrev Next

Chapter6.VideoTableofContentsSDL_GetVideoSurface—returnsapointertothecurrentdisplaysurfaceSDL_GetVideoInfo—returnsapointertoinformationaboutthevideohardwareSDL_VideoDriverName—ObtainthenameofthevideodriverSDL_ListModes—ReturnsapointertoanarrayofavailablescreendimensionsforthegivenformatandvideoflagsSDL_VideoModeOK—Checktoseeifaparticularvideomodeissupported.SDL_SetVideoMode—Setupavideomodewiththespecifiedwidth,heightandbits-per-pixel.SDL_UpdateRect—Makessurethegivenareaisupdatedonthegivenscreen.SDL_UpdateRects—Makessurethegivenlistofrectanglesisupdatedonthegivenscreen.SDL_Flip—SwapsscreenbuffersSDL_SetColors—Setsaportionofthecolormapforthegiven8-bitsurface.SDL_SetPalette—Setsthecolorsinthepaletteofan8-bitsurface.SDL_SetGamma—SetsthecolorgammafunctionforthedisplaySDL_GetGammaRamp—GetsthecolorgammalookuptablesforthedisplaySDL_SetGammaRamp—SetsthecolorgammalookuptablesforthedisplaySDL_MapRGB—MapaRGBcolorvaluetoapixelformat.SDL_MapRGBA—MapaRGBAcolorvaluetoapixelformat.SDL_GetRGB—GetRGBvaluesfromapixelinthespecifiedpixelformat.SDL_GetRGBA—GetRGBAvaluesfromapixelinthespecifiedpixelformat.SDL_CreateRGBSurface—CreateanemptySDL_SurfaceSDL_CreateRGBSurfaceFrom—CreateanSDL_SurfacefrompixeldataSDL_FreeSurface—Frees(deletes)aSDL_SurfaceSDL_LockSurface—Lockasurfacefordirectlyaccess.SDL_UnlockSurface—Unlocksapreviouslylockedsurface.SDL_LoadBMP—LoadaWindowsBMPfileintoanSDL_Surface.SDL_SaveBMP—SaveanSDL_SurfaceasaWindowsBMPfile.SDL_SetColorKey—Setsthecolorkey(transparentpixel)inablittablesurfaceandRLEacceleration.SDL_SetAlpha—AdjustthealphapropertiesofasurfaceSDL_SetClipRect—Setstheclippingrectangleforasurface.SDL_GetClipRect—Getstheclippingrectangleforasurface.

SDL_ConvertSurface—Convertsasurfacetothesameformatasanothersurface.SDL_BlitSurface—Thisperformsafastblitfromthesourcesurfacetothedestinationsurface.SDL_FillRect—ThisfunctionperformsafastfillofthegivenrectanglewithsomecolorSDL_DisplayFormat—ConvertasurfacetothedisplayformatSDL_DisplayFormatAlpha—ConvertasurfacetothedisplayformatSDL_WarpMouse—Setthepositionofthemousecursor.SDL_CreateCursor—Createsanewmousecursor.SDL_FreeCursor—FreesacursorcreatedwithSDL_CreateCursor.SDL_SetCursor—Setthecurrentlyactivemousecursor.SDL_GetCursor—Getthecurrentlyactivemousecursor.SDL_ShowCursor—Togglewhetherornotthecursorisshownonthescreen.SDL_GL_LoadLibrary—SpecifyanOpenGLlibrarySDL_GL_GetProcAddress—GettheaddressofaGLfunctionSDL_GL_GetAttribute—GetthevalueofaspecialSDL/OpenGLattributeSDL_GL_SetAttribute—SetaspecialSDL/OpenGLattributeSDL_GL_SwapBuffers—SwapOpenGLframebuffers/UpdateDisplaySDL_CreateYUVOverlay—CreateaYUVvideooverlaySDL_LockYUVOverlay—LockanoverlaySDL_UnlockYUVOverlay—UnlockanoverlaySDL_DisplayYUVOverlay—BlittheoverlaytothedisplaySDL_FreeYUVOverlay—FreeaYUVvideooverlaySDL_GLattr—SDLGLAttributesSDL_Rect—DefinesarectangularareaSDL_Color—FormatindependentcolordescriptionSDL_Palette—Colorpalettefor8-bitpixelformatsSDL_PixelFormat—StoressurfaceformatinformationSDL_Surface—GraphicalSurfaceStructureSDL_VideoInfo—VideoTargetinformationSDL_Overlay—YUVvideooverlay

SDLpresentsaverysimpleinterfacetothedisplayframebuffer.Theframebufferisrepresentedasanoffscreensurfacetowhichyoucanwritedirectly.Ifyouwantthescreentoshowwhatyouhavewritten,calltheupdatefunctionwhichwillguaranteethatthedesiredportionofthescreenisupdated.

BeforeyoucallanyoftheSDLvideofunctions,youmustfirstcall

SDL_Init(SDL_INIT_VIDEO),whichinitializesthevideoandeventsintheSDLlibrary.Checkthereturncode,whichshouldbe0,toseeiftherewereanyerrorsinstartingup.

Ifyouusebothsoundandvideoinyourapplication,youneedtocallSDL_Init(SDL_INIT_AUDIO|SDL_INIT_VIDEO)beforeopeningthesounddevice,otherwiseunderWin32DirectX,youwon'tbeabletosetfull-screendisplaymodes.

Afteryouhaveinitializedthelibrary,youcanstartupthevideodisplayinanumberofways.Theeasiestwayistopickacommonscreenresolutionanddepthandjustinitializethevideo,checkingforerrors.Youwillprobablygetwhatyouwant,butSDLmaybeemulatingyourrequestedmodeandconvertingthedisplayonupdate.Thebestwayistoquery,forthebestvideomodeclosesttothedesiredone,andthenconvertyourimagestothatpixelformat.

SDLcurrentlysupportsanybitdepth>=8bitsperpixel.8bppformatsareconsidered8-bitpalettizedmodes,while12,15,16,24,and32bitsperpixelareconsidered"packedpixel"modes,meaningeachpixelcontainstheRGBcolorcomponentspackedinthebitsofthepixel.

Afteryouhaveinitializedyourvideomode,youcantakethesurfacethatwasreturned,andwritetoitlikeanyotherframebuffer,callingtheupdateroutineasyougo.

Whenyouhavefinishedyourvideoaccessandarereadytoquityourapplication,youshouldcall"SDL_Quit()"toshutdownthevideoandevents.

Prev Home NextSDL_GetError Up SDL_GetVideoSurface

SDLLibraryDocumentationPrev Next

SDL_GetVideoSurface

Name

SDL_GetVideoSurface--returnsapointertothecurrentdisplaysurface

Synopsis#include"SDL.h"

SDL_Surface*SDL_GetVideoSurface(void);

Description

Thisfunctionreturnsapointertothecurrentdisplaysurface.IfSDLisdoingformatconversiononthedisplaysurface,thisfunctionreturnsthepubliclyvisiblesurface,nottherealvideosurface.

SeeAlso

SDL_Surface

Prev Home NextVideo Up SDL_GetVideoInfo

SDLLibraryDocumentationPrev Next

SDL_GetVideoInfo

Name

SDL_GetVideoInfo--returnsapointertoinformationaboutthevideohardware

Synopsis#include"SDL.h"

SDL_VideoInfo*SDL_GetVideoInfo(void);

Description

Thisfunctionreturnsaread-onlypointertoinformationaboutthevideohardware.IfthisiscalledbeforeSDL_SetVideoMode,thevfmtmemberofthereturnedstructurewillcontainthepixelformatofthe"best"videomode.

SeeAlso

SDL_SetVideoMode,SDL_VideoInfo

Prev Home NextSDL_GetVideoSurface Up SDL_VideoDriverName

SDLLibraryDocumentationPrev Next

SDL_VideoDriverName

Name

SDL_VideoDriverName--Obtainthenameofthevideodriver

Synopsis#include"SDL.h"

char*SDL_VideoDriverName(char*namebuf,intmaxlen);

Description

Thebufferpointedtobynamebufisfilleduptoamaximumofmaxlencharacters(includetheNULLterminator)withthenameoftheinitialisedvideodriver.Thedrivernameisasimpleonewordidentifierlike"x11"or"windib".

ReturnValue

ReturnsNULLifvideohasnotbeeninitialisedwithSDL_Initorapointertonamebufotherwise.

SeeAlso

SDL_InitSDL_InitSubSystem

Prev Home NextSDL_GetVideoInfo Up SDL_ListModes

SDLLibraryDocumentationPrev Next

SDL_ListModes

Name

SDL_ListModes--Returnsapointertoanarrayofavailablescreendimensionsforthegivenformatandvideoflags

Synopsis#include"SDL.h"

SDL_Rect**SDL_ListModes(SDL_PixelFormat*format,Uint32flags);

Description

Returnapointertoanarrayofavailablescreendimensionsforthegivenformatandvideoflags,sortedlargesttosmallest.ReturnsNULLiftherearenodimensionsavailableforaparticularformat,or-1ifanydimensionisokayforthegivenformat.

IfformatisNULL,themodelistwillbefortheformatreturnedbySDL_GetVideoInfo()->vfmt.TheflagparameterisanOR'dcombinationofsurfaceflags.TheflagsarethesameasthoseusedSDL_SetVideoModeandtheyplayastrongroleindecidingwhatmodesarevalid.Forinstance,ifyoupassSDL_HWSURFACEasaflagonlymodesthatsupporthardwarevideosurfaceswillbereturned.

ExampleSDL_Rect**modes;

inti;

.

.

.

/*Getavailablefullscreen/hardwaremodes*/

modes=SDL_ListModes(NULL,SDL_FULLSCREEN|SDL_HWSURFACE);

/*Checkisthereareanymodesavailable*/

if(modes==(SDL_Rect**)0){

printf("Nomodesavailable!\n");

exit(-1);

}

/*Checkiforresolutionisrestricted*/

if(modes==(SDL_Rect**)-1){

printf("Allresolutionsavailable.\n");

}

else{

/*Printvalidmodes*/

printf("AvailableModes\n");

for(i=0;modes[i];++i)

printf("%dx%d\n",modes[i]->w,modes[i]->h);

}

.

.

SeeAlso

SDL_SetVideoMode,SDL_GetVideoInfo,SDL_Rect,SDL_PixelFormat

Prev Home NextSDL_VideoDriverName Up SDL_VideoModeOK

SDLLibraryDocumentationPrev Next

SDL_VideoModeOK

Name

SDL_VideoModeOK--Checktoseeifaparticularvideomodeissupported.

Synopsis#include"SDL.h"

intSDL_VideoModeOK(intwidth,intheight,intbpp,Uint32flags);

Description

SDL_VideoModeOKreturns0iftherequestedmodeisnotsupportedunderanybitdepth,orreturnsthebits-per-pixeloftheclosestavailablemodewiththegivenwidth,heightandrequestedsurfaceflags(seeSDL_SetVideoMode).

Thebits-per-pixelvaluereturnedisonlyasuggestedmode.YoucanusuallyrequestandbppyouwantwhensettingthevideomodeandSDLwillemulatethatcolordepthwithashadowvideosurface.

TheargumentstoSDL_VideoModeOKarethesameonesyouwouldpasstoSDL_SetVideoMode

ExampleSDL_Surface*screen;

Uint32bpp;

.

.

.

printf("Checkingmode640x480@16bpp.\n");

bpp=SDL_VideoModeOK(640,480,16,SDL_HWSURFACE);

if(!bpp){

printf("Modenotavailable.\n");

exit(-1);

}

printf("SDLRecommends640x480@%dbpp.\n",bpp);

screen=SDL_SetVideoMode(640,480,bpp,SDL_HWSURFACE);

.

.

SeeAlso

SDL_SetVideoMode,SDL_GetVideoInfo

Prev Home NextSDL_ListModes Up SDL_SetVideoMode

SDLLibraryDocumentationPrev Next

SDL_SetVideoMode

Name

SDL_SetVideoMode--Setupavideomodewiththespecifiedwidth,heightandbits-per-pixel.

Synopsis#include"SDL.h"

SDL_Surface*SDL_SetVideoMode(intwidth,intheight,intbpp,Uint32flags);

Description

Setupavideomodewiththespecifiedwidth,heightandbits-per-pixel.

Ifbppis0,itistreatedasthecurrentdisplaybitsperpixel.

TheflagsparameteristhesameastheflagsfieldoftheSDL_Surfacestructure.OR'dcombinationsofthefollowingvaluesarevalid.

SDL_SWSURFACE CreatethevideosurfaceinsystemmemorySDL_HWSURFACE Createthevideosurfaceinvideomemory

SDL_ASYNCBLIT

Enablestheuseofasynchronousupdatesofthedisplaysurface.ThiswillusuallyslowdownblittingonsingleCPUmachines,butmayprovideaspeedincreaseonSMPsystems.

SDL_ANYFORMAT

Normally,ifavideosurfaceoftherequestedbits-per-pixel(bpp)isnotavailable,SDLwillemulateonewithashadowsurface.PassingSDL_ANYFORMATpreventsthisandcausesSDLtousethevideosurface,regardlessofitspixeldepth.

SDL_HWPALETTE

GiveSDLexclusivepaletteaccess.WithoutthisflagyoumaynotalwaysgetthethecolorsyourequestwithSDL_SetColorsorSDL_SetPalette.

SDL_DOUBLEBUF

Enablehardwaredoublebuffering;onlyvalidwithSDL_HWSURFACE.CallingSDL_Flipwillflipthebuffersandupdatethescreen.Alldrawingwilltakeplaceonthesurfacethatisnotdisplayedatthemoment.IfdoublebufferingcouldnotbeenabledthenSDL_FlipwilljustperformaSDL_UpdateRectontheentirescreen.

SDL_FULLSCREEN

SDLwillattempttouseafullscreenmode.Ifahardwareresolutionchangeisnotpossible(forwhateverreason),thenexthigherresolutionwillbeusedandthedisplaywindowcenteredonablackbackground.

SDL_OPENGL

CreateanOpenGLrenderingcontext.YoushouldhavepreviouslysetOpenGLvideoattributeswithSDL_GL_SetAttribute.CreateanOpenGLrenderingcontext,likeabove,butallow

SDL_OPENGLBLIT normalblittingoperations.Thescreen(2D)surfacemayhaveanalphachannel,andSDL_UpdateRectsmustbeusedforupdatingchangestothescreensurface.

SDL_RESIZABLE

Createaresizablewindow.WhenthewindowisresizedbytheuseraSDL_VIDEORESIZEeventisgeneratedandSDL_SetVideoModecanbecalledagainwiththenewsize.

SDL_NOFRAME

Ifpossible,SDL_NOFRAMEcausesSDLtocreateawindowwithnotitlebarorframedecoration.Fullscreenmodesautomaticallyhavethisflagset.

Note:WhateverflagsSDL_SetVideoModecouldsatisfyaresetintheflagsmemberofthereturnedsurface.

Note:Thebppparameteristhenumberofbitsperpixel,soabppof24usesthepackedrepresentationof3bytes/pixel.Forthemorecommon4bytes/pixelmode,useabppof32.Somewhatoddly,both15and16willrequesta2bytes/pixelmode,butdifferentpixelformats.

ReturnValue

Theframebuffersurface,orNULLifitfails.ThesurfacereturnedisfreedbySDL_Quit()andshouldntbefreedbythecaller.

SeeAlso

SDL_LockSurface,SDL_SetColors,SDL_Flip,SDL_Surface

Prev Home NextSDL_VideoModeOK Up SDL_UpdateRect

SDLLibraryDocumentationPrev Next

SDL_UpdateRect

Name

SDL_UpdateRect--Makessurethegivenareaisupdatedonthegivenscreen.

Synopsis#include"SDL.h"

voidSDL_UpdateRect(SDL_Surface*screen,Sint32x,Sint32y,Sint32w,Sint32h);

Description

Makessurethegivenareaisupdatedonthegivenscreen.Therectanglemustbeconfinedwithinthescreenboundaries(noclippingisdone).

If'x','y','w'and'h'areall0,SDL_UpdateRectwillupdatetheentirescreen.

Thisfunctionshouldnotbecalledwhile'screen'islocked.

SeeAlso

SDL_UpdateRects,SDL_Rect,SDL_Surface,SDL_LockSurface

Prev Home NextSDL_SetVideoMode Up SDL_UpdateRects

SDLLibraryDocumentationPrev Next

SDL_UpdateRects

Name

SDL_UpdateRects--Makessurethegivenlistofrectanglesisupdatedonthegivenscreen.

Synopsis#include"SDL.h"

voidSDL_UpdateRects(SDL_Surface*screen,intnumrects,SDL_Rect*rects);

Description

Makessurethegivenlistofrectanglesisupdatedonthegivenscreen.Therectanglesmustallbeconfinedwithinthescreenboundaries(noclippingisdone).

Thisfunctionshouldnotbecalledwhilescreenislocked.

Note:Itisadvicedtocallthisfunctiononlyonceperframe,sinceeachcallhassomeprocessingoverhead.Thisisnorestrictionsinceyoucanpassanynumberofrectangleseachtime.

Therectanglesarenotautomaticallymergedorcheckedforoverlap.Ingeneral,theprogrammercanusehisknowledgeabouthisparticularrectanglestomergetheminanefficientway,toavoidoverdraw.

SeeAlso

SDL_UpdateRect,SDL_Rect,SDL_Surface,SDL_LockSurface

Prev Home NextSDL_UpdateRect Up SDL_Flip

SDLLibraryDocumentationPrev Next

SDL_Flip

Name

SDL_Flip--Swapsscreenbuffers

Synopsis#include"SDL.h"

intSDL_Flip(SDL_Surface*screen);

Description

Onhardwarethatsupportsdouble-buffering,thisfunctionsetsupaflipandreturns.Thehardwarewillwaitforverticalretrace,andthenswapvideobuffersbeforethenextvideosurfaceblitorlockwillreturn.Onhardwarethatdoesn'tsupportdouble-buffering,thisisequivalenttocallingSDL_UpdateRect(screen,0,0,0,0)

TheSDL_DOUBLEBUFflagmusthavebeenpassedtoSDL_SetVideoMode,whensettingthevideomodeforthisfunctiontoperformhardwareflipping.

ReturnValue

Thisfunctionreturns0ifsuccessful,or-1iftherewasanerror.

SeeAlso

SDL_SetVideoMode,SDL_UpdateRect,SDL_Surface

Prev Home NextSDL_UpdateRects Up SDL_SetColors

SDLLibraryDocumentationPrev Next

SDL_SetColors

Name

SDL_SetColors--Setsaportionofthecolormapforthegiven8-bitsurface.

Synopsis#include"SDL.h"

intSDL_SetColors(SDL_Surface*surface,SDL_Color*colors,intfirstcolor,intncolors);

Description

Setsaportionofthecolormapforthegiven8-bitsurface.

Whensurfaceisthesurfaceassociatedwiththecurrentdisplay,thedisplaycolormapwillbeupdatedwiththerequestedcolors.IfSDL_HWPALETTEwassetinSDL_SetVideoModeflags,SDL_SetColorswillalwaysreturn1,andthepaletteisguaranteedtobesetthewayyoudesire,evenifthewindowcolormaphastobewarpedorrununderemulation.

ThecolorcomponentsofaSDL_Colorstructureare8-bitsinsize,givingyouatotalof2563=16777216colors.

Palettized(8-bit)screensurfaceswiththeSDL_HWPALETTEflaghavetwopalettes,alogicalpalettethatisusedformappingblitsto/fromthesurfaceandaphysicalpalette(thatdetermineshowthehardwarewillmapthecolorstothedisplay).SDL_SetColorsmodifiesbothpalettes(ifpresent),andisequivalenttocallingSDL_SetPalettewiththeflagssetto(SDL_LOGPAL|SDL_PHYSPAL).

ReturnValue

Ifsurfaceisnotapalettizedsurface,thisfunctiondoesnothing,returning0.IfallofthecolorsweresetaspassedtoSDL_SetColors,itwillreturn1.Ifnotallthecolorentriesweresetexactlyasgiven,itwillreturn0,andyoushouldlookatthesurfacepalettetodeterminetheactualcolorpalette.

Example/*Createadisplaysurfacewithagrayscalepalette*/

SDL_Surface*screen;

SDL_Colorcolors[256];

inti;

.

.

.

/*Fillcolorswithcolorinformation*/

for(i=0;i<256;i++){

colors[i].r=i;

colors[i].g=i;

colors[i].b=i;

}

/*Createdisplay*/

screen=SDL_SetVideoMode(640,480,8,SDL_HWPALETTE);

if(!screen){

printf("Couldn'tsetvideomode:%s\n",SDL_GetError());

exit(-1);

}

/*Setpalette*/

SDL_SetColors(screen,colors,0,256);

.

.

.

.

SeeAlso

SDL_ColorSDL_Surface,SDL_SetPalette,SDL_SetVideoMode

Prev Home NextSDL_Flip Up SDL_SetPalette

SDLLibraryDocumentationPrev Next

SDL_SetPalette

Name

SDL_SetPalette--Setsthecolorsinthepaletteofan8-bitsurface.

Synopsis#include"SDL.h"

intSDL_SetPalette(SDL_Surface*surface,intflags,SDL_Color*colors,intfirstcolor,intncolors);

Description

Setsaportionofthepaletteforthegiven8-bitsurface.

Palettized(8-bit)screensurfaceswiththeSDL_HWPALETTEflaghavetwopalettes,alogicalpalettethatisusedformappingblitsto/fromthesurfaceandaphysicalpalette(thatdetermineshowthehardwarewillmapthecolorstothedisplay).SDL_BlitSurfacealwaysusesthelogicalpalettewhenblittingsurfaces(ifithastoconvertbetweensurfacepixelformats).Becauseofthis,itisoftenusefultomodifyonlyoneortheotherpalettetoachievevariousspecialcoloreffects(e.g.,screenfading,colorflashes,screendimming).

ThisfunctioncanmodifyeitherthelogicalorphysicalpalettebyspecifingSDL_LOGPALorSDL_PHYSPALtheintheflagsparameter.

Whensurfaceisthesurfaceassociatedwiththecurrentdisplay,thedisplaycolormapwillbeupdatedwiththerequestedcolors.IfSDL_HWPALETTEwassetinSDL_SetVideoModeflags,SDL_SetPalettewillalwaysreturn1,andthepaletteisguaranteedtobesetthewayyoudesire,evenifthewindowcolormaphastobewarpedorrununderemulation.

ThecolorcomponentsofaSDL_Colorstructureare8-bitsinsize,givingyouatotalof2563=16777216colors.

ReturnValue

Ifsurfaceisnotapalettizedsurface,thisfunctiondoesnothing,returning0.IfallofthecolorsweresetaspassedtoSDL_SetPalette,itwillreturn1.Ifnotallthecolorentriesweresetexactlyasgiven,itwillreturn0,andyoushouldlookatthesurfacepalettetodeterminetheactualcolorpalette.

Example/*Createadisplaysurfacewithagrayscalepalette*/

SDL_Surface*screen;

SDL_Colorcolors[256];

inti;

.

.

.

/*Fillcolorswithcolorinformation*/

for(i=0;i<256;i++){

colors[i].r=i;

colors[i].g=i;

colors[i].b=i;

}

/*Createdisplay*/

screen=SDL_SetVideoMode(640,480,8,SDL_HWPALETTE);

if(!screen){

printf("Couldn'tsetvideomode:%s\n",SDL_GetError());

exit(-1);

}

/*Setpalette*/

SDL_SetPalette(screen,SDL_LOGPAL|SDL_PHYSPAL,colors,0,256);

.

.

.

.

SeeAlso

SDL_SetColors,SDL_SetVideoMode,SDL_Surface,SDL_Color

Prev Home NextSDL_SetColors Up SDL_SetGamma

SDLLibraryDocumentationPrev Next

SDL_SetGamma

Name

SDL_SetGamma--Setsthecolorgammafunctionforthedisplay

Synopsis#include"SDL.h"

intSDL_SetGamma(floatredgamma,floatgreengamma,floatbluegamma);

Description

Setsthe"gammafunction"forthedisplayofeachcolorcomponent.Gammacontrolsthebrightness/contrastofcolorsdisplayedonthescreen.Agammavalueof1.0isidentity(i.e.,noadjustmentismade).

Thisfunctionadjuststhegammabasedonthe"gammafunction"parameter,youcandirectlyspecifylookuptablesforgammaadjustmentwithSDL_SetGammaRamp.

Notalldisplayhardwareisabletochangegamma.

ReturnValue

Returns-1onerror(orifgammaadjustmentisnotsupported).

SeeAlso

SDL_GetGammaRampSDL_SetGammaRamp

Prev Home NextSDL_SetPalette Up SDL_GetGammaRamp

SDLLibraryDocumentationPrev Next

SDL_GetGammaRamp

Name

SDL_GetGammaRamp--Getsthecolorgammalookuptablesforthedisplay

Synopsis#include"SDL.h"

intSDL_GetGammaRamp(Uint16*redtable,Uint16*greentable,Uint16*bluetable);

Description

Getsthegammatranslationlookuptablescurrentlyusedbythedisplay.Eachtableisanarrayof256Uint16values.

Notalldisplayhardwareisabletochangegamma.

ReturnValue

Returns-1onerror.

SeeAlso

SDL_SetGammaSDL_SetGammaRamp

Prev Home NextSDL_SetGamma Up SDL_SetGammaRamp

SDLLibraryDocumentationPrev Next

SDL_SetGammaRamp

Name

SDL_SetGammaRamp--Setsthecolorgammalookuptablesforthedisplay

Synopsis#include"SDL.h"

intSDL_SetGammaRamp(Uint16*redtable,Uint16*greentable,Uint16*bluetable);

Description

Setsthegammalookuptablesforthedisplayforeachcolorcomponent.Eachtableisanarrayof256Uint16values,representingamappingbetweentheinputandoutputforthatchannel.Theinputistheindexintothearray,andtheoutputisthe16-bitgammavalueatthatindex,scaledtotheoutputcolorprecision.YoumaypassNULLtoanyofthechannelstoleavethemunchanged.

Thisfunctionadjuststhegammabasedonlookuptables,youcanalsohavethegammacalculatedbasedona"gammafunction"parameterwithSDL_SetGamma.

Notalldisplayhardwareisabletochangegamma.

ReturnValue

Returns-1onerror(orifgammaadjustmentisnotsupported).

SeeAlso

SDL_SetGammaSDL_GetGammaRamp

Prev Home NextSDL_GetGammaRamp Up SDL_MapRGB

SDLLibraryDocumentationPrev Next

SDL_MapRGB

Name

SDL_MapRGB--MapaRGBcolorvaluetoapixelformat.

Synopsis#include"SDL.h"

Uint32SDL_MapRGB(SDL_PixelFormat*fmt,Uint8r,Uint8g,Uint8b);

Description

MapstheRGBcolorvaluetothespecifiedpixelformatandreturnsthepixelvalueasa32-bitint.

Iftheformathasapalette(8-bit)theindexoftheclosestmatchingcolorinthepalettewillbereturned.

Ifthespecifiedpixelformathasanalphacomponentitwillbereturnedasall1bits(fullyopaque).

ReturnValue

ApixelvaluebestapproximatingthegivenRGBcolorvalueforagivenpixelformat.Ifthepixelformatbpp(colordepth)islessthan32-bppthentheunusedupperbitsofthereturnvaluecansafelybeignored(e.g.,witha16-bppformatthereturnvaluecanbeassignedtoaUint16,andsimilarlyaUint8foran8-bppformat).

SeeAlso

SDL_GetRGB,SDL_GetRGBA,SDL_MapRGBA,SDL_PixelFormat

Prev Home NextSDL_SetGammaRamp Up SDL_MapRGBA

SDLLibraryDocumentationPrev Next

SDL_MapRGBA

Name

SDL_MapRGBA--MapaRGBAcolorvaluetoapixelformat.

Synopsis#include"SDL.h"

Uint32SDL_MapRGBA(SDL_PixelFormat*fmt,Uint8r,Uint8g,Uint8b,Uint8a);

Description

MapstheRGBAcolorvaluetothespecifiedpixelformatandreturnsthepixelvalueasa32-bitint.

Iftheformathasapalette(8-bit)theindexoftheclosestmatchingcolorinthepalettewillbereturned.

Ifthespecifiedpixelformathasnoalphacomponentthealphavaluewillbeignored(asitwillbeinformatswithapalette).

ReturnValue

ApixelvaluebestapproximatingthegivenRGBAcolorvalueforagivenpixelformat.Ifthepixelformatbpp(colordepth)islessthan32-bppthentheunusedupperbitsofthereturnvaluecansafelybeignored(e.g.,witha16-bppformatthereturnvaluecanbeassignedtoaUint16,andsimilarlyaUint8foran8-bppformat).

SeeAlso

SDL_GetRGB,SDL_GetRGBA,SDL_MapRGB,SDL_PixelFormat

Prev Home NextSDL_MapRGB Up SDL_GetRGB

SDLLibraryDocumentationPrev Next

SDL_GetRGB

Name

SDL_GetRGB--GetRGBvaluesfromapixelinthespecifiedpixelformat.

Synopsis#include"SDL.h"

voidSDL_GetRGB(Uint32pixel,SDL_PixelFormat*fmt,Uint8*r,Uint8*g,Uint8*b);

Description

GetRGBcomponentvaluesfromapixelstoredinthespecifiedpixelformat.

Thisfunctionusestheentire8-bit[0..255]rangewhenconvertingcolorcomponentsfrompixelformatswithlessthan8-bitsperRGBcomponent(e.g.,acompletelywhitepixelin16-bitRGB565formatwouldreturn[0xff,0xff,0xff]not[0xf8,0xfc,0xf8]).

SeeAlso

SDL_GetRGBA,SDL_MapRGB,SDL_MapRGBA,SDL_PixelFormat

Prev Home NextSDL_MapRGBA Up SDL_GetRGBA

SDLLibraryDocumentationPrev Next

SDL_GetRGBA

Name

SDL_GetRGBA--GetRGBAvaluesfromapixelinthespecifiedpixelformat.

Synopsis#include"SDL.h"

voidSDL_GetRGBA(Uint32pixel,SDL_PixelFormat*fmt,Uint8*r,Uint8*g,Uint8*b,Uint8*a);

Description

GetRGBAcomponentvaluesfromapixelstoredinthespecifiedpixelformat.

Thisfunctionusestheentire8-bit[0..255]rangewhenconvertingcolorcomponentsfrompixelformatswithlessthan8-bitsperRGBcomponent(e.g.,acompletelywhitepixelin16-bitRGB565formatwouldreturn[0xff,0xff,0xff]not[0xf8,0xfc,0xf8]).

Ifthesurfacehasnoalphacomponent,thealphawillbereturnedas0xff(100%opaque).

SeeAlso

SDL_GetRGB,SDL_MapRGB,SDL_MapRGBA,SDL_PixelFormat

Prev Home NextSDL_GetRGB Up SDL_CreateRGBSurface

SDLLibraryDocumentationPrev Next

SDL_CreateRGBSurface

Name

SDL_CreateRGBSurface--CreateanemptySDL_Surface

Synopsis#include"SDL.h"

SDL_Surface*SDL_CreateRGBSurface(Uint32flags,intwidth,intheight,intdepth,Uint32Rmask,Uint32Gmask,Uint32Bmask,Uint32Amask);

Description

Allocateanemptysurface(mustbecalledafterSDL_SetVideoMode)

Ifdepthis8bitsanemptypaletteisallocatedforthesurface,otherwisea'packed-pixel'SDL_PixelFormatiscreatedusingthe[RGBA]mask'sprovided(seeSDL_PixelFormat).Theflagsspecifiesthetypeofsurfacethatshouldbecreated,itisanOR'dcombinationofthefollowingpossiblevalues.

SDL_SWSURFACE

SDLwillcreatethesurfaceinsystemmemory.Thisimprovestheperformanceofpixellevelaccess,howeveryoumaynotbeabletotakeadvantageofsometypesofhardwareblitting.

SDL_HWSURFACE

SDLwillattempttocreatethesurfaceinvideomemory.ThiswillallowSDLtotakeadvantageofVideo->Videoblits(whichareoftenaccelerated).

SDL_SRCCOLORKEY

Thisflagturnsoncolourkeyingforblitsfromthissurface.IfSDL_HWSURFACEisalsospecifiedandcolourkeyedblitsarehardware-accelerated,thenSDLwillattempttoplacethesurfaceinvideomemory.UseSDL_SetColorKeytosetorclearthisflagaftersurfacecreation.

SDL_SRCALPHA

Thisflagturnsonalpha-blendingforblitsfromthissurface.IfSDL_HWSURFACEisalsospecifiedandalpha-blendingblitsarehardware-accelerated,thenthesurfacewillbeplacedinvideomemoryifpossible.UseSDL_SetAlphatosetorclearthisflagaftersurfacecreation.

Note:Ifanalpha-channelisspecified(thatis,ifAmaskisnonzero),thentheSDL_SRCALPHAflagisautomaticallyset.YoumayremovethisflagbycallingSDL_SetAlphaaftersurfacecreation.

ReturnValue

Returnsthecreatedsurface,orNULLuponerror.

Example/*Createa32-bitsurfacewiththebytesofeachpixelinR,G,B,Aorder,

asexpectedbyOpenGLfortextures*/

SDL_Surface*surface;

Uint32rmask,gmask,bmask,amask;

/*SDLinterpretseachpixelasa32-bitnumber,soourmasksmustdepend

ontheendianness(byteorder)ofthemachine*/

#ifSDL_BYTEORDER==SDL_BIG_ENDIAN

rmask=0xff000000;

gmask=0x00ff0000;

bmask=0x0000ff00;

amask=0x000000ff;

#else

rmask=0x000000ff;

gmask=0x0000ff00;

bmask=0x00ff0000;

amask=0xff000000;

#endif

surface=SDL_CreateRGBSurface(SDL_SWSURFACE,width,height,32,

rmask,gmask,bmask,amask);

if(surface==NULL){

fprintf(stderr,"CreateRGBSurfacefailed:%s\n",SDL_GetError());

exit(1);

}

SeeAlso

SDL_CreateRGBSurfaceFrom,SDL_FreeSurface,SDL_SetVideoMode,SDL_LockSurface,SDL_PixelFormat,SDL_SurfaceSDL_SetAlphaSDL_SetColorKey

Prev Home NextSDL_GetRGBA Up SDL_CreateRGBSurfaceFrom

SDLLibraryDocumentationPrev Next

SDL_CreateRGBSurfaceFrom

Name

SDL_CreateRGBSurfaceFrom--CreateanSDL_Surfacefrompixeldata

Synopsis#include"SDL.h"

SDL_Surface*SDL_CreateRGBSurfaceFrom(void*pixels,intwidth,intheight,intdepth,intpitch,Uint32Rmask,Uint32Gmask,Uint32Bmask,Uint32Amask);

Description

CreatesanSDL_Surfacefromtheprovidedpixeldata.

Thedatastoredinpixelsisassumedtobeofthedepthspecifiedintheparameterlist.ThepixeldataisnotcopiedintotheSDL_SurfacestructuresoitshouldnotbefreeduntilthesurfacehasbeenfreedwithacalledtoSDL_FreeSurface.pitchisthelengthofeachscanlineinbytes.

SeeSDL_CreateRGBSurfaceforamoredetaileddescriptionoftheotherparameters.

ReturnValue

Returnsthecreatedsurface,orNULLuponerror.

SeeAlso

SDL_CreateRGBSurface,SDL_FreeSurface

Prev Home NextSDL_CreateRGBSurface Up SDL_FreeSurface

SDLLibraryDocumentationPrev Next

SDL_FreeSurface

Name

SDL_FreeSurface--Frees(deletes)aSDL_Surface

Synopsis#include"SDL.h"

voidSDL_FreeSurface(SDL_Surface*surface);

Description

FreestheresourcesusedbyapreviouslycreatedSDL_Surface.IfthesurfacewascreatedusingSDL_CreateRGBSurfaceFromthenthepixeldataisnotfreed.

SeeAlso

SDL_CreateRGBSurfaceSDL_CreateRGBSurfaceFrom

Prev Home NextSDL_CreateRGBSurfaceFrom Up SDL_LockSurface

SDLLibraryDocumentationPrev Next

SDL_LockSurface

Name

SDL_LockSurface--Lockasurfacefordirectlyaccess.

Synopsis#include"SDL.h"

intSDL_LockSurface(SDL_Surface*surface);

Description

SDL_LockSurfacesetsupasurfacefordirectlyaccessingthepixels.BetweencallstoSDL_LockSurfaceandSDL_UnlockSurface,youcanwritetoandreadfromsurface->pixels,usingthepixelformatstoredinsurface->format.Onceyouaredoneaccessingthesurface,youshoulduseSDL_UnlockSurfacetoreleaseit.

Notallsurfacesrequirelocking.IfSDL_MUSTLOCK(surface)evaluatesto0,thenyoucanreadandwritetothesurfaceatanytime,andthepixelformatofthesurfacewillnotchange.

Nooperatingsystemorlibrarycallsshouldbemadebetweenlock/unlockpairs,ascriticalsystemlocksmaybeheldduringthistime.

Itshouldbenoted,thatsinceSDL1.1.8surfacelocksarerecursive.Thismeansthatyoucanlockasurfacemultipletimes,buteachlockmusthaveamatchunlock.

.

.

SDL_LockSurface(surface);

.

/*Surfaceislocked*/

/*Directpixelaccessonsurfacehere*/

.

SDL_LockSurface(surface);

.

/*Moredirectpixelaccessonsurface*/

.

SDL_UnlockSurface(surface);

/*Surfaceisstilllocked*/

/*Note:Isversions<1.1.8,thesurfacewouldhavebeen*/

/*nolongerlockedatthisstage*/

.

SDL_UnlockSurface(surface);

/*Surfaceisnowunlocked*/

.

.

ReturnValue

SDL_LockSurfacereturns0,or-1ifthesurfacecouldn'tbelocked.

SeeAlsoSDL_UnlockSurface

Prev Home NextSDL_FreeSurface Up SDL_UnlockSurface

SDLLibraryDocumentationPrev Next

SDL_UnlockSurface

Name

SDL_UnlockSurface--Unlocksapreviouslylockedsurface.

Synopsis#include"SDL.h"

voidSDL_UnlockSurface(SDL_Surface*surface);

Description

SurfacesthatwerepreviouslylockedusingSDL_LockSurfacemustbeunlockedwithSDL_UnlockSurface.Surfacesshouldbeunlockedassoonaspossible.

Itshouldbenotedthatsince1.1.8,surfacelocksarerecursive.SeeSDL_LockSurface.

SeeAlsoSDL_LockSurface

Prev Home NextSDL_LockSurface Up SDL_LoadBMP

SDLLibraryDocumentationPrev Next

SDL_LoadBMP

Name

SDL_LoadBMP--LoadaWindowsBMPfileintoanSDL_Surface.

Synopsis#include"SDL.h"

SDL_Surface*SDL_LoadBMP(constchar*file);

Description

LoadsasurfacefromanamedWindowsBMPfile.

ReturnValue

Returnsthenewsurface,orNULLiftherewasanerror.

SeeAlsoSDL_SaveBMP

Prev Home NextSDL_UnlockSurface Up SDL_SaveBMP

SDLLibraryDocumentationPrev Next

SDL_SaveBMP

Name

SDL_SaveBMP--SaveanSDL_SurfaceasaWindowsBMPfile.

Synopsis#include"SDL.h"

intSDL_SaveBMP(SDL_Surface*surface,constchar*file);

Description

SavestheSDL_SurfacesurfaceasaWindowsBMPfilenamedfile.

ReturnValue

Returns0ifsuccessfulor-1iftherewasanerror.

SeeAlsoSDL_LoadBMP

Prev Home NextSDL_LoadBMP Up SDL_SetColorKey

SDLLibraryDocumentationPrev Next

SDL_SetColorKey

Name

SDL_SetColorKey--Setsthecolorkey(transparentpixel)inablittablesurfaceandRLEacceleration.

Synopsis#include"SDL.h"

intSDL_SetColorKey(SDL_Surface*surface,Uint32flag,Uint32key);

Description

Setsthecolorkey(transparentpixel)inablittablesurfaceandenablesordisablesRLEblitacceleration.

RLEaccelerationcansubstantiallyspeedupblittingofimageswithlargehorizontalrunsoftransparentpixels(i.e.,pixelsthatmatchthekeyvalue).Thekeymustbeofthesamepixelformatasthesurface,SDL_MapRGBisoftenusefulforobtaininganacceptablevalue.

IfflagisSDL_SRCCOLORKEYthenkeyisthetransparentpixelvalueinthesourceimageofablit.

IfflagisOR'dwithSDL_RLEACCELthenthesurfacewillbedrawusingRLEaccelerationwhendrawnwithSDL_BlitSurface.ThesurfacewillactuallybeencodedforRLEaccelerationthefirsttimeSDL_BlitSurfaceorSDL_DisplayFormatiscalledonthesurface.

Ifflagis0,thisfunctionclearsanycurrentcolorkey.

ReturnValue

Thisfunctionreturns0,or-1iftherewasanerror.

SeeAlso

SDL_BlitSurface,SDL_DisplayFormat,SDL_MapRGB,SDL_SetAlpha

Prev Home NextSDL_SaveBMP Up SDL_SetAlpha

SDLLibraryDocumentationPrev Next

SDL_SetAlpha

Name

SDL_SetAlpha--Adjustthealphapropertiesofasurface

Synopsis#include"SDL.h"

intSDL_SetAlpha(SDL_Surface*surface,Uint32flag,Uint8alpha);

Description

Note:ThisfunctionandthesemanticsofSDLalphablendinghavechangedsinceversion1.1.4.Upuntilversion1.1.5,analphavalueof0wasconsideredopaqueandavalueof255wasconsideredtransparent.Thishasnowbeeninverted:0(SDL_ALPHA_TRANSPARENT)isnowconsideredtransparentand255(SDL_ALPHA_OPAQUE)isnowconsideredopaque.

SDL_SetAlphaisusedforsettingtheper-surfacealphavalueand/orenablinganddisablingalphablending.

Thesurfaceparameterspecifieswhichsurfacewhosealphaattributesyouwishtoadjust.flagsisusedtospecifywhetheralphablendingshouldbeused(SDL_SRCALPHA)andwhetherthesurfaceshoulduseRLEaccelerationforblitting(SDL_RLEACCEL).flagscanbeanOR'dcombinationofthesetwooptions,oneoftheseoptionsor0.IfSDL_SRCALPHAisnotpassedasaflagthenallalphainformationisignoredwhenblittingthesurface.Thealphaparameteristheper-surfacealphavalue;asurfaceneednothaveanalphachanneltouseper-surfacealphaandblittingcanstillbeacceleratedwithSDL_RLEACCEL.

Note:Theper-surfacealphavalueof128isconsideredaspecialcaseandisoptimised,soit'smuchfasterthanotherper-surfacevalues.

Alphaeffectssurfaceblittinginthefollowingways:

RGBA->RGBwithSDL_SRCALPHA

Thesourceisalpha-blendedwiththedestination,usingthealphachannel.SDL_SRCCOLORKEYandtheper-surfacealphaareignored.

RGBA->RGBwithoutSDL_SRCALPHA

TheRGBdataiscopiedfromthesource.Thesourcealphachannelandtheper-surfacealphavalueareignored.

RGB->RGBAwithSDL_SRCALPHA

Thesourceisalpha-blendedwiththedestinationusingtheper-surfacealphavalue.IfSDL_SRCCOLORKEYisset,onlythepixelsnotmatchingthecolorkeyvaluearecopied.Thealphachannelofthecopiedpixelsissettoopaque.

RGB->RGBAwithoutSDL_SRCALPHA

TheRGBdataiscopiedfromthesourceandthealphavalueofthecopiedpixelsissettoopaque.IfSDL_SRCCOLORKEYisset,onlythepixelsnotmatchingthecolorkeyvaluearecopied.

RGBA->RGBAwithSDL_SRCALPHA

Thesourceisalpha-blendedwiththedestinationusingthesourcealphachannel.Thealphachannelinthedestinationsurfaceisleftuntouched.SDL_SRCCOLORKEYisignored.

RGBA->RGBAwithoutSDL_SRCALPHA

TheRGBAdataiscopiedtothedestinationsurface.IfSDL_SRCCOLORKEYisset,onlythepixelsnotmatchingthecolorkeyvaluearecopied.

RGB->RGBwithSDL_SRCALPHA

Thesourceisalpha-blendedwiththedestinationusingtheper-surfacealphavalue.IfSDL_SRCCOLORKEYisset,onlythepixelsnotmatchingthecolorkeyvaluearecopied.

RGB->RGBwithoutSDL_SRCALPHA

TheRGBdataiscopiedfromthesource.IfSDL_SRCCOLORKEYisset,onlythepixelsnotmatchingthecolorkeyvaluearecopied.

Note:NotethatRGBA->RGBAblits(withSDL_SRCALPHAset)keepthealphaofthedestinationsurface.ThismeansthatyoucannotcomposetwoarbitraryRGBAsurfacesthiswayandgettheresultyouwouldexpectfrom"overlaying"them;thedestinationalphawillworkasamask.

Alsonotethatper-pixelandper-surfacealphacannotbecombined;theper-pixelalphaisalwaysusedifavailable

ReturnValue

Thisfunctionreturns0,or-1iftherewasanerror.

SeeAlso

SDL_MapRGBA,SDL_GetRGBA,SDL_DisplayFormatAlpha,SDL_BlitSurface

Prev Home NextSDL_SetColorKey Up SDL_SetClipRect

SDLLibraryDocumentationPrev Next

SDL_SetClipRect

Name

SDL_SetClipRect--Setstheclippingrectangleforasurface.

Synopsis#include"SDL.h"

voidSDL_SetClipRect(SDL_Surface*surface,SDL_Rect*rect);

Description

Setstheclippingrectangleforasurface.Whenthissurfaceisthedestinationofablit,onlytheareawithinthecliprectanglewillbedrawninto.

Therectanglepointedtobyrectwillbeclippedtotheedgesofthesurfacesothatthecliprectangleforasurfacecanneverfalloutsidetheedgesofthesurface.

IfrectisNULLtheclippingrectanglewillbesettothefullsizeofthesurface.

SeeAlso

SDL_GetClipRect,SDL_BlitSurface,SDL_Surface

Prev Home NextSDL_SetAlpha Up SDL_GetClipRect

SDLLibraryDocumentationPrev Next

SDL_GetClipRect

Name

SDL_GetClipRect--Getstheclippingrectangleforasurface.

Synopsis#include"SDL.h"

voidSDL_GetClipRect(SDL_Surface*surface,SDL_Rect*rect);

Description

Getstheclippingrectangleforasurface.Whenthissurfaceisthedestinationofablit,onlytheareawithinthecliprectangleisdrawninto.

Therectanglepointedtobyrectwillbefilledwiththeclippingrectangleofthesurface.

SeeAlso

SDL_SetClipRect,SDL_BlitSurface,SDL_Surface

Prev Home NextSDL_SetClipRect Up SDL_ConvertSurface

SDLLibraryDocumentationPrev Next

SDL_ConvertSurface

Name

SDL_ConvertSurface--Convertsasurfacetothesameformatasanothersurface.

Synopsis#include"SDL/SDL.h"

SDL_Surface*SDL_ConvertSurface(SDL_Surface*src,SDL_PixelFormat*fmt,Uint32flags);

Description

Createsanewsurfaceofthespecifiedformat,andthencopiesandmapsthegivensurfacetoit.Ifthisfunctionfails,itreturnsNULL.

TheflagsparameterispassedtoSDL_CreateRGBSurfaceandhasthosesemantics.

ThisfunctionisusedinternallybySDL_DisplayFormat.

ThisfunctioncanonlybecalledafterSDL_Init.

ReturnValue

Returnseitherapointertothenewsurface,orNULLonerror.

SeeAlso

SDL_CreateRGBSurface,SDL_DisplayFormat,SDL_PixelFormat,SDL_Surface

Prev Home NextSDL_GetClipRect Up SDL_BlitSurface

SDLLibraryDocumentationPrev Next

SDL_BlitSurface

Name

SDL_BlitSurface--Thisperformsafastblitfromthesourcesurfacetothedestinationsurface.

Synopsis#include"SDL.h"

intSDL_BlitSurface(SDL_Surface*src,SDL_Rect*srcrect,SDL_Surface*dst,SDL_Rect*dstrect);

Description

Thisperformsafastblitfromthesourcesurfacetothedestinationsurface.

Onlythepositionisusedinthedstrect(thewidthandheightareignored).

IfeithersrcrectordstrectareNULL,theentiresurface(srcordst)iscopied.

Thefinalblitrectangleissavedindstrectafterallclippingisperformed(srcrectisnotmodified).

Theblitfunctionshouldnotbecalledonalockedsurface.

TheresultsofblittingoperationsvarygreatlydependingonwhetherSDL_SRCAPLHAissetornot.SeeSDL_SetAlphaforanexplainationofhowthisaffectsyourresults.Colorkeyingandalphaattributesalsointeractwithsurfaceblitting,asthefollowingpseudo-codeshouldhopefullyexplain.

if(sourcesurfacehasSDL_SRCALPHAset){

if(sourcesurfacehasalphachannel(thatis,format->Amask!=0))

blitusingper-pixelalpha,ignoringanycolourkey

else{

if(sourcesurfacehasSDL_SRCCOLORKEYset)

blitusingthecolourkeyANDtheper-surfacealphavalue

else

blitusingtheper-surfacealphavalue

}

}else{

if(sourcesurfacehasSDL_SRCCOLORKEYset)

blitusingthecolourkey

else

ordinaryopaquerectangularblit

}

ReturnValue

Iftheblitissuccessful,itreturns0,otherwiseitreturns-1.

Ifeitherofthesurfaceswereinvideomemory,andtheblitreturns-2,thevideomemorywaslost,soitshouldbereloadedwithartworkandre-blitted:

while(SDL_BlitSurface(image,imgrect,screen,dstrect)==-2){

while(SDL_LockSurface(image))<0)

Sleep(10);

--Writeimagepixelstoimage->pixels--

SDL_UnlockSurface(image);

}

ThishappensunderDirectX5.0whenthesystemswitchesawayfromyourfullscreenapplication.Lockingthesurfacewillalsofailuntilyouhaveaccesstothevideomemoryagain.

SeeAlso

SDL_LockSurface,SDL_FillRect,SDL_Surface,SDL_Rect

Prev Home NextSDL_ConvertSurface Up SDL_FillRect

SDLLibraryDocumentationPrev Next

SDL_FillRect

Name

SDL_FillRect--Thisfunctionperformsafastfillofthegivenrectanglewithsomecolor

Synopsis#include"SDL.h"

intSDL_FillRect(SDL_Surface*dst,SDL_Rect*dstrect,Uint32color);

Description

Thisfunctionperformsafastfillofthegivenrectanglewithcolor.IfdstrectisNULL,thewholesurfacewillbefilledwithcolor.

Thecolorshouldbeapixeloftheformatusedbythesurface,andcanbegeneratedbytheSDL_MapRGBorSDL_MapRGBAfunctions.Ifthecolorvaluecontainsanalphavaluethenthedestinationissimply"filled"withthatalphainformation,noblendingtakesplace.

Ifthereisacliprectanglesetonthedestination(setviaSDL_SetClipRect)thenthisfunctionwillclipbasedontheintersectionofthecliprectangleandthedstrectrectangleandthedstrectrectanglewillbemodifiedtorepresenttheareaactuallyfilled.

ReturnValue

Thisfunctionreturns0onsuccess,or-1onerror.

SeeAlso

SDL_MapRGB,SDL_MapRGBA,SDL_BlitSurface,SDL_Rect

Prev Home NextSDL_BlitSurface Up SDL_DisplayFormat

SDLLibraryDocumentationPrev Next

SDL_DisplayFormat

Name

SDL_DisplayFormat--Convertasurfacetothedisplayformat

Synopsis#include"SDL.h"

SDL_Surface*SDL_DisplayFormat(SDL_Surface*surface);

Description

Thisfunctiontakesasurfaceandcopiesittoanewsurfaceofthepixelformatandcolorsofthevideoframebuffer,suitableforfastblittingontothedisplaysurface.ItcallsSDL_ConvertSurface

Ifyouwanttotakeadvantageofhardwarecolorkeyoralphablitacceleration,youshouldsetthecolorkeyandalphavaluebeforecallingthisfunction.

Ifyouwantanalphachannel,seeSDL_DisplayFormatAlpha.

ReturnValue

Iftheconversionfailsorrunsoutofmemory,itreturnsNULL

SeeAlso

SDL_ConvertSurface,SDL_DisplayFormatAlphaSDL_SetAlpha,SDL_SetColorKey,SDL_Surface

Prev Home NextSDL_FillRect Up SDL_DisplayFormatAlpha

SDLLibraryDocumentationPrev Next

SDL_DisplayFormatAlpha

Name

SDL_DisplayFormatAlpha--Convertasurfacetothedisplayformat

Synopsis#include"SDL.h"

SDL_Surface*SDL_DisplayFormatAlpha(SDL_Surface*surface);

Description

Thisfunctiontakesasurfaceandcopiesittoanewsurfaceofthepixelformatandcolorsofthevideoframebufferplusanalphachannel,suitableforfastblittingontothedisplaysurface.ItcallsSDL_ConvertSurface

Ifyouwanttotakeadvantageofhardwarecolorkeyoralphablitacceleration,youshouldsetthecolorkeyandalphavaluebeforecallingthisfunction.

Thisfunctioncanbeusedtoconvertacolourkeytoanalphachannel,iftheSDL_SRCCOLORKEYflagissetonthesurface.Thegeneratedsurfacewillthenbetransparent(alpha=0)wherethepixelsmatchthecolourkey,andopaque(alpha=255)elsewhere.

ReturnValue

Iftheconversionfailsorrunsoutofmemory,itreturnsNULL

SeeAlso

SDL_ConvertSurface,SDL_SetAlpha,SDL_SetColorKey,SDL_DisplayFormat,SDL_Surface

Prev Home NextSDL_DisplayFormat Up SDL_WarpMouse

SDLLibraryDocumentationPrev Next

SDL_WarpMouse

Name

SDL_WarpMouse--Setthepositionofthemousecursor.

Synopsis#include"SDL.h"

voidSDL_WarpMouse(Uint16x,Uint16y);

Description

Setthepositionofthemousecursor(generatesamousemotionevent).

SeeAlso

SDL_MouseMotionEvent

Prev Home NextSDL_DisplayFormatAlpha Up SDL_CreateCursor

SDLLibraryDocumentationPrev Next

SDL_CreateCursor

Name

SDL_CreateCursor--Createsanewmousecursor.

Synopsis#include"SDL.h"

SDL_Cursor*SDL_CreateCursor(Uint8*data,Uint8*mask,intw,inth,inthot_x,inthot_y);

Description

Createacursorusingthespecifieddataandmask(inMSBformat).Thecursorwidthmustbeamultipleof8bits.

Thecursoriscreatedinblackandwhiteaccordingtothefollowing:

Data/Mask Resultingpixelonscreen0/1 White1/1 Black0/0 Transparent1/0 Invertedcolorifpossible,blackifnot.

CursorscreatedwiththisfunctionmustbefreedwithSDL_FreeCursor.

Example/*Stolenfromthemailinglist*/

/*CreatesanewmousecursorfromanXPM*/

/*XPM*/

staticconstchar*arrow[]={

/*widthheightnum_colorschars_per_pixel*/

"323231",

/*colors*/

"Xc#000000",

".c#ffffff",

"cNone",

/*pixels*/

"X",

"XX",

"X.X",

"X..X",

"X...X",

"X....X",

"X.....X",

"X......X",

"X.......X",

"X........X",

"X.....XXXXX",

"X..X..X",

"X.XX..X",

"XXX..X",

"XX..X",

"X..X",

"X..X",

"X..X",

"XX",

"",

"",

"",

"",

"",

"",

"",

"",

"",

"",

"",

"",

"",

"0,0"

};

staticSDL_Cursor*init_system_cursor(constchar*image[])

{

inti,row,col;

Uint8data[4*32];

Uint8mask[4*32];

inthot_x,hot_y;

i=-1;

for(row=0;row<32;++row){

for(col=0;col<32;++col){

if(col%8){

data[i]<<=1;

mask[i]<<=1;

}else{

++i;

data[i]=mask[i]=0;

}

switch(image[4+row][col]){

case'X':

data[i]|=0x01;

k[i]|=0x01;

break;

case'.':

mask[i]|=0x01;

break;

case'':

break;

}

}

}

sscanf(image[4+row],"%d,%d",&hot_x,&hot_y);

returnSDL_CreateCursor(data,mask,32,32,hot_x,hot_y);

}

SeeAlso

SDL_FreeCursor,SDL_SetCursor,SDL_ShowCursor

Prev Home NextSDL_WarpMouse Up SDL_FreeCursor

SDLLibraryDocumentationPrev Next

SDL_FreeCursor

Name

SDL_FreeCursor--FreesacursorcreatedwithSDL_CreateCursor.

Synopsis#include"SDL.h"

voidSDL_FreeCursor(SDL_Cursor*cursor);

Description

FreesaSDL_CursorthatwascreatedusingSDL_CreateCursor.

SeeAlso

SDL_CreateCursor

Prev Home NextSDL_CreateCursor Up SDL_SetCursor

SDLLibraryDocumentationPrev Next

SDL_SetCursor

Name

SDL_SetCursor--Setthecurrentlyactivemousecursor.

Synopsis#include"SDL.h"

void*SDL_SetCursor(SDL_Cursor*cursor);

Description

Setsthecurrentlyactivecursortothespecifiedone.Ifthecursoriscurrentlyvisible,thechangewillbeimmediatelyrepresentedonthedisplay.

SeeAlso

SDL_GetCursor,SDL_CreateCursor,SDL_ShowCursor

Prev Home NextSDL_FreeCursor Up SDL_GetCursor

SDLLibraryDocumentationPrev Next

SDL_GetCursor

Name

SDL_GetCursor--Getthecurrentlyactivemousecursor.

Synopsis#include"SDL.h"

SDL_Cursor*SDL_GetCursor(void);

Description

Returnsthecurrentlyactivemousecursor.

SeeAlso

SDL_SetCursor,SDL_CreateCursor,SDL_ShowCursor

Prev Home NextSDL_SetCursor Up SDL_ShowCursor

SDLLibraryDocumentationPrev Next

SDL_ShowCursor

Name

SDL_ShowCursor--Togglewhetherornotthecursorisshownonthescreen.

Synopsis#include"SDL.h"

intSDL_ShowCursor(inttoggle);

Description

Togglewhetherornotthecursorisshownonthescreen.PassingSDL_ENABLEdisplaysthecursorandpassingSDL_DISABLEhidesit.ThecurrentstateofthemousecursorcanbequeriedbypassingSDL_QUERY,eitherSDL_DISABLEorSDL_ENABLEwillbereturned.

Thecursorstartsoffdisplayed,butcanbeturnedoff.

ReturnValue

Returnsthecurrentstateofthecursor.

SeeAlso

SDL_CreateCursor,SDL_SetCursor

Prev Home NextSDL_GetCursor Up SDL_GL_LoadLibrary

SDLLibraryDocumentationPrev Next

SDL_GL_LoadLibrary

Name

SDL_GL_LoadLibrary--SpecifyanOpenGLlibrary

Synopsis#include"SDL.h"

intSDL_GL_LoadLibrary(constchar*path);

Description

Ifyouwish,youmayloadtheOpenGLlibraryatruntime,thismustbedonebeforeSDL_SetVideoModeiscalled.ThepathoftheGLlibraryispassedtoSDL_GL_LoadLibraryanditreturns0onsuccess,or-1onanerror.YoumustthenuseSDL_GL_GetProcAddresstoretrievefunctionpointerstoGLfunctions.

SeeAlsoSDL_GL_GetProcAddress

Prev Home NextSDL_ShowCursor Up SDL_GL_GetProcAddress

SDLLibraryDocumentationPrev Next

SDL_GL_GetProcAddress

Name

SDL_GL_GetProcAddress--GettheaddressofaGLfunction

Synopsis#include"SDL.h"

void*SDL_GL_GetProcAddress(constchar*proc);

Description

ReturnstheaddressoftheGLfunctionproc,orNULLifthefunctionisnotfound.IftheGLlibraryisloadedatruntime,withSDL_GL_LoadLibrary,thenallGLfunctionsmustberetrievedthisway.UsuallythisisusedtoretrievefunctionpointerstoOpenGLextensions.

Exampletypedefvoid(*GL_ActiveTextureARB_Func)(unsignedint);

GL_ActiveTextureARB_FuncglActiveTextureARB_ptr=0;

inthas_multitexture=1;

.

.

.

/*Getfunctionpointer*/

glActiveTextureARB_ptr=(GL_ActiveTextureARB_Func)SDL_GL_GetProcAddress("glActiveTextureARB");

/*Checkforavalidfunctionptr*/

if(!glActiveTextureARB_ptr){

fprintf(stderr,"MultitextureExtensionsnotpresent.\n");

has_multitexture=0;

}

.

.

.

.

if(has_multitexture){

glActiveTextureARB_ptr(GL_TEXTURE0_ARB);

.

.

}

else{

.

.

}

SeeAlsoSDL_GL_LoadLibrary

Prev Home NextSDL_GL_LoadLibrary Up SDL_GL_GetAttribute

SDLLibraryDocumentationPrev Next

SDL_GL_GetAttribute

Name

SDL_GL_GetAttribute--GetthevalueofaspecialSDL/OpenGLattribute

Synopsis#include"SDL.h"

intSDL_GL_GetAttribute(SDLGLattrattr,int*value);

Description

PlacesthevalueoftheSDL/OpenGLattributeattrintovalue.ThisisusefulafteracalltoSDL_SetVideoModetocheckwhetheryourattributeshavebeensetasyouexpected.

ReturnValue

Returns0onsuccess,or-1onanerror.

SeeAlso

SDL_GL_SetAttribute,GLAttributes

Prev Home NextSDL_GL_GetProcAddress Up SDL_GL_SetAttribute

SDLLibraryDocumentationPrev Next

SDL_GL_SetAttribute

Name

SDL_GL_SetAttribute--SetaspecialSDL/OpenGLattribute

Synopsis#include"SDL.h"

intSDL_GL_SetAttribute(SDL_GLattrattr,intvalue);

Description

SetstheOpenGLattributeattrtovalue.Theattributesyousetdon'ttakeeffectuntilafteracalltoSDL_SetVideoMode.YoushoulduseSDL_GL_GetAttributetocheckthevaluesafteraSDL_SetVideoModecall.

ReturnValue

Returns0onsuccess,or-1onerror.

ExampleSDL_GL_SetAttribute(SDL_GL_RED_SIZE,5);

SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,5);

SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,5);

SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);

SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);

if((screen=SDL_SetVideoMode(640,480,16,SDL_OPENGL))==NULL){

fprintf(stderr,"Couldn'tsetGLmode:%s\n",SDL_GetError());

SDL_Quit();

return;

}

Note:TheSDL_DOUBLEBUFflagisnotrequiredtoenabledoublebufferingwhensettinganOpenGLvideomode.DoublebufferingisenabledordisabledusingtheSDL_GL_DOUBLEBUFFERattribute.

SeeAlso

SDL_GL_GetAttribute,GLAttributes

Prev Home NextSDL_GL_GetAttribute Up SDL_GL_SwapBuffers

SDLLibraryDocumentationPrev Next

SDL_GL_SwapBuffers

Name

SDL_GL_SwapBuffers--SwapOpenGLframebuffers/UpdateDisplay

Synopsis#include"SDL.h"

voidSDL_GL_SwapBuffers(void);

Description

SwaptheOpenGLbuffers,ifdouble-bufferingissupported.

SeeAlso

SDL_SetVideoMode,SDL_GL_SetAttribute

Prev Home NextSDL_GL_SetAttribute Up SDL_CreateYUVOverlay

SDLLibraryDocumentationPrev Next

SDL_CreateYUVOverlay

Name

SDL_CreateYUVOverlay--CreateaYUVvideooverlay

Synopsis#include"SDL.h"

SDL_Overlay*SDL_CreateYUVOverlay(intwidth,intheight,Uint32format,SDL_Surface*display);

Description

SDL_CreateYUVOverlaycreatesaYUVoverlayofthespecifiedwidth,heightandformat(seeSDL_Overlayforalistofavailableformats),fortheprovideddisplay.ASDL_Overlaystructureisreturned.

Theterm'overlay'isamisnomersince,unlesstheoverlayiscreatedinhardware,thecontentsforthedisplaysurfaceunderneaththeareawheretheoverlayisshownwillbeoverwrittenwhentheoverlayisdisplayed.

SeeAlso

SDL_Overlay,SDL_DisplayYUVOverlay,SDL_FreeYUVOverlay

Prev Home NextSDL_GL_SwapBuffers Up SDL_LockYUVOverlay

SDLLibraryDocumentationPrev Next

SDL_LockYUVOverlay

Name

SDL_LockYUVOverlay--Lockanoverlay

Synopsis#include"SDL.h"

intSDL_LockYUVOverlay(SDL_Overlay*overlay);

Description

MuchthesameasSDL_LockSurface,SDL_LockYUVOverlaylockstheoverlayfordirectaccesstopixeldata.

ReturnValue

Returns0onsuccess,or-1onanerror.

SeeAlso

SDL_UnlockYUVOverlay,SDL_CreateYUVOverlay,SDL_Overlay

Prev Home NextSDL_CreateYUVOverlay Up SDL_UnlockYUVOverlay

SDLLibraryDocumentationPrev Next

SDL_UnlockYUVOverlay

Name

SDL_UnlockYUVOverlay--Unlockanoverlay

Synopsis#include"SDL.h"

voidSDL_UnlockYUVOverlay(SDL_Overlay*overlay);

Description

TheoppositetoSDL_LockYUVOverlay.Unlocksapreviouslylockedoverlay.Anoverlaymustbeunlockedbeforeitcanbedisplayed.

SeeAlso

SDL_UnlockYUVOverlay,SDL_CreateYUVOverlay,SDL_Overlay

Prev Home NextSDL_LockYUVOverlay Up SDL_DisplayYUVOverlay

SDLLibraryDocumentationPrev Next

SDL_DisplayYUVOverlay

Name

SDL_DisplayYUVOverlay--Blittheoverlaytothedisplay

Synopsis#include"SDL.h"

intSDL_DisplayYUVOverlay(SDL_Overlay*overlay,SDL_Rect*dstrect);

Description

Blittheoverlaytothesurfacespecifiedwhenitwascreated.TheSDL_Rectstructure,dstrect,specifiesthepositionandsizeofthedestination.Ifthedstrectisalargerorsmallerthantheoverlaythentheoverlaywillbescaled,thisisoptimizedfor2xscaling.

ReturnValues

Returns0onsuccess

SeeAlso

SDL_Overlay,SDL_CreateYUVOverlay

Prev Home NextSDL_UnlockYUVOverlay Up SDL_FreeYUVOverlay

SDLLibraryDocumentationPrev Next

SDL_FreeYUVOverlay

Name

SDL_FreeYUVOverlay--FreeaYUVvideooverlay

Synopsis#include"SDL.h"

voidSDL_FreeYUVOverlay(SDL_Overlay*overlay);

Description

FreesandoverlaycreatedbySDL_CreateYUVOverlay.

SeeAlso

SDL_Overlay,SDL_DisplayYUVOverlay,SDL_FreeYUVOverlay

Prev Home NextSDL_DisplayYUVOverlay Up SDL_GLattr

SDLLibraryDocumentationPrev Next

SDL_GLattr

Name

SDL_GLattr--SDLGLAttributes

Attributes

SDL_GL_RED_SIZE Sizeoftheframebufferredcomponent,inbitsSDL_GL_GREEN_SIZE Sizeoftheframebuffergreencomponent,inbitsSDL_GL_BLUE_SIZE Sizeoftheframebufferbluecomponent,inbitsSDL_GL_ALPHA_SIZE Sizeoftheframebufferalphacomponent,inbitsSDL_GL_DOUBLEBUFFER 0or1,enableordisabledoublebufferingSDL_GL_BUFFER_SIZE Sizeoftheframebuffer,inbitsSDL_GL_DEPTH_SIZE Sizeofthedepthbuffer,inbitsSDL_GL_STENCIL_SIZE Sizeofthestencilbuffer,inbits

SDL_GL_ACCUM_RED_SIZESizeoftheaccumulationbufferredcomponent,inbits

SDL_GL_ACCUM_GREEN_SIZESizeoftheaccumulationbuffergreencomponent,inbits

SDL_GL_ACCUM_BLUE_SIZESizeoftheaccumulationbufferbluecomponent,inbits

SDL_GL_ACCUM_ALPHA_SIZESizeoftheaccumulationbufferalphacomponent,inbits

Description

WhileyoucansetmostOpenGLattributesnormally,theattributeslistabovemustbeknownbeforeSDLsetsthevideomode.TheseattributesasetandreadwithSDL_GL_SetAttributeandSDL_GL_GetAttribute.

SeeAlso

SDL_GL_SetAttribute,SDL_GL_GetAttribute

Prev Home NextSDL_FreeYUVOverlay Up SDL_Rect

SDLLibraryDocumentationPrev Next

SDL_Rect

Name

SDL_Rect--Definesarectangulararea

StructureDefinitiontypedefstruct{

Sint16x,y;

Uint16w,h;

}SDL_Rect;

StructureData

x,y Positionoftheupper-leftcorneroftherectanglew,h Thewidthandheightoftherectangle

Description

ASDL_Rectdefinesarectangularareaofpixels.ItisusedbySDL_BlitSurfacetodefineblittingregionsandbyseveralothervideofunctions.

SeeAlso

SDL_BlitSurface,SDL_UpdateRect

Prev Home NextSDL_GLattr Up SDL_Color

SDLLibraryDocumentationPrev Next

SDL_Color

Name

SDL_Color--Formatindependentcolordescription

StructureDefinitiontypedefstruct{

Uint8r;

Uint8g;

Uint8b;

Uint8unused;

}SDL_Color;

StructureData

r Redintensityg Greenintensityb Blueintensityunused Unused

Description

SDL_Colordescribesacolorinaformatindependentway.YoucanconvertaSDL_ColortoapixelvalueforacertainpixelformatusingSDL_MapRGB.

SeeAlso

SDL_PixelFormat,SDL_SetColors,SDL_Palette

Prev Home NextSDL_Rect Up SDL_Palette

SDLLibraryDocumentationPrev Next

SDL_Palette

Name

SDL_Palette--Colorpalettefor8-bitpixelformats

StructureDefinitiontypedefstruct{

intncolors;

SDL_Color*colors;

}SDL_Palette;

StructureData

ncolors Numberofcolorsusedinthispalettecolors PointertoSDL_Colorstructuresthatmakeupthepalette.

Description

Eachpixelinan8-bitsurfaceisanindexintothecolorsfieldoftheSDL_PalettestructurestoreinSDL_PixelFormat.ASDL_Paletteshouldneverneedtobecreatedmanually.ItisautomaticallycreatedwhenSDLallocatesaSDL_PixelFormatforasurface.ThecolorsvaluesofaSDL_SurfacespalettecanbesetwiththeSDL_SetColors.

SeeAlso

SDL_Color,SDL_Surface,SDL_SetColorsSDL_SetPalette

Prev Home NextSDL_Color Up SDL_PixelFormat

SDLLibraryDocumentationPrev Next

SDL_PixelFormat

Name

SDL_PixelFormat--Storessurfaceformatinformation

StructureDefinitiontypedefstruct{

SDL_Palette*palette;

Uint8BitsPerPixel;

Uint8BytesPerPixel;

Uint32Rmask,Gmask,Bmask,Amask;

Uint8Rshift,Gshift,Bshift,Ashift;

Uint8Rloss,Gloss,Bloss,Aloss;

Uint32colorkey;

Uint8alpha;

}SDL_PixelFormat;

StructureData

palette Pointertothepalette,orNULLiftheBitsPerPixel>8

BitsPerPixelThenumberofbitsusedtorepresenteachpixelinasurface.Usually8,16,24or32.

BytesPerPixelThenumberofbytesusedtorepresenteachpixelinasurface.Usuallyonetofour.

[RGBA]mask Binarymaskusedtoretrieveindividualcolorvalues[RGBA]loss Precisionlossofeachcolorcomponent(2[RGBA]loss)[RGBA]shift Binaryleftshiftofeachcolorcomponentinthepixelvaluecolorkey Pixelvalueoftransparentpixelsalpha Overallsurfacealphavalue

Description

ASDL_PixelFormatdescribestheformatofthepixeldatastoredatthepixelsfieldofaSDL_Surface.EverysurfacestoresaSDL_PixelFormatintheformatfield.

Ifyouwishtodopixellevelmodificationsonasurface,thenunderstandinghowSDLstoresitscolorinformationisessential.

8-bitpixelformatsaretheeasiesttounderstand.Sinceitsan8-bitformat,wehave8BitsPerPixeland1BytesPerPixel.SinceBytesPerPixelis1,allpixelsarerepresentedbyaUint8whichcontainsanindexintopalette->colors.So,todeterminethecolorofapixelina8-bitsurface:wereadthecolorindexfromsurface->pixelsandweusethatindextoreadtheSDL_Colorstructurefromsurface->format->palette->colors.Likeso:

SDL_Surface*surface;

SDL_PixelFormat*fmt;

SDL_Color*color;

Uint8index;

.

.

/*Createsurface*/

.

.

fmt=surface->format;

/*Checkthebitdepthofthesurface*/

if(fmt->BitsPerPixel!=8){

fprintf(stderr,"Notan8-bitsurface.\n");

return(-1);

}

/*Lockthesurface*/

SDL_LockSurface(surface);

/*Getthetopleftpixel*/

index=*(Uint8*)surface->pixels;

color=fmt->palette->colors[index];

/*Unlockthesurface*/

SDL_UnlockSurface(surface);

printf("PixelColor->Red:%d,Green:%d,Blue:%d.Index:%d\n",

color->r,color->g,color->b,index);

.

.

Pixelformatsabove8-bitareanentirelydifferentexperience.Theyareconsideredtobe"TrueColor"formatsandthecolorinformationisstoredinthepixelsthemselves,notinapalette.Themask,shiftandlossfieldstellushowthecolorinformationisencoded.Themaskfieldsallowustoisolateeachcolorcomponent,theshiftfieldstellusthenumberofbitstotherightofeachcomponentinthepixelvalueandthelossfieldstellusthenumberofbitslostfromeachcomponentwhenpacking8-bitcolorcomponentinapixel.

/*Extractingcolorcomponentsfroma32-bitcolorvalue*/

SDL_PixelFormat*fmt;

SDL_Surface*surface;

Uint32temp,pixel;

Uint8red,green,blue,alpha;

.

.

.

fmt=surface->format;

SDL_LockSurface(surface);

pixel=*((Uint32*)surface->pixels);

SDL_UnlockSurface(surface);

/*GetRedcomponent*/

temp=pixel&fmt->Rmask;/*Isolateredcomponent*/

temp=temp>>fmt->Rshift;/*Shiftitdownto8-bit*/

temp=temp<<fmt->Rloss;/*Expandtoafull8-bitnumber*/

red=(Uint8)temp;

/*GetGreencomponent*/

temp=pixel&fmt->Gmask;/*Isolategreencomponent*/

temp=temp>>fmt->Gshift;/*Shiftitdownto8-bit*/

temp=temp<<fmt->Gloss;/*Expandtoafull8-bitnumber*/

green=(Uint8)temp;

/*GetBluecomponent*/

temp=pixel&fmt->Bmask;/*Isolatebluecomponent*/

temp=temp>>fmt->Bshift;/*Shiftitdownto8-bit*/

temp=temp<<fmt->Bloss;/*Expandtoafull8-bitnumber*/

blue=(Uint8)temp;

/*GetAlphacomponent*/

temp=pixel&fmt->Amask;/*Isolatealphacomponent*/

temp=temp>>fmt->Ashift;/*Shiftitdownto8-bit*/

temp=temp<<fmt->Aloss;/*Expandtoafull8-bitnumber*/

alpha=(Uint8)temp;

printf("PixelColor->R:%d,G:%d,B:%d,A:%d\n",red,green,blue,alpha);

.

.

.

SeeAlso

SDL_Surface,SDL_MapRGB

Prev Home NextSDL_Palette Up SDL_Surface

SDLLibraryDocumentationPrev Next

SDL_Surface

Name

SDL_Surface--GraphicalSurfaceStructure

StructureDefinitiontypedefstructSDL_Surface{

Uint32flags;/*Read-only*/

SDL_PixelFormat*format;/*Read-only*/

intw,h;/*Read-only*/

Uint16pitch;/*Read-only*/

void*pixels;/*Read-write*/

/*clippinginformation*/

SDL_Rectclip_rect;/*Read-only*/

/*Referencecount--usedwhenfreeingsurface*/

intrefcount;/*Read-mostly*/

/*Thisstructurealsocontainsprivatefieldsnotshownhere*/

}SDL_Surface;

StructureData

flags Surfaceflagsformat Pixelformatw,h Widthandheightofthesurfacepitch Lengthofasurfacescanlineinbytespixels Pointertotheactualpixeldataclip_rect surfacecliprectangle

Description

SDL_Surface'srepresentareasof"graphical"memory,memorythatcanbedrawnto.ThevideoframebufferisreturnedasaSDL_SurfacebySDL_SetVideoModeandSDL_GetVideoSurface.Mostofthefieldsshouldbeprettyobvious.wandharethewidthandheightofthesurfaceinpixels.pixelsisapointertotheactualpixeldata,thesurfaceshouldbelockedbeforeaccessingthisfield.Theclip_rectfieldistheclippingrectangleassetbySDL_SetClipRect.

Thefollowingaresupportedintheflagsfield.

SDL_SWSURFACE SurfaceisstoredinsystemmemorySDL_HWSURFACE SurfaceisstoredinvideomemorySDL_ASYNCBLIT SurfaceusesasynchronousblitsifpossibleSDL_ANYFORMAT Allowsanypixel-format(Displaysurface)SDL_HWPALETTE SurfacehasexclusivepaletteSDL_DOUBLEBUF Surfaceisdoublebuffered(Displaysurface)SDL_FULLSCREEN Surfaceisfullscreen(DisplaySurface)SDL_OPENGL SurfacehasanOpenGLcontext(DisplaySurface)SDL_OPENGLBLIT SurfacesupportsOpenGLblitting(DisplaySurface)SDL_RESIZABLE Surfaceisresizable(DisplaySurface)SDL_HWACCEL SurfaceblituseshardwareaccelerationSDL_SRCCOLORKEY SurfaceusecolorkeyblittingSDL_RLEACCEL ColorkeyblittingisacceleratedwithRLESDL_SRCALPHA SurfaceblitusesalphablendingSDL_PREALLOC Surfaceusespreallocatedmemory

SeeAlso

SDL_PixelFormat

Prev Home NextSDL_PixelFormat Up SDL_VideoInfo

SDLLibraryDocumentationPrev Next

SDL_VideoInfo

Name

SDL_VideoInfo--VideoTargetinformation

StructureDefinitiontypedefstruct{

Uint32hw_available:1;

Uint32wm_available:1;

Uint32blit_hw:1;

Uint32blit_hw_CC:1;

Uint32blit_hw_A:1;

Uint32blit_sw:1;

Uint32blit_sw_CC:1;

Uint32blit_sw_A:1;

Uint32blit_fill;

Uint32video_mem;

SDL_PixelFormat*vfmt;

}SDL_VideoInfo;

StructureData

hw_available Isitpossibletocreatehardwaresurfaces?wm_available Isthereawindowmanageravailableblit_hw Arehardwaretohardwareblitsaccelerated?blit_hw_CC Arehardwaretohardwarecolorkeyblitsaccelerated?blit_hw_A Arehardwaretohardwarealphablitsaccelerated?blit_sw Aresoftwaretohardwareblitsaccelerated?blit_sw_CC Aresoftwaretohardwarecolorkeyblitsaccelerated?blit_sw_A Aresoftwaretohardwarealphablitsaccelerated?blit_fill Arecolorfillsaccelerated?video_mem TotalamountofvideomemoryinKilobytesvfmt Pixelformatofthevideodevice

Description

This(read-only)structureisreturnedbySDL_GetVideoInfo.Itcontainsinformationoneitherthe'best'availablemode(ifcalledbeforeSDL_SetVideoMode)orthecurrentvideomode.

SeeAlso

SDL_PixelFormat,SDL_GetVideoInfo

Prev Home NextSDL_Surface Up SDL_Overlay

SDLLibraryDocumentationPrev Next

SDL_Overlay

Name

SDL_Overlay--YUVvideooverlay

StructureDefinitiontypedefstruct{

Uint32format;

intw,h;

intplanes;

Uint16*pitches;

Uint8**pixels;

Uint32hw_overlay:1;

}SDL_Overlay;

StructureData

format Overlayformat(seebelow)w,h Widthandheightofoverlayplanes Numberofplanesintheoverlay.Usuallyeither1or3

pitchesAnarrayofpitches,oneforeachplane.Pitchisthelengthofarowinbytes.

pixelsAnarrayofpointerstotehdataofeachplane.Theoverlayshouldbelockedbeforethesepointersareused.

hw_overlay Thiswillbesetto1iftheoverlayishardwareaccelerated.

Description

ASDL_OverlayissimilartoaSDL_SurfaceexceptitstoresaYUVoverlay.Allthefieldsarereadonly,exceptforpixelswhichshouldbelockedbeforeuse.Theformatfieldstorestheformatoftheoverlaywhichisoneofthefollowing:

#defineSDL_YV12_OVERLAY0x32315659/*Planarmode:Y+V+U*/

#defineSDL_IYUV_OVERLAY0x56555949/*Planarmode:Y+U+V*/

#defineSDL_YUY2_OVERLAY0x32595559/*Packedmode:Y0+U0+Y1+V0*/

#defineSDL_UYVY_OVERLAY0x59565955/*Packedmode:U0+Y0+V0+Y1*/

#defineSDL_YVYU_OVERLAY0x55595659/*Packedmode:Y0+V0+Y1+U0*/

MoreinformationonYUVformatscanbefoundathttp://www.webartz.com/fourcc/indexyuv.htm.

SeeAlso

SDL_CreateYUVOverlay,SDL_LockYUVOverlay,SDL_UnlockYUVOverlay,SDL_FreeYUVOverlay

Prev Home NextSDL_VideoInfo Up WindowManagement

SDLLibraryDocumentationPrev Next

Chapter7.WindowManagementTableofContentsSDL_WM_SetCaption—Setsthewindowtileandiconname.SDL_WM_GetCaption—Getsthewindowtitleandiconname.SDL_WM_SetIcon—Setstheiconforthedisplaywindow.SDL_WM_IconifyWindow—Iconify/MinimisethewindowSDL_WM_ToggleFullScreen—TogglesfullscreenmodeSDL_WM_GrabInput—Grabsmouseandkeyboardinput.

SDLprovidesasmallsetofwindowmanagementfunctionswhichallowapplicationstochangetheirtitleandtogglefromwindowedmodetofullscreen(ifavailable)

Prev Home NextSDL_Overlay Up SDL_WM_SetCaption

SDLLibraryDocumentationPrev Next

SDL_WM_GetCaption

Name

SDL_WM_GetCaption--Getsthewindowtitleandiconname.

Synopsis#include"SDL.h"

voidSDL_WM_GetCaption(char**title,char**icon);

Description

Setpointerstothewindowtitleandiconname.

SeeAlso

SDL_WM_SetCaption,SDL_WM_SetIcon

Prev Home NextSDL_WM_SetCaption Up SDL_WM_SetIcon

SDLLibraryDocumentationPrev Next

SDL_WM_SetCaption

Name

SDL_WM_SetCaption--Setsthewindowtileandiconname.

Synopsis#include"SDL.h"

voidSDL_WM_SetCaption(constchar*title,constchar*icon);

Description

Setsthetitle-barandiconnameofthedisplaywindow.

SeeAlso

SDL_WM_GetCaption,SDL_WM_SetIcon

Prev Home NextWindowManagement Up SDL_WM_GetCaption

SDLLibraryDocumentationPrev Next

SDL_WM_SetIcon

Name

SDL_WM_SetIcon--Setstheiconforthedisplaywindow.

Synopsis#include"SDL.h"

voidSDL_WM_SetIcon(SDL_Surface*icon,Uint8*mask);

Description

Setstheiconforthedisplaywindow.Win32iconsmustbe32x32.

ThisfunctionmustbecalledbeforethefirstcalltoSDL_SetVideoMode.

Ittakesaniconsurface,andamaskinMSBformat.

IfmaskisNULL,theentireiconsurfacewillbeusedastheicon.

ExampleSDL_WM_SetIcon(SDL_LoadBMP("icon.bmp"),NULL);

SeeAlso

SDL_SetVideoMode,SDL_WM_SetCaption

Prev Home NextSDL_WM_GetCaption Up SDL_WM_IconifyWindow

SDLLibraryDocumentationPrev Next

SDL_WM_IconifyWindow

Name

SDL_WM_IconifyWindow--Iconify/Minimisethewindow

Synopsis#include"SDL.h"

intSDL_WM_IconifyWindow(void);

Description

IftheapplicationisrunninginawindowmanagedenvironmentSDLattemptstoiconify/minimiseit.IfSDL_WM_IconifyWindowissuccessful,theapplicationwillreceiveaSDL_APPACTIVElossevent.

ReturnValue

Returnsnon-zeroonsuccessor0ificonificationisnotsupportorwasrefusedbythewindowmanager.

Prev Home NextSDL_WM_SetIcon Up SDL_WM_ToggleFullScreen

SDLLibraryDocumentationPrev Next

SDL_WM_ToggleFullScreen

Name

SDL_WM_ToggleFullScreen--Togglesfullscreenmode

Synopsis#include"SDL.h"

intSDL_WM_ToggleFullScreen(SDL_Surface*surface);

Description

Togglestheapplicationbetweenwindowedandfullscreenmode,ifsupported.(X11istheonlytargetcurrentlysupported,BeOSsupportisexperimental).

ReturnValue

Returns0onfailureor1onsuccess.

Prev Home NextSDL_WM_IconifyWindow Up SDL_WM_GrabInput

SDLLibraryDocumentationPrev Next

SDL_WM_GrabInput

Name

SDL_WM_GrabInput--Grabsmouseandkeyboardinput.

Synopsis#include"SDL.h"

SDL_GrabModeSDL_WM_GrabInput(SDL_GrabModemode);

Description

Grabbingmeansthatthemouseisconfinedtotheapplicationwindow,andnearlyallkeyboardinputispasseddirectlytotheapplication,andnotinterpretedbyawindowmanager,ifany.

WhenmodeisSDL_GRAB_QUERYthegrabmodeisnotchanged,butthecurrentgrabmodeisreturned.

typedefenum{

SDL_GRAB_QUERY,

SDL_GRAB_OFF,

SDL_GRAB_ON

}SDL_GrabMode;

ReturnValue

Thecurrent/newSDL_GrabMode.

Prev Home NextSDL_WM_ToggleFullScreen Up Events

SDLLibraryDocumentationPrev Next

Chapter8.EventsTableofContentsIntroductionSDLEventStructures.EventFunctions.

IntroductionEventhandlingallowsyourapplicationtoreceiveinputfromtheuser.Eventhandlingisinitalised(alongwithvideo)withacallto:

SDL_Init(SDL_INIT_VIDEO);

Internally,SDLstoresalltheeventswaitingtobehandledinaneventqueue.UsingfunctionslikeSDL_PollEventandSDL_PeepEventsyoucanobserveandhandlewaitinginputevents.

ThekeytoeventhandlinginSDListheSDL_Eventunion.TheeventqueueitselfiscomposedofaseriesofSDL_Eventunions,oneforeachwaitingevent.SDL_EventunionsarereadfromthequeuewiththeSDL_PollEventfunctionanditisthenuptotheapplicationtoprocesstheinformationstoredwiththem.

Prev Home NextSDL_WM_GrabInput Up SDLEventStructures.

SDLLibraryDocumentationPrev Chapter8.Events Next

SDLEventStructures.TableofContentsSDL_Event—GeneraleventstructureSDL_ActiveEvent—ApplicationvisibilityeventstructureSDL_KeyboardEvent—KeyboardeventstructureSDL_MouseMotionEvent—MousemotioneventstructureSDL_MouseButtonEvent—MousebuttoneventstructureSDL_JoyAxisEvent—JoystickaxismotioneventstructureSDL_JoyButtonEvent—JoystickbuttoneventstructureSDL_JoyHatEvent—JoystickhatpositionchangeeventstructureSDL_JoyBallEvent—JoysticktrackballmotioneventstructureSDL_ResizeEvent—WindowresizeeventstructureSDL_ExposeEvent—QuitrequestedeventSDL_SysWMEvent—Platform-dependentwindowmanagerevent.SDL_UserEvent—Auser-definedeventtypeSDL_QuitEvent—QuitrequestedeventSDL_keysym—KeysymstructureSDLKey—Keysymdefinitions.

Prev Home NextEvents Up SDL_Event

SDLLibraryDocumentationPrev Next

SDL_Event

Name

SDL_Event--Generaleventstructure

StructureDefinitiontypedefunion{

Uint8type;

SDL_ActiveEventactive;

SDL_KeyboardEventkey;

SDL_MouseMotionEventmotion;

SDL_MouseButtonEventbutton;

SDL_JoyAxisEventjaxis;

SDL_JoyBallEventjball;

SDL_JoyHatEventjhat;

SDL_JoyButtonEventjbutton;

SDL_ResizeEventresize;

SDL_ExposeEventexpose;

SDL_QuitEventquit;

SDL_UserEventuser;

SDL_SywWMEventsyswm;

}SDL_Event;

StructureData

type Thetypeofeventactive Activationeventkey Keyboardeventmotion Mousemotioneventbutton Mousebuttoneventjaxis Joystickaxismotioneventjball Joysticktrackballmotioneventjhat Joystickhatmotioneventjbutton Joystickbuttoneventresize Applicationwindowresizeeventexpose Applicationwindowexposeeventquit Applicationquitrequesteventuser Userdefinedeventsyswm Undefinedwindowmanagerevent

Description

TheSDL_EventunionisthecoretoalleventhandlingisSDL,itsprobablythemostimportantstructureafterSDL_Surface.SDL_EventisaunionofalleventstructuresusedinSDL,usingitisasimplematterofknowingwhichunionmemberrelatestowhicheventtype.

Eventtype EventStructureSDL_ACTIVEEVENT SDL_ActiveEventSDL_KEYDOWN/UP SDL_KeyboardEventSDL_MOUSEMOTION SDL_MouseMotionEventSDL_MOUSEBUTTONDOWN/UP SDL_MouseButtonEventSDL_JOYAXISMOTION SDL_JoyAxisEventSDL_JOYBALLMOTION SDL_JoyBallEventSDL_JOYHATMOTION SDL_JoyHatEventSDL_JOYBUTTONDOWN/UP SDL_JoyButtonEventSDL_QUIT SDL_QuitEventSDL_SYSWMEVENT SDL_SysWMEventSDL_VIDEORESIZE SDL_ResizeEventSDL_VIDEOEXPOSE SDL_ExposeEventSDL_USEREVENT SDL_UserEvent

Use

TheSDL_Eventstructurehastwouses

Readingeventsontheeventqueue

Placingeventsontheeventqueue

ReadingeventsfromtheeventqueueisdonewitheitherSDL_PollEventorSDL_PeepEvents.We'lluseSDL_PollEventandstepthroughanexample.

Firstoff,wecreateanemptySDL_Eventstructure.

SDL_Eventtest_event;

SDL_PollEventremovesthenexteventfromtheeventqueue,iftherearenoeventsonthequeueitreturns0otherwiseitreturns1.Weuseawhilelooptoprocesseacheventinturn.

while(SDL_PollEvent(&test_event)){

TheSDL_PollEventfunctiontakeapointertoanSDL_Eventstructurethatistobefilledwitheventinformation.WeknowthatifSDL_PollEventremovesaneventfromthequeuethentheeventinformationwillbeplacedinourtest_eventstructure,butwealsoknowthatthetypeofeventwillbeplacedinthetypememberoftest_event.Sotohandleeacheventtypeseperatelyweuseaswitchstatement.

switch(test_event.type){

Weneedtoknowwhatkindofeventswe'relookingforandtheeventtype'softhoseevents.Soletsassumewewanttodetectwheretheuserismovingthemousepointerwithinourapplication.WelookthroughoureventtypesandnoticethatSDL_MOUSEMOTIONis,morethanlikely,theeventwe'relookingfor.AlittlemoreresearchtellsusethatSDL_MOUSEMOTIONeventsarehandledwithintheSDL_MouseMotionEventstructurewhichisthemotionmemberofSDL_Event.WecancheckfortheSDL_MOUSEMOTIONeventtypewithinourswitchstatementlikeso:

caseSDL_MOUSEMOTION:

Allweneeddonowisreadtheinformationoutofthemotionmemberoftest_event.

printf("Wegotamotionevent.\n");

printf("Currentmousepositionis:(%d,%d)\n",test_event.motion.x,test_event.motion.y);

break;

default:

printf("UnhandledEvent!\n");

break;

}

}

printf("Eventqueueempty.\n");

Itisalsopossibletopusheventsontotheeventqueueandsouseitasatwo-waycommunicationpath.BothSDL_PushEventandSDL_PeepEventsallowyoutoplaceeventsontotheeventqueue.ThisisusuallyusedtoplaceaSDL_USEREVENTontheeventqueue,howeveryoucoulduseittopostfakeinputeventsifyouwished.Creatingyourowneventsisasimplematterofchoosingtheeventtypeyouwant,settingthetypememberandfillingtheappropriatememberstructurewithinformation.

SDL_Eventuser_event;

user_event.type=SDL_USEREVENT;

user_event.user.code=2;

user_event.user.data1=NULL;

user_event.user.data2=NULL;

SDL_PushEvent(&user_event);

SeeAlso

SDL_PollEvent,SDL_PushEvent,SDL_PeepEvents

Prev Home NextSDLEventStructures. Up SDL_ActiveEvent

SDLLibraryDocumentationPrev Next

SDL_ActiveEvent

Name

SDL_ActiveEvent--Applicationvisibilityeventstructure

StructureDefinitiontypedefstruct{

Uint8type;

Uint8gain;

Uint8state;

}SDL_ActiveEvent;

StructureData

type SDL_ACTIVEEVENT.

gain 0iftheeventisalossor1ifitisagain.

state

SDL_APPMOUSEFOCUSifmousefocuswasgainedorlost,SDL_APPINPUTFOCUSifinputfocuswasgainedorlost,orSDL_APPACTIVEiftheapplicationwasiconified(gain=0)orrestored(gain=1).

Description

SDL_ActiveEventisamemberoftheSDL_EventunionandisusedwhenaneventoftypeSDL_ACTIVEEVENTisreported.

WhenthemouseleavesorentersthewindowareaaSDL_APPMOUSEFOCUStypeactivationeventoccurs,ifthemouseenteredthewindowthengainwillbe1,otherwisegainwillbe0.ASDL_APPINPUTFOCUStypeactivationeventoccurswhentheapplicationlosesorgainskeyboardfocus.Thisusuallyoccurswhenanotherapplicationismadeactive.Finally,aSDL_APPACTIVEtypeeventoccurswhentheapplicationiseitherminimised/iconified(gain=0)orrestored.

Note:Thiseventdoesnotoccurwhenanapplicationwindowisfirstcreated.

SeeAlso

SDL_Event,SDL_GetAppState

Prev Home NextSDL_Event Up SDL_KeyboardEvent

SDLLibraryDocumentationPrev Next

SDL_KeyboardEvent

Name

SDL_KeyboardEvent--Keyboardeventstructure

StructureDefinitiontypedefstruct{

Uint8type;

Uint8state;

SDL_keysymkeysym;

}SDL_KeyboardEvent;

StructureData

type SDL_KEYDOWNorSDL_KEYUPstate SDL_PRESSEDorSDL_RELEASEDkeysym Containskeypressinformation

Description

SDL_KeyboardEventisamemberoftheSDL_EventunionandisusedwhenaneventoftypeSDL_KEYDOWNorSDL_KEYUPisreported.

Thetypeandstateactuallyreportthesameinformation,theyjustusedifferentvaluestodoit!Akeyboardeventoccurswhenakeyisreleased(type=SDK_KEYUPorstate=SDL_RELEASED)andwhenakeyispressed(type=SDL_KEYDOWNorstate=SDL_PRESSED).Theinformationonwhatkeywaspressedorreleasedisinthekeysymstructure.

Note:RepeatingSDL_KEYDOWNeventswilloccurifkeyrepeatisenabled(seeSDL_EnableKeyRepeat).

SeeAlso

SDL_Event,SDL_keysym,SDL_EnableKeyRepeat,SDL_EnableUNICODE

Prev Home NextSDL_ActiveEvent Up SDL_MouseMotionEvent

SDLLibraryDocumentationPrev Next

SDL_MouseMotionEvent

Name

SDL_MouseMotionEvent--Mousemotioneventstructure

StructureDefinitiontypedefstruct{

Uint8type;

Uint8state;

Uint16x,y;

Sint16xrel,yrel;

}SDL_MouseMotionEvent;

StructureData

type SDL_MOUSEMOTION

state Thecurrentbuttonstatex,y TheX/Ycoordinatesofthemousexrel,yrel RelativemotionintheX/Ydirection

Description

SDL_MouseMotionEventisamemberoftheSDL_EventunionandisusedwhenaneventoftypeSDL_MOUSEMOTIONisreported.

Simplyput,aSDL_MOUSEMOTIONtypeeventoccurswhenausermovesthemousewithintheapplicationwindoworwhenSDL_WarpMouseiscalled.Boththeabsolute(xandy)andrelative(xrelandyrel)coordinatesarereportedalongwiththecurrentbuttonstates(state).ThebuttonstatecanbeinterpretedusingtheSDL_BUTTONmacro(seeSDL_GetMouseState).

Ifthecursorishidden(SDL_ShowCursor(0))andtheinputisgrabbed(SDL_WM_GrabInput(SDL_GRAB_ON)),thenthemousewillgiverelativemotioneventsevenwhenthecursorreachestheedgefothescreen.ThisiscurrentlyonlyimplementedonWindowsandLinux/Unix-a-likes.

SeeAlso

SDL_Event,SDL_MouseButtonEvent

Prev Home NextSDL_KeyboardEvent Up SDL_MouseButtonEvent

SDLLibraryDocumentationPrev Next

SDL_MouseButtonEvent

Name

SDL_MouseButtonEvent--Mousebuttoneventstructure

StructureDefinitiontypedefstruct{

Uint8type;

Uint8button;

Uint8state;

Uint16x,y;

}SDL_MouseButtonEvent;

StructureData

type SDL_MOUSEBUTTONDOWNorSDL_MOUSEBUTTONUP

buttonThemousebuttonindex(SDL_BUTTON_LEFT,SDL_BUTTON_MIDDLE,SDL_BUTTON_RIGHT)

state SDL_PRESSEDorSDL_RELEASEDx,y TheX/Ycoordinatesofthemouseatpress/releasetime

Description

SDL_MouseButtonEventisamemberoftheSDL_EventunionandisusedwhenaneventoftypeSDL_MOUSEBUTTONDOWNorSDL_MOUSEBUTTONUPisreported.

Whenamousebuttonpressorreleaseisdetectedthennumberofthebuttonpressed(from1to255,with1usuallybeingtheleftbuttonand2theright)isplacedintobutton,thepositionofthemousewhenthiseventoccuredisstoredinthexandtheyfields.LikeSDL_KeyboardEvent,informationonwhethertheeventwasapressorareleaseeventisstoredinboththetypeandstatefields,butthisshouldbeobvious.

SeeAlso

SDL_Event,SDL_MouseMotionEvent

Prev Home NextSDL_MouseMotionEvent Up SDL_JoyAxisEvent

SDLLibraryDocumentationPrev Next

SDL_JoyAxisEvent

Name

SDL_JoyAxisEvent--Joystickaxismotioneventstructure

StructureDefinitiontypedefstruct{

Uint8type;

Uint8which;

Uint8axis;

Sint16value;

}SDL_JoyAxisEvent;

StructureData

type SDL_JOYAXISMOTION

which Joystickdeviceindexaxis JoystickaxisindexvalueAxisvalue(range:-32768to32767)

Description

SDL_JoyAxisEventisamemberoftheSDL_EventunionandisusedwhenaneventoftypeSDL_JOYAXISMOTIONisreported.

ASDL_JOYAXISMOTIONeventoccurswheneverausermovesanaxisonthejoystick.Thefieldwhichistheindexofthejoystickthatreportedtheeventandaxisistheindexoftheaxis(foramoredetailedexplainationseetheJoysticksection).valueisthecurrentpositionoftheaxis.

SeeAlso

SDL_Event,JoystickFunctions,SDL_JoystickEventState,SDL_JoystickGetAxis

Prev Home NextSDL_MouseButtonEvent Up SDL_JoyButtonEvent

SDLLibraryDocumentationPrev Next

SDL_JoyButtonEvent

Name

SDL_JoyButtonEvent--Joystickbuttoneventstructure

StructureDefinitiontypedefstruct{

Uint8type;

Uint8which;

Uint8button;

Uint8state;

}SDL_JoyButtonEvent;

StructureData

type SDL_JOYBUTTONDOWNorSDL_JOYBUTTONUPwhich Joystickdeviceindexbutton Joystickbuttonindexstate SDL_PRESSEDorSDL_RELEASED

Description

SDL_JoyButtonEventisamemberoftheSDL_EventunionandisusedwhenaneventoftypeSDL_JOYBUTTONDOWNorSDL_JOYBUTTONUPisreported.

ASDL_JOYBUTTONDOWNorSDL_JOYBUTTONUPeventoccurswheneverauserpressesorreleasesabuttononajoystick.Thefieldwhichistheindexofthejoystickthatreportedtheeventandbuttonistheindexofthebutton(foramoredetailedexplainationseetheJoysticksection).stateisthecurrentstateorthebuttonwhichiseitherSDL_PRESSEDorSDL_RELEASED.

SeeAlso

SDL_Event,JoystickFunctions,SDL_JoystickEventState,SDL_JoystickGetButton

Prev Home NextSDL_JoyAxisEvent Up SDL_JoyHatEvent

SDLLibraryDocumentationPrev Next

SDL_JoyHatEvent

Name

SDL_JoyHatEvent--Joystickhatpositionchangeeventstructure

StructureDefinitiontypedefstruct{

Uint8type;

Uint8which;

Uint8hat;

Uint8value;

}SDL_JoyHatEvent;

StructureData

type SDL_JOY

which Joystickdeviceindexhat JoystickhatindexvalueHatposition

Description

SDL_JoyHatEventisamemberoftheSDL_EventunionandisusedwhenaneventoftypeSDL_JOYHATMOTIONisreported.

ASDL_JOYHATMOTIONeventoccurswheneverausermovesahatonthejoystick.Thefieldwhichistheindexofthejoystickthatreportedtheeventandhatistheindexofthehat(foramoredetailedexlainationseetheJoysticksection).valueisthecurrentpositionofthehat.ItisalogicallyOR'dcombinationofthefollowingvalues(whosemeaningsshouldbeprettyobvious:):

SDL_HAT_CENTERED

SDL_HAT_UP

SDL_HAT_RIGHT

SDL_HAT_DOWN

SDL_HAT_LEFT

Thefollowingdefinesarealsoprovided:

SDL_HAT_RIGHTUP

SDL_HAT_RIGHTDOWN

SDL_HAT_LEFTUP

SDL_HAT_LEFTDOWN

SeeAlso

SDL_Event,JoystickFunctions,SDL_JoystickEventState,SDL_JoystickGetHat

Prev Home NextSDL_JoyButtonEvent Up SDL_JoyBallEvent

SDLLibraryDocumentationPrev Next

SDL_JoyBallEvent

Name

SDL_JoyBallEvent--Joysticktrackballmotioneventstructure

StructureDefinitiontypedefstruct{

Uint8type;

Uint8which;

Uint8ball;

Sint16xrel,yrel;

}SDL_JoyBallEvent;

StructureData

type SDL_JOYBALLMOTION

which Joystickdeviceindexball Joysticktrackballindexxrel,yrel TherelativemotionintheX/Ydirection

Description

SDL_JoyBallEventisamemberoftheSDL_EventunionandisusedwhenaneventoftypeSDL_JOYBALLMOTIONisreported.

ASDL_JOYBALLMOTIONeventoccurswhenausermovesatrackballonthejoystick.Thefieldwhichistheindexofthejoystickthatreportedtheeventandballistheindexofthetrackball(foramoredetailedexplainationseetheJoysticksection).Trackballsonlyreturnrelativemotion,thisisthechangeinpositionontheballsinceitwaslastpolled(lastcycleoftheeventloop)anditisstoredinxrelandyrel.

SeeAlso

SDL_Event,JoystickFunctions,SDL_JoystickEventState,SDL_JoystickGetBall

Prev Home NextSDL_JoyHatEvent Up SDL_ResizeEvent

SDLLibraryDocumentationPrev Next

SDL_ResizeEvent

Name

SDL_ResizeEvent--Windowresizeeventstructure

StructureDefinitiontypedefstruct{

Uint8type;

intw,h;

}SDL_ResizeEvent;

StructureData

type SDL_VIDEORESIZE

w,h Newwidthandheightofthewindow

Description

SDL_ResizeEventisamemberoftheSDL_EventunionandisusedwhenaneventoftypeSDL_VIDEORESIZEisreported.

WhenSDL_RESIZABLEispassedasaflagtoSDL_SetVideoModetheuserisallowedtoresizetheapplicationswindow.WhenthewindowisresizedanSDL_VIDEORESIZEisreport,withthenewwindowwidthandheightvaluesstoredinwandh,respectively.WhenanSDL_VIDEORESIZEisrecievedthewindowshouldberesizedtothenewdimensionsusingSDL_SetVideoMode.

SeeAlso

SDL_Event,SDL_SetVideoMode

Prev Home NextSDL_JoyBallEvent Up SDL_ExposeEvent

SDLLibraryDocumentationPrev Next

SDL_ExposeEvent

Name

SDL_ExposeEvent--Quitrequestedevent

StructureDefinitiontypedefstruct{

Uint8type

}SDL_ExposeEvent;

StructureData

type SDL_QUIT

Description

SDL_ExposeEventisamemberoftheSDL_EventunionandisusedwhananeventoftypeSDL_VIDEOEXPOSEisreported.

AVIDEOEXPOSEeventistriggeredwhenthescreenhasbeenmodifiedoutsideoftheapplication,usuallybythewindowmanagerandneedstoberedrawn.

SeeAlso

SDL_Event,SDL_SetEventFilter

Prev Home NextSDL_ResizeEvent Up SDL_SysWMEvent

SDLLibraryDocumentationPrev Next

SDL_SysWMEvent

Name

SDL_SysWMEvent--Platform-dependentwindowmanagerevent.

Description

Thesystemwindowmanagereventcontainsapointertosystem-specificinformationaboutunknownwindowmanagerevents.IfyouenablethiseventusingSDL_EventState(),itwillbegeneratedwheneverunhandledeventsarereceivedfromthewindowmanager.Thiscanbeused,forexample,toimplementcut-and-pasteinyourapplication.

typedefstruct{

Uint8type;/*AlwaysSDL_SysWM*/

}SDL_SysWMEvent;

Ifyouwanttoobtainsystem-specificinformationaboutthewindowmanager,youcanfilltheversionmemberofaSDL_SysWMinfostructure(detailscanbefoundinSDL_syswm.h,whichmustbeincluded)usingtheSDL_VERSION()macrofoundinSDL_version.h,andpassittothefunction:

intSDL_GetWMInfo(SDL_SysWMinfo*info);

SeeAlsoSDL_EventState

Prev Home NextSDL_ExposeEvent Up SDL_UserEvent

SDLLibraryDocumentationPrev Next

SDL_UserEvent

Name

SDL_UserEvent--Auser-definedeventtype

StructureDefinitiontypedefstruct{

Uint8type;

intcode;

void*data1;

void*data2;

}SDL_UserEvent;

StructureData

type SDL_USEREVENTthroughtoSDL_NUMEVENTS-1code Userdefinedeventcodedata1Userdefineddatapointerdata2Userdefineddatapointer

Description

SDL_UserEventisintheusermemberofthestructureSDL_Event.Thiseventisunique,itisnevercreatedbySDLbutonlybytheuser.TheeventcanbepushedontotheeventqueueusingSDL_PushEvent.Thecontentsofthestructuremembersorcompletelyuptotheprogrammer,theonlyrequirementisthattypeisavaluefromSDL_USEREVENTtoSDL_NUMEVENTS-1(inclusive).

ExamplesSDL_Eventevent;

event.type=SDL_USEREVENT;

event.user.code=my_event_code;

event.user.data1=significant_data;

event.user.data2=0;

SDL_PushEvent(&event);

SeeAlso

SDL_Event,SDL_PushEvent

Prev Home NextSDL_SysWMEvent Up SDL_QuitEvent

SDLLibraryDocumentationPrev Next

SDL_QuitEvent

Name

SDL_QuitEvent--Quitrequestedevent

StructureDefinitiontypedefstruct{

Uint8type

}SDL_QuitEvent;

StructureData

type SDL_QUIT

Description

SDL_QuitEventisamemberoftheSDL_EventunionandisusedwhananeventoftypeSDL_QUITisreported.

Ascanbeseen,theSDL_QuitEventstructureservesnousefulpurpose.Theeventitself,ontheotherhand,isveryimportant.Ifyoufilteroutorignoreaquiteventthenitisimpossiblefortheusertoclosethewindow.Ontheotherhand,ifyoudoacceptaquiteventthentheapplicationwindowwillbeclosed,andscreenupdateswillstillreportsuccesseventthoughtheapplicationwillnolongerbevisible.

Note:ThemacroSDL_QuitRequestedwillreturnnon-zeroifaquiteventispending

SeeAlso

SDL_Event,SDL_SetEventFilter

Prev Home NextSDL_UserEvent Up SDL_keysym

SDLLibraryDocumentationPrev Next

SDL_keysym

Name

SDL_keysym--Keysymstructure

StructureDefinitiontypedefstruct{

Uint8scancode;

SDLKeysym;

SDLModmod;

Uint16unicode;

}SDL_keysym;

StructureData

scancodeHardwarespecificscancodesym SDLvirtualkeysymmod Currentkeymodifiersunicode Translatedcharacter

Description

TheSDL_keysymstructureisusedbyreportingkeypressesandreleasessinceitisapartoftheSDL_KeyboardEvent.

Thescancodefieldshouldgenerallybeleftalone,itisthehardwaredependentscancodereturnedbythekeyboard.Thesymfieldisextremelyuseful.ItistheSDL-definedvalueofthekey(seeSDLKeySyms.Thisfieldisveryusefulwhenyouarecheckingforcertainkeypresses,likeso:

.

.

while(SDL_PollEvent(&event)){

switch(event.type){

caseSDL_KEYDOWN:

if(event.key.keysym.sym==SDLK_LEFT)

move_left();

break;

.

.

.

}

}

.

.

modstoresthecurrentstateofthekeyboardmodifiersasexplainedinSDL_GetModState.TheunicodeisonlyusedwhenUNICODEtranslationisenabledwithSDL_EnableUNICODE.Ifunicodeisnon-zerothenthisatheUNICODEcharactercorrespondingtothekeypress.Ifthehigh9bitsofthecharacterare0,thenthismapstotheequivalentASCIIcharacter:

charch;

if((keysym.unicode&0xFF80)==0){

ch=keysym.unicode&0x7F;

}

else{

printf("AnInternationalCharacter.\n");

}

UNICODEtranslationdoeshaveaslightoverheadsodon'tenableitunlessitsneeded.

SeeAlso

SDLKey

Prev Home NextSDL_QuitEvent Up SDLKey

SDLLibraryDocumentationPrev Next

SDLKey

Name

SDLKey--Keysymdefinitions.

Description

Table8-1.SDLKeysymdefinitions

SDLKey ASCIIvalue CommonnameSDLK_BACKSPACE '\b' backspaceSDLK_TAB '\t' tabSDLK_CLEAR clearSDLK_RETURN '\r' returnSDLK_PAUSE pauseSDLK_ESCAPE '^[' escapeSDLK_SPACE '' spaceSDLK_EXCLAIM '!' exclaimSDLK_QUOTEDBL '"' quotedblSDLK_HASH '#' hashSDLK_DOLLAR '$' dollarSDLK_AMPERSAND '&' ampersandSDLK_QUOTE ''' quoteSDLK_LEFTPAREN '(' leftparenthesisSDLK_RIGHTPAREN ')' rightparenthesisSDLK_ASTERISK '*' asteriskSDLK_PLUS '+' plussignSDLK_COMMA ',' commaSDLK_MINUS '-' minussignSDLK_PERIOD '.' periodSDLK_SLASH '/' forwardslashSDLK_0 '0' 0SDLK_1 '1' 1SDLK_2 '2' 2SDLK_3 '3' 3

SDLK_4 '4' 4SDLK_5 '5' 5SDLK_6 '6' 6SDLK_7 '7' 7SDLK_8 '8' 8SDLK_9 '9' 9SDLK_COLON ':' colonSDLK_SEMICOLON ';' semicolonSDLK_LESS '<' less-thansignSDLK_EQUALS '=' equalssignSDLK_GREATER '>' greater-thansignSDLK_QUESTION '?' questionmarkSDLK_AT '@' atSDLK_LEFTBRACKET '[' leftbracketSDLK_BACKSLASH '\' backslashSDLK_RIGHTBRACKET ']' rightbracketSDLK_CARET '^' caretSDLK_UNDERSCORE '_' underscoreSDLK_BACKQUOTE '`' graveSDLK_a 'a' aSDLK_b 'b' bSDLK_c 'c' cSDLK_d 'd' dSDLK_e 'e' eSDLK_f 'f' fSDLK_g 'g' gSDLK_h 'h' hSDLK_i 'i' iSDLK_j 'j' jSDLK_k 'k' kSDLK_l 'l' l

SDLK_m 'm' m

SDLK_n 'n' nSDLK_o 'o' oSDLK_p 'p' pSDLK_q 'q' qSDLK_r 'r' rSDLK_s 's' sSDLK_t 't' tSDLK_u 'u' uSDLK_v 'v' vSDLK_w 'w' wSDLK_x 'x' xSDLK_y 'y' ySDLK_z 'z' zSDLK_DELETE '^?' deleteSDLK_KP0 keypad0SDLK_KP1 keypad1SDLK_KP2 keypad2SDLK_KP3 keypad3SDLK_KP4 keypad4SDLK_KP5 keypad5SDLK_KP6 keypad6SDLK_KP7 keypad7SDLK_KP8 keypad8SDLK_KP9 keypad9SDLK_KP_PERIOD '.' keypadperiodSDLK_KP_DIVIDE '/' keypaddivideSDLK_KP_MULTIPLY '*' keypadmultiplySDLK_KP_MINUS '-' keypadminusSDLK_KP_PLUS '+' keypadplus

SDLK_KP_ENTER '\r' keypadenterSDLK_KP_EQUALS '=' keypadequals

SDLK_UP uparrowSDLK_DOWN downarrowSDLK_RIGHT rightarrowSDLK_LEFT leftarrowSDLK_INSERT insertSDLK_HOME homeSDLK_END endSDLK_PAGEUP pageupSDLK_PAGEDOWN pagedownSDLK_F1 F1SDLK_F2 F2SDLK_F3 F3SDLK_F4 F4SDLK_F5 F5SDLK_F6 F6SDLK_F7 F7SDLK_F8 F8SDLK_F9 F9SDLK_F10 F10SDLK_F11 F11SDLK_F12 F12SDLK_F13 F13SDLK_F14 F14SDLK_F15 F15SDLK_NUMLOCK numlockSDLK_CAPSLOCK capslockSDLK_SCROLLOCK scrollockSDLK_RSHIFT rightshift

SDLK_LSHIFT leftshiftSDLK_RCTRL rightctrlSDLK_LCTRL leftctrl

SDLK_RALT rightaltSDLK_LALT leftaltSDLK_RMETA rightmetaSDLK_LMETA leftmetaSDLK_LSUPER leftwindowskeySDLK_RSUPER rightwindowskeySDLK_MODE modeshiftSDLK_HELP helpSDLK_PRINT print-screenSDLK_SYSREQ SysRqSDLK_BREAK breakSDLK_MENU menuSDLK_POWER powerSDLK_EURO euro

Table8-2.SDLmodifierdefinitions

SDLModifier MeaningKMOD_NONE NomodifiersapplicableKMOD_NUM NumlockisdownKMOD_CAPS CapslockisdownKMOD_LCTRL LeftControlisdownKMOD_RCTRL RightControlisdownKMOD_RSHIFT RightShiftisdownKMOD_LSHIFT LeftShiftisdownKMOD_RALT RightAltisdownKMOD_LALT LeftAltisdownKMOD_CTRL AControlkeyisdown

KMOD_SHIFT AShiftkeyisdownKMOD_ALT AnAltkeyisdown

Prev Home NextSDL_keysym Up EventFunctions.

SDLLibraryDocumentationPrev Chapter8.Events Next

EventFunctions.TableofContentsSDL_PumpEvents—Pumpstheeventloop,gatheringeventsfromtheinputdevices.SDL_PeepEvents—Checkstheeventqueueformessagesandoptionallyreturnsthem.SDL_PollEvent—Pollsforcurrentlypendingevents.SDL_WaitEvent—Waitsindefinitelyforthenextavailableevent.SDL_PushEvent—PushesaneventontotheeventqueueSDL_SetEventFilter—Setsupafiltertoprocessalleventsbeforetheyarepostedtotheeventqueue.SDL_GetEventFilter—RetrievesapointertoheeventfilterSDL_EventState—Thisfunctionallowsyoutosetthestateofprocessingcertainevents.SDL_GetKeyState—GetasnapshotofthecurrentkeyboardstateSDL_GetModState—Getthestateofmodifierkeys.SDL_SetModState—SetthecurrentkeymodifierstateSDL_GetKeyName—GetthenameofanSDLvirtualkeysymSDL_EnableUNICODE—EnableUNICODEtranslationSDL_EnableKeyRepeat—Setkeyboardrepeatrate.SDL_GetMouseState—RetrievethecurrentstateofthemouseSDL_GetRelativeMouseState—RetrievethecurrentstateofthemouseSDL_GetAppState—GetthestateoftheapplicationSDL_JoystickEventState—Enable/disablejoystickeventpolling

SDL_PumpEvents Pumpstheeventloop,gatheringeventsfromtheinputdevices

SDL_PeepEvents Checkstheeventqueueformessagesandoptionallyreturnsthem

SDL_PollEvent PollsforcurrentlypendingeventsSDL_WaitEvent WaitsindefinitelyforthenextavailableeventSDL_PushEvent PushesaneventontotheeventqueueSDL_SetEventFilter Setsupafiltertoprocessallevents

Allowsyoutosetthestateofprocessingcertain

SDL_EventState events

SDL_GetKeyState GetasnapshotofthecurrentkeyboardstateSDL_GetModState GetthestateofmodifierkeysSDL_SetModState SetthestateofmodifierkeysSDL_GetKeyName GetthenameofanSDLvirtualkeysymSDL_EnableUNICODE EnableUNICODEtranslationSDL_EnableKeyRepeat SetkeyboardrepeatrateSDL_GetMouseState RetrievethecurrentstateofthemouseSDL_GetRelativeMouseState RetrievethecurrentstateofthemouseSDL_GetAppState GetthestateoftheapplicationSDL_JoystickEventState Enable/disablejoystickeventpolling

Prev Home NextSDLKey Up SDL_PumpEvents

SDLLibraryDocumentationPrev Next

SDL_PumpEvents

Name

SDL_PumpEvents--Pumpstheeventloop,gatheringeventsfromtheinputdevices.

Synopsis#include"SDL.h"

voidSDL_PumpEvents(void);

Description

Pumpstheeventloop,gatheringeventsfromtheinputdevices.

SDL_PumpEventsgathersallthependinginputinformationfromdevicesandplacesitontheeventqueue.WithoutcallstoSDL_PumpEventsnoeventswouldeverbeplacedonthequeue.OftencallstheneedforSDL_PumpEventsishiddenfromtheusersinceSDL_PollEventandSDL_WaitEventimplicitlycallSDL_PumpEvents.However,ifyouarenotpollingorwaitingforevents(e.g.yourfilteringthem),thenyoumustcallSDL_PumpEventstoforceaneventqueueupdate.

Note:Youcanonlycallthisfunctioninthethreadthatsetthevideomode.

SeeAlsoSDL_PollEvent

Prev Home NextEventFunctions. Up SDL_PeepEvents

SDLLibraryDocumentationPrev Next

SDL_WaitEvent

Name

SDL_WaitEvent--Waitsindefinitelyforthenextavailableevent.

Synopsis#include"SDL.h"

intSDL_WaitEvent(SDL_Event*event);

Description

Waitsindefinitelyforthenextavailableevent,returning1,or0iftherewasanerrorwhilewaitingforevents.

IfeventisnotNULL,thenexteventisremovedfromthequeueandstoredinthatarea.

SeeAlso

SDL_Event,SDL_PollEvent

Prev Home NextSDL_PollEvent Up SDL_PushEvent

SDLLibraryDocumentationPrev Next

SDL_PeepEvents

Name

SDL_PeepEvents--Checkstheeventqueueformessagesandoptionallyreturnsthem.

Synopsis#include"SDL.h"

intSDL_PeepEvents(SDL_Event*events,intnumevents,SDL_eventactionaction,Uint32mask);

Description

Checkstheeventqueueformessagesandoptionallyreturnsthem.

IfactionisSDL_ADDEVENT,uptonumeventseventswillbeaddedtothebackoftheeventqueue.

IfactionisSDL_PEEKEVENT,uptonumeventseventsatthefrontoftheeventqueue,matchingmask,willbereturnedandwillnotberemovedfromthequeue.

IfactionisSDL_GETEVENT,uptonumeventseventsatthefrontoftheeventqueue,matchingmask,willbereturnedandwillberemovedfromthequeue.

Thisfunctionisthread-safe.

ReturnValue

Thisfunctionreturnsthenumberofeventsactuallystored,or-1iftherewasanerror.

SeeAlso

SDL_Event,SDL_PollEvent,SDL_PushEvent

Prev Home NextSDL_PumpEvents Up SDL_PollEvent

SDLLibraryDocumentationPrev Next

SDL_PollEvent

Name

SDL_PollEvent--Pollsforcurrentlypendingevents.

Synopsis#include"SDL.h"

intSDL_PollEvent(SDL_Event*event);

Description

Pollsforcurrentlypendingevents,andreturns1ifthereareanypendingevents,or0iftherearenoneavailable.

IfeventisnotNULL,thenexteventisremovedfromthequeueandstoredinthatarea.

ExamplesSDL_Eventevent;/*Eventstructure*/

.

.

.

/*Checkforevents*/

while(SDL_PollEvent(&event)){/*Loopuntiltherearenoeventsleftonthequeue*/

switch(event.type){/*Processtheappropiateeventtype*/

caseSDL_KEYDOWN:/*HandleaKEYDOWNevent*/

printf("Oh!Keypress\n");

break;

caseSDL_MOUSEMOTION:

.

.

.

default:/*Reportanunhandledevent*/

printf("Idon'tknowwhatthiseventis!\n");

}

}

SeeAlso

SDL_Event,SDL_WaitEvent,SDL_PeepEvents

Prev Home NextSDL_PeepEvents Up SDL_WaitEvent

SDLLibraryDocumentationPrev Next

SDL_PushEvent

Name

SDL_PushEvent--Pushesaneventontotheeventqueue

Synopsis#include"SDL.h"

intSDL_PushEvent(SDL_Event*event);

Description

Theeventqueuecanactuallybeusedasatwowaycommunicationchannel.Notonlycaneventsbereadfromthequeue,buttheusercanalsopushtheirowneventsontoit.eventisapointertotheeventstructureyouwishtopushontothequeue.

Note:Pushingdeviceinputeventsontothequeuedoesn'tmodifythestateofthedevicewithinSDL.

ReturnValue

Returns0onsuccessor-1iftheeventcouldn'tbepushed.

Examples

SeeSDL_Event.

SeeAlso

SDL_PollEvent,SDL_PeepEvents,SDL_Event

Prev Home NextSDL_WaitEvent Up SDL_SetEventFilter

SDLLibraryDocumentationPrev Next

SDL_SetEventFilter

Name

SDL_SetEventFilter--Setsupafiltertoprocessalleventsbeforetheyarepostedtotheeventqueue.

Synopsis#include"SDL.h"

voidSDL_SetEventFilter(SDL_EventFilterfilter);

Description

Thisfunctionsetsupafiltertoprocessalleventsbeforetheyarepostedtotheeventqueue.Thisisaverypowerfulandflexiblefeature.Thefilterisprototypedas:

typedefint(*SDL_EventFilter)(constSDL_Event*event);

Ifthefilterreturns1,thentheeventwillbeaddedtotheinternalqueue.Ifitreturns0,thentheeventwillbedroppedfromthequeue.Thisallowsselectivefilteringofdynamically.

ThereisonecaveatwhendealingwiththeSDL_QUITEVENTeventtype.Theeventfilterisonlycalledwhenthewindowmanagerdesirestoclosetheapplicationwindow.Iftheeventfilterreturns1,thenthewindowwillbeclosed,otherwisethewindowwillremainopenifpossible.Ifthequiteventisgeneratedbyaninterruptsignal,itwillbypasstheinternalqueueandbedeliveredtotheapplicationatthenexteventpoll.

Note:EventspushedontothequeuewithSDL_PushEventorSDL_PeepEventsdonotgetpassedthroughtheeventfilter.

Note:BeCareful!Theeventfilterfunctionmayruninadifferentthreadsobecarefulwhatyoudowithinit.

SeeAlso

SDL_Event,SDL_GetEventFilter,SDL_PushEvent

Prev Home NextSDL_PushEvent Up SDL_GetEventFilter

SDLLibraryDocumentationPrev Next

SDL_GetEventFilter

Name

SDL_GetEventFilter--Retrievesapointertoheeventfilter

Synopsis#include"SDL.h"

SDL_EventFilterSDL_GetEventFilter(void);

Description

ThisfunctionretriecesapointertotheeventfilterthatwaspreviouslysetusingSDL_SetEventFilter.AnSDL_EventFilterfunctionisdefinedas:

typedefint(*SDL_EventFilter)(constSDL_Event*event);

ReturnValue

ReturnsapointertotheeventfilterorNULLifnofilterhasbeenset.

SeeAlso

SDL_Event,SDL_SetEventFilter

Prev Home NextSDL_SetEventFilter Up SDL_EventState

SDLLibraryDocumentationPrev Next

SDL_EventState

Name

SDL_EventState--Thisfunctionallowsyoutosetthestateofprocessingcertainevents.

Synopsis#include"SDL.h"

Uint8SDL_EventState(Uint8type,intstate);

Description

Thisfunctionallowsyoutosetthestateofprocessingcertaineventtype's.

IfstateissettoSDL_IGNORE,thateventtypewillbeautomaticallydroppedfromtheeventqueueandwillnotbefiltered.

IfstateissettoSDL_ENABLE,thateventtypewillbeprocessednormally.

IfstateissettoSDL_QUERY,SDL_EventStatewillreturnthecurrentprocessingstateofthespecifiedeventtype.

Alistofeventtype'scanbefoundintheSDL_Eventsection.

SeeAlso

SDL_Event

Prev Home NextSDL_GetEventFilter Up SDL_GetKeyState

SDLLibraryDocumentationPrev Next

SDL_GetKeyState

Name

SDL_GetKeyState--Getasnapshotofthecurrentkeyboardstate

Synopsis#include"SDL.h"

Uint8*SDL_GetKeyState(int*numkeys);

Description

Getsasnapshotofthecurrentkeyboardstate.Thecurrentstateisreturnasapointertoanarray,thesizeofthisarrayisstoredinnumkeys.ThearrayisindexedbytheSDLK_*symbols.Avalueof1meansthekeyispressedandavalueof0meansitsnot.ThepointerreturnedisapointertoaninternalSDLarrayandshouldnotbefreedbythecaller.

Note:UseSDL_PumpEventstoupdatethestatearray.

ExampleUint8*keystate=SDL_GetKeyState(NULL);

if(keystate[SDLK_RETURN])printf("ReturnKeyPressed.\n");

SeeAlso

SDLKeySymbols,SDL_PumpEvents

Prev Home NextSDL_EventState Up SDL_GetModState

SDLLibraryDocumentationPrev Next

SDL_GetModState

Name

SDL_GetModState--Getthestateofmodifierkeys.

Synopsis#include"SDL.h"

SDLModSDL_GetModState(void);

Description

Returnsthecurrentstateofthemodifierkeys(CTRL,ALT,etc.).

ReturnValue

ThereturnvaluecanbeanOR'dcombinationoftheSDLModenum.

SDLMod

typedefenum{

KMOD_NONE=0x0000,

KMOD_LSHIFT=0x0001,

KMOD_RSHIFT=0x0002,

KMOD_LCTRL=0x0040,

KMOD_RCTRL=0x0080,

KMOD_LALT=0x0100,

KMOD_RALT=0x0200,

KMOD_LMETA=0x0400,

KMOD_RMETA=0x0800,

KMOD_NUM=0x1000,

KMOD_CAPS=0x2000,

KMOD_MODE=0x4000,

}SDLMod;

SDLalsodefinesthefollowingsymbolsforconvenience:

#defineKMOD_CTRL(KMOD_LCTRL|KMOD_RCTRL)

#defineKMOD_SHIFT(KMOD_LSHIFT|KMOD_RSHIFT)

#defineKMOD_ALT(KMOD_LALT|KMOD_RALT)

#defineKMOD_META(KMOD_LMETA|KMOD_RMETA)

SeeAlsoSDL_GetKeyState

Prev Home NextSDL_GetKeyState Up SDL_SetModState

SDLLibraryDocumentationPrev Next

SDL_SetModState

Name

SDL_SetModState--Setthecurrentkeymodifierstate

Synopsis#include"SDL.h"

voidSDL_SetModState(SDLModmodstate);

Description

TheinverseofSDL_GetModState,SDL_SetModStateallowsyoutoimposemodifierkeystatesonyourapplication.

Simplypassyourdesiredmodifierstatesintomodstate.ThisvaluemybealogicalOR'dcombinationofthefollowing:

typedefenum{

KMOD_NONE=0x0000,

KMOD_LSHIFT=0x0001,

KMOD_RSHIFT=0x0002,

KMOD_LCTRL=0x0040,

KMOD_RCTRL=0x0080,

KMOD_LALT=0x0100,

KMOD_RALT=0x0200,

KMOD_LMETA=0x0400,

KMOD_RMETA=0x0800,

KMOD_NUM=0x1000,

KMOD_CAPS=0x2000,

KMOD_MODE=0x4000,

}SDLMod;

SeeAlsoSDL_GetModState

Prev Home NextSDL_GetModState Up SDL_GetKeyName

SDLLibraryDocumentationPrev Next

SDL_GetKeyName

Name

SDL_GetKeyName--GetthenameofanSDLvirtualkeysym

Synopsis#include"SDL.h"

char*SDL_GetKeyName(SDLKeykey);

Description

ReturnstheSDL-definednameoftheSDLKeykey.

SeeAlso

SDLKey

Prev Home NextSDL_SetModState Up SDL_EnableUNICODE

SDLLibraryDocumentationPrev Next

SDL_EnableUNICODE

Name

SDL_EnableUNICODE--EnableUNICODEtranslation

Synopsis#include"SDL.h"

intSDL_EnableUNICODE(intenable);

Description

Enables/DisablesUnicodekeyboardtranslation.

Toobtainthecharactercodescorrespondingtoreceivedkeyboardevents,Unicodetranslationmustfirstbeturnedonusingthisfunction.Thetranslationincursaslightoverheadforeachkeyboardeventandisthereforedisabledbydefault.Foreachsubsequentlyreceivedkeydownevent,theunicodememberoftheSDL_keysymstructurewillthencontainthecorrespondingcharactercode,orzeroforkeysymsthatdonotcorrespondtoanycharactercode.

Avalueof1forenableenablesUnicodetranslation;0disablesit,and-1leavesitunchanged(usefulforqueryingthecurrenttranslationmode).

Notethatonlykeypresseventswillbetranslated,notreleaseevents.

ReturnValue

Returnstheprevioustranslationmode(0or1).

SeeAlso

SDL_keysym

Prev Home NextSDL_GetKeyName Up SDL_EnableKeyRepeat

SDLLibraryDocumentationPrev Next

SDL_EnableKeyRepeat

Name

SDL_EnableKeyRepeat--Setkeyboardrepeatrate.

Synopsis#include"SDL.h"

intSDL_EnableKeyRepeat(intdelay,intinterval);

Description

Enablesordisablesthekeyboardrepeatrate.delayspecifieshowlongthekeymustbepressedbeforeitbeginsrepeating,itthenrepeatsatthespeedspecifiedbyinterval.Bothdelayandintervalareexpressedinmilliseconds.

Settingdelayto0disableskeyrepeatingcompletely.GooddefaultvaluesareSDL_DEFAULT_REPEAT_DELAYandSDL_DEFAULT_REPEAT_INTERVAL.

ReturnValue

Returns0onsuccessand-1onfailure.

Prev Home NextSDL_EnableUNICODE Up SDL_GetMouseState

SDLLibraryDocumentationPrev Next

SDL_GetMouseState

Name

SDL_GetMouseState--Retrievethecurrentstateofthemouse

Synopsis#include"SDL.h"

Uint8SDL_GetMouseState(int*x,int*y);

Description

Thecurrentbuttonstateisreturnedasabuttonbitmask,whichcanbetestedusingtheSDL_BUTTON(X)macros,andxandyaresettothecurrentmousecursorposition.YoucanpassNULLforeitherxory.

ExampleSDL_PumpEvents();

if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(1))

printf("MouseButton1(left)ispressed.\n");

SeeAlso

SDL_GetRelativeMouseState,SDL_PumpEvents

Prev Home NextSDL_EnableKeyRepeat Up SDL_GetRelativeMouseState

SDLLibraryDocumentationPrev Next

SDL_GetRelativeMouseState

Name

SDL_GetRelativeMouseState--Retrievethecurrentstateofthemouse

Synopsis#include"SDL.h"

Uint8SDL_GetRelativeMouseState(int*x,int*y);

Description

Thecurrentbuttonstateisreturnedasabuttonbitmask,whichcanbetestedusingtheSDL_BUTTON(X)macros,andxandyaresettothechangeinthemousepositionsincethelastcalltoSDL_GetRelativeMouseStateorsinceeventinitialization.YoucanpassNULLforeitherxory.

SeeAlsoSDL_GetMouseState

Prev Home NextSDL_GetMouseState Up SDL_GetAppState

SDLLibraryDocumentationPrev Next

SDL_GetAppState

Name

SDL_GetAppState--Getthestateoftheapplication

Synopsis#include"SDL.h"

Uint8SDL_GetAppState(void);

Description

Thisfunctionreturnsthecurrentstateoftheapplication.Thevaluereturnedisabitwisecombinationof:

SDL_APPMOUSEFOCUS Theapplicationhasmousefocus.SDL_APPINPUTFOCUS TheapplicationhaskeyboardfocusSDL_APPACTIVE Theapplicationisvisible

SeeAlso

SDL_ActiveEvent

Prev Home NextSDL_GetRelativeMouseState Up SDL_JoystickEventState

SDLLibraryDocumentationPrev Next

SDL_JoystickEventState

Name

SDL_JoystickEventState--Enable/disablejoystickeventpolling

Synopsis#include"SDL.h"

intSDL_JoystickEventState(intstate);

Description

Thisfunctionisusedtoenableordisablejoystickeventprocessing.WithjoystickeventprocessingdisabledyouwillhavetoupdatejoystickstateswithSDL_JoystickUpdateandreadthejoystickinformationmanually.stateiseitherSDL_QUERY,SDL_ENABLEorSDL_IGNORE.

Note:Joystickeventhandlingisprefered

ReturnValue

IfstateisSDL_QUERYthenthecurrentstateisreturned,otherwisethenewprocessingstateisreturned.

SeeAlso

SDLJoystickFunctions,SDL_JoystickUpdate,SDL_JoyAxisEvent,SDL_JoyBallEvent,SDL_JoyButtonEvent,SDL_JoyHatEvent

Prev Home NextSDL_GetAppState Up Joystick

SDLLibraryDocumentationPrev Next

Chapter9.JoystickTableofContentsSDL_NumJoysticks—Countavailablejoysticks.SDL_JoystickName—Getjoystickname.SDL_JoystickOpen—Opensajoystickforuse.SDL_JoystickOpened—DetermineifajoystickhasbeenopenedSDL_JoystickIndex—GettheindexofanSDL_Joystick.SDL_JoystickNumAxes—GetthenumberofjoystickaxesSDL_JoystickNumBalls—GetthenumberofjoysticktrackballsSDL_JoystickNumHats—GetthenumberofjoystickhatsSDL_JoystickNumButtons—GetthenumberofjoysitckbuttonsSDL_JoystickUpdate—UpdatesthestateofalljoysticksSDL_JoystickGetAxis—GetthecurrentstateofanaxisSDL_JoystickGetHat—GetthecurrentstateofajoystickhatSDL_JoystickGetButton—GetthecurrentstateofagivenbuttononagivenjoystickSDL_JoystickGetBall—GetrelativetrackballmotionSDL_JoystickClose—Closesapreviouslyopenedjoystick

Joysticks,andothersimilarinputdevices,haveaverystrongroleingameplayingandSDLprovidescomprehensivesupportforthem.Axes,Buttons,POVHatsandtrackballsareallsupported.

JoysticksupportisinitializedbypassedtheSDL_INIT_JOYSTICKflagtoSDL_Init.OnceinitilizedjoysticksmustbeopenedusingSDL_JoystickOpen.

Whileusingthefunctionsdescribeinthissectonmayseemlikethebestwaytoaccessandreadfromjoysticks,inmostcasestheyaren't.Ideallyjoysticksshouldbereadusingtheeventsystem.Toenablethis,youmustsetthejoystickeventprocessingstatewithSDL_JoystickEventState.Joysticksmustbeopenedbeforetheycanbeusedofcourse.

Note:IfyouarenothandlingthejoystickviatheeventqueuethenyoumustexplicitlyrequestajoystickupdatebycallingSDL_JoystickUpdate.

Note:ForceFeedbackisnotyetsupport.Sam(slouken@libsdl.org)is

solicitingsuggestionsfrompeoplewithforce-feedbackexperienceonthebestwattodesgintheAPI.

Prev Home NextSDL_JoystickEventState Up SDL_NumJoysticks

SDLLibraryDocumentationPrev Next

SDL_NumJoysticks

Name

SDL_NumJoysticks--Countavailablejoysticks.

Synopsis#include"SDL.h"

intSDL_NumJoysticks(void);

Description

Countsthenumberofjoysticksattachedtothesystem.

ReturnValue

Returnsthenumberofattachedjoysticks

SeeAlso

SDL_JoystickName,SDL_JoystickOpen

Prev Home NextJoystick Up SDL_JoystickName

SDLLibraryDocumentationPrev Next

SDL_JoystickName

Name

SDL_JoystickName--Getjoystickname.

Synopsis#include"SDL.h"

constchar*SDL_JoystickName(intindex);

Description

Gettheimplementationdependentnameofjoystick.TheindexparameterreferstotheN'thjoystickonthesystem.

ReturnValue

Returnsacharpointertothejoystickname.

Examples/*Printthenamesofallattachedjoysticks*/

intnum_joy,i;

num_joy=SDL_NumJoysticks();

printf("%djoysticksfound\n",num_joy);

for(i=0;i<num_joy;i++)

printf("%s\n",SDL_JoystickName(i));

SeeAlsoSDL_JoystickOpen

Prev Home NextSDL_NumJoysticks Up SDL_JoystickOpen

SDLLibraryDocumentationPrev Next

SDL_JoystickOpen

Name

SDL_JoystickOpen--Opensajoystickforuse.

Synopsis#include"SDL.h"

SDL_Joystick*SDL_JoystickOpen(intindex);

Description

OpensajoystickforusewithinSDL.TheindexreferstotheN'thjoystickinthesystem.Ajoystickmustbeopenedbeforeitgamebeused.

ReturnValue

ReturnsaSDL_Joystickstructureonsuccess.NULLonfailure.

ExamplesSDL_Joystick*joy;

//Checkforjoystick

if(SDL_NumJoysticks()>0){

//Openjoystick

joy=SDL_JoystickOpen(0);

if(joy)

{

printf("OpenedJoystick0\n");

printf("Name:%s\n",SDL_JoystickName(0));

printf("NumberofAxes:%d\n",SDL_JoystickNumAxes(joy));

printf("NumberofButtons:%d\n",SDL_JoystickNumButtons(joy));

printf("NumberofBalls:%d\n",SDL_JoystickNumBalls(joy));

}

else

printf("Couldn'topenJoystick0\n");

//Closeifopened

if(SDL_JoystickOpened(0))

SDL_JoystickClose(joy);

}

SeeAlsoSDL_JoystickClose

Prev Home NextSDL_JoystickName Up SDL_JoystickOpened

SDLLibraryDocumentationPrev Next

SDL_JoystickOpened

Name

SDL_JoystickOpened--Determineifajoystickhasbeenopened

Synopsis#include"SDL.h"

intSDL_JoystickOpened(intindex);

Description

Determineswhetherajoystickhasalreadybeenopenedwithintheapplication.indexreferstotheN'thjoystickonthesystem.

ReturnValue

Returns1ifthejoystickhasbeenopened,or0ifithasnot.

SeeAlso

SDL_JoystickOpen,SDL_JoystickClose

Prev Home NextSDL_JoystickOpen Up SDL_JoystickIndex

SDLLibraryDocumentationPrev Next

SDL_JoystickIndex

Name

SDL_JoystickIndex--GettheindexofanSDL_Joystick.

Synopsis#include"SDL.h"

intSDL_JoystickIndex(SDL_Joystick*joystick);

Description

ReturnstheindexofagivenSDL_Joystickstructure.

ReturnValue

Indexnumberofthejoystick.

SeeAlsoSDL_JoystickOpen

Prev Home NextSDL_JoystickOpened Up SDL_JoystickNumAxes

SDLLibraryDocumentationPrev Next

SDL_JoystickNumAxes

Name

SDL_JoystickNumAxes--Getthenumberofjoystickaxes

Synopsis#include"SDL.h"

intSDL_JoystickNumAxes(SDL_Joystick*joystick);

Description

ReturnthenumberofaxesavailablefromapreviouslyopenedSDL_Joystick.

ReturnValue

Numberofaxes.

SeeAlso

SDL_JoystickGetAxis,SDL_JoystickOpen

Prev Home NextSDL_JoystickIndex Up SDL_JoystickNumBalls

SDLLibraryDocumentationPrev Next

SDL_JoystickNumBalls

Name

SDL_JoystickNumBalls--Getthenumberofjoysticktrackballs

Synopsis#include"SDL.h"

intSDL_JoystickNumBalls(SDL_Joystick*joystick);

Description

ReturnthenumberoftrackballsavailablefromapreviouslyopenedSDL_Joystick.

ReturnValue

Numberoftrackballs.

SeeAlso

SDL_JoystickGetBall,SDL_JoystickOpen

Prev Home NextSDL_JoystickNumAxes Up SDL_JoystickNumHats

SDLLibraryDocumentationPrev Next

SDL_JoystickNumHats

Name

SDL_JoystickNumHats--Getthenumberofjoystickhats

Synopsis#include"SDL.h"

intSDL_JoystickNumHats(SDL_Joystick*joystick);

Description

ReturnthenumberofhatsavailablefromapreviouslyopenedSDL_Joystick.

ReturnValue

Numberofhats.

SeeAlso

SDL_JoystickGetHat,SDL_JoystickOpen

Prev Home NextSDL_JoystickNumBalls Up SDL_JoystickNumButtons

SDLLibraryDocumentationPrev Next

SDL_JoystickNumButtons

Name

SDL_JoystickNumButtons--Getthenumberofjoysitckbuttons

Synopsis#include"SDL.h"

intSDL_JoystickNumButtons(SDL_Joystick*joystick);

Description

ReturnthenumberofbuttonsavailablefromapreviouslyopenedSDL_Joystick.

ReturnValue

Numberofbuttons.

SeeAlso

SDL_JoystickGetButton,SDL_JoystickOpen

Prev Home NextSDL_JoystickNumHats Up SDL_JoystickUpdate

SDLLibraryDocumentationPrev Next

SDL_JoystickUpdate

Name

SDL_JoystickUpdate--Updatesthestateofalljoysticks

Synopsis#include"SDL.h"

voidSDL_JoystickUpdate(void);

Description

Updatesthestate(position,buttons,etc.)ofallopenjoysticks.IfjoystickeventshavebeenenabledwithSDL_JoystickEventStatethenthisiscalledautomaticallyintheeventloop.

SeeAlsoSDL_JoystickEventState

Prev Home NextSDL_JoystickNumButtons Up SDL_JoystickGetAxis

SDLLibraryDocumentationPrev Next

SDL_JoystickGetAxis

Name

SDL_JoystickGetAxis--Getthecurrentstateofanaxis

Synopsis#include"SDL.h"

Sint16SDL_JoystickGetAxis(SDL_Joystick*joystick,intaxis);

Description

SDL_JoystickGetAxisreturnsthecurrentstateofthegivenaxisonthegivenjoystick.

OnmostmodernjoystickstheXaxisisusuallyrepresentedbyaxis0andtheYaxisbyaxis1.ThevaluereturnedbySDL_JoystickGetAxisisasignedinteger(-32768to32768)representingthecurrentpositionoftheaxis,itmaybenecessarytoimposecertaintolerancesonthesevaluestoaccountforjitter.Itisworthnotingthatsomejoysticksuseaxes2and3forextrabuttons.

ReturnValue

Returnsa16-bitsignedintegerrepresentingthecurrentpositionoftheaxis.

ExamplesSint16x_move,y_move;

SDL_Joystick*joy1;

.

.

x_move=SDL_JoystickGetAxis(joy1,0);

y_move=SDL_JoystickGetAxis(joy1,1);

SeeAlsoSDL_JoystickNumAxes

Prev Home NextSDL_JoystickUpdate Up SDL_JoystickGetHat

SDLLibraryDocumentationPrev Next

SDL_JoystickGetHat

Name

SDL_JoystickGetHat--Getthecurrentstateofajoystickhat

Synopsis#include"SDL.h"

Uint8SDL_JoystickGetHat(SDL_Joystick*joystick,inthat);

Description

SDL_JoystickGetHatreturnsthecurrentstateofthegivenhatonthegivenjoystick.

ReturnValue

ThecurrentstateisreturnedasaUint8whichisdefinedasanOR'dcombinationofoneormoreofthefollowing

SDL_HAT_CENTERED

SDL_HAT_UP

SDL_HAT_RIGHT

SDL_HAT_DOWN

SDL_HAT_LEFT

SDL_HAT_RIGHTUP

SDL_HAT_RIGHTDOWN

SDL_HAT_LEFTUP

SDL_HAT_LEFTDOWN

SeeAlsoSDL_JoystickNumHats

Prev Home NextSDL_JoystickGetAxis Up SDL_JoystickGetButton

SDLLibraryDocumentationPrev Next

SDL_JoystickGetButton

Name

SDL_JoystickGetButton--Getthecurrentstateofagivenbuttononagivenjoystick

Synopsis#include"SDL.h"

Uint8SDL_JoystickGetButton(SDL_Joystick*joystick,intbutton);

Description

SDL_JoystickGetButtonreturnsthecurrentstateofthegivenbuttononthegivenjoystick.

ReturnValue

1ifthebuttonispressed.Otherwise,0.

SeeAlsoSDL_JoystickNumButtons

Prev Home NextSDL_JoystickGetHat Up SDL_JoystickGetBall

SDLLibraryDocumentationPrev Next

SDL_JoystickGetBall

Name

SDL_JoystickGetBall--Getrelativetrackballmotion

Synopsis#include"SDL.h"

intSDL_JoystickGetBall(SDL_Joystick*joystick,intball,int*dx,int*dy);

Description

Gettheballaxischange.

TrackballscanonlyreturnrelativemotionsincethelastcalltoSDL_JoystickGetBall,thesemotiondeltasaplacedintodxanddy.

ReturnValue

Returns0onsuccessor-1onfailure

Examplesintdelta_x,delta_y;

SDL_Joystick*joy;

.

.

.

SDL_JoystickUpdate();

if(SDL_JoystickGetBall(joy,0,&delta_x,&delta_y)==-1)

printf("TrackBallReadError!\n");

printf("TrackballDelta-X:%d,Y:%d\n",delta_x,delta_y);

SeeAlsoSDL_JoystickNumBalls

Prev Home NextSDL_JoystickGetButton Up SDL_JoystickClose

SDLLibraryDocumentationPrev Next

SDL_JoystickClose

Name

SDL_JoystickClose--Closesapreviouslyopenedjoystick

Synopsis#include"SDL.h"

voidSDL_JoystickClose(SDL_Joystick*joystick);

Description

CloseajoystickthatwaspreviouslyopenedwithSDL_JoystickOpen.

SeeAlso

SDL_JoystickOpen,SDL_JoystickOpened

Prev Home NextSDL_JoystickGetBall Up Audio

SDLLibraryDocumentationPrev Next

Chapter10.AudioTableofContentsSDL_AudioSpec—AudioSpecificationStructureSDL_OpenAudio—Openstheaudiodevicewiththedesiredparameters.SDL_PauseAudio—PausesandunpausestheaudiocallbackprocessingSDL_GetAudioStatus—GetthecurrentaudiostateSDL_LoadWAV—LoadaWAVEfileSDL_FreeWAV—FreespreviouslyopenedWAVdataSDL_AudioCVT—AudioConversionStructureSDL_BuildAudioCVT—InitializesaSDL_AudioCVTstructureforconversionSDL_ConvertAudio—Convertaudiodatatoadesiredaudioformat.SDL_MixAudio—MixaudiodataSDL_LockAudio—LockoutthecallbackfunctionSDL_UnlockAudio—UnlockthecallbackfunctionSDL_CloseAudio—Shutsdownaudioprocessingandclosestheaudiodevice.

Soundonthecomputeristranslatedfromwavesthatyouhearintoaseriesofvalues,orsamples,eachrepresentingtheamplitudeofthewave.Whenthesesamplesaresentinastreamtoasoundcard,anapproximationoftheoriginalwavecanberecreated.Themorebitsusedtorepresenttheamplitude,andthegreaterfrequencythesesamplesaregathered,theclosertheapproximatedsoundistotheoriginal,andthebetterthequalityofsound.

Thislibrarysupportsboth8and16bitsignedandunsignedsoundsamples,atfrequenciesrangingfrom11025Hzto44100Hz,dependingontheunderlyinghardware.Ifthehardwaredoesn'tsupportthedesiredaudioformatorfrequency,itcanbeemulatedifdesired(SeeSDL_OpenAudio())

Acommonlysupportedaudioformatis16bitspersampleat22050Hz.

Prev Home NextSDL_JoystickClose Up SDL_AudioSpec

SDLLibraryDocumentationPrev Next

SDL_AudioSpec

Name

SDL_AudioSpec--AudioSpecificationStructure

StructureDefinitiontypedefstruct{

intfreq;

Uint16format;

Uint8channels;

Uint8silence;

Uint16samples;

Uint32size;

void(*callback)(void*userdata,Uint8*stream,intlen);

void*userdata;

}SDL_AudioSpec;

StructureData

freq Audiofrequencyinsamplespersecondformat Audiodataformatchannels Numberofchannels:1mono,2stereosilence Audiobuffersilencevalue(calculated)samples Audiobuffersizeinsamplessize Audiobuffersizeinbytes(calculated)callback(..) Callbackfunctionforfillingtheaudiobufferuserdata Pointertheuserdatawhichispassedtothecallbackfunction

Description

TheSDL_AudioSpecstructureisusedtodescribetheformatofsomeaudiodata.ThisstructureisusedbySDL_OpenAudioandSDL_LoadWAV.WhileallfieldsareusedbySDL_OpenAudioonlyfreq,format,samplesandchannelsareusedbySDL_LoadWAV.Wewilldetailthesecommonmembershere.

freqThenumberofsamplessenttothesounddeviceeverysecond.Commonvaluesare11025,22050and44100.Thehigherthebetter.

format

Specifiesthesizeandtypeofeachsampleelement

AUDIO_U8

Unsigned8-bitsamples

AUDIO_S8

Signed8-bitsamples

AUDIO_U16orAUDIO_U16LSB

Unsigned16-bitlittle-endiansamples

AUDIO_S16orAUDIO_S16LSB

Signed16-bitlittle-endiansamples

AUDIO_U16MSB

Unsigned16-bitbig-endiansamples

AUDIO_S16MSB

Signed16-bitbig-endiansamples

AUDIO_U16SYS

EitherAUDIO_U16LSBorAUDIO_U16MSBdependingonyousystemsendianness

AUDIO_S16SYS

EitherAUDIO_S16LSBorAUDIO_S16MSBdependingonyousystemsendianness

channelsThenumberofseperatesoundchannels.1ismono(singlechannel),2isstereo(dualchannel).

samples

WhenusedwithSDL_OpenAudiothisreferstothesizeoftheaudiobufferinsamples.Asampleachunkofaudiodataofthesizespecifiedinformatmulitpliedbythenumberofchannels.WhentheSDL_AudioSpecisusedwithSDL_LoadWAVsamplesissetto4096.

SeeAlso

SDL_OpenAudio,SDL_LoadWAV

Prev Home NextAudio Up SDL_OpenAudio

SDLLibraryDocumentationPrev Next

SDL_OpenAudio

Name

SDL_OpenAudio--Openstheaudiodevicewiththedesiredparameters.

Synopsis#include"SDL.h"

intSDL_OpenAudio(SDL_AudioSpec*desired,SDL_AudioSpec*obtained);

Description

Thisfunctionopenstheaudiodevicewiththedesiredparameters,andreturns0ifsuccessful,placingtheactualhardwareparametersinthestructurepointedtobyobtained.IfobtainedisNULL,theaudiodatapassedtothecallbackfunctionwillbeguaranteedtobeintherequestedformat,andwillbeautomaticallyconvertedtothehardwareaudioformatifnecessary.Thisfunctionreturns-1ifitfailedtoopentheaudiodevice,orcouldn'tsetuptheaudiothread.

ToopentheaudiodeviceadesiredSDL_AudioSpecmustbecreated.

SDL_AudioSpec*desired;

.

.

desired=(SDL_AudioSpec*)malloc(sizeof(SDL_AudioSpec));

Youmustthenfillthisstructurewithyourdesiredaudiospecifications.

desired->freq

Thedesiredaudiofrequencyinsamples-per-second.

desired->format

Thedesiredaudioformat(seeSDL_AudioSpec)

desired->samples

Thedesiredsizeoftheaudiobufferinsamples.Thisnumbershouldbeapoweroftwo,andmaybeadjustedbytheaudiodrivertoavaluemoresuitableforthehardware.Goodvaluesseemtorangebetween512and8192inclusive,dependingontheapplicationandCPUspeed.Smallervaluesyieldfasterresponsetime,butcanleadtounderflowiftheapplicationisdoingheavyprocessingandcannotfilltheaudiobufferintime.AstereosampleconsistsofbothrightandleftchannelsinLRordering.Notethatthenumberofsamplesisdirectlyrelatedtotimebythefollowingformula:ms=(samples*1000)/freq

desired->callback

Thisshouldbesettoafunctionthatwillbecalledwhentheaudiodeviceisreadyformoredata.Itispassedapointertotheaudiobuffer,andthelengthinbytesoftheaudiobuffer.Thisfunctionusuallyrunsinaseparatethread,andsoyoushouldprotectdatastructuresthatitaccessesbycallingSDL_LockAudioandSDL_UnlockAudioinyourcode.Thecallbackprototypeis:

voidcallback(void*userdata,Uint8*stream,intlen);

userdataisthepointerstoredinuserdatafieldoftheSDL_AudioSpec.streamisapointertotheaudiobufferyouwanttofillwithinformationandlenisthelengthoftheaudiobufferinbytes.

desired->userdata

Thispointerispassedasthefirstparametertothecallbackfunction.

SDL_OpenAudioreadsthesefieldsfromthedesiredSDL_AudioSpecstructurepasstothefunctionandattemptstofindanaudioconfigurationmatchingyourdesired.Asmentionedabove,iftheobtainedparameterisNULLthenSDLwithconvertfromyourdesiredaudiosettingstothehardwaresettingsasitplays.

IfobtainedisNULLthenthedesiredSDL_AudioSpecisyourworkingspecification,otherwisetheobtainedSDL_AudioSpecbecomestheworkingspecificationandthedesirecspecificationcanbedeleted.ThedataintheworkingspecificationisusedwhenbuildingSDL_AudioCVT'sforconvertingloadeddatatothehardwareformat.

SDL_OpenAudiocalculatesthesizeandsilencefieldsforboththedesiredandobtainedspecifications.Thesizefieldstoresthetotalsizeoftheaudiobufferinbytes,whilethesilencestoresthevalueusedtorepresentsilenceintheaudiobuffer

Theaudiodevicestartsoutplayingsilencewhenit'sopened,andshouldbeenabledforplayingbycallingSDL_PauseAudio(0)whenyouarereadyforyouraudiocallbackfunctiontobecalled.Sincetheaudiodrivermaymodifytherequestedsizeoftheaudiobuffer,youshouldallocateanylocalmixingbuffersafteryouopentheaudiodevice.

Examples/*Prototypeofourcallbackfunction*/

voidmy_audio_callback(void*userdata,Uint8*stream,intlen);

/*Opentheaudiodevice*/

SDL_AudioSpec*desired,*obtained;

SDL_AudioSpec*hardware_spec;

/*AllocateadesiredSDL_AudioSpec*/

desired=(SDL_AudioSpec*)malloc(sizeof(SDL_AudioSpec));

/*AllocatespacefortheobtainedSDL_AudioSpec*/

obtained=(SDL_AudioSpec*)malloc(sizeof(SDL_AudioSpec));

/*22050Hz-FMRadioquality*/

desired->freq=22050;

/*16-bitsignedaudio*/

desired->format=AUDIO_S16LSB;

/*Mono*/

desired->channels=0;

/*Largeaudiobufferreducesriskofdropoutsbutincreasesresponsetime*/

desired->samples=8192;

/*Ourcallbackfunction*/

desired->callback=my_audio_callback;

desired->userdata=NULL;

/*Opentheaudiodevice*/

if(SDL_OpenAudio(desired,obtained)<0){

fprintf(stderr,"Couldn'topenaudio:%s\n",SDL_GetError());

exit(-1);

}

/*desiredspecisnolongerneeded*/

free(desired);

hardware_spec=obtained;

.

.

/*Preparecallbackforplaying*/

.

.

.

/*Startplaying*/

SDL_PauseAudio(0);

SeeAlso

SDL_AudioSpec,SDL_LockAudio,SDL_UnlockAudio,SDL_PauseAudio

Prev Home NextSDL_AudioSpec Up SDL_PauseAudio

SDLLibraryDocumentationPrev Next

SDL_PauseAudio

Name

SDL_PauseAudio--Pausesandunpausestheaudiocallbackprocessing

Synopsis#include"SDL.h"

voidSDL_PauseAudio(intpause_on);

Description

Thisfunctionpausesandunpausestheaudiocallbackprocessing.Itshouldbecalledwithpause_on=0afteropeningtheaudiodevicetostartplayingsound.Thisissoyoucansafelyinitializedataforyourcallbackfunctionafteropeningtheaudiodevice.Silencewillbewrittentotheaudiodeviceduringthepause.

SeeAlso

SDL_GetAudioStatus,SDL_OpenAudio

Prev Home NextSDL_OpenAudio Up SDL_GetAudioStatus

SDLLibraryDocumentationPrev Next

SDL_GetAudioStatus

Name

SDL_GetAudioStatus--Getthecurrentaudiostate

Synopsis#include"SDL.h"

SDL_audiostatusSDL_GetAudioStatus(void);

Descriptiontypedefenum{

SDL_AUDIO_STOPPED,

SDL_AUDIO_PAUSED,

SDL_AUDIO_PLAYING

}SDL_audiostatus;

ReturnseitherSDL_AUDIO_STOPPED,SDL_AUDIO_PAUSEDorSDL_AUDIO_PLAYINGdependingonthecurrentaudiostate.

SeeAlsoSDL_PauseAudio

Prev Home NextSDL_PauseAudio Up SDL_LoadWAV

SDLLibraryDocumentationPrev Next

SDL_LoadWAV

Name

SDL_LoadWAV--LoadaWAVEfile

Synopsis#include"SDL.h"

SDL_AudioSpec*SDL_LoadWAV(constchar*file,SDL_AudioSpec*spec,Uint8**audio_buf,Uint32*audio_len);

Description

SDL_LoadWAVThisfunctionloadsaWAVEfileintomemory.

Ifthisfunctionsucceeds,itreturnsthegivenSDL_AudioSpec,filledwiththeaudiodataformatofthewavedata,andsetsaudio_buftoamalloc'dbuffercontainingtheaudiodata,andsetsaudio_lentothelengthofthataudiobuffer,inbytes.YouneedtofreetheaudiobufferwithSDL_FreeWAVwhenyouaredonewithit.

ThisfunctionreturnsNULLandsetstheSDLerrormessageifthewavefilecannotbeopened,usesanunknowndataformat,oriscorrupt.Currentlyraw,MS-ADPCMandIMA-ADPCMWAVEfilesaresupported.

ExampleSDL_AudioSpecwav_spec;

Uint32wav_length;

Uint8*wav_buffer;

/*LoadtheWAV*/

if(SDL_LoadWAV("test.wav",&wav_spec,&wav_buffer,&wav_length)==NULL){

fprintf(stderr,"Couldnotopentest.wav:%s\n",SDL_GetError());

exit(-1);

}

.

.

.

/*DostuffwiththeWAV*/

.

.

/*FreeIt*/

SDL_FreeWAV(wav_buffer);

SeeAlso

SDL_AudioSpec,SDL_OpenAudio,SDL_FreeWAV

Prev Home NextSDL_GetAudioStatus Up SDL_FreeWAV

SDLLibraryDocumentationPrev Next

SDL_FreeWAV

Name

SDL_FreeWAV--FreespreviouslyopenedWAVdata

Synopsis#include"SDL.h"

voidSDL_FreeWAV(Uint8*audio_buf);

Description

AfteraWAVEfilehasbeenopenedwithSDL_LoadWAVitsdatacaneventuallybefreedwithSDL_FreeWAV.audio_bufisapointertothebuffercreatedbySDL_LoadWAV.

SeeAlsoSDL_LoadWAV

Prev Home NextSDL_LoadWAV Up SDL_AudioCVT

SDLLibraryDocumentationPrev Next

SDL_AudioCVT

Name

SDL_AudioCVT--AudioConversionStructure

StructureDefinitiontypedefstruct{

intneeded;

Uint16src_format;

Uint16dest_format;

doublerate_incr;

Uint8*buf;

intlen;

intlen_cvt;

intlen_mult;

doublelen_ratio;

void(*filters[10])(structSDL_AudioCVT*cvt,Uint16format);

intfilter_index;

}SDL_AudioCVT;

StructureData

needed Settooneiftheconversionispossiblesrc_format Audioformatofthesourcedest_format Audioformatofthedestinationrate_incr Rateconversionincrementbuf Audiobufferlen Lengthoftheoriginalaudiobufferinbyteslen_cvt Lengthofconvertedaudiobufferinbytes(calculated)len_mult bufmustbelen*len_multbytesinsize(calculated)len_ratio Finalaudiosizeislen*len_ratiofilters[10](..) Pointerstofunctionsneededforthisconversionfilter_index Currentconversionfunction

Description

TheSDL_AudioCVTisusedtoconvertaudiodatabetweendifferentformats.ASDL_AudioCVTstructureiscreatedwiththeSDL_BuildAudioCVTfunction,whiletheactualconversionisdonebytheSDL_ConvertAudiofunction.

ManyofthefieldsintheSDL_AudioCVTstructureshouldbeconsideredprivateandtheirfunctionwillnotbediscussedhere.

Uint8*buf

Thispointstotheaudiodatathatwillbeusedintheconversion.Itisboththesourceandthedestination,whichmeanstheconvertedaudiodataoverwritestheoriginaldata.Italsomeansthattheconverteddatamaybelargerthantheoriginaldata(ifyouwereconvertingfrom8-bitto16-bit,forinstance),soyoumustensurebufislargeenough.Seebelow.

intlen

Thisisthelengthoftheoriginalaudiodatainbytes.

intlen_mult

Asexplainedabove,theaudiobufferneedstobebigenoughtostoretheconverteddata,whichmaybebiggerthantheoriginalaudiodata.Thelengthofbufshouldbelen*len_mult.

doublelen_ratio

Whenyouhavefinishedconvertingyouraudiodata,youneedtoknowhowmuchofyouraudiobufferisvalid.len*len_ratioisthesizeoftheconvertedaudiodatainbytes.Thisisverysimilartolen_mult,howeverwhentheconvertaudiodataisshorterthantheoriginallen_multwouldbe1.len_ratio,ontheotherhand,wouldbeafractionalnumberbetween0and1.

SeeAlso

SDL_BuildAudioCVT,SDL_ConvertAudio,SDL_AudioSpec

Prev Home NextSDL_FreeWAV Up SDL_BuildAudioCVT

SDLLibraryDocumentationPrev Next

SDL_BuildAudioCVT

Name

SDL_BuildAudioCVT--InitializesaSDL_AudioCVTstructureforconversion

Synopsis#include"SDL.h"

intSDL_BuildAudioCVT(SDL_AudioCVT*cvt,Uint16src_format,Uint8src_channels,intsrc_rate,Uint16dst_format,Uint8dst_channels,intdst_rate);

Description

BeforeanSDL_AudioCVTstructurecanbeusedtoconvertaudiodataitmustbeinitializedwithsourceanddestinationinformation.

src_formatanddst_formatarethesourceanddestinationformatoftheconversion.(ForinformationonaudioformatsseeSDL_AudioSpec).src_channelsanddst_channelsarethenumberofchannelsinthesourceanddestinationformats.Finally,src_rateanddst_ratearethefrequencyorsamples-per-secondofthesourceanddestinationformats.Onceagain,seeSDL_AudioSpec.

ReturnValues

Returns-1ifthefiltercouldnotbebuiltor1ifitcould.

Examples

SeeSDL_ConvertAudio.

SeeAlso

SDL_ConvertAudio,SDL_AudioCVT

Prev Home NextSDL_AudioCVT Up SDL_ConvertAudio

SDLLibraryDocumentationPrev Next

SDL_ConvertAudio

Name

SDL_ConvertAudio--Convertaudiodatatoadesiredaudioformat.

Synopsis#include"SDL.h"

intSDL_ConvertAudio(SDL_AudioCVT*cvt);

Description

SDL_ConvertAudiotakesoneparameter,cvt,whichwaspreviouslyinitilized.InitilizingaSDL_AudioCVTisatwostepprocess.Firstofall,thestructuremustbepassedtoSDL_BuildAudioCVTalongwithsourceanddestinationformatparameters.Secondly,thecvt->bufandcvt->lenfieldsmustbesetup.cvt->bufshouldpointtotheaudiodataandcvt->lenshouldbesettothelengthoftheaudiodatainbytes.Remember,thelengthofthebufferpointedtobybufshowbelen*len_multbytesinlength.

OncetheSDL_AudioCVTstructureisinitilizedthenwecanpassittoSDL_ConvertAudio,whichwillconverttheaudiodatapointertobycvt->buf.IfSDL_ConvertAudioreturned0thentheconversionwascompletedsuccessfully,otherwise-1isreturned.

Iftheconversioncompletedsuccessfullythentheconvertedaudiodatacanbereadfromcvt->buf.Theamountofvalid,converted,audiodatainthebufferisequaltocvt->len*cvt->len_ratio.

Examples/*ConvertingsomeWAVdatatohardwareformat*/

voidmy_audio_callback(void*userdata,Uint8*stream,intlen);

SDL_AudioSpec*desired,*obtained;

SDL_AudioSpecwav_spec;

SDL_AudioCVTwav_cvt;

Uint32wav_len;

Uint8*wav_buf;

intret;

/*Allocatedaudiospecs*/

desired=(SDL_AudioSpec*)malloc(sizeof(SDL_AudioSpec));

obtained=(SDL_AudioSpec*)malloc(sizeof(SDL_AudioSpec));

/*Setdesiredformat*/

desired->freq=22050;

desired->format=AUDIO_S16LSB;

desired->samples=8192;

desired->callback=my_audio_callback;

desired->userdata=NULL;

/*Opentheaudiodevice*/

if(SDL_OpenAudio(desired,obtained)<0){

fprintf(stderr,"Couldn'topenaudio:%s\n",SDL_GetError());

exit(-1);

}

free(desired);

/*Loadthetest.wav*/

if(SDL_LoadWAV("test.wav",&wav_spec,&wav_buf,&wav_len)==NULL){

fprintf(stderr,"Couldnotopentest.wav:%s\n",SDL_GetError());

SDL_CloseAudio();

free(obtained);

exit(-1);

}

/*BuildAudioCVT*/

ret=SDL_BuildAudioCVT(&wav_cvt,

wav_spec.format,wav_spec.channels,wav_spec.freq,

obtained->format,obtained->channels,obtained->freq);

/*Checkthattheconvertwasbuilt*/

if(ret==-1){

fprintf(stderr,"Couldn'tbuildconverter!\n");

SDL_CloseAudio();

free(obtained);

SDL_FreeWAV(wav_buf);

}

/*Setupforconversion*/

wav_cvt.buf=(Uint8*)malloc(wav_len*wav_cvt.len_mult);

wav_cvt.len=wav_len;

memcpy(wav_cvt.buf,wav_buf,wav_len);

/*WecandeletetooriginalWAVdatanow*/

SDL_FreeWAV(wav_buf);

/*Andnowwe'rereadytoconvert*/

SDL_ConvertAudio(&wav_cvt);

/*dowhatever*/

.

.

.

.

SeeAlso

SDL_BuildAudioCVT,SDL_AudioCVT

Prev Home NextSDL_BuildAudioCVT Up SDL_MixAudio

SDLLibraryDocumentationPrev Next

SDL_MixAudio

Name

SDL_MixAudio--Mixaudiodata

Synopsis#include"SDL.h"

voidSDL_MixAudio(Uint8*dst,Uint8*src,Uint32len,intvolume);

Description

Thisfunctiontakestwoaudiobuffersoflenbyteseachoftheplayingaudioformatandmixesthem,performingaddition,volumeadjustment,andoverflowclipping.Thevolumerangesfrom0toSDL_MIX_MAXVOLUMEandshouldbesettothemaximumvalueforfullaudiovolume.Notethisdoesnotchangehardwarevolume.Thisisprovidedforconvenience--youcanmixyourownaudiodata.

Note:Donotusethisfunctionformixingtogethermorethantwostreamsofsampledata.Theoutputfromrepeatedapplicationofthisfunctionmaybedistortedbyclipping,becausethereisnoaccumulatorwithgreaterrangethantheinput(nottomentionthisbeinganinefficientwayofdoingit).UsemixingfunctionsfromSDL_mixer,OpenAL,orwriteyourownmixerinstead.

SeeAlsoSDL_OpenAudio

Prev Home NextSDL_ConvertAudio Up SDL_LockAudio

SDLLibraryDocumentationPrev Next

SDL_LockAudio

Name

SDL_LockAudio--Lockoutthecallbackfunction

Synopsis#include"SDL.h"

voidSDL_LockAudio(void);

Description

Thelockmanipulatedbythesefunctionsprotectsthecallbackfunction.DuringaLockAudioperiod,youcanbeguaranteedthatthecallbackfunctionisnotrunning.Donotcallthesefromthecallbackfunctionoryouwillcausedeadlock.

SeeAlsoSDL_OpenAudio

Prev Home NextSDL_MixAudio Up SDL_UnlockAudio

SDLLibraryDocumentationPrev Next

SDL_UnlockAudio

Name

SDL_UnlockAudio--Unlockthecallbackfunction

Synopsis#include"SDL.h"

voidSDL_UnlockAudio(void);

Description

UnlocksapreviousSDL_LockAudiocall.

SeeAlsoSDL_OpenAudio

Prev Home NextSDL_LockAudio Up SDL_CloseAudio

SDLLibraryDocumentationPrev Next

SDL_CloseAudio

Name

SDL_CloseAudio--Shutsdownaudioprocessingandclosestheaudiodevice.

Synopsis#include"SDL.h"

voidSDL_CloseAudio(void);

Description

Thisfunctionshutsdownaudioprocessingandclosestheaudiodevice.

SeeAlsoSDL_OpenAudio

Prev Home NextSDL_UnlockAudio Up CD-ROM

SDLLibraryDocumentationPrev Next

Chapter11.CD-ROMTableofContentsSDL_CDNumDrives—ReturnsthenumberofCD-ROMdrivesonthesystem.SDL_CDName—Returnsahuman-readable,system-dependentidentifierfortheCD-ROM.SDL_CDOpen—OpensaCD-ROMdriveforaccess.SDL_CDStatus—Returnsthecurrentstatusofthegivendrive.SDL_CDPlay—PlayaCDSDL_CDPlayTracks—PlaythegivenCDtrack(s)SDL_CDPause—PausesaCDROMSDL_CDResume—ResumesaCDROMSDL_CDStop—StopsaCDROMSDL_CDEject—EjectsaCDROMSDL_CDClose—ClosesaSDL_CDhandleSDL_CD—CDROMDriveInformationSDL_CDtrack—CDTrackInformationStructure

SDLsupportsaudiocontrolofupto32localCD-ROMdrivesatonce.

YouusethisAPItoperformallthebasicfunctionsofaCDplayer,includinglistingthetracks,playing,stopping,andejectingtheCD-ROM.(Currently,multi-changerCDdrivesarenotsupported.)

BeforeyoucallanyoftheSDLCD-ROMfunctions,youmustfirstcall"SDL_Init(SDL_INIT_CDROM)",whichscansthesystemforCD-ROMdrives,andsetstheprogramupforaudiocontrol.Checkthereturncode,whichshouldbe0,toseeiftherewereanyerrorsinstartingup.

Afteryouhaveinitializedthelibrary,youcanfindouthowmanydrivesareavailableusingtheSDL_CDNumDrives()function.ThefirstdrivelistedisthesystemdefaultCD-ROMdrive.Afteryouhavechosenadrive,andhaveopeneditwithSDL_CDOpen(),youcancheckthestatusandstartplayingifthere'saCDinthedrive.

ACD-ROMisorganizedintooneormoretracks,eachconsistingofacertainnumberof"frames".Eachframeis~2Kinsize,andatnormalplayingspeed,a

CDplays75framespersecond.SDLworkswiththenumberofframesonaCD,butthiscaneasilybeconvertedtothemorefamiliarminutes/secondsformatbyusingtheFRAMES_TO_MSF()macro.

Prev Home NextSDL_CloseAudio Up SDL_CDNumDrives

SDLLibraryDocumentationPrev Next

SDL_CDNumDrives

Name

SDL_CDNumDrives--ReturnsthenumberofCD-ROMdrivesonthesystem.

Synopsis#include"SDL.h"

intSDL_CDNumDrives(void);

Description

ReturnsthenumberofCD-ROMdrivesonthesystem.

SeeAlsoSDL_CDOpen

Prev Home NextCD-ROM Up SDL_CDName

SDLLibraryDocumentationPrev Next

SDL_CDName

Name

SDL_CDName--Returnsahuman-readable,system-dependentidentifierfortheCD-ROM.

Synopsis#include"SDL.h"

constchar*SDL_CDName(intdrive);

Description

Returnsahuman-readable,system-dependentidentifierfortheCD-ROM.driveistheindexofthedrive.Driveindicesstartto0andendatSDL_CDNumDrives()-1.

Examples

"/dev/cdrom"

"E:"

"/dev/disk/ide/1/master"

SeeAlsoSDL_CDNumDrives

Prev Home NextSDL_CDNumDrives Up SDL_CDOpen

SDLLibraryDocumentationPrev Next

SDL_CDOpen

Name

SDL_CDOpen--OpensaCD-ROMdriveforaccess.

Synopsis#include"SDL.h"

SDL_CD*SDL_CDOpen(intdrive);

Description

OpensaCD-ROMdriveforaccess.ItreturnsaSDL_CDstructureonsuccess,orNULLifthedrivewasinvalidorbusy.ThisnewlyopenedCD-ROMbecomesthedefaultCDusedwhenotherCDfunctionsarepassedaNULLCD-ROMhandle.

Drivesarenumberedstartingwith0.Drive0isthesystemdefaultCD-ROM.

ExamplesSDL_CD*cdrom;

intcur_track;

intmin,sec,frame;

SDL_Init(SDL_INIT_CDROM);

atexit(SDL_Quit);

/*CheckforCDdrives*/

if(!SDL_CDNumDrives()){

/*Nonefound*/

fprintf(stderr,"NoCDROMdevicesavailable\n");

exit(-1);

}

/*Openthedefaultdrive*/

cdrom=SDL_CDOpen(0);

/*Didifopen?CheckifcdromisNULL*/

if(!cdrom){

fprintf(stderr,"Couldn'topendrive:%s\n",SDL_GetError());

exit(-1);

}

/*PrintVolumeinfo*/

printf("Name:%s\n",SDL_CDName(0));

printf("Tracks:%d\n",cdrom->numtracks);

for(cur_track=0;cur_track<cdrom->numtracks;cur_track++){

FRAMES_TO_MSF(cdrom->track[cur_track].length,&min,&sec,&frame);

printf("\tTrack%d:Length%d:%d\n",cur_track,min,sec);

}

SDL_CDClose(cdrom);

SeeAlso

SDL_CD,SDL_CDtrack,SDL_CDClose

Prev Home NextSDL_CDName Up SDL_CDStatus

SDLLibraryDocumentationPrev Next

SDL_CDStatus

Name

SDL_CDStatus--Returnsthecurrentstatusofthegivendrive.

Synopsis#include"SDL.h"

CDstatusSDL_CDStatus(SDL_CD*cdrom);

/*Givenastatus,returnstrueifthere'sadiskinthedrive*/

#defineCD_INDRIVE(status)((int)status>0)

Description

Thisfunctionreturnsthecurrentstatusofthegivendrive.Statusisdescribedlikeso:

typedefenum{

CD_TRAYEMPTY,

CD_STOPPED,

CD_PLAYING,

CD_PAUSED,

CD_ERROR=-1

}CDstatus;

IfthedrivehasaCDinit,thetableofcontentsoftheCDandcurrentplaypositionoftheCDwillbestoredintheSDL_CDstructure.

ThemacroCD_INDRIVEisprovidedforconvenience,andgivenastatusreturnstrueifthere'sadiskinthedrive.

Note:SDL_CDStatusalsoupdatestheSDL_CDstructurepassedtoit.

ExampleintplayTrack(inttrack)

{

intplaying=0;

if(CD_INDRIVE(SDL_CDStatus(cdrom))){

/*clamptotheactualnumberoftracksontheCD*/

if(track>=cdrom->numtracks){

track=cdrom->numtracks-1;

}

if(SDL_CDPlayTracks(cdrom,track,0,1,0)==0){

playing=1;

}

}

returnplaying;

}

SeeAlsoSDL_CD

Prev Home NextSDL_CDOpen Up SDL_CDPlay

SDLLibraryDocumentationPrev Next

SDL_CDPlay

Name

SDL_CDPlay--PlayaCD

Synopsis#include"SDL.h"

intSDL_CDPlay(SDL_CD*cdrom,intstart,intlength);

Description

Playsthegivencdrom,startingaframestartforlengthframes.

ReturnValues

Returns0onsuccess,or-1onanerror.

SeeAlso

SDL_CDPlayTracks,SDL_CDStop

Prev Home NextSDL_CDStatus Up SDL_CDPlayTracks

SDLLibraryDocumentationPrev Next

SDL_CDPlayTracks

Name

SDL_CDPlayTracks--PlaythegivenCDtrack(s)

Synopsis#include"SDL.h"

intSDL_CDPlayTracks(SDL_CD*cdrom,intstart_track,intstart_frame,intntracks,intnframes));

Description

SDL_CDPlayTracksplaysthegivenCDstartingattrackstart_track,forntrackstracks.

start_frameistheframeoffset,fromthebeginningofthestart_track,atwhichtostart.nframesistheframeoffset,fromthebeginningofthelasttrack(start_track+ntracks),atwhichtoendplaying.

SDL_CDPlayTracksshouldonlybecalledaftercallingSDL_CDStatustogettrackinformationabouttheCD.

Note:Datatracksareignored.

ReturnValue

Returns0,or-1iftherewasanerror.

Examples/*assumingcdromisapreviouslyopeneddevice*/

/*PlaytheentireCD*/

if(CD_INDRIVE(SDL_CDStatus(cdrom)))

SDL_CDPlayTracks(cdrom,0,0,0,0);

/*Playthefirsttrack*/

if(CD_INDRIVE(SDL_CDStatus(cdrom)))

SDL_CDPlayTracks(cdrom,0,0,1,0);

/*Playfirst15secondsofthe2ndtrack*/

if(CD_INDRIVE(SDL_CDStatus(cdrom)))

SDL_CDPlayTracks(cdrom,1,0,0,CD_FPS*15);

SeeAlso

SDL_CDPlay,SDL_CDStatus,SDL_CD

Prev Home NextSDL_CDPlay Up SDL_CDPause

SDLLibraryDocumentationPrev Next

SDL_CDPause

Name

SDL_CDPause--PausesaCDROM

Synopsis#include"SDL.h"

intSDL_CDPause(SDL_CD*cdrom);

Description

Pausesplayonthegivencdrom.

ReturnValue

Returns0onsuccess,or-1onanerror.

SeeAlso

SDL_CDPlay,SDL_CDResume

Prev Home NextSDL_CDPlayTracks Up SDL_CDResume

SDLLibraryDocumentationPrev Next

SDL_CDResume

Name

SDL_CDResume--ResumesaCDROM

Synopsis#include"SDL.h"

intSDL_CDResume(SDL_CD*cdrom);

Description

Resumesplayonthegivencdrom.

ReturnValue

Returns0onsuccess,or-1onanerror.

SeeAlso

SDL_CDPlay,SDL_CDPause

Prev Home NextSDL_CDPause Up SDL_CDStop

SDLLibraryDocumentationPrev Next

SDL_CDStop

Name

SDL_CDStop--StopsaCDROM

Synopsis#include"SDL.h"

intSDL_CDStop(SDL_CD*cdrom);

Description

Stopsplayonthegivencdrom.

ReturnValue

Returns0onsuccess,or-1onanerror.

SeeAlso

SDL_CDPlay,

Prev Home NextSDL_CDResume Up SDL_CDEject

SDLLibraryDocumentationPrev Next

SDL_CDEject

Name

SDL_CDEject--EjectsaCDROM

Synopsis#include"SDL.h"

intSDL_CDEject(SDL_CD*cdrom);

Description

Ejectsthegivencdrom.

ReturnValue

Returns0onsuccess,or-1onanerror.

SeeAlso

SDL_CD

Prev Home NextSDL_CDStop Up SDL_CDClose

SDLLibraryDocumentationPrev Next

SDL_CDClose

Name

SDL_CDClose--ClosesaSDL_CDhandle

Synopsis#include"SDL.h"

voidSDL_CDClose(SDL_CD*cdrom);

Description

Closesthegivencdromhandle.

SeeAlso

SDL_CDOpen,SDL_CD

Prev Home NextSDL_CDEject Up SDL_CD

SDLLibraryDocumentationPrev Next

SDL_CD

Name

SDL_CD--CDROMDriveInformation

StructureDefinitiontypedefstruct{

intid;

CDstatusstatus;

intnumtracks;

intcur_track;

intcur_frame;

SDL_CDtracktrack[SDL_MAX_TRACKS+1];

}SDL_CD;

StructureData

id Privatedriveidentifierstatus Drivestatusnumtracks NumberoftracksontheCDcur_track Currenttrackcur_frame Currentframeoffsetwithinthetrack

track[SDL_MAX_TRACKS+1] Arrayoftrackdescriptions.(seeSDL_CDtrack)

Description

AnSDL_CDstructureisreturnedbySDL_CDOpen.ItrepresentsanopenedCDROMdeviceandstoresinformationonthelayoutofthetracksonthedisc.

AframeisthebasedataunitofaCD.CD_FPSframesisequalto1secondofmusic.SDLprovidestwomacrosforconvertingbetweentimeandframes:FRAMES_TO_MSF(f,M,S,F)andMSF_TO_FRAMES.

Examplesintmin,sec,frame;

intframe_offset;

FRAMES_TO_MSF(cdrom->cur_frame,&min,&sec,&frame);

printf("CurrentPosition:%dminutes,%dseconds,%dframes\n",min,sec,frame);

frame_offset=MSF_TO_FRAMES(min,sec,frame);

SeeAlso

SDL_CDOpen,SDL_CDtrack

Prev Home NextSDL_CDClose Up SDL_CDtrack

SDLLibraryDocumentationPrev Next

SDL_CDtrack

Name

SDL_CDtrack--CDTrackInformationStructure

StructureDefinitiontypedefstruct{

Uint8id;

Uint8type;

Uint32length;

Uint32offset;

}SDL_CDtrack;

StructureData

id Tracknumber(0-99)type SDL_AUDIO_TRACKorSDL_DATA_TRACKlength Length,inframes,ofthistrackoffset Frameoffsettothebeginningofthistrack

Description

SDL_CDtrackstoresdataoneachtrackonaCD,itsfieldsshouldbeprettyselfexplainatory.ItisamemberatheSDL_CDstructure.

Note:Framescanbeconvertedtostandardtimings.ThereareCD_FPSframespersecond,soSDL_CDtrack.length/CD_FPS=length_in_seconds.

SeeAlso

SDL_CD

Prev Home Next

SDL_CD Up Multi-threadedProgramming

SDLLibraryDocumentationPrev Next

Chapter12.Multi-threadedProgrammingTableofContentsSDL_CreateThread—Createsanewthreadofexecutionthatsharesitsparent'sproperties.SDL_ThreadID—Getthe32-bitthreadidentifierforthecurrentthread.SDL_GetThreadID—GettheSDLthreadIDofaSDL_ThreadSDL_WaitThread—Waitforathreadtofinish.SDL_KillThread—Gracelesslyterminatesthethread.SDL_CreateMutex—CreateamutexSDL_DestroyMutex—DestroyamutexSDL_mutexP—LockamutexSDL_mutexV—UnlockamutexSDL_CreateSemaphore—Createsanewsemaphoreandassignsaninitialvaluetoit.SDL_DestroySemaphore—DestroysasemaphorethatwascreatedbySDL_CreateSemaphore.SDL_SemWait—Lockasemaphoreandsuspendthethreadifthesemaphorevalueiszero.SDL_SemTryWait—Attempttolockasemaphorebutdon'tsuspendthethread.SDL_SemWaitTimeout—Lockasemaphore,butonlywaituptoaspecifiedmaximumtime.SDL_SemPost—Unlockasemaphore.SDL_SemValue—Returnthecurrentvalueofasemaphore.SDL_CreateCond—CreateaconditionvariableSDL_DestroyCond—DestroyaconditionvariableSDL_CondSignal—RestartathreadwaitonaconditionvariableSDL_CondBroadcast—RestartallthreadswaitingonaconditionvariableSDL_CondWait—WaitonaconditionvariableSDL_CondWaitTimeout—Waitonaconditionvariable,withtimeout

SDLprovidesfunctionsforcreatingthreads,mutexes,semphoresandconditionvariables.

Ingeneral,youmustbeveryawareofconcurrencyanddataintegrityissueswhenwritingmulti-threadedprograms.Somegoodguidelinesinclude:

Don'tcallSDLvideo/eventfunctionsfromseparatethreads

Don'tuseanylibraryfunctionsinseparatethreads

Don'tperformanymemorymanagementinseparatethreads

Lockglobalvariableswhichmaybeaccessedbymultiplethreads

Neverterminatethreads,alwayssetaflagandwaitforthemtoquit

Thinkverycarefullyaboutallpossiblewaysyourcodemayinteract

Note:SDL'sthreadingisnotimplementedonMacOS,duetothatlackofpreemptivethreadsupport(MacOSXdosntsufferfromthisproblem)

Prev Home NextSDL_CDtrack Up SDL_CreateThread

SDLLibraryDocumentationPrev Next

SDL_CreateThread

Name

SDL_CreateThread--Createsanewthreadofexecutionthatsharesitsparent'sproperties.

Synopsis#include"SDL.h"

#include"SDL_thread.h"

SDL_Thread*SDL_CreateThread(int(*fn)(void*),void*data);

Description

SDL_CreateThreadcreatesanewthreadofexecutionthatsharesallofitsparent'sglobalmemory,signalhandlers,filedescriptors,etc,andrunsthefunctionfnpassedthevoidpointerdataThethreadquitswhenthisfunctionreturns.

SeeAlsoSDL_KillThread

Prev Home NextMulti-threadedProgramming Up SDL_ThreadID

SDLLibraryDocumentationPrev Next

SDL_ThreadID

Name

SDL_ThreadID--Getthe32-bitthreadidentifierforthecurrentthread.

Synopsis#include"SDL.h"

#include"SDL_thread.h"

Uint32SDL_ThreadID(void);

Description

Getthe32-bitthreadidentifierforthecurrentthread.

Prev Home NextSDL_CreateThread Up SDL_GetThreadID

SDLLibraryDocumentationPrev Next

SDL_GetThreadID

Name

SDL_GetThreadID--GettheSDLthreadIDofaSDL_Thread

Synopsis#include"SDL.h"

#include"SDL_thread.h"

Uint32SDL_GetThreadID(SDL_Thread*thread);

Description

ReturnstheIDofaSDL_ThreadcreatedbySDL_CreateThread.

SeeAlso

SDL_CreateThread

Prev Home NextSDL_ThreadID Up SDL_WaitThread

SDLLibraryDocumentationPrev Next

SDL_WaitThread

Name

SDL_WaitThread--Waitforathreadtofinish.

Synopsis#include"SDL.h"

#include"SDL_thread.h"

voidSDL_WaitThread(SDL_Thread*thread,int*status);

Description

Waitforathreadtofinish(timeoutsarenotsupported).

ReturnValue

Thereturncodeforthethreadfunctionisplacedintheareapointedtobystatus,ifstatusisnotNULL.

SeeAlsoSDL_CreateThread

Prev Home NextSDL_GetThreadID Up SDL_KillThread

SDLLibraryDocumentationPrev Next

SDL_KillThread

Name

SDL_KillThread--Gracelesslyterminatesthethread.

Synopsis#include"SDL.h"

#include"SDL_thread.h"

voidSDL_KillThread(SDL_Thread*thread);

Description

SDL_KillThreadgracelesslyterminatesthethreadassociatedwiththread.Ifpossible,youshouldusesomeotherformofIPCtosignalthethreadtoquit.

SeeAlso

SDL_CreateThread,SDL_WaitThread

Prev Home NextSDL_WaitThread Up SDL_CreateMutex

SDLLibraryDocumentationPrev Next

SDL_CreateMutex

Name

SDL_CreateMutex--Createamutex

Synopsis#include"SDL.h"

#include"SDL_thread.h"

SDL_mutex*SDL_CreateMutex(void);

Description

Createanew,unlockedmutex.

ExamplesSDL_mutex*mut;

mut=SDL_CreateMutex();

.

.

if(SDL_mutexP(mut)==-1){

fprintf(stderr,"Couldn'tlockmutex\n");

exit(-1);

}

.

/*Dostuffwhilemutexislocked*/

.

.

if(SDL_mutexV(mut)==-1){

fprintf(stderr,"Couldn'tunlockmutex\n");

exit(-1);

}

SDL_DestroyMutex(mut);

SeeAlso

SDL_mutexP,SDL_mutexV,SDL_DestroyMutex

Prev Home NextSDL_KillThread Up SDL_DestroyMutex

SDLLibraryDocumentationPrev Next

SDL_DestroyMutex

Name

SDL_DestroyMutex--Destroyamutex

Synopsis#include"SDL.h"

#include"SDL_thread.h"

voidSDL_DestroyMutex(SDL_mutex*mutex);

Description

Destroyapreviouslycreatedmutex.

SeeAlsoSDL_CreateMutex

Prev Home NextSDL_CreateMutex Up SDL_mutexP

SDLLibraryDocumentationPrev Next

SDL_mutexP

Name

SDL_mutexP--Lockamutex

Synopsis#include"SDL.h"

#include"SDL_thread.h"

intSDL_mutexP(SDL_mutex*mutex);

Description

Locksthemutex,whichwaspreviouslycreatedwithSDL_CreateMutex.IfthemutexisalreadylockedthenSDL_mutexPwillnotreturnuntilitisunlocked.Returns0onsuccess,or-1onanerror.

SDLalsodefinesamacro#defineSDL_LockMutex(m)SDL_mutexP(m).

SeeAlso

SDL_CreateMutex,SDL_mutexV

Prev Home NextSDL_DestroyMutex Up SDL_mutexV

SDLLibraryDocumentationPrev Next

SDL_mutexV

Name

SDL_mutexV--Unlockamutex

Synopsis#include"SDL.h"

#include"SDL_thread.h"

intSDL_mutexV(SDL_mutex*mutex);

Description

Unlocksthemutex,whichwaspreviouslycreatedwithSDL_CreateMutex.Returns0onsuccess,or-1onanerror.

SDLalsodefinesamacro#defineSDL_UnlockMutex(m)SDL_mutexV(m).

SeeAlso

SDL_CreateMutex,SDL_mutexP

Prev Home NextSDL_mutexP Up SDL_CreateSemaphore

SDLLibraryDocumentationPrev Next

SDL_CreateSemaphore

Name

SDL_CreateSemaphore--Createsanewsemaphoreandassignsaninitialvaluetoit.

Synopsis#include"SDL.h"

#include"SDL_thread.h"

SDL_sem*SDL_CreateSemaphore(Uint32initial_value);

Description

SDL_CreateSemaphore()createsanewsemaphoreandinitializesitwiththevalueinitial_value.EachlockingoperationonthesemaphorebySDL_SemWait,SDL_SemTryWaitorSDL_SemWaitTimeoutwillatomicallydecrementthesemaphorevalue.Thelockingoperationwillbeblockedifthesemaphorevalueisnotpositive(greaterthanzero).EachunlockoperationbySDL_SemPostwillatomicallyincrementthesemaphorevalue.

ReturnValue

ReturnsapointertoaninitializedsemaphoreorNULLiftherewasanerror.

ExamplesSDL_sem*my_sem;

my_sem=SDL_CreateSemaphore(INITIAL_SEM_VALUE);

if(my_sem==NULL){

returnCREATE_SEM_FAILED;

}

SeeAlso

SDL_DestroySemaphore,SDL_SemWait,SDL_SemTryWait,SDL_SemWaitTimeout,SDL_SemPost,SDL_SemValue

Prev Home NextSDL_mutexV Up SDL_DestroySemaphore

SDLLibraryDocumentationPrev Next

SDL_DestroySemaphore

Name

SDL_DestroySemaphore--DestroysasemaphorethatwascreatedbySDL_CreateSemaphore.

Synopsis#include"SDL.h"

#include"SDL_thread.h"

voidSDL_DestroySemaphore(SDL_sem*sem);

Description

SDL_DestroySemaphoredestroysthesemaphorepointedtobysemthatwascreatedbySDL_CreateSemaphore.Itisnotsafetodestroyasemaphoreiftherearethreadscurrentlyblockedwaitingonit.

Examplesif(my_sem!=NULL){

SDL_DestroySemaphore(my_sem);

my_sem=NULL;

}

SeeAlso

SDL_CreateSemaphore,SDL_SemWait,SDL_SemTryWait,SDL_SemWaitTimeout,SDL_SemPost,SDL_SemValue

Prev Home NextSDL_CreateSemaphore Up SDL_SemWait

SDLLibraryDocumentationPrev Next

SDL_SemWait

Name

SDL_SemWait--Lockasemaphoreandsuspendthethreadifthesemaphorevalueiszero.

Synopsis#include"SDL.h"

#include"SDL_thread.h"

intSDL_SemWait(SDL_sem*sem);

Description

SDL_SemWait()suspendsthecallingthreaduntileitherthesemaphorepointedtobysemhasapositivevalue,thecallisinterruptedbyasignalorerror.Ifthecallissuccessfulitwillatomicallydecrementthesemaphorevalue.

AfterSDL_SemWait()issuccessful,thesemaphorecanbereleasedanditscountatomicallyincrementedbyasuccessfulcalltoSDL_SemPost.

ReturnValue

Returns0ifsuccessfulor-1iftherewasanerror(leavingthesemaphoreunchanged).

Examplesif(SDL_SemWait(my_sem)==-1){

returnWAIT_FAILED;

}

...

SDL_SemPost(my_sem);

SeeAlso

SDL_CreateSemaphore,SDL_DestroySemaphore,SDL_SemTryWait,SDL_SemWaitTimeout,SDL_SemPost,SDL_SemValue

Prev Home NextSDL_DestroySemaphore Up SDL_SemTryWait

SDLLibraryDocumentationPrev Next

SDL_SemTryWait

Name

SDL_SemTryWait--Attempttolockasemaphorebutdon'tsuspendthethread.

Synopsis#include"SDL.h"

#include"SDL_thread.h"

intSDL_SemTryWait(SDL_sem*sem);

Description

SDL_SemTryWaitisanon-blockingvarientofSDL_SemWait.Ifthevalueofthesemaphorepointedtobysemispositiveitwillatomicallydecrementthesemaphorevalueandreturn0,otherwiseitwillreturnSDL_MUTEX_TIMEOUTinsteadofsuspendingthethread.

AfterSDL_SemTryWaitissuccessful,thesemaphorecanbereleasedanditscountatomicallyincrementedbyasuccessfulcalltoSDL_SemPost.

ReturnValue

Returns0ifthesemaphorewassuccessfullylockedoreitherSDL_MUTEX_TIMEOUTor-1ifthethreadwouldhavesuspendedortherewasanerror,respectivly.

Ifthesemaphorewasnotsuccessfullylocked,thesemaphorewillbeunchanged.

Examplesres=SDL_SemTryWait(my_sem);

if(res==SDL_MUTEX_TIMEOUT){

returnTRY_AGAIN;

}

if(res==-1){

returnWAIT_ERROR;

}

...

SDL_SemPost(my_sem);

SeeAlso

SDL_CreateSemaphore,SDL_DestroySemaphore,SDL_SemWait,SDL_SemWaitTimeout,SDL_SemPost,SDL_SemValue

Prev Home NextSDL_SemWait Up SDL_SemWaitTimeout

SDLLibraryDocumentationPrev Next

SDL_SemWaitTimeout

Name

SDL_SemWaitTimeout--Lockasemaphore,butonlywaituptoaspecifiedmaximumtime.

Synopsis#include"SDL.h"

#include"SDL_thread.h"

intSDL_SemWaitTimeout(SDL_sem*sem,Uint32timeout);

Description

SDL_SemWaitTimeout()isavarientofSDL_SemWaitwithamaximumtimeoutvalue.Ifthevalueofthesemaphorepointedtobysemispositive(greaterthanzero)itwillatomicallydecrementthesemaphorevalueandreturn0,otherwiseitwillwaituptotimeoutmillisecondstryingtolockthesemaphore.Thisfunctionistobeavoidedifpossiblesinceonsomeplatformsitisimplementedbypollingthesemaphoreeverymillisecondinabusyloop.

AfterSDL_SemWaitTimeout()issuccessful,thesemaphorecanbereleasedanditscountatomicallyincrementedbyasuccessfulcalltoSDL_SemPost.

ReturnValue

Returns0ifthesemaphorewassuccessfullylockedoreitherSDL_MUTEX_TIMEOUTor-1ifthetimeoutperiodwasexceededortherewasanerror,respectivly.

Ifthesemaphorewasnotsuccessfullylocked,thesemaphorewillbeunchanged.

Examplesres=SDL_SemWaitTimeout(my_sem,WAIT_TIMEOUT_MILLISEC);

if(res==SDL_MUTEX_TIMEOUT){

returnTRY_AGAIN;

}

if(res==-1){

returnWAIT_ERROR;

}

...

SDL_SemPost(my_sem);

SeeAlso

SDL_CreateSemaphore,SDL_DestroySemaphore,SDL_SemWait,SDL_SemTryWait,SDL_SemPost,SDL_SemValue

Prev Home NextSDL_SemTryWait Up SDL_SemPost

SDLLibraryDocumentationPrev Next

SDL_SemPost

Name

SDL_SemPost--Unlockasemaphore.

Synopsis#include"SDL.h"

#include"SDL_thread.h"

intSDL_SemPost(SDL_sem*sem);

Description

SDL_SemPostunlocksthesemaphorepointedtobysemandatomicallyincrementsthesemaphoresvalue.Threadsthatwereblockingonthesemaphoremaybescheduledafterthiscallsucceeds.

SDL_SemPostshouldbecalledafterasemaphoreislockedbyasuccessfulcalltoSDL_SemWait,SDL_SemTryWaitorSDL_SemWaitTimeout.

ReturnValue

Returns0ifsuccessfulor-1iftherewasanerror(leavingthesemaphoreunchanged).

ExamplesSDL_SemPost(my_sem);

SeeAlso

SDL_CreateSemaphore,SDL_DestroySemaphore,SDL_SemWait,SDL_SemTryWait,SDL_SemWaitTimeout,SDL_SemValue

Prev Home NextSDL_SemWaitTimeout Up SDL_SemValue

SDLLibraryDocumentationPrev Next

SDL_SemValue

Name

SDL_SemValue--Returnthecurrentvalueofasemaphore.

Synopsis#include"SDL.h"

#include"SDL/SDL_thread.h"

Uint32SDL_SemValue(SDL_sem*sem);

Description

SDL_SemValue()returnsthecurrentsemaphorevaluefromthesemaphorepointedtobysem.

ReturnValue

Returnscurrentvalueofthesemaphore.

Examplessem_value=SDL_SemValue(my_sem);

SeeAlso

SDL_CreateSemaphore,SDL_DestroySemaphore,SDL_SemWait,SDL_SemTryWait,SDL_SemWaitTimeout,SDL_SemPost

Prev Home NextSDL_SemPost Up SDL_CreateCond

SDLLibraryDocumentationPrev Next

SDL_CreateCond

Name

SDL_CreateCond--Createaconditionvariable

Synopsis#include"SDL.h"

#include"SDL_thread.h"

SDL_cond*SDL_CreateCond(void);

Description

Createsaconditionvariable.

ExamplesSDL_cond*cond;

cond=SDL_CreateCond();

.

.

/*Dostuff*/

.

.

SDL_DestroyCond(cond);

SeeAlso

SDL_DestroyCond,SDL_CondWait,SDL_CondSignal

Prev Home NextSDL_SemValue Up SDL_DestroyCond

SDLLibraryDocumentationPrev Next

SDL_DestroyCond

Name

SDL_DestroyCond--Destroyaconditionvariable

Synopsis#include"SDL.h"

#include"SDL_thread.h"

voidSDL_DestroyCond(SDL_cond*cond);

Description

Destroysaconditionvariable.

SeeAlsoSDL_CreateCond

Prev Home NextSDL_CreateCond Up SDL_CondSignal

SDLLibraryDocumentationPrev Next

SDL_CondSignal

Name

SDL_CondSignal--Restartathreadwaitonaconditionvariable

Synopsis#include"SDL.h"

#include"SDL_thread.h"

intSDL_CondSignal(SDL_cond*cond);

Description

Restartoneofthethreadsthatarewaitingontheconditionvariable,cond.Returns0onsuccessof-1onanerror.

SeeAlso

SDL_CondWait,SDL_CondBroadcast

Prev Home NextSDL_DestroyCond Up SDL_CondBroadcast

SDLLibraryDocumentationPrev Next

SDL_CondBroadcast

Name

SDL_CondBroadcast--Restartallthreadswaitingonaconditionvariable

Synopsis#include"SDL.h"

#include"SDL_thread.h"

intSDL_CondBroadcast(SDL_cond*cond);

Description

Restartsallthreadsthatarewaitingontheconditionvariable,cond.Returns0onsuccess,or-1onanerror.

SeeAlso

SDL_CondSignal,SDL_CondWait

Prev Home NextSDL_CondSignal Up SDL_CondWait

SDLLibraryDocumentationPrev Next

SDL_CondWait

Name

SDL_CondWait--Waitonaconditionvariable

Synopsis#include"SDL.h"

#include"SDL_thread.h"

intSDL_CondWait(SDL_cond*cond,SDL_mutex*mut);

Description

Waitontheconditionvariablecondandunlocktheprovidedmutex.Themutexmustthelockedbeforeenteringthisfunction.Returns0whenitissignalled,or-1onanerror.

SeeAlso

SDL_CondWaitTimeout,SDL_CondSignal,SDL_mutexP

Prev Home NextSDL_CondBroadcast Up SDL_CondWaitTimeout

SDLLibraryDocumentationPrev Next

SDL_CondWaitTimeout

Name

SDL_CondWaitTimeout--Waitonaconditionvariable,withtimeout

Synopsis#include"SDL.h"

#include"SDL_thread.h"

intSDL_CondWaitTimeout(SDL_cond*cond,SDL_mutex*mutex,Uint32ms);

Description

Waitontheconditionvariablecondfor,atmost,msmilliseconds.mutisunlockedsoitmustbelockedwhenthefunctioniscalled.ReturnsSDL_MUTEX_TIMEDOUTiftheconditionisnotsignalledintheallottedtime,0ifitwassignalledor-1onanerror.

SeeAlsoSDL_CondWait

Prev Home NextSDL_CondWait Up Time

SDLLibraryDocumentationPrev Next

Chapter13.TimeTableofContentsSDL_GetTicks—GetthenumberofmillisecondssincetheSDLlibraryinitialization.SDL_Delay—Waitaspecifiednumberofmillisecondsbeforereturning.SDL_AddTimer—Addatimerwhichwillcallacallbackafterthespecifiednumberofmillisecondshaselapsed.SDL_RemoveTimer—RemoveatimerwhichwasaddedwithSDL_AddTimer.SDL_SetTimer—Setacallbacktorunafterthespecifiednumberofmillisecondshaselapsed.

SDLprovidesseveralcross-platformfunctionsfordealingwithtime.Itprovidesawaytogetthecurrenttime,awaytowaitalittlewhile,andasimpletimermechanism.Thesefunctionsgiveyoutwowaysofmovinganobjecteveryxmilliseconds:

Useatimercallbackfunction.Thismayhavethebadeffectthatitrunsinaseperatethreadorusesalarmsignals,butit'seasiertoimplement.

Oryoucangetthenumberofmillisecondspassed,andmovetheobjectif,forexample,30mspassed.

Prev Home NextSDL_CondWaitTimeout Up SDL_GetTicks

SDLLibraryDocumentationPrev Next

SDL_GetTicks

Name

SDL_GetTicks--GetthenumberofmillisecondssincetheSDLlibraryinitialization.

Synopsis#include"SDL.h"

Uint32SDL_GetTicks(void);

Description

GetthenumberofmillisecondssincetheSDLlibraryinitialization.Notethatthisvaluewrapsiftheprogramrunsformorethan~49days.

SeeAlsoSDL_Delay

Prev Home NextTime Up SDL_Delay

SDLLibraryDocumentationPrev Next

SDL_Delay

Name

SDL_Delay--Waitaspecifiednumberofmillisecondsbeforereturning.

Synopsis#include"SDL.h"

voidSDL_Delay(Uint32ms);

Description

Waitaspecifiednumberofmillisecondsbeforereturning.SDL_Delaywillwaitatleastthespecifiedtime,butpossiblelongerduetoOSscheduling.

Note:Countonadelaygranularityofatleast10ms.Someplatformshaveshorterclockticksbutthisisthemostcommon.

SeeAlsoSDL_AddTimer

Prev Home NextSDL_GetTicks Up SDL_AddTimer

SDLLibraryDocumentationPrev Next

SDL_AddTimer

Name

SDL_AddTimer--Addatimerwhichwillcallacallbackafterthespecifiednumberofmillisecondshaselapsed.

Synopsis#include"SDL.h"

SDL_TimerIDSDL_AddTimer(Uint32interval,SDL_NewTimerCallbackcallback,void*param);

Callback/*typedefinitionforthe"new"timercallbackfunction*/

typedefUint32(*SDL_NewTimerCallback)(Uint32interval,void*param);

Description

Addsacallbackfunctiontoberunafterthespecifiednumberofmillisecondshaselapsed.ThecallbackfunctionispassedthecurrenttimerintervalandtheusersuppliedparameterfromtheSDL_AddTimercallandreturnsthenexttimerinterval.Ifthereturnedvaluefromthecallbackisthesameastheonepassedin,theperiodicalarmcontinues,otherwiseanewalarmisscheduled.

TocancelacurrentlyrunningtimercallSDL_RemoveTimerwiththetimerIDreturnedfromSDL_AddTimer.

Thetimercallbackfunctionmayruninadifferentthreadthanyourmainprogram,andsoshouldn'tcallanyfunctionsfromwithinitself.YoumayalwayscallSDL_PushEvent,however.

Thegranularityofthetimerisplatform-dependent,butyoushouldcountonitbeingatleast10msasthisisthemostcommonnumber.Thismeansthatifyourequesta16mstimer,yourcallbackwillrunapproximately20mslateronanunloadedsystem.Ifyouwantedtosetaflagsignalingaframeupdateat30framespersecond(every33ms),youmightsetatimerfor30ms(seeexamplebelow).Ifyouusethisfunction,youneedtopassSDL_INIT_TIMERtoSDL_Init.

ReturnValue

ReturnsanIDvaluefortheaddedtimerorNULLiftherewasanerror.

Examplesmy_timer_id=SDL_AddTimer((33/10)*10,my_callbackfunc,my_callback_param);

SeeAlso

SDL_RemoveTimer,SDL_PushEvent

Prev Home NextSDL_Delay Up SDL_RemoveTimer

SDLLibraryDocumentationPrev Next

SDL_RemoveTimer

Name

SDL_RemoveTimer--RemoveatimerwhichwasaddedwithSDL_AddTimer.

Synopsis#include"SDL.h"

SDL_boolSDL_RemoveTimer(SDL_TimerIDid);

Description

RemovesatimercallbackpreviouslyaddedwithSDL_AddTimer.

ReturnValue

Returnsabooleanvalueindicatingsuccess.

ExamplesSDL_RemoveTimer(my_timer_id);

SeeAlsoSDL_AddTimer

Prev Home NextSDL_AddTimer Up SDL_SetTimer

SDLLibraryDocumentationPrev

SDL_SetTimer

Name

SDL_SetTimer--Setacallbacktorunafterthespecifiednumberofmillisecondshaselapsed.

Synopsis#include"SDL.h"

intSDL_SetTimer(Uint32interval,SDL_TimerCallbackcallback);

Callback

/*Functionprototypeforthetimercallbackfunction*/typedefUint32(*SDL_TimerCallback)(Uint32interval);

Description

Setacallbacktorunafterthespecifiednumberofmillisecondshaselapsed.Thecallbackfunctionispassedthecurrenttimerintervalandreturnsthenexttimerinterval.Ifthereturnedvalueisthesameastheonepassedin,theperiodicalarmcontinues,otherwiseanewalarmisscheduled.

Tocancelacurrentlyrunningtimer,callSDL_SetTimer(0,NULL);

Thetimercallbackfunctionmayruninadifferentthreadthanyourmainconstant,andsoshouldn'tcallanyfunctionsfromwithinitself.

Themaximumresolutionofthistimeris10ms,whichmeansthatifyourequesta16mstimer,yourcallbackwillrunapproximately20mslateronanunloadedsystem.Ifyouwantedtosetaflagsignalingaframeupdateat30framespersecond(every33ms),youmightsetatimerfor30ms(seeexamplebelow).

Ifyouusethisfunction,youneedtopassSDL_INIT_TIMERtoSDL_Init().

Note:ThisfunctioniskeptforcompatibilitybuthasbeensupersededbythenewtimerfunctionsSDL_AddTimerandSDL_RemoveTimerwhichsupportmultipletimers.

ExamplesSDL_SetTimer((33/10)*10,my_callback);

SeeAlsoSDL_AddTimer

Prev Home SDL_RemoveTimer Up

top related