table of contents · sdl_cdresume — resumes a cdrom sdl_cdstop — stops a cdrom sdl_cdeject —...
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
I.SDLGuideTableofContentsPreface1.TheBasics2.GraphicsandVideo3.Inputhandling4.Examples
Prev Home NextSDLLibraryDocumentation Preface
AboutSDLTheSDLlibraryisdesignedtomakeiteasytowritegamesthatrunonLinux,*BSD,MacOS,Win32andBeOSusingthevariousnativehigh-performancemediainterfaces,(forvideo,audio,etc)andpresentingasinglesource-codelevelAPItoyourapplication.SDLisafairlylowlevelAPI,butusingit,completelyportableapplicationscanbewrittenwithagreatdealofflexibility.
Prev Home NextSDLGuide Up AboutSDLdoc
AboutSDLdocSDLdoc(TheSDLDocumentationProject)wasformedtocompletelyrewritetheSDLdocumentationandtokeepitcontinuallyuptodate.TheteamconsistscompletelyofvolunteersrangingfrompeopleworkingwithSDLintheirsparetimetopeoplewhouseSDLintheireverydayworkinglives.
Thelatestversionofthisdocumentationcanalwaysbefoundhere:http://sdldoc.csn.ul.ieDownloadablePS,manpagesandhtmltarballsareavailableathttp://sdldoc.csn.ul.ie/pub/
Prev Home NextPreface Up Credits
CreditsSamLantinga,[email protected],[email protected]årdJulianPetersonKenJordanMaximSobolevWesleyPooleMichaelVanceAndreasUmbachAndreasHofmeister
Prev Home NextAboutSDLdoc Up TheBasics
IntroductionTheSDLGuidesectionisprettyincomplete.Ifyoufeelyouhaveanythingtoaddmailakawaka@skynet.ieorvisithttp://akawaka.csn.ul.ie/tne/.
Prev Home NextCredits Up InitializingSDL
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
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
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.
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
*
*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
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:
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
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
IntroductionForthemomenttheseexamplesaretakendirectlyfromtheoldSDLdocumentation.Bythe1.2releasetheseexamplesshouldhopefullydealwithmostcommonSDLprogrammingproblems.
Prev Home NextHandlingtheKeyboard Up 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
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
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
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
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);
}
II.SDLReferenceTableofContents5.General6.Video7.WindowManagement8.Events9.Joystick10.Audio11.CD-ROM12.Multi-threadedProgramming13.Time
Prev Home NextTimeExamples General
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
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
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();
Description
SDL_QuitSubSystemallowsyoutoshutdownasubsystemthathasbeenpreviouslyinitializedbySDL_InitorSDL_InitSubSystem.TheflagstellsSDL_QuitSubSystemwhichsubsystemstoshutdown,itusesthesamevaluesthatarepassedtoSDL_Init.
Description
SDL_QuitshutsdownallSDLsubsystemsandfreestheresourcesallocatedtothem.Thisshouldalwaysbecalledbeforeyouexit.ForthesakeofsimplicityyoucansetSDL_Quitasyouratexitcall,like:
SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO);
atexit(SDL_Quit);
.
.
Note:Whileusingatexitmaybebefineforsmallprograms,moreadvancedusersshouldshutdownSDLintheirowncleanupcode.Plus,usingatexitinalibraryisasurewaytocrashdynamicallyloadedcode
Description
SDL_WasInitallowsyoutoseewhichSDLsubsytemshavebeeninitialized.flagsisabitwiseOR'dcombinationofthesubsystemsyouwishtocheck(seeSDL_Initforalistofsubsystemflags).
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");
Description
SDL_GetErrorreturnsaNULLterminatedstringcontaininginformationaboutthelastinternalSDLerror.
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
Description
Thisfunctionreturnsapointertothecurrentdisplaysurface.IfSDLisdoingformatconversiononthedisplaysurface,thisfunctionreturnsthepubliclyvisiblesurface,nottherealvideosurface.
Description
Thisfunctionreturnsaread-onlypointertoinformationaboutthevideohardware.IfthisiscalledbeforeSDL_SetVideoMode,thevfmtmemberofthereturnedstructurewillcontainthepixelformatofthe"best"videomode.
Description
Thebufferpointedtobynamebufisfilleduptoamaximumofmaxlencharacters(includetheNULLterminator)withthenameoftheinitialisedvideodriver.Thedrivernameisasimpleonewordidentifierlike"x11"or"windib".
Name
SDL_ListModes--Returnsapointertoanarrayofavailablescreendimensionsforthegivenformatandvideoflags
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
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);
.
.
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
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
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
Description
Onhardwarethatsupportsdouble-buffering,thisfunctionsetsupaflipandreturns.Thehardwarewillwaitforverticalretrace,andthenswapvideobuffersbeforethenextvideosurfaceblitorlockwillreturn.Onhardwarethatdoesn'tsupportdouble-buffering,thisisequivalenttocallingSDL_UpdateRect(screen,0,0,0,0)
TheSDL_DOUBLEBUFflagmusthavebeenpassedtoSDL_SetVideoMode,whensettingthevideomodeforthisfunctiontoperformhardwareflipping.
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
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
Description
Setsthe"gammafunction"forthedisplayofeachcolorcomponent.Gammacontrolsthebrightness/contrastofcolorsdisplayedonthescreen.Agammavalueof1.0isidentity(i.e.,noadjustmentismade).
Thisfunctionadjuststhegammabasedonthe"gammafunction"parameter,youcandirectlyspecifylookuptablesforgammaadjustmentwithSDL_SetGammaRamp.
Notalldisplayhardwareisabletochangegamma.
Description
Getsthegammatranslationlookuptablescurrentlyusedbythedisplay.Eachtableisanarrayof256Uint16values.
Notalldisplayhardwareisabletochangegamma.
Description
Setsthegammalookuptablesforthedisplayforeachcolorcomponent.Eachtableisanarrayof256Uint16values,representingamappingbetweentheinputandoutputforthatchannel.Theinputistheindexintothearray,andtheoutputisthe16-bitgammavalueatthatindex,scaledtotheoutputcolorprecision.YoumaypassNULLtoanyofthechannelstoleavethemunchanged.
Thisfunctionadjuststhegammabasedonlookuptables,youcanalsohavethegammacalculatedbasedona"gammafunction"parameterwithSDL_SetGamma.
Notalldisplayhardwareisabletochangegamma.
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
Description
MapstheRGBAcolorvaluetothespecifiedpixelformatandreturnsthepixelvalueasa32-bitint.
Iftheformathasapalette(8-bit)theindexoftheclosestmatchingcolorinthepalettewillbereturned.
Ifthespecifiedpixelformathasnoalphacomponentthealphavaluewillbeignored(asitwillbeinformatswithapalette).
ReturnValue
ApixelvaluebestapproximatingthegivenRGBAcolorvalueforagivenpixelformat.Ifthepixelformatbpp(colordepth)islessthan32-bppthentheunusedupperbitsofthereturnvaluecansafelybeignored(e.g.,witha16-bppformatthereturnvaluecanbeassignedtoaUint16,andsimilarlyaUint8foran8-bppformat).
Description
GetRGBcomponentvaluesfromapixelstoredinthespecifiedpixelformat.
Thisfunctionusestheentire8-bit[0..255]rangewhenconvertingcolorcomponentsfrompixelformatswithlessthan8-bitsperRGBcomponent(e.g.,acompletelywhitepixelin16-bitRGB565formatwouldreturn[0xff,0xff,0xff]not[0xf8,0xfc,0xf8]).
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
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.
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
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.
Description
FreestheresourcesusedbyapreviouslycreatedSDL_Surface.IfthesurfacewascreatedusingSDL_CreateRGBSurfaceFromthenthepixeldataisnotfreed.
SeeAlso
SDL_CreateRGBSurfaceSDL_CreateRGBSurfaceFrom
Prev Home NextSDL_CreateRGBSurfaceFrom Up SDL_LockSurface
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*/
.
.
Description
SurfacesthatwerepreviouslylockedusingSDL_LockSurfacemustbeunlockedwithSDL_UnlockSurface.Surfacesshouldbeunlockedassoonaspossible.
Itshouldbenotedthatsince1.1.8,surfacelocksarerecursive.SeeSDL_LockSurface.
Description
Setsthecolorkey(transparentpixel)inablittablesurfaceandenablesordisablesRLEblitacceleration.
RLEaccelerationcansubstantiallyspeedupblittingofimageswithlargehorizontalrunsoftransparentpixels(i.e.,pixelsthatmatchthekeyvalue).Thekeymustbeofthesamepixelformatasthesurface,SDL_MapRGBisoftenusefulforobtaininganacceptablevalue.
IfflagisSDL_SRCCOLORKEYthenkeyisthetransparentpixelvalueinthesourceimageofablit.
IfflagisOR'dwithSDL_RLEACCELthenthesurfacewillbedrawusingRLEaccelerationwhendrawnwithSDL_BlitSurface.ThesurfacewillactuallybeencodedforRLEaccelerationthefirsttimeSDL_BlitSurfaceorSDL_DisplayFormatiscalledonthesurface.
Ifflagis0,thisfunctionclearsanycurrentcolorkey.
SeeAlso
SDL_BlitSurface,SDL_DisplayFormat,SDL_MapRGB,SDL_SetAlpha
Prev Home NextSDL_SaveBMP Up SDL_SetAlpha
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
SeeAlso
SDL_MapRGBA,SDL_GetRGBA,SDL_DisplayFormatAlpha,SDL_BlitSurface
Prev Home NextSDL_SetColorKey Up SDL_SetClipRect
Description
Setstheclippingrectangleforasurface.Whenthissurfaceisthedestinationofablit,onlytheareawithinthecliprectanglewillbedrawninto.
Therectanglepointedtobyrectwillbeclippedtotheedgesofthesurfacesothatthecliprectangleforasurfacecanneverfalloutsidetheedgesofthesurface.
IfrectisNULLtheclippingrectanglewillbesettothefullsizeofthesurface.
Description
Getstheclippingrectangleforasurface.Whenthissurfaceisthedestinationofablit,onlytheareawithinthecliprectangleisdrawninto.
Therectanglepointedtobyrectwillbefilledwiththeclippingrectangleofthesurface.
SeeAlso
SDL_SetClipRect,SDL_BlitSurface,SDL_Surface
Prev Home NextSDL_SetClipRect Up SDL_ConvertSurface
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.
SeeAlso
SDL_CreateRGBSurface,SDL_DisplayFormat,SDL_PixelFormat,SDL_Surface
Prev Home NextSDL_GetClipRect Up SDL_BlitSurface
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
Description
Thisfunctionperformsafastfillofthegivenrectanglewithcolor.IfdstrectisNULL,thewholesurfacewillbefilledwithcolor.
Thecolorshouldbeapixeloftheformatusedbythesurface,andcanbegeneratedbytheSDL_MapRGBorSDL_MapRGBAfunctions.Ifthecolorvaluecontainsanalphavaluethenthedestinationissimply"filled"withthatalphainformation,noblendingtakesplace.
Ifthereisacliprectanglesetonthedestination(setviaSDL_SetClipRect)thenthisfunctionwillclipbasedontheintersectionofthecliprectangleandthedstrectrectangleandthedstrectrectanglewillbemodifiedtorepresenttheareaactuallyfilled.
SeeAlso
SDL_MapRGB,SDL_MapRGBA,SDL_BlitSurface,SDL_Rect
Prev Home NextSDL_BlitSurface Up SDL_DisplayFormat
Description
Thisfunctiontakesasurfaceandcopiesittoanewsurfaceofthepixelformatandcolorsofthevideoframebuffer,suitableforfastblittingontothedisplaysurface.ItcallsSDL_ConvertSurface
Ifyouwanttotakeadvantageofhardwarecolorkeyoralphablitacceleration,youshouldsetthecolorkeyandalphavaluebeforecallingthisfunction.
Ifyouwantanalphachannel,seeSDL_DisplayFormatAlpha.
SeeAlso
SDL_ConvertSurface,SDL_DisplayFormatAlphaSDL_SetAlpha,SDL_SetColorKey,SDL_Surface
Prev Home NextSDL_FillRect Up SDL_DisplayFormatAlpha
Description
Thisfunctiontakesasurfaceandcopiesittoanewsurfaceofthepixelformatandcolorsofthevideoframebufferplusanalphachannel,suitableforfastblittingontothedisplaysurface.ItcallsSDL_ConvertSurface
Ifyouwanttotakeadvantageofhardwarecolorkeyoralphablitacceleration,youshouldsetthecolorkeyandalphavaluebeforecallingthisfunction.
Thisfunctioncanbeusedtoconvertacolourkeytoanalphachannel,iftheSDL_SRCCOLORKEYflagissetonthesurface.Thegeneratedsurfacewillthenbetransparent(alpha=0)wherethepixelsmatchthecolourkey,andopaque(alpha=255)elsewhere.
SeeAlso
SDL_ConvertSurface,SDL_SetAlpha,SDL_SetColorKey,SDL_DisplayFormat,SDL_Surface
Prev Home NextSDL_DisplayFormat Up SDL_WarpMouse
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);
}
Description
Setsthecurrentlyactivecursortothespecifiedone.Ifthecursoriscurrentlyvisible,thechangewillbeimmediatelyrepresentedonthedisplay.
Description
Togglewhetherornotthecursorisshownonthescreen.PassingSDL_ENABLEdisplaysthecursorandpassingSDL_DISABLEhidesit.ThecurrentstateofthemousecursorcanbequeriedbypassingSDL_QUERY,eitherSDL_DISABLEorSDL_ENABLEwillbereturned.
Thecursorstartsoffdisplayed,butcanbeturnedoff.
Description
Ifyouwish,youmayloadtheOpenGLlibraryatruntime,thismustbedonebeforeSDL_SetVideoModeiscalled.ThepathoftheGLlibraryispassedtoSDL_GL_LoadLibraryanditreturns0onsuccess,or-1onanerror.YoumustthenuseSDL_GL_GetProcAddresstoretrievefunctionpointerstoGLfunctions.
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{
.
.
}
Description
PlacesthevalueoftheSDL/OpenGLattributeattrintovalue.ThisisusefulafteracalltoSDL_SetVideoModetocheckwhetheryourattributeshavebeensetasyouexpected.
Description
SetstheOpenGLattributeattrtovalue.Theattributesyousetdon'ttakeeffectuntilafteracalltoSDL_SetVideoMode.YoushoulduseSDL_GL_GetAttributetocheckthevaluesafteraSDL_SetVideoModecall.
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_SetVideoMode,SDL_GL_SetAttribute
Prev Home NextSDL_GL_SetAttribute Up SDL_CreateYUVOverlay
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
Description
MuchthesameasSDL_LockSurface,SDL_LockYUVOverlaylockstheoverlayfordirectaccesstopixeldata.
SeeAlso
SDL_UnlockYUVOverlay,SDL_CreateYUVOverlay,SDL_Overlay
Prev Home NextSDL_CreateYUVOverlay Up SDL_UnlockYUVOverlay
Description
TheoppositetoSDL_LockYUVOverlay.Unlocksapreviouslylockedoverlay.Anoverlaymustbeunlockedbeforeitcanbedisplayed.
SeeAlso
SDL_UnlockYUVOverlay,SDL_CreateYUVOverlay,SDL_Overlay
Prev Home NextSDL_LockYUVOverlay Up SDL_DisplayYUVOverlay
Description
Blittheoverlaytothesurfacespecifiedwhenitwascreated.TheSDL_Rectstructure,dstrect,specifiesthepositionandsizeofthedestination.Ifthedstrectisalargerorsmallerthantheoverlaythentheoverlaywillbescaled,thisisoptimizedfor2xscaling.
SeeAlso
SDL_Overlay,SDL_DisplayYUVOverlay,SDL_FreeYUVOverlay
Prev Home NextSDL_DisplayYUVOverlay Up SDL_GLattr
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.
Description
ASDL_Rectdefinesarectangularareaofpixels.ItisusedbySDL_BlitSurfacetodefineblittingregionsandbyseveralothervideofunctions.
Description
SDL_Colordescribesacolorinaformatindependentway.YoucanconvertaSDL_ColortoapixelvalueforacertainpixelformatusingSDL_MapRGB.
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
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);
.
.
.
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
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.
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
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
Description
Setstheiconforthedisplaywindow.Win32iconsmustbe32x32.
ThisfunctionmustbecalledbeforethefirstcalltoSDL_SetVideoMode.
Ittakesaniconsurface,andamaskinMSBformat.
IfmaskisNULL,theentireiconsurfacewillbeusedastheicon.
Description
IftheapplicationisrunninginawindowmanagedenvironmentSDLattemptstoiconify/minimiseit.IfSDL_WM_IconifyWindowissuccessful,theapplicationwillreceiveaSDL_APPACTIVElossevent.
ReturnValue
Returnsnon-zeroonsuccessor0ificonificationisnotsupportorwasrefusedbythewindowmanager.
Prev Home NextSDL_WM_SetIcon Up SDL_WM_ToggleFullScreen
Description
Togglestheapplicationbetweenwindowedandfullscreenmode,ifsupported.(X11istheonlytargetcurrentlysupported,BeOSsupportisexperimental).
Description
Grabbingmeansthatthemouseisconfinedtotheapplicationwindow,andnearlyallkeyboardinputispasseddirectlytotheapplication,andnotinterpretedbyawindowmanager,ifany.
WhenmodeisSDL_GRAB_QUERYthegrabmodeisnotchanged,butthecurrentgrabmodeisreturned.
typedefenum{
SDL_GRAB_QUERY,
SDL_GRAB_OFF,
SDL_GRAB_ON
}SDL_GrabMode;
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.
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
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
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.
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
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.
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.
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
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
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
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
Description
SDL_ResizeEventisamemberoftheSDL_EventunionandisusedwhenaneventoftypeSDL_VIDEORESIZEisreported.
WhenSDL_RESIZABLEispassedasaflagtoSDL_SetVideoModetheuserisallowedtoresizetheapplicationswindow.WhenthewindowisresizedanSDL_VIDEORESIZEisreport,withthenewwindowwidthandheightvaluesstoredinwandh,respectively.WhenanSDL_VIDEORESIZEisrecievedthewindowshouldberesizedtothenewdimensionsusingSDL_SetVideoMode.
Description
SDL_ExposeEventisamemberoftheSDL_EventunionandisusedwhananeventoftypeSDL_VIDEOEXPOSEisreported.
AVIDEOEXPOSEeventistriggeredwhenthescreenhasbeenmodifiedoutsideoftheapplication,usuallybythewindowmanagerandneedstoberedrawn.
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);
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);
Description
SDL_QuitEventisamemberoftheSDL_EventunionandisusedwhananeventoftypeSDL_QUITisreported.
Ascanbeseen,theSDL_QuitEventstructureservesnousefulpurpose.Theeventitself,ontheotherhand,isveryimportant.Ifyoufilteroutorignoreaquiteventthenitisimpossiblefortheusertoclosethewindow.Ontheotherhand,ifyoudoacceptaquiteventthentheapplicationwindowwillbeclosed,andscreenupdateswillstillreportsuccesseventthoughtheapplicationwillnolongerbevisible.
Note:ThemacroSDL_QuitRequestedwillreturnnon-zeroifaquiteventispending
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.
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
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
Description
Pumpstheeventloop,gatheringeventsfromtheinputdevices.
SDL_PumpEventsgathersallthependinginputinformationfromdevicesandplacesitontheeventqueue.WithoutcallstoSDL_PumpEventsnoeventswouldeverbeplacedonthequeue.OftencallstheneedforSDL_PumpEventsishiddenfromtheusersinceSDL_PollEventandSDL_WaitEventimplicitlycallSDL_PumpEvents.However,ifyouarenotpollingorwaitingforevents(e.g.yourfilteringthem),thenyoumustcallSDL_PumpEventstoforceaneventqueueupdate.
Note:Youcanonlycallthisfunctioninthethreadthatsetthevideomode.
Description
Waitsindefinitelyforthenextavailableevent,returning1,or0iftherewasanerrorwhilewaitingforevents.
IfeventisnotNULL,thenexteventisremovedfromthequeueandstoredinthatarea.
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.
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");
}
}
Description
Theeventqueuecanactuallybeusedasatwowaycommunicationchannel.Notonlycaneventsbereadfromthequeue,buttheusercanalsopushtheirowneventsontoit.eventisapointertotheeventstructureyouwishtopushontothequeue.
Note:Pushingdeviceinputeventsontothequeuedoesn'tmodifythestateofthedevicewithinSDL.
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
Description
ThisfunctionretriecesapointertotheeventfilterthatwaspreviouslysetusingSDL_SetEventFilter.AnSDL_EventFilterfunctionisdefinedas:
typedefint(*SDL_EventFilter)(constSDL_Event*event);
Description
Thisfunctionallowsyoutosetthestateofprocessingcertaineventtype's.
IfstateissettoSDL_IGNORE,thateventtypewillbeautomaticallydroppedfromtheeventqueueandwillnotbefiltered.
IfstateissettoSDL_ENABLE,thateventtypewillbeprocessednormally.
IfstateissettoSDL_QUERY,SDL_EventStatewillreturnthecurrentprocessingstateofthespecifiedeventtype.
Alistofeventtype'scanbefoundintheSDL_Eventsection.
Description
Getsasnapshotofthecurrentkeyboardstate.Thecurrentstateisreturnasapointertoanarray,thesizeofthisarrayisstoredinnumkeys.ThearrayisindexedbytheSDLK_*symbols.Avalueof1meansthekeyispressedandavalueof0meansitsnot.ThepointerreturnedisapointertoaninternalSDLarrayandshouldnotbefreedbythecaller.
Note:UseSDL_PumpEventstoupdatethestatearray.
ExampleUint8*keystate=SDL_GetKeyState(NULL);
if(keystate[SDLK_RETURN])printf("ReturnKeyPressed.\n");
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)
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;
Description
Enables/DisablesUnicodekeyboardtranslation.
Toobtainthecharactercodescorrespondingtoreceivedkeyboardevents,Unicodetranslationmustfirstbeturnedonusingthisfunction.Thetranslationincursaslightoverheadforeachkeyboardeventandisthereforedisabledbydefault.Foreachsubsequentlyreceivedkeydownevent,theunicodememberoftheSDL_keysymstructurewillthencontainthecorrespondingcharactercode,orzeroforkeysymsthatdonotcorrespondtoanycharactercode.
Avalueof1forenableenablesUnicodetranslation;0disablesit,and-1leavesitunchanged(usefulforqueryingthecurrenttranslationmode).
Notethatonlykeypresseventswillbetranslated,notreleaseevents.
Description
Enablesordisablesthekeyboardrepeatrate.delayspecifieshowlongthekeymustbepressedbeforeitbeginsrepeating,itthenrepeatsatthespeedspecifiedbyinterval.Bothdelayandintervalareexpressedinmilliseconds.
Settingdelayto0disableskeyrepeatingcompletely.GooddefaultvaluesareSDL_DEFAULT_REPEAT_DELAYandSDL_DEFAULT_REPEAT_INTERVAL.
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
Description
Thecurrentbuttonstateisreturnedasabuttonbitmask,whichcanbetestedusingtheSDL_BUTTON(X)macros,andxandyaresettothechangeinthemousepositionsincethelastcalltoSDL_GetRelativeMouseStateorsinceeventinitialization.YoucanpassNULLforeitherxory.
Description
Thisfunctionreturnsthecurrentstateoftheapplication.Thevaluereturnedisabitwisecombinationof:
SDL_APPMOUSEFOCUS Theapplicationhasmousefocus.SDL_APPINPUTFOCUS TheapplicationhaskeyboardfocusSDL_APPACTIVE Theapplicationisvisible
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
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([email protected])is
solicitingsuggestionsfrompeoplewithforce-feedbackexperienceonthebestwattodesgintheAPI.
Prev Home NextSDL_JoystickEventState Up SDL_NumJoysticks
Description
Gettheimplementationdependentnameofjoystick.TheindexparameterreferstotheN'thjoystickonthesystem.
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));
Description
OpensajoystickforusewithinSDL.TheindexreferstotheN'thjoystickinthesystem.Ajoystickmustbeopenedbeforeitgamebeused.
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);
}
Description
Determineswhetherajoystickhasalreadybeenopenedwithintheapplication.indexreferstotheN'thjoystickonthesystem.
SeeAlso
SDL_JoystickGetAxis,SDL_JoystickOpen
Prev Home NextSDL_JoystickIndex Up SDL_JoystickNumBalls
SeeAlso
SDL_JoystickGetBall,SDL_JoystickOpen
Prev Home NextSDL_JoystickNumAxes Up SDL_JoystickNumHats
SeeAlso
SDL_JoystickGetHat,SDL_JoystickOpen
Prev Home NextSDL_JoystickNumBalls Up SDL_JoystickNumButtons
SeeAlso
SDL_JoystickGetButton,SDL_JoystickOpen
Prev Home NextSDL_JoystickNumHats Up SDL_JoystickUpdate
Description
Updatesthestate(position,buttons,etc.)ofallopenjoysticks.IfjoystickeventshavebeenenabledwithSDL_JoystickEventStatethenthisiscalledautomaticallyintheeventloop.
Description
SDL_JoystickGetAxisreturnsthecurrentstateofthegivenaxisonthegivenjoystick.
OnmostmodernjoystickstheXaxisisusuallyrepresentedbyaxis0andtheYaxisbyaxis1.ThevaluereturnedbySDL_JoystickGetAxisisasignedinteger(-32768to32768)representingthecurrentpositionoftheaxis,itmaybenecessarytoimposecertaintolerancesonthesevaluestoaccountforjitter.Itisworthnotingthatsomejoysticksuseaxes2and3forextrabuttons.
ExamplesSint16x_move,y_move;
SDL_Joystick*joy1;
.
.
x_move=SDL_JoystickGetAxis(joy1,0);
y_move=SDL_JoystickGetAxis(joy1,1);
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
Description
Gettheballaxischange.
TrackballscanonlyreturnrelativemotionsincethelastcalltoSDL_JoystickGetBall,thesemotiondeltasaplacedintodxanddy.
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);
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
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.
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*/
SeeAlso
SDL_AudioSpec,SDL_LockAudio,SDL_UnlockAudio,SDL_PauseAudio
Prev Home NextSDL_AudioSpec Up SDL_PauseAudio
Description
Thisfunctionpausesandunpausestheaudiocallbackprocessing.Itshouldbecalledwithpause_on=0afteropeningtheaudiodevicetostartplayingsound.Thisissoyoucansafelyinitializedataforyourcallbackfunctionafteropeningtheaudiodevice.Silencewillbewrittentotheaudiodeviceduringthepause.
Descriptiontypedefenum{
SDL_AUDIO_STOPPED,
SDL_AUDIO_PAUSED,
SDL_AUDIO_PLAYING
}SDL_audiostatus;
ReturnseitherSDL_AUDIO_STOPPED,SDL_AUDIO_PAUSEDorSDL_AUDIO_PLAYINGdependingonthecurrentaudiostate.
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);
Description
AfteraWAVEfilehasbeenopenedwithSDL_LoadWAVitsdatacaneventuallybefreedwithSDL_FreeWAV.audio_bufisapointertothebuffercreatedbySDL_LoadWAV.
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
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.
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*/
.
.
.
.
Description
Thisfunctiontakestwoaudiobuffersoflenbyteseachoftheplayingaudioformatandmixesthem,performingaddition,volumeadjustment,andoverflowclipping.Thevolumerangesfrom0toSDL_MIX_MAXVOLUMEandshouldbesettothemaximumvalueforfullaudiovolume.Notethisdoesnotchangehardwarevolume.Thisisprovidedforconvenience--youcanmixyourownaudiodata.
Note:Donotusethisfunctionformixingtogethermorethantwostreamsofsampledata.Theoutputfromrepeatedapplicationofthisfunctionmaybedistortedbyclipping,becausethereisnoaccumulatorwithgreaterrangethantheinput(nottomentionthisbeinganinefficientwayofdoingit).UsemixingfunctionsfromSDL_mixer,OpenAL,orwriteyourownmixerinstead.
Description
Thelockmanipulatedbythesefunctionsprotectsthecallbackfunction.DuringaLockAudioperiod,youcanbeguaranteedthatthecallbackfunctionisnotrunning.Donotcallthesefromthecallbackfunctionoryouwillcausedeadlock.
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
Description
Returnsahuman-readable,system-dependentidentifierfortheCD-ROM.driveistheindexofthedrive.Driveindicesstartto0andendatSDL_CDNumDrives()-1.
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);
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;
}
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.
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);
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);
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.
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
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.
Description
Getthe32-bitthreadidentifierforthecurrentthread.
Prev Home NextSDL_CreateThread Up SDL_GetThreadID
Description
SDL_KillThreadgracelesslyterminatesthethreadassociatedwiththread.Ifpossible,youshouldusesomeotherformofIPCtosignalthethreadtoquit.
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);
Description
Locksthemutex,whichwaspreviouslycreatedwithSDL_CreateMutex.IfthemutexisalreadylockedthenSDL_mutexPwillnotreturnuntilitisunlocked.Returns0onsuccess,or-1onanerror.
SDLalsodefinesamacro#defineSDL_LockMutex(m)SDL_mutexP(m).
Description
Unlocksthemutex,whichwaspreviouslycreatedwithSDL_CreateMutex.Returns0onsuccess,or-1onanerror.
SDLalsodefinesamacro#defineSDL_UnlockMutex(m)SDL_mutexV(m).
Description
SDL_CreateSemaphore()createsanewsemaphoreandinitializesitwiththevalueinitial_value.EachlockingoperationonthesemaphorebySDL_SemWait,SDL_SemTryWaitorSDL_SemWaitTimeoutwillatomicallydecrementthesemaphorevalue.Thelockingoperationwillbeblockedifthesemaphorevalueisnotpositive(greaterthanzero).EachunlockoperationbySDL_SemPostwillatomicallyincrementthesemaphorevalue.
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
Description
SDL_DestroySemaphoredestroysthesemaphorepointedtobysemthatwascreatedbySDL_CreateSemaphore.Itisnotsafetodestroyasemaphoreiftherearethreadscurrentlyblockedwaitingonit.
SeeAlso
SDL_CreateSemaphore,SDL_SemWait,SDL_SemTryWait,SDL_SemWaitTimeout,SDL_SemPost,SDL_SemValue
Prev Home NextSDL_CreateSemaphore Up SDL_SemWait
Description
SDL_SemWait()suspendsthecallingthreaduntileitherthesemaphorepointedtobysemhasapositivevalue,thecallisinterruptedbyasignalorerror.Ifthecallissuccessfulitwillatomicallydecrementthesemaphorevalue.
AfterSDL_SemWait()issuccessful,thesemaphorecanbereleasedanditscountatomicallyincrementedbyasuccessfulcalltoSDL_SemPost.
SeeAlso
SDL_CreateSemaphore,SDL_DestroySemaphore,SDL_SemTryWait,SDL_SemWaitTimeout,SDL_SemPost,SDL_SemValue
Prev Home NextSDL_DestroySemaphore Up SDL_SemTryWait
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
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
Description
SDL_SemPostunlocksthesemaphorepointedtobysemandatomicallyincrementsthesemaphoresvalue.Threadsthatwereblockingonthesemaphoremaybescheduledafterthiscallsucceeds.
SDL_SemPostshouldbecalledafterasemaphoreislockedbyasuccessfulcalltoSDL_SemWait,SDL_SemTryWaitorSDL_SemWaitTimeout.
SeeAlso
SDL_CreateSemaphore,SDL_DestroySemaphore,SDL_SemWait,SDL_SemTryWait,SDL_SemWaitTimeout,SDL_SemValue
Prev Home NextSDL_SemWaitTimeout Up SDL_SemValue
SeeAlso
SDL_CreateSemaphore,SDL_DestroySemaphore,SDL_SemWait,SDL_SemTryWait,SDL_SemWaitTimeout,SDL_SemPost
Prev Home NextSDL_SemPost Up SDL_CreateCond
Description
Restartoneofthethreadsthatarewaitingontheconditionvariable,cond.Returns0onsuccessof-1onanerror.
Description
Restartsallthreadsthatarewaitingontheconditionvariable,cond.Returns0onsuccess,or-1onanerror.
Description
Waitontheconditionvariablecondandunlocktheprovidedmutex.Themutexmustthelockedbeforeenteringthisfunction.Returns0whenitissignalled,or-1onanerror.
SeeAlso
SDL_CondWaitTimeout,SDL_CondSignal,SDL_mutexP
Prev Home NextSDL_CondBroadcast Up SDL_CondWaitTimeout
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.
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
Description
GetthenumberofmillisecondssincetheSDLlibraryinitialization.Notethatthisvaluewrapsiftheprogramrunsformorethan~49days.
Description
Waitaspecifiednumberofmillisecondsbeforereturning.SDL_Delaywillwaitatleastthespecifiedtime,butpossiblelongerduetoOSscheduling.
Note:Countonadelaygranularityofatleast10ms.Someplatformshaveshorterclockticksbutthisisthemostcommon.
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.
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.