Acheron
Loading...
Searching...
No Matches
component.hpp
1#pragma once
2
3#include "types.hpp"
4#include "component_array.hpp"
5
6#include <cassert>
7#include <memory>
8#include <print>
9#include <unordered_map>
10
11namespace acheron::ecs {
12 template<typename T>
14 static inline ComponentID ID = static_cast<ComponentID>(-1); // -1 means "unassigned"
15 };
16
20 class ComponentManager {
21 public:
22
23 ComponentManager() : nextComponentID(0) {}
24
32 template<typename T>
34 assert(ComponentType<T>::ID == static_cast<ComponentID>(-1) && "Duplicate registration");
35
36 ComponentType<T>::ID = nextComponentID++;
37 componentArrays[ComponentType<T>::ID] = std::make_shared<ComponentArray<T>>();
38 }
39
48 template<typename T>
49 ComponentID GetComponentID() {
50 assert(ComponentType<T>::ID != static_cast<ComponentID>(-1) && "Component not registered");
51 return ComponentType<T>::ID;
52 }
53
62 template<typename T>
63 void AddComponent(Entity entity, T component) {
64 GetComponentArray<T>()->InsertData(entity, component);
65 }
66
73 template<typename T>
74 void RemoveComponent(Entity entity) {
75 GetComponentArray<T>()->RemoveData(entity);
76 }
77
85 template<typename T>
86 T& GetComponent(Entity entity) {
87 return GetComponentArray<T>()->GetData(entity);
88 }
89
97 template<typename T>
98 bool HasComponent(Entity entity) {
99 return GetComponentArray<T>()->HasData(entity); // you’ll need a HasData function in ComponentArray
100 }
101
107 void EntityDespawned(Entity entity);
108
109 private:
110 std::unordered_map<const char*, ComponentID> componentTypes;
111 std::unordered_map<ComponentID, std::shared_ptr<IComponentArray>> componentArrays;
112 ComponentID nextComponentID;
113
122 template<typename T>
123 std::shared_ptr<ComponentArray<T>> GetComponentArray() {
124 ComponentID id = GetComponentID<T>();
125 return std::static_pointer_cast<ComponentArray<T>>(componentArrays[id]);
126 }
127 };
128}
void RemoveComponent(Entity entity)
Removes a component and its data from an entity.
Definition component.hpp:74
T & GetComponent(Entity entity)
Get components data associated with an entity.
Definition component.hpp:86
void AddComponent(Entity entity, T component)
Adds a component and its data to an entity.
Definition component.hpp:63
bool HasComponent(Entity entity)
Checks if en entity has a component.
Definition component.hpp:98
void RegisterComponent()
Registers a component type creating a ComponentArray and an ID.
Definition component.hpp:33
ComponentID GetComponentID()
Gets the ID of a component.
Definition component.hpp:49
void EntityDespawned(Entity entity)
Remove components associated with an entity.
Definition component.cpp:5
Definition component.hpp:13