diff options
author | Lizzy Fleckenstein <lizzy@vlhl.dev> | 2024-06-19 18:07:47 +0200 |
---|---|---|
committer | Lizzy Fleckenstein <lizzy@vlhl.dev> | 2024-06-19 18:07:55 +0200 |
commit | 49948b4cc0f73d02a8932c525690a35e8efb6ac5 (patch) | |
tree | 1ee33d5393046939a37fdef00b3484e87ff3ec6d /src/ticker.c | |
parent | ead2881be92d33076c2104dbd75bad3561f26088 (diff) | |
download | silly_game-49948b4cc0f73d02a8932c525690a35e8efb6ac5.tar.xz |
add client
Signed-off-by: Lizzy Fleckenstein <lizzy@vlhl.dev>
Diffstat (limited to 'src/ticker.c')
-rw-r--r-- | src/ticker.c | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/ticker.c b/src/ticker.c new file mode 100644 index 0000000..d3c25b5 --- /dev/null +++ b/src/ticker.c @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: 2024 Lizzy Fleckenstein <lizzy@vlhl.dev> +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +#include "ticker.h" + +static struct timespec timestamp_now() +{ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); // TODO: handle error + return ts; +} + +static uint64_t timestamp_diff(struct timespec a, struct timespec b) +{ + return NANOS * ((uint64_t) a.tv_sec - b.tv_sec) + ((int64_t) a.tv_nsec - b.tv_nsec); +} + +void ticker_init(ticker *t, uint64_t f) +{ + t->freq_nanos = f; + t->timestamp = timestamp_now(); +} + +bool ticker_tick(ticker *t, uint64_t *dtime) +{ + struct timespec ts = timestamp_now(); + *dtime = timestamp_diff(ts, t->timestamp); + if (*dtime < t->freq_nanos) + return false; + t->timestamp = ts; + return true; +} + +// millis +int ticker_timeout(ticker *t) +{ + uint64_t nanos = timestamp_diff(timestamp_now(), t->timestamp); + if (t->freq_nanos > nanos) + return (t->freq_nanos - nanos) / 1000000; // nanos to millis + else + return 0; +} |