Untitled Game engine no.5  1.0
ComponentArray.hpp
1 #ifndef COMPARRAY_H
2 #define COMPARRAY_H
3 #include "Types.hpp"
4 #include "pch.hpp"
5 #include <unordered_map>
6 namespace Engine {
11  virtual void EntityDestroyed(EntityID entity) = 0;
12  };
13 
14  template<typename T>
17 
18  private:
19  // TODO: make this packed later, will need more maps and shit
20 
22  std::vector<Ref<T>> m_DataArray;
24  std::unordered_map<EntityID, size_t> m_EntityMap;
25 
27  size_t m_nextIdx = 0;
28 
29  public:
32 
36  Ref<T> Insert(EntityID id, Ref<T> c) {
37  m_EntityMap.emplace(id, m_nextIdx);
38  m_DataArray.push_back(c);
39  ++m_nextIdx;
40  return c;
41  }
42 
43 
47  Ref<T> Insert(EntityID id, T c) {
48  // check if we have a component for this entity
49  // if we have it then do nothing
50  // TODO: or should we replace?
51  auto itr = m_EntityMap.find(id);
52  if (itr != m_EntityMap.end())
53  return m_DataArray[itr->second];
54 
55  m_EntityMap.emplace(id, m_nextIdx);
56  Ref<T> data = CreateRef<T>(c);
57  m_DataArray.push_back(data);
58  ++m_nextIdx;
59  return data;
60  }
61 
64  void Remove(EntityID id) {
65  // does not have a component of this type
66  auto itr = m_EntityMap.find(id);
67  if (itr == m_EntityMap.end())
68  return;
69 
70  size_t idx = itr->second;
71  // erase the component at the right idx
72  m_DataArray.erase(m_DataArray.begin() + idx);
73  m_EntityMap.erase(itr);
74  --m_nextIdx;
75  }
76 
80  Ref<T> GetComp(EntityID id) {
81  auto itr = m_EntityMap.find(id);
82  if (itr == m_EntityMap.end())
83  return nullptr;
84 
85  size_t idx = itr->second;
86 
87  return m_DataArray[idx];
88  }
89 
92  void EntityDestroyed(EntityID id) {
93  Remove(id);
94  }
95  };
96 
97 }
98 #endif
Engine::Ref
std::shared_ptr< T > Ref
Has stuff for making references a lot more easily shared smart pointer.
Definition: Base.hpp:21
Engine::ComponentDataArray::ComponentDataArray
ComponentDataArray()
Constructor.
Definition: ComponentArray.hpp:31
Engine::ComponentDataArray::Insert
Ref< T > Insert(EntityID id, T c)
Definition: ComponentArray.hpp:47
Engine::ComponentDataArray
An array of components of type T.
Definition: ComponentArray.hpp:16
Engine::ComponentDataArray::GetComp
Ref< T > GetComp(EntityID id)
Definition: ComponentArray.hpp:80
Engine::IComponentDataArray
Interface for an array of components.
Definition: ComponentArray.hpp:8
Engine::IComponentDataArray::EntityDestroyed
virtual void EntityDestroyed(EntityID entity)=0
Engine::ComponentDataArray::Insert
Ref< T > Insert(EntityID id, Ref< T > c)
Definition: ComponentArray.hpp:36
Engine
Definition: Animation.hpp:14
Engine::ComponentDataArray::EntityDestroyed
void EntityDestroyed(EntityID id)
Definition: ComponentArray.hpp:92
Engine::ComponentDataArray::Remove
void Remove(EntityID id)
Definition: ComponentArray.hpp:64