Acheron
Loading...
Searching...
No Matches
component_array.hpp
1#pragma once
2
3#include "types.hpp"
4
5#include <print>
6#include <vector>
7#include <cassert>
8#include <unordered_map>
9
10namespace acheron::ecs {
15 virtual ~IComponentArray() = default;
19 virtual void EntityDespawned(Entity entity) {}
20 };
21
29 template<typename T>
31 public:
32
41 void InsertData(Entity entity, T component) {
42 assert(entityToIndex.find(entity) == entityToIndex.end() && "Duplicate components on entity");
43
44 size_t newIndex = componentArray.size();
45 entityToIndex[entity] = newIndex;
46 indexToEntity[newIndex] = entity;
47 componentArray.push_back(std::move(component));
48 }
49
57 bool HasData(Entity entity) const {
58 return entityToIndex.find(entity) != entityToIndex.end();
59 }
60
68 void RemoveData(Entity entity) {
69 assert(entityToIndex.find(entity) != entityToIndex.end() && "Removal called for component that doesn't exist");
70
71 size_t indexOfRemoved = entityToIndex[entity];
72 size_t indexOfLast = componentArray.size() - 1;
73
74 componentArray[indexOfRemoved] = std::move(componentArray[indexOfLast]);
75
76 Entity entityOfLast = indexToEntity[indexOfLast];
77 entityToIndex[entityOfLast] = indexOfRemoved;
78 indexToEntity[indexOfRemoved] = entityOfLast;
79
80 entityToIndex.erase(entity);
81 indexToEntity.erase(indexOfLast);
82 componentArray.pop_back();
83 }
84
92 T& GetData(Entity entity) {
93 assert(entityToIndex.find(entity) != entityToIndex.end() && "Trying to get Component that doesn't exist");
94 return componentArray[entityToIndex[entity]];
95 }
96
102 void EntityDespawned(Entity entity) override {
103 if (entityToIndex.find(entity) != entityToIndex.end()) {
104 RemoveData(entity);
105 }
106 }
107
108 private:
109 std::vector<T> componentArray;
110 std::unordered_map<Entity, size_t> entityToIndex;
111 std::unordered_map<size_t, Entity> indexToEntity;
112 };
113}
Container for components.
Definition component_array.hpp:30
T & GetData(Entity entity)
Gets component data from an entity.
Definition component_array.hpp:92
void InsertData(Entity entity, T component)
Add a component and its data to an entity.
Definition component_array.hpp:41
bool HasData(Entity entity) const
Checks if en entity has a component.
Definition component_array.hpp:57
void EntityDespawned(Entity entity) override
Called when an entity is despawned to remove all its component data.
Definition component_array.hpp:102
void RemoveData(Entity entity)
Removes a component and its data associated with an entity.
Definition component_array.hpp:68
Interface for component arrays.
Definition component_array.hpp:14
virtual void EntityDespawned(Entity entity)
Called when an entity is despawned.
Definition component_array.hpp:19