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
Nexus.hpp
Go to the documentation of this file.
1
6
7#pragma once
8
9#include <cstdint> // for uint32_t
10#include <unordered_map> // for component pools
11#include <array> // to construct surveys
12#include <memory> // for std::unique_ptr
13#include <utility> // for std::move
14#include <cassert> // for bond asserts
15#include <cstdlib> // for std::abort
16#include <vector> // for bonds
17
18#include "Imago/ECS/Entity.hpp"
24#include "Imago/ECS/Bond.hpp"
26
27namespace Imago::ECS
28{
29
31 using ComponentTypeId = uint32_t;
32
33 // NOTE: Here we use the Meyer's Singleton:
34 // the detail namespace contains a function for getting the next id, the first line only runs once because it is a static local variable
35 // and hence the memory is only allocated once, the return statement returns the id and then increments it for every call so that we get a new, sequential id every call
36 // after it is a templated function that returns the id for each component type. Since it is templated a new version of this function is compiled for each type passed through
37 // meaning that the static id variable is assigned only once for each component type and that specific id is returned whenever the function for that component type is called.
38 // This allows us to to match component types to their corresponding id dynamically and without the compiler having to manage one persistent id slot per type.
39
41 namespace detail
42 {
52 inline ComponentTypeId next_component_type_id()
53 {
54 static ComponentTypeId id = 0; // allocated only once for the first function call
55 return id++;
56 }
57 }
58
68 template <typename T>
70 {
71 static const ComponentTypeId id = detail::next_component_type_id(); // assigned only once for the first function call
72 return id;
73 }
74
84 class Nexus {
85 private:
86
87 EntityManager _entityManager;
88 CommandBuffer _commandBuffer;
89 std::unordered_map<ComponentTypeId, std::unique_ptr<SparseSetBase>> _pools;
90 std::vector<std::unique_ptr<Bond>> _bonds;
91 std::unordered_map<ComponentTypeId, Bond*> _bondMap;
92
93 // --- component pool helpers ---
94
103 template <typename T>
104 SparseSet<T>* get_pool();
105
112 template <typename T>
113 SparseSet<T>* find_pool();
114
115 // --- immediate calls for CommandBuffer ---
116
121 void destroy_immediate(Entity e);
122
129 template <typename T>
130 void bind_immediate(Entity e, T component);
131
137 template <typename T>
138 void unbind_immediate(Entity e);
139
140 // --- bond helpers ---
141
151 template <typename T>
152 Bond* find_bond();
153
154 public:
155
156 // NOTE: the Nexus need to be a friend class with the CommandBuffer so that the CommandBuffer can access its private methods for making immediate changes
157 friend class CommandBuffer;
158
162 Nexus();
163
164 // explicitly disallow copy and move behavior
165 Nexus(const Nexus&) = delete;
166 Nexus& operator=(const Nexus&) = delete;
167 Nexus(Nexus&&) = delete;
168 Nexus& operator=(Nexus&&) = delete;
169
170 // --- entity and component methods ---
171
176 Entity create();
177
186 void destroy(Entity e);
187
193 bool is_valid(Entity e) const;
194
210 template <typename T>
211 void bind(Entity e, T component);
212
222 template <typename T>
223 void unbind(Entity e);
224
234 template <typename T>
235 void patch(Entity e, T component);
236
247 template <typename T>
248 T& get(Entity e);
249
257 template <typename T>
258 T* try_to_get(Entity e);
259
266 template <typename T>
267 bool has(Entity e);
268
269 // -- survey and bond methods ---
270
277 template <typename... Components>
278 SurveyHandle<Components...> survey();
279
289 template <typename... Components>
290 BondHandle<Components...> bond();
291
292 //-----------------------
293 //Command Buffer Methods
294 //-----------------------
295
299 void flush();
300
301 };
302
303 //-----------
304 //definitions
305 //-----------
306
307 template <typename T>
308 SparseSet<T>* Nexus::get_pool()
309 {
310 // get the id at that component type
311 uint32_t id = get_component_type_id<T>();
312
313 // try to find the id in _pools
314 auto location = _pools.find(id);
315
316 // if it does not exist, create a new one
317 if (location == _pools.end()) {
318 location = _pools.emplace(id, std::make_unique<SparseSet<T>>()).first;
319 }
320
321 // return the pool at that location casted to a raw SparseSet<T> pointer
322 return static_cast<SparseSet<T>*>(location->second.get());
323 }
324
325 template <typename T>
326 SparseSet<T>* Nexus::find_pool()
327 {
328 // get the id at that component type
329 uint32_t id = get_component_type_id<T>();
330
331 // try to find it the id in _pools
332 auto location = _pools.find(id);
333
334 // if it does not exist return nullptr
335 if (location == _pools.end()) {
336 return nullptr;
337 }
338
339 // otherwise return the pool casted to a raw SparseSet<T> pointer
340 return static_cast<SparseSet<T>*>(location->second.get());
341 }
342
343 template <typename T>
344 void Nexus::bind_immediate(Entity e, T component)
345 {
346 // get the pool for that component type
347 SparseSet<T>* pool = get_pool<T>();
348
349 // add the component to that pool
350 pool->insert(e, std::move(component));
351
352 // notify the bonds about the bind if any (this goes after the insert)
353 Bond* currentBond = find_bond<T>();
354 if (currentBond != nullptr) {
355 currentBond->on_component_bound(e);
356 }
357 }
358
359 template <typename T>
360 void Nexus::unbind_immediate(Entity e)
361 {
362 // get the pool for that component type
363 SparseSet<T>* pool = find_pool<T>();
364 if (pool == nullptr) return;
365
366 // notify the bonds about the unbind if any (this goes before the removal, order matters)
367 Bond* currentBond = find_bond<T>();
368 if (currentBond != nullptr) {
369 currentBond->on_component_unbound(e);
370 }
371
372 // remove the component from that pool
373 pool->remove(e);
374 }
375
376 template <typename T>
377 Bond* Nexus::find_bond()
378 {
379 // get the id at the component type
380 ComponentTypeId id = get_component_type_id<T>();
381
382 // try to find the id in _bondMap
383 auto location = _bondMap.find(id);
384
385 // if it does not exist return nullptr
386 if (location == _bondMap.end()) {
387 return nullptr;
388 }
389
390 // otherwise return the bond
391 return location->second;
392 }
393
394 //TODO: set up error messaging so it reports it through Nexus to avoid user confusion
395 template <typename T>
396 void Nexus::bind(Entity e, T component)
397 {
398 _commandBuffer.defer_bind<T>(e, component);
399 }
400
401 template <typename T>
403 {
404 _commandBuffer.defer_unbind<T>(e);
405 }
406
407 //TODO: set up error messaging so it reports it through Nexus to avoid user confusion
408 template <typename T>
409 void Nexus::patch(Entity e, T component)
410 {
411 // get the pool for that component type
412 SparseSet<T>* pool = get_pool<T>();
413
414 // replace that component
415 pool->replace(e, std::move(component));
416 }
417
418 template <typename T>
420 {
421 // get the pool for that component type
422 SparseSet<T>* pool = find_pool<T>();
423 assert(pool != nullptr && "[Nexus] Get called for a component type with no registered pool.");
424
425 // return the component
426 return pool->get(e);
427 }
428
429 template <typename T>
431 {
432 // get the pool for that component type
433 SparseSet<T>* pool = find_pool<T>();
434 if (pool == nullptr) return nullptr;
435
436 // return the component or nullptr
437 return pool->try_to_get(e);
438 }
439
440 template <typename T>
442 {
443 // get the pool for that component type
444 SparseSet<T>* pool = find_pool<T>();
445 if (pool == nullptr) return false;
446
447 // return if it has the component
448 return pool->has(e);
449 }
450
451 template <typename... Components>
452 SurveyHandle<Components...> Nexus::survey()
453 {
454 // create an array of SparseSet pointers per type packed into Components arguments
455 //TODO: the solution to use get_pool instead of find_pool is to avoid passing a nullptr into Survey's constructor, consider this solution vs doing a null check in the constructor
456 std::array<SparseSetBase*, sizeof...(Components)> pools = { get_pool<Components>()... };
457
458 // construct and return the survey
459 return SurveyHandle<Components...>(pools);
460 }
461
462 template <typename... Components>
463 BondHandle<Components...> Nexus::bond()
464 {
465 // collect the component type ids of the passed in pools
466 std::array<ComponentTypeId, sizeof...(Components)> poolTypes = { get_component_type_id<Components>() ... };
467
468 // create variables to determine whether the ids match a created bond or not
469 Bond* found = nullptr; // the matching bond if one exists (first one seen)
470 size_t mapped = 0; // how many ids already belong to a bond
471 bool sameBond = true; // whether or not the requested ids belong to the same bond
472
473 // loop through the component types to determine if a bond already exists, or if it does not and can/cannot be created
474 for (ComponentTypeId id : poolTypes) {
475
476 // go to the next id if it is not associated with any bonds
477 auto location = _bondMap.find(id);
478 if (location == _bondMap.end()) continue;
479
480 // if the id is associated with a bond increase mapped
481 mapped++;
482
483 // if found is still null set it so we can keep track of it in the future
484 if (found == nullptr) {
485
486 found = location->second;
487
488 // if found is not associated with the current id's bond it is not the sameBond
489 } else if (found != location->second) {
490 sameBond = false;
491 }
492 }
493
494 // if none of the ids belong to a bond we can create a new one
495 if (mapped == 0) {
496
497 // get the pools requested for the bond
498 std::vector<SparseSetBase*> pools = { get_pool<Components>()... };
499
500 // NOTE: we use a rew pointer and owned to create this unique pointer instead of make_unique
501 // because the constructor is private and only accessible because of the friend class
502 // and make_unique constructs the object inside as std::function that is not a friend of Bond
503
504 // create the bond
505 std::unique_ptr<Bond> owned(new Bond(std::move(pools)));
506
507 // get the raw Bond pointer and put it in the bond map for every bonded component
508 Bond* bondPtr = owned.get();
509 for (ComponentTypeId id : poolTypes) {
510 _bondMap[id] = bondPtr;
511 }
512
513 // put the unique pointer in the bonds vector (leaves owned empty)
514 _bonds.push_back(std::move(owned));
515
516 // return the BondHandle
517 return BondHandle<Components...>(bondPtr);
518 }
519
520 // if every id belongs to the same Bond, we can just create the BondHandle
521 if (mapped == sizeof...(Components) && sameBond && found->get_pool_count() == sizeof...(Components)) {
522 return BondHandle<Components...>(found);
523 }
524
525 // anything else means there is no bond and it can not be created because it shares a component pool with an existing bond
526 //TODO: integrate failure for this case with the logger (ideally it can be a compiler error before the user even runs code)
527 assert(false && "[Nexus] bond<>() was requested for components that are already bonded!");
528 std::abort();
529 }
530
531 //--------------------------
532 // Command Buffer Defintions
533 //--------------------------
534
535 template <typename T>
536 void CommandBuffer::defer_bind(Entity e, T component)
537 {
538 // create and push back the lambda for a bind command
539 _bindQueue.push_back([this, e, component = std::move(component)]() mutable {
540 _nexus.bind_immediate<T>(e, std::move(component));
541 });
542 }
543
544 template <typename T>
546 {
547 // create and push back the lambda for an unbind command
548 _unbindQueue.push_back([this, e]() {
549 _nexus.unbind_immediate<T>(e);
550 });
551 }
552}
Defines the BondHandle, this is the view that users will access to iterate over the Entities of a Bon...
Defines the Bond class which will be a permanent group of component pools that are kept sorted so tha...
Defines the Command Buffer to solve undefined behavior resulting from modifying containers while iter...
Owns the lifetime of every Entity in the engine, it creates, destroys, and valildates every entity....
Defines the Entity alias and the free functions used to pack and unpack it.
uint32_t Entity
A packed identifier: 20 bits of index, 12 bits of generation.
Definition Entity.hpp:20
ComponentTypeId get_component_type_id()
returns the ComponenTypeId for component of type T.
Definition Nexus.hpp:69
uint32_t ComponentTypeId
alias for component ids for pool storage
Definition Nexus.hpp:31
Declares the SparseSetBase interface.
Defines the concrete SparseSet templated class.
Defines the Survey, how the users will iterate over Entities with specified components in Systems.
Lightweight view over a Bond. This is returned by value from Nexus::Bond<Components....
Definition BondHandle.hpp:31
A Bond permanently reorders every pool within it so that every Entity that has all of the components ...
Definition Bond.hpp:29
size_t get_pool_count() const
Returns the number of component pools in the bond.
Definition Bond.cpp:85
void defer_bind(Entity e, T component)
Queues a bind_immediate command lambda.
Definition Nexus.hpp:536
void defer_unbind(Entity e)
Queues an unbind_immediate command lambda.
Definition Nexus.hpp:545
Creates, destroys, and validates Entity handles.
Definition EntityManager.hpp:36
void bind(Entity e, T component)
Binds a component of type T to Entity e.
Definition Nexus.hpp:396
void flush()
calls _commandBuffer.flush() to call the immediate methods that actually apply the deferred changes t...
Definition Nexus.cpp:47
Nexus()
Construct a new Nexus object and instantiates the command buffer.
Definition Nexus.cpp:6
void unbind(Entity e)
Unbinds a component of type T from Entity e if possible.
Definition Nexus.hpp:402
SurveyHandle< Components... > survey()
Returns a survey of the specified components.
Definition Nexus.hpp:452
Entity create()
Creates a new Entity.
Definition Nexus.cpp:9
BondHandle< Components... > bond()
Does one of three things depending on the current state of Bonds already in the Nexus:
Definition Nexus.hpp:463
bool is_valid(Entity e) const
Checks whether an Entity is still valid.
Definition Nexus.cpp:42
void destroy(Entity e)
Destroys an Entity and removes it from every component pool it is in.
Definition Nexus.cpp:15
void patch(Entity e, T component)
Overwrites an Entity's existing component of type T with new component data.
Definition Nexus.hpp:409
T & get(Entity e)
Returns a reference to the Entity's component of type T.
Definition Nexus.hpp:419
bool has(Entity e)
Check whether an Entity currently has a component of type T.
Definition Nexus.hpp:441
T * try_to_get(Entity e)
Returns a reference to the Entity's component of type T if it has it and nullptr otherwise.
Definition Nexus.hpp:430
Type-erased interface for SparseSet<T>.
Definition SparseSetBase.hpp:21
SparseSet concrete class templated to a component type, acts as Imago ECS's component pool.
Definition SparseSet.hpp:33
bool has(Entity e) const override
checks whether an Entity currently has a component stored in this pool
Definition SparseSet.hpp:233
T & replace(Entity e, T component)
replaces a component with new data
Definition SparseSet.hpp:131
T * try_to_get(Entity e)
tries to get a component and returns nullptr if one does not exist
Definition SparseSet.hpp:176
T & get(Entity e)
returns a reference to the Entity's component
Definition SparseSet.hpp:150
The Survey takes Components as templated arguments and acts as an iterator over all entities with all...
Definition SurveyHandle.hpp:32