prosperon/source/engine/timer.c

87 lines
1.5 KiB
C
Raw Normal View History

2022-06-21 12:48:19 -05:00
#include "timer.h"
2023-01-18 17:15:36 -06:00
#include "log.h"
2023-05-12 13:22:05 -05:00
#include <stdlib.h>
2022-06-21 12:48:19 -05:00
#include <stb_ds.h>
2022-06-21 12:48:19 -05:00
2022-08-25 15:48:15 -05:00
struct timer *timers;
2023-03-05 22:05:22 -06:00
static int first = -1;
2022-08-22 08:55:54 -05:00
2023-05-12 13:22:05 -05:00
void check_timer(struct timer *t, double dt) {
if (!t->on)
return;
2022-12-28 16:50:54 -06:00
2023-05-12 13:22:05 -05:00
t->remain_time -= dt;
2022-08-22 08:55:54 -05:00
2023-05-12 13:22:05 -05:00
if (t->remain_time <= 0) {
t->cb(t->data);
if (t->repeat) {
t->remain_time = t->interval;
return;
2022-08-22 08:55:54 -05:00
}
2023-05-12 13:22:05 -05:00
timer_pause(t);
return;
}
2022-06-21 12:48:19 -05:00
}
2022-12-28 16:50:54 -06:00
void timer_update(double dt) {
2023-05-12 13:22:05 -05:00
for (int i = 0; i < arrlen(timers); i++)
check_timer(&timers[i], dt);
2022-08-25 15:48:15 -05:00
}
2022-08-22 08:55:54 -05:00
2023-03-17 10:25:35 -05:00
int timer_make(double interval, void (*callback)(void *param), void *param, int own) {
2023-05-12 13:22:05 -05:00
struct timer new;
new.remain_time = interval;
new.interval = interval;
new.cb = callback;
new.data = param;
new.repeat = 1;
new.owndata = own;
new.next = -1;
if (first < 0) {
timer_start(&new);
arrput(timers, new);
return arrlen(timers) - 1;
} else {
int retid = first;
first = id2timer(first)->next;
*id2timer(retid) = new;
timer_start(id2timer(retid));
return retid;
}
2022-06-21 12:48:19 -05:00
}
2022-06-30 10:31:23 -05:00
void timer_pause(struct timer *t) {
2023-05-12 13:22:05 -05:00
if (!t->on) return;
t->on = 0;
2022-06-30 10:31:23 -05:00
}
2022-08-22 08:55:54 -05:00
void timer_stop(struct timer *t) {
2023-05-12 13:22:05 -05:00
if (!t->on) return;
t->on = 0;
t->remain_time = t->interval;
2022-08-22 08:55:54 -05:00
}
2022-06-30 10:31:23 -05:00
2022-08-22 08:55:54 -05:00
void timer_start(struct timer *t) {
2023-05-12 13:22:05 -05:00
if (t->on) return;
t->on = 1;
2022-06-30 10:31:23 -05:00
}
2023-03-17 10:25:35 -05:00
void timer_remove(int id) {
2023-05-12 13:22:05 -05:00
struct timer *t = id2timer(id);
if (t->owndata) free(t->data);
t->next = first;
first = id;
2022-08-22 08:55:54 -05:00
}
void timerr_settime(struct timer *t, double interval) {
2023-05-12 13:22:05 -05:00
t->remain_time += (interval - t->interval);
t->interval = interval;
2023-01-18 17:15:36 -06:00
}
2023-05-12 13:22:05 -05:00
struct timer *id2timer(int id) {
return &timers[id];
2023-03-05 22:05:22 -06:00
}