Hello everyone!
I have been playing around with SDL, and was looking to make use of some custom user events for gamestate management.
The idea is that gamestates are stored in a stack, with the topmost being the one that can handle events/be updated/drawn/etc. If something were to trigger a gamestate change (for example, pressing the “P” key would pause the game), then a relevant custom user-event would be pushed onto the queue and then operated on.
The issue I’ve run into is that the event is operated on at a later time, in a different frame than the one it was pushed in. SDL_PollEvent seems to only grab one event at a time.
I took some timing, and the delay between when an event would be pushed and when it would be handled when using SDL_PollEvent was between 2ms and 30ms(if I were to move the mouse around to generate fake events).
However, when I started using SDL_WaitEventTimeout with a delay of 1ms, the pushed events were handled almost immediately, even with noise generated. It was consistently pushed and handled within 1-2ms, sometimes less than 1ms.
Is there a reason to not use SDL_WaitEvent with a delay of 1ms over SDL_PollEvent?
Would a delay of ~20ms for a custom event to change state(like pause the game) even be noticable or “feel off”, or am I just optimizing prematurely? My gut says that a 20ms delay will make it feel off.
Here’s a snippet of what I’m doing:
Uint32 myEventType = SDL_RegisterEvents(1);
SDL_Event event;
SDL_memset(&event, 0, sizeof(event)); /* or SDL_zero(event) */
event.type = myEventType;
while (1)
{
while (SDL_WaitEventTimeout(&ev, 1))
// while (SDL_PollEvent(&ev))
{
if (ev.type == SDL_QUIT)
{
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
else if (ev.type == SDL_KEYDOWN)
{
std::cout << "Pushing event, recieved at" << ev.key.timestamp << "\n";
event.user.timestamp = SDL_GetTicks();
// SDL_PeepEvents(&event, 1, SDL_ADDEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT);
SDL_PeepEvents(&event, 1, SDL_ADDEVENT, SDL_FIRSTEVENT, SDL_LASTEVENT);
}
else if (ev.type == SDL_USEREVENT)
{
std::cout << "User Event at " << ev.user.timestamp << "\n";
std::cout << "Current ticks: " << SDL_GetTicks() << "\n";
}
}
std::cout << "Frame\n";
SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}