Olympe Engine 2.0
2D Game Engine with ECS Architecture
Loading...
Searching...
No Matches
ECS_Register.h
Go to the documentation of this file.
1/*
2
3*/
4#pragma once
5#include "ECS_Entity.h"
6#include "ECS_Components.h"
7#include "ECS_Systems.h"
8
9#include <unordered_map>
10#include <memory>
11#include <stdexcept>
12#include <algorithm>
13#include <iostream>
14#include <vector>
15#include <queue>
16
17// --- Component Pool Implementation (Contiguous Storage) ---
18template <typename T>
20{
21public:
22 // The actual data container (contiguous storage for cache efficiency)
23 std::vector<T> m_data;
24 // Map from EntityID to index in the data vector
25 std::unordered_map<EntityID, size_t> m_entityToIndex;
26 // Map from index to EntityID (needed for swap-and-pop)
27 std::vector<EntityID> m_indexToEntity;
28
30 {
31 // DEPRECATED LIMITATION
32 // m_data.reserve(MAX_ENTITIES);
33 // m_indexToEntity.reserve(MAX_ENTITIES);
34 }
35
36 // Virtual function implementation: removes a component using swap-and-pop
37 void RemoveComponent(EntityID entity) override
38 {
39 if (!m_entityToIndex.count(entity)) return;
40
41 size_t indexOfRemoved = m_entityToIndex[entity];
42 size_t indexOfLast = m_data.size() - 1;
43
44 // Swap-and-pop optimization: maintains data contiguity
46 {
47 // 1. Move/Swap data in the vector
49
50 // 2. Update the mapping for the moved Entity
54 }
55
56 // 3. Remove the last element (which is the component to be deleted)
57 m_data.pop_back();
58 m_indexToEntity.pop_back();
59
60 // 4. Clean up the mapping for the deleted Entity
61 m_entityToIndex.erase(entity);
62 }
63
64 // Adds a component (T) for the given EntityID
65 // Constructs the component in-place using perfect forwarding
66 template<typename... Args>
67 void AddComponent(EntityID entity, Args&&... args)
68 {
69 if (m_entityToIndex.count(entity)) return;
70
71 size_t newIndex = m_data.size();
72
73 m_data.emplace_back(std::forward<Args>(args)...);
74 m_indexToEntity.push_back(entity);
75 m_entityToIndex[entity] = newIndex;
76 }
77
78 // Fast access to the component by EntityID
80 {
81 if (!m_entityToIndex.count(entity))
82 {
83 throw std::runtime_error("Component not found for entity.");
84 }
85 return m_data[m_entityToIndex[entity]];
86 }
87
88 bool HasComponent(EntityID entity) const
89 {
90 return m_entityToIndex.count(entity) > 0;
91 }
92};
Core ECS component definitions.
ComponentTypeID GetComponentTypeID_Static()
Definition ECS_Entity.h:56
std::uint64_t EntityID
Definition ECS_Entity.h:21
void RemoveComponent(EntityID entity) override
void AddComponent(EntityID entity, Args &&... args)
std::vector< EntityID > m_indexToEntity
std::vector< T > m_data
bool HasComponent(EntityID entity) const
std::unordered_map< EntityID, size_t > m_entityToIndex
T & GetComponent(EntityID entity)