Acheron
Loading...
Searching...
No Matches
event.hpp
1#pragma once
2
3#include "types.hpp"
4
5#include <any>
6#include <cassert>
7#include <functional>
8#include <typeindex>
9#include <unordered_map>
10#include <vector>
11
12namespace acheron::ecs {
13 class World;
14
23 public:
28 template<typename T>
29 using Callback = std::function<void(World&, const T&)>;
30
39 template<typename T>
40 void Subscribe(World& world, Callback<T> callback) {
41 auto& vec = subscribers[typeid(T)];
42 vec.push_back([&world, callback](const std::any& e) {
43 callback(world, std::any_cast<const T&>(e));
44 });
45 }
46
55 template<typename T>
56 void Emit(const T& event) {
57 events[typeid(T)].push_back(event);
58 }
59
66 void Dispatch() {
67 for (auto& [type, vec] : events) {
68 auto& subs = subscribers[type];
69 for (auto& e : vec) {
70 for (auto& sub : subs) {
71 sub(e);
72 }
73 }
74 }
75 events.clear();
76 }
77
78 private:
79 std::unordered_map<std::type_index, std::vector<std::any>> events;
80 std::unordered_map<std::type_index, std::vector<std::function<void(const std::any&)>>> subscribers;
81 };
82
86 template<typename T>
88 Entity entity;
89 T* component;
90 };
91
95 template<typename T>
97 Entity entity;
98 };
99
100
104 template<typename T>
106 Entity entity;
107 T* component;
108 };
109}
Manages subscribing, dispatching, and creating events.
Definition event.hpp:22
void Dispatch()
Dispatch all queued events.
Definition event.hpp:66
std::function< void(World &, const T &)> Callback
Function signature for event callbacks.
Definition event.hpp:29
void Emit(const T &event)
Emit an event.
Definition event.hpp:56
void Subscribe(World &world, Callback< T > callback)
Subscribe to an event type.
Definition event.hpp:40
Central context for the ECS.
Definition world.hpp:20
Event emitted when a component is added to an entity.
Definition event.hpp:87
Event emitted when a component is removed from an entity.
Definition event.hpp:96
Event emitted when a component is set on en entity.
Definition event.hpp:105