Fumofumotris/source/fumoengine/include/event.c

58 lines
1.2 KiB
C
Raw Normal View History

2024-04-22 22:13:13 +00:00
#include "event.h"
2024-04-03 23:31:47 +00:00
2024-04-22 22:13:13 +00:00
#define INIT_CAPACITY 16
2024-04-03 23:31:47 +00:00
2024-04-22 22:13:13 +00:00
size_t clbks_size(size_t capacity) {
return sizeof(union func) * capacity;
2024-04-03 23:31:47 +00:00
}
2024-04-22 22:13:13 +00:00
bool CreateEvent(struct Event *event)
2024-04-03 23:31:47 +00:00
{
2024-04-22 22:13:13 +00:00
union func *callbacks = malloc(clbks_size(INIT_CAPACITY));
2024-04-09 22:10:30 +00:00
2024-04-22 22:13:13 +00:00
if (callbacks == nullptr)
2024-04-09 22:10:30 +00:00
return false;
2024-04-22 22:13:13 +00:00
*event = (struct Event) {
.clbks = callbacks,
2024-04-03 23:31:47 +00:00
.len = 0,
2024-04-22 22:13:13 +00:00
.capacity = INIT_CAPACITY,
2024-04-03 23:31:47 +00:00
};
2024-04-09 22:10:30 +00:00
return true;
2024-04-03 23:31:47 +00:00
}
2024-04-22 22:13:13 +00:00
void FreeEvent(struct Event *event)
{
free(event->clbks);
}
bool EventSubscribe(struct Event *event, union func callback)
2024-04-03 23:31:47 +00:00
{
2024-04-22 22:13:13 +00:00
if (event->len == event->capacity) {
size_t new_cap = event->capacity * 2;
union func *new_clbks = realloc(event->clbks, clbks_size(new_cap));
if (new_clbks == nullptr)
return false;
event->clbks = new_clbks;
event->capacity = new_cap;
2024-04-03 23:31:47 +00:00
}
2024-04-22 22:13:13 +00:00
event->clbks[event->len++] = callback;
return true;
}
void EventInvoke(struct Event *event, void *arg)
{
for (size_t i = 0; i < event->len; i++) {
event->clbks[i].generic(arg);
}
2024-04-03 23:31:47 +00:00
}
2024-05-02 22:17:37 +00:00
void EventInvokeUpdate(struct Event *event, Time dt)
2024-04-03 23:31:47 +00:00
{
2024-04-22 22:13:13 +00:00
for (size_t i = 0; i < event->len; i++) {
event->clbks[i].update(dt);
2024-04-03 23:31:47 +00:00
}
}