ImagoEngine
A C++ 2D game engine built on a sparse-set ECS, with scenes, scheduled systems, events, and action-based input
Loading...
Searching...
No Matches
Broadcaster.hpp
Go to the documentation of this file.
1
6
7#pragma once
8
9#include <cstdint> // for uint32_t
10#include <functional> // for std::function
11#include <unordered_map> // for std::unordered_map
12#include <algorithm> // for std::remove_if
13#include <cassert> // for assert
14#include <type_traits> // for checking if T is a const reference in subscribe and unsubscribe
15#include <spdlog/spdlog.h> // for error logging
16#include <vector> // for storage
17
18namespace Imago::Engine
19{
20
21 //forward declaration so that it can be used in the function signatures
22 struct SceneContext;
23
25 using EventTypeId = uint32_t;
26
27 //NOTE: this is again the meyers singleton, see Nexus.hpp for more details about how it works
28
29 namespace detail
30 {
40 inline EventTypeId next_event_type_id()
41 {
42 static EventTypeId id = 0;
43 return id++;
44 }
45 }
46
56 template <typename T>
58 {
59 static const EventTypeId id = detail::next_event_type_id();
60 return id;
61 }
62
71 private:
72
77 using ErasedFn = void(*)();
78
82 struct Subscriber {
83 ErasedFn systemAddress;
84 std::function<void(SceneContext&, const void*)> invoke;
85 };
86
87 SceneContext& _ctx;
88 std::unordered_map<EventTypeId, std::vector<Subscriber>> _subscribers;
89
90 // NOTE: this variable exists so we can keep track of how many broadcasts emit has made
91 // and not subscribe or unsubscribe from any systems during an emit
92
93 uint32_t _broadcastDepth = 0;
94
104 static std::vector<Subscriber>::iterator find_subscriber(std::vector<Subscriber>& subscribers, ErasedFn system);
105
106 public:
107
112 template <typename T>
113 using SystemFn = void (*)(SceneContext&, const T&);
114
119 explicit Broadcaster(SceneContext& ctx);
120
121 // explicitly disallow copy and move behavior
122 Broadcaster(const Broadcaster&) = delete;
123 Broadcaster& operator=(const Broadcaster&) = delete;
124 Broadcaster(Broadcaster&&) = delete;
125 Broadcaster& operator=(Broadcaster&&) = delete;
126
136 template <typename T>
137 void emit(const T& event);
138
144 template <typename T>
145 void subscribe(SystemFn<T> system);
146
156 template <typename T>
157 void unsubscribe(SystemFn<T> system);
158
162 void clear();
163
164 };
165
166 //-----------
167 //definitions
168 //-----------
169
170 template <typename T>
171 void Broadcaster::emit(const T& event)
172 {
173 // get the id at this event type
175
176 // if the event vector does not exist return
177 auto it = _subscribers.find(id);
178 if (it == _subscribers.end()) return;
179
180 // if we are here it was found so get a reference
181 std::vector<Subscriber>& subscribers = it->second;
182
183 // iterate though it calling the lambas and keeping track of broadcast depth accordingly
184 _broadcastDepth++;
185 for (const Subscriber& subscriber : subscribers) {
186 subscriber.invoke(_ctx, &event);
187 }
188 _broadcastDepth--;
189 }
190
191 template <typename T>
193 {
194 // make sure T is not a const reference so that ids do not get messaed up
195 static_assert(!std::is_const_v<T> && !std::is_reference_v<T>, "[Broadcaster] Event type T must not be const or a reference");
196
197 //TODO: eventually have a system for this that just waits on the subscribe instead of crashing
198 // ensure ther are no broadcasts currently occuring
199 assert(_broadcastDepth == 0 && "[Broadcaster] you are trying to subscribe to an event while the Broadcaster is emitting!");
200
201 //TODO: this should crash the game in a build come up for a solution with this with the logger
202 // ensure the system is not null
203 assert(system != nullptr && "[Broadcaster] you are trying to subscribe a null system to an event!");
204
205 // get the id of the event being subscribe dto
207
208 // create or get the vector that matches with id
209 std::vector<Subscriber>& subscribers = _subscribers[id];
210
211 // NOTE: in C++ reinterpret_cast<T>() tells the compiler to treat the same bits as a different type with no conversion and no checking
212 // in this case, since we are casting function pointers the address (which is what we want) will stay the same and the type the compiler associates
213 // with it will change so we can store all system addresses in the same vector.
214
215 // convert the system to ErasedFn to store its address and make sure that system is not already in the vector
216 ErasedFn erasedSystem = reinterpret_cast<ErasedFn>(system);
217 if (find_subscriber(subscribers, erasedSystem) != subscribers.end()) return;
218
219 // buld the Subscriber wrapper and add it to _subscribers
220 Subscriber subscriber = {
221 erasedSystem,
222 [system](SceneContext& ctx, const void* event) {
223 system(ctx, *static_cast<const T*>(event));
224 }
225 };
226 subscribers.push_back(subscriber);
227 }
228
229 template <typename T>
231 {
232 // make sure T is not a const reference so that ids do not get messaed up
233 static_assert(!std::is_const_v<T> && !std::is_reference_v<T>, "[Broadcaster] Event type T must not be const or a reference");
234
235 //TODO: eventually have a system for this that just waits on the subscribe instead of crashing
236 // ensure ther are no broadcasts currently occuring
237 assert(_broadcastDepth == 0 && "[Broadcaster] you are trying to unsubscribe from an event while the Broadcaster is emitting!");
238
239 //TODO: intergrate spdlog into editor logger once it exists
240 // get the id of the event and make sure it existt
242 auto it = _subscribers.find(id);
243 if (it == _subscribers.end()) {
244 spdlog::warn("[Broadcaster] You are trying to unsubscribe from an event that the system is already not subscribed to");
245 return;
246 }
247
248 // get reference to the subscribers vector
249 std::vector<Subscriber>& subscribers = it->second;
250
251 // convert to erasedFn so we can check the address
252 ErasedFn erasedSystem = reinterpret_cast<ErasedFn>(system);
253
254 //NOTE: remove if shifts the elements that do not match the condition in the lambda toward the front and return an iterator to where the end
255 // would be if the ones that did match were gone.
256
257 // erase the subscriber from its vector if addresss match, storing whether or not something was removed
258 auto newEnd = std::remove_if(subscribers.begin(), subscribers.end(), [erasedSystem](const Subscriber& s) { return s.systemAddress == erasedSystem ; });
259
260 //TODO: intergrate spdlog into editor logger once it exists
261 // if nothing changed, report and return
262 if (newEnd == subscribers.end()) {
263 spdlog::warn("[Broadcaster] You are trying to unsubscribe from an event that the system is already not subscribed to");
264 return;
265 }
266
267 // if something changed, remove it
268 subscribers.erase(newEnd, subscribers.end());
269 }
270}
EventTypeId get_event_type_id()
Returns the EventTypeId for the event of type T.
Definition Broadcaster.hpp:57
uint32_t EventTypeId
Alias for event ids in event storage.
Definition Broadcaster.hpp:25
void emit(const T &event)
Call every system subscribed to EventType T in subcription order.
Definition Broadcaster.hpp:171
void(*)(SceneContext &, const T &) SystemFn
Function pointer to a system that recieves SceneContext and an EventType and returns nothing.
Definition Broadcaster.hpp:113
void unsubscribe(SystemFn< T > system)
Removes the system function pointer from the list for EventType T.
Definition Broadcaster.hpp:230
void subscribe(SystemFn< T > system)
Adds the system function pointer to the list for EventType T. Called during scene initialization.
Definition Broadcaster.hpp:192
Broadcaster(SceneContext &ctx)
Construct a new Broadcaster object with the current SceneContext.
Definition Broadcaster.cpp:9
void clear()
Drops every subscription for every event type.
Definition Broadcaster.cpp:18
Gives systems access to the persistent engine objects they could need.
Definition SceneContext.hpp:30