summaryrefslogtreecommitdiff
path: root/lib/timer.c
blob: 8b7b221cc1620dfe77c96689e170ac7df7200604 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <cetris.h>

#ifdef _WIN32
#include <windows.h>

#if CETRIS_HI_RES
DWORD WINAPI cetris_game_loop(void* data) {
  cetris_game* game = (cetris_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 (!update_game_tick(game)) {
	    break;
    }
    Sleep(1);
  }
  return 0;
}
#else
DWORD WINAPI cetris_game_loop(void* data) {
  cetris_game* game = (cetris_game*)data;
  while(1) {
    if (game->waiting) break;
    game->tick += 16;
    if (!update_game_tick(game)) {
	    break;
    }
    Sleep(16); // little less than 60hz
  }
}
#endif
CETRIS_EXPORT void cetris_start_game(cetris_game *g) {
  g->waiting = false;
  HANDLE thread = CreateThread(NULL, 0, cetris_game_loop, g, 0, NULL);
}
CETRIS_EXPORT void cetris_stop_game(cetris_game *g) {
  init_game(g, NULL);
}
#else
#include <pthread.h>
#include <unistd.h>

#if CETRIS_HI_RES
#include <time.h>
void *cetris_game_loop(void* data) {
  cetris_game *game = (cetris_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 (!update_game_tick(game)) {
	    break;
    }
    usleep(1000);
  }
  return 0;
}
#else
void *cetris_game_loop(void *data) {
  cetris_game* game = (cetris_game*)data;
  while(1) {
    if (game->waiting) break;
    game->tick += 16;
    if (!update_game_tick(game)) {
	    break;
    }
    // could be more accurate, keeping
    // it consistant with windows
    usleep(16000);
  }
}
#endif
CETRIS_EXPORT void cetris_start_game(cetris_game *g) {
  g->waiting = false;
  pthread_t thread;
  pthread_create(&thread, NULL, cetris_game_loop, (void*)g);
}
CETRIS_EXPORT void cetris_stop_game(cetris_game *g) {
  init_game(g, NULL);
}
#endif