diff options
Diffstat (limited to 'frontends/timer.c')
| -rw-r--r-- | frontends/timer.c | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/frontends/timer.c b/frontends/timer.c new file mode 100644 index 0000000..9ae90ca --- /dev/null +++ b/frontends/timer.c @@ -0,0 +1,86 @@ +#ifdef _WIN32 +#include <windows.h> + +#if CETRIS_HI_RES +static DWORD WINAPI ctrs_game_loop(void* data) { + ctrs_game* game = (ctrs_game*)data; + LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds; + LARGE_INTEGER Frequency; + QueryPerformanceFrequency(&Frequency); + QueryPerformanceCounter(&StartingTime); + while(1) { + if (game->waiting) break; + QueryPerformanceCounter(&EndingTime); + ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart; + ElapsedMicroseconds.QuadPart *= 1000000; + ElapsedMicroseconds.QuadPart /= Frequency.QuadPart; + game->timer = ElapsedMicroseconds.QuadPart; + game->tick = ElapsedMicroseconds.QuadPart / 1000; + if (!ctrs_update_game_tick(game)) { + break; + } + Sleep(1); + } + return 0; +} +#else +static DWORD WINAPI ctrs_game_loop(void* data) { + ctrs_game* game = (ctrs_game*)data; + while(1) { + if (game->waiting) break; + game->tick += 16; + if (!ctrs_update_game_tick(game)) { + break; + } + Sleep(16); // little less than 60hz + } +} +#endif +static void ctrs_start_game(ctrs_game *g) { + g->waiting = false; + HANDLE thread = CreateThread(NULL, 0, ctrs_game_loop, g, 0, NULL); +} +#else +#include <pthread.h> +#include <unistd.h> + +#if CETRIS_HI_RES +#include <time.h> +static void *ctrs_game_loop(void* data) { + ctrs_game *game = (ctrs_game*)data; + struct timespec start_time, end_time; + clock_gettime(CLOCK_MONOTONIC_RAW, &start_time); + while (1) { + if (game->waiting) break; + clock_gettime(CLOCK_MONOTONIC_RAW, &end_time); + long nsec_elapsed = (end_time.tv_sec - start_time.tv_sec) * (long)1e9 + (end_time.tv_nsec - start_time.tv_nsec); + game->timer = nsec_elapsed / 1000; + game->tick = nsec_elapsed / 1000000; + if (!ctrs_update_game_tick(game)) { + break; + } + usleep(1000); + } + return 0; +} +#else +static void *ctrs_game_loop(void *data) { + ctrs_game* game = (ctrs_game*)data; + while(1) { + if (game->waiting) break; + game->tick += 16; + if (!ctrs_update_game_tick(game)) { + break; + } + // could be more accurate, keeping + // it consistant with windows + usleep(16000); + } +} +#endif +static void ctrs_start_game(ctrs_game *g) { + g->waiting = false; + pthread_t thread; + pthread_create(&thread, NULL, ctrs_game_loop, (void*)g); +} +#endif |