Add an SDL timer

This commit is contained in:
Joshua Granick
2014-06-10 08:43:47 -07:00
parent 090c3cba28
commit 09e3637918
2 changed files with 52 additions and 9 deletions

View File

@@ -16,7 +16,7 @@ namespace lime {
SDLApplication::SDLApplication () {
SDL_Init (SDL_INIT_VIDEO);
SDL_Init (SDL_INIT_VIDEO | SDL_INIT_TIMER);
}
@@ -28,14 +28,39 @@ namespace lime {
}
static SDL_TimerID timerID = 0;
bool timerActive = false;
Uint32 OnTimer (Uint32 interval, void *) {
SDL_Event event;
SDL_UserEvent userevent;
userevent.type = SDL_USEREVENT;
userevent.code = 0;
userevent.data1 = NULL;
userevent.data2 = NULL;
event.type = SDL_USEREVENT;
event.user = userevent;
timerActive = false;
timerID = 0;
SDL_PushEvent (&event);
return 0;
}
int SDLApplication::Exec () {
SDL_Event event;
active = true;
bool firstTime = true;
lastUpdate = SDL_GetTicks ();
Uint32 currentUpdate = 0;
int deltaTime = 0;
bool firstTime = true;
Uint32 nextUpdate = lastUpdate;
while (active) {
@@ -45,6 +70,14 @@ namespace lime {
firstTime = false;
if (timerActive && timerID) {
SDL_RemoveTimer (timerID);
timerActive = false;
timerID = 0;
}
HandleEvent (&event);
event.type = -1;
if (!active) break;
@@ -58,14 +91,15 @@ namespace lime {
}
currentUpdate = SDL_GetTicks ();
deltaTime = currentUpdate - lastUpdate;
if (deltaTime > 16) {
if (currentUpdate - lastUpdate < 16) {
updateEvent.deltaTime = deltaTime;
UpdateEvent::Dispatch (&updateEvent);
timerActive = true;
timerID = SDL_AddTimer (lastUpdate + 16 - currentUpdate, OnTimer, 0);
RenderEvent::Dispatch (&renderEvent);
} else {
OnTimer (0, 0);
}
@@ -87,6 +121,14 @@ namespace lime {
switch (event->type) {
case SDL_USEREVENT:
currentUpdate = SDL_GetTicks ();
updateEvent.deltaTime = currentUpdate - lastUpdate;
UpdateEvent::Dispatch (&updateEvent);
RenderEvent::Dispatch (&renderEvent);
break;
case SDL_JOYAXISMOTION:
case SDL_JOYBALLMOTION:
case SDL_JOYBUTTONDOWN:

View File

@@ -33,6 +33,7 @@ namespace lime {
void ProcessWindowEvent (SDL_Event* event);
bool active;
Uint32 currentUpdate;
KeyEvent keyEvent;
Uint32 lastUpdate;
MouseEvent mouseEvent;