prosperon/source/engine/timer.c

100 lines
1.8 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>
2023-11-07 12:45:52 -06:00
#include "script.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
}
void timer_update(double dt, double scale) {
double sdt = dt*scale;
2023-05-12 13:22:05 -05:00
for (int i = 0; i < arrlen(timers); i++)
if (timers[i].app)
check_timer(&timers[i], dt);
else
check_timer(&timers[i], sdt);
2022-08-25 15:48:15 -05:00
}
2022-08-22 08:55:54 -05:00
int timer_make(double interval, void (*callback)(void *param), void *param, int own, int app) {
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;
new.app = app;
2023-05-12 13:22:05 -05:00
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);
2023-11-07 12:45:52 -06:00
free_callee(t->data);
2023-05-12 13:22:05 -05:00
t->next = first;
2023-05-29 10:47:30 -05:00
t->on = 0;
2023-05-12 13:22:05 -05:00
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
}
2023-11-07 12:45:52 -06:00
void timers_free()
{
for (int i = 0; i < arrlen(timers); i++)
free_callee(timers[i].data);
}