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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
|
#include "teensy_context.h"
#include <math.h>
#include <stdarg.h>
#include <time.h>
#include "teensy_platform.h"
#include "teensy_renderer.h"
ty_Ctx ctx;
bool is_init(void)
{
int scr_size = ctx.hints.scr_width * ctx.hints.scr_height;
return scr_size > 0;
}
void ty_init(ty_Hints hints)
{
ty_init_mem();
ctx.hints = hints;
ctx.ticrate = 1.0 / hints.ticrate;
ctx.prev_tic_ts = 0;
ty_platform_init(&ctx);
ty_init_renderer();
}
void ty_deinit(void)
{
assert(is_init());
ty_platform_deinit();
ty_deinit_renderer();
ty_deinit_mem();
}
bool ty_button_down(ty_Button btn)
{
assert(btn < TY_BTN_COUNT);
return ctx.down[btn];
}
bool ty_button_pressed(ty_Button btn)
{
assert(btn < TY_BTN_COUNT);
return ctx.pressed[btn];
}
ty_Vec2i ty_mouse_pos(void)
{
return ty_platform_get_mouse();
}
bool ty_is_game_running(void)
{
assert(is_init());
return !ty_platform_os_wants_quit();
}
double ty_get_time(void)
{
assert(is_init());
return ty_platform_get_time();
}
static
void update_buttons(void)
{
for (int btn = 0; btn < TY_BTN_COUNT; btn++) {
bool down = ty_platform_is_button_down(btn);
ctx.pressed[btn] = down && !ctx.down[btn];
ctx.down[btn] = down;
}
}
int ty_tick(void)
{
assert(is_init());
double current_time = ty_get_time();
double time_since_tic = current_time - ctx.prev_tic_ts;
int tics = time_since_tic / ctx.ticrate;
if (tics > 0) {
update_buttons();
ctx.prev_tic_ts = current_time;
ty_platform_frame(r.screen);
}
return tics;
}
// TODO: Find a better place for this
void ty_sleep(uint64_t ms)
{
assert(is_init());
struct timespec ts;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000000;
nanosleep(&ts, NULL);
}
char *ty_format_args(const char *fmt, va_list list)
{
va_list args;
va_copy(args, list);
int len = vsnprintf(NULL, 0, fmt, args);
char *text = ty_talloc(sizeof(char) * (len + 1));
va_end(args);
va_copy(args, list);
vsnprintf(text, len + 1, fmt, args);
va_end(args);
return text;
}
char *ty_format(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
char *text = ty_format_args(fmt, args);
va_end(args);
return text;
}
|