#include "SDL_internal.h"
#include "../SDL_main_callbacks.h"
#include <emscripten.h>
static Uint32 callback_rate_increment = 0;
static bool iterate_after_waitevent = false;
static bool callback_rate_changed = false;
static void SDLCALL MainCallbackRateHintChanged(void *userdata, const char *name, const char *oldValue, const char *newValue)
{
callback_rate_changed = true;
iterate_after_waitevent = newValue && (SDL_strcmp(newValue, "waitevent") == 0);
if (iterate_after_waitevent) {
callback_rate_increment = 0;
} else {
const double callback_rate = newValue ? SDL_atof(newValue) : 0.0;
if (callback_rate > 0.0) {
callback_rate_increment = (Uint32) SDL_NS_TO_MS((double) SDL_NS_PER_SECOND / callback_rate);
} else {
callback_rate_increment = 0;
}
}
}
static bool saw_new_event = false;
static bool SDLCALL EmscriptenMainCallbackEventWatcher(void *userdata, SDL_Event *event)
{
saw_new_event = true;
return true;
}
static void EmscriptenInternalMainloop(void)
{
if (callback_rate_changed) {
callback_rate_changed = false;
if (callback_rate_increment == 0) {
emscripten_set_main_loop_timing(EM_TIMING_RAF, 1);
} else {
emscripten_set_main_loop_timing(EM_TIMING_SETTIMEOUT, callback_rate_increment);
}
}
if (iterate_after_waitevent) {
SDL_PumpEvents();
if (!saw_new_event) {
return;
}
saw_new_event = false;
}
const SDL_AppResult rc = SDL_IterateMainCallbacks(!iterate_after_waitevent);
if (rc != SDL_APP_CONTINUE) {
SDL_QuitMainCallbacks(rc);
emscripten_cancel_main_loop(); exit((rc == SDL_APP_FAILURE) ? 1 : 0); }
}
int SDL_EnterAppMainCallbacks(int argc, char *argv[], SDL_AppInit_func appinit, SDL_AppIterate_func appiter, SDL_AppEvent_func appevent, SDL_AppQuit_func appquit)
{
SDL_AppResult rc = SDL_InitMainCallbacks(argc, argv, appinit, appiter, appevent, appquit);
if (rc == SDL_APP_CONTINUE) {
if (!SDL_AddEventWatch(EmscriptenMainCallbackEventWatcher, NULL)) {
rc = SDL_APP_FAILURE;
} else {
SDL_AddHintCallback(SDL_HINT_MAIN_CALLBACK_RATE, MainCallbackRateHintChanged, NULL);
callback_rate_changed = false;
emscripten_set_main_loop(EmscriptenInternalMainloop, 0, 0); if (callback_rate_increment > 0.0) {
emscripten_set_main_loop_timing(EM_TIMING_SETTIMEOUT, callback_rate_increment);
}
}
} else {
SDL_QuitMainCallbacks(rc);
}
return (rc == SDL_APP_FAILURE) ? 1 : 0;
}