Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
EntityMap.h
Go to the documentation of this file.
1/* Copyright (C) 2026 Wildfire Games.
2 * This file is part of 0 A.D.
3 *
4 * 0 A.D. is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * 0 A.D. is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 */
17#ifndef INCLUDED_ENTITYMAP
18#define INCLUDED_ENTITYMAP
19
20#include "lib/debug.h"
24
25#include <cstddef>
26#include <cstdint>
27#include <cstdlib>
28#include <iterator>
29#include <new>
30
31/**
32 * A fast replacement for map<entity_id_t, T>.
33 * We make the following assumptions:
34 * - entity id's (keys) are unique
35 * - modifications (add / delete) are far less frequent then look-ups
36 * - preformance for iteration is important
37 */
38template<class T> class EntityMap
39{
40private:
41 EntityMap(const EntityMap&); // non-copyable
42 EntityMap& operator=(const EntityMap&); // non-copyable
43
44public:
46 typedef T mapped_type;
47 template<class K, class V> struct key_val {
48 typedef K first_type;
49 typedef V second_type;
52 };
54
55private:
56 size_t m_BufferSize; // number of elements in the buffer
57 size_t m_BufferCapacity; // capacity of the buffer
58 value_type* m_Buffer; // vector with all the mapped key-value pairs
59
60 size_t m_Count; // number of 'valid' entity id's
61
62public:
63
65 {
66 // for entitymap we allocate the buffer right away
67 // with first element in buffer being the Invalid Entity
68 m_Buffer = (value_type*)malloc(sizeof(value_type) * (m_BufferCapacity + 1));
69 if (!m_Buffer)
70 throw std::bad_alloc();
71
72 // create the first element:
74 m_Buffer[1].first = 0xFFFFFFFF; // ensure end() always has 0xFFFFFFFF
75 }
76 inline ~EntityMap()
77 {
78 free(m_Buffer);
79 }
80
81 // Iterators
82 template<class U> struct _iter
83 {
84 using iterator_category = std::forward_iterator_tag;
85 using value_type = U;
86 using difference_type = std::ptrdiff_t;
87 using pointer = U*;
88 using reference = U&;
89
90 U* val;
91 inline _iter(U* init) : val(init) {}
92 inline U& operator*() { return *val; }
93 inline U* operator->() { return val; }
94 inline _iter& operator++() // ++it
95 {
96 ++val;
97 while (val->first == INVALID_ENTITY) ++val; // skip any invalid entities
98 return *this;
99 }
100 inline _iter operator++(int) // it++
101 {
102 _iter it = *this;
103 ++val;
104 while (val->first == INVALID_ENTITY) ++val; // skip any invalid entities
105 return it;
106 }
107 inline bool operator==(_iter other) { return val == other.val; }
108 inline bool operator!=(_iter other) { return val != other.val; }
109 inline operator _iter<U const>() const { return _iter<U const>(val); }
110 };
111
114
116 {
117 value_type* ptr = m_Buffer + 1; // skip the first INVALID_ENTITY
118 while (ptr->first == INVALID_ENTITY) ++ptr; // skip any other invalid entities
119 return ptr;
120 }
121 inline iterator end()
122 {
124 }
125 inline const_iterator begin() const
126 {
127 value_type* ptr = m_Buffer + 1; // skip the first INVALID_ENTITY
128 while (ptr->first == INVALID_ENTITY) ++ptr; // skip any other invalid entities
129 return ptr;
130 }
131 inline const_iterator end() const
132 {
134 }
135
136 // Size
137 inline bool empty() const { return m_Count == 0; }
138 inline size_t size() const { return m_Count; }
139
140 // Modification
141 void insert(const key_type key, const mapped_type& value)
142 {
143 if (key >= m_BufferCapacity) // do we need to resize buffer?
144 {
145 size_t newCapacity = m_BufferCapacity + 4096;
146 while (key >= newCapacity) newCapacity += 4096;
147 // always allocate +1 behind the scenes, because end() must have a 0xFFFFFFFF key
148 value_type* mem = (value_type*)realloc(m_Buffer, sizeof(value_type) * (newCapacity + 1));
149 if (!mem)
150 {
151 debug_warn("EntityMap::insert() realloc failed! Out of memory.");
152 throw std::bad_alloc(); // fail to expand and insert
153 }
154 m_BufferCapacity = newCapacity;
155 m_Buffer = mem;
156 goto fill_gaps;
157 }
158 else if (key > m_BufferSize) // weird insert far beyond the end
159 {
160fill_gaps:
161 // set all entity id's to INVALID_ENTITY inside the new range
162 for (size_t i = m_BufferSize; i <= key; ++i)
163 m_Buffer[i].first = INVALID_ENTITY;
164 m_BufferSize = key; // extend the new size
165 }
166
167 value_type& item = m_Buffer[key];
168 key_type oldKey = item.first;
169 item.first = key;
170 if (key == m_BufferSize) // push_back
171 {
172 ++m_BufferSize; // expand
173 ++m_Count;
174 new (&item.second) mapped_type(value); // copy ctor to init
175 m_Buffer[m_BufferSize].first = 0xFFFFFFFF; // ensure end() always has 0xFFFFFFFF
176 }
177 else if(!item.first) // insert new to middle
178 {
179 ++m_Count;
180 new (&item.second) mapped_type(value); // copy ctor to init
181 }
182 else // set existing value
183 {
184 if (oldKey == INVALID_ENTITY)
185 m_Count++;
186 item.second = value; // overwrite existing
187 }
188 }
189
191 {
192 value_type* ptr = it.val;
193 if (ptr->first != INVALID_ENTITY)
194 {
195 ptr->first = INVALID_ENTITY;
196 ptr->second.~T(); // call dtor
197 --m_Count;
198 }
199 }
201 {
202 if (key < m_BufferSize)
203 {
204 value_type* ptr = m_Buffer + key;
205 if (ptr->first != INVALID_ENTITY)
206 {
207 ptr->first = INVALID_ENTITY;
208 ptr->second.~T(); // call dtor
209 --m_Count;
210 }
211 }
212 }
213 inline void clear()
214 {
215 // orphan whole range
216 value_type* ptr = m_Buffer;
218 for (; ptr != end; ++ptr)
219 {
220 if (ptr->first != INVALID_ENTITY)
221 {
222 ptr->first = INVALID_ENTITY;
223 ptr->second.~T(); // call dtor
224 }
225 }
226 m_Count = 0; // no more valid entities
227 }
228
229 // Operations
231 {
232 if (key < m_BufferSize) // is this key in the range of existing entitites?
233 {
234 value_type* ptr = m_Buffer + key;
235 if (ptr->first != INVALID_ENTITY)
236 return ptr;
237 }
238 return m_Buffer + m_BufferSize; // return iterator end()
239 }
240 inline const_iterator find(const entity_id_t key) const
241 {
242 if (key < m_BufferSize) // is this key in the range of existing entitites?
243 {
244 const value_type* ptr = m_Buffer + key;
245 if (ptr->first != INVALID_ENTITY)
246 return ptr;
247 }
248 return m_Buffer + m_BufferSize; // return iterator end()
249 }
250 inline size_t count(const entity_id_t key) const
251 {
252 if (key < m_BufferSize)
253 {
254 if (m_Buffer[key].first != INVALID_ENTITY)
255 return 1;
256 }
257 return 0;
258 }
259};
260
261template<typename T>
263{
264 void operator()(ISerializer& serialize, const char* /*name*/, EntityMap<T>& value)
265 {
266 size_t len = value.size();
267 serialize.NumberU32_Unbounded("length", static_cast<std::uint32_t>(len));
268 size_t count = 0;
269 for (typename EntityMap<T>::iterator it = value.begin(); it != value.end(); ++it)
270 {
271 serialize.NumberU32_Unbounded("key", it->first);
272 Serializer(serialize, "value", it->second);
273 count++;
274 }
275 // test to see if the entityMap count wasn't wrong
276 // (which causes a crashing deserialisation)
277 ENSURE(count == len);
278 }
279
280 void operator()(IDeserializer& deserialize, const char* /*name*/, EntityMap<T>& value)
281 {
282 value.clear();
283 uint32_t len;
284 deserialize.NumberU32_Unbounded("length", len);
285 for (size_t i = 0; i < len; ++i)
286 {
287 entity_id_t k;
288 T v;
289 deserialize.NumberU32_Unbounded("key", k);
290 Serializer(deserialize, "value", v);
291 value.insert(k, v);
292 }
293 }
294};
295
296
297#endif
Helper templates definitions for serializing/deserializing common objects.
void Serializer(S &serialize, const char *name, Args &&... args)
Definition: SerializeTemplates.h:51
A fast replacement for map<entity_id_t, T>.
Definition: EntityMap.h:39
size_t size() const
Definition: EntityMap.h:138
EntityMap()
Definition: EntityMap.h:64
const_iterator end() const
Definition: EntityMap.h:131
void erase(iterator it)
Definition: EntityMap.h:190
EntityMap(const EntityMap &)
size_t m_Count
Definition: EntityMap.h:60
void insert(const key_type key, const mapped_type &value)
Definition: EntityMap.h:141
const_iterator begin() const
Definition: EntityMap.h:125
_iter< value_type const > const_iterator
Definition: EntityMap.h:113
const_iterator find(const entity_id_t key) const
Definition: EntityMap.h:240
_iter< value_type > iterator
Definition: EntityMap.h:112
void clear()
Definition: EntityMap.h:213
EntityMap & operator=(const EntityMap &)
size_t count(const entity_id_t key) const
Definition: EntityMap.h:250
T mapped_type
Definition: EntityMap.h:46
~EntityMap()
Definition: EntityMap.h:76
iterator find(const entity_id_t key)
Definition: EntityMap.h:230
size_t m_BufferCapacity
Definition: EntityMap.h:57
void erase(const entity_id_t key)
Definition: EntityMap.h:200
value_type * m_Buffer
Definition: EntityMap.h:58
entity_id_t key_type
Definition: EntityMap.h:45
key_val< entity_id_t, T > value_type
Definition: EntityMap.h:53
size_t m_BufferSize
Definition: EntityMap.h:56
bool empty() const
Definition: EntityMap.h:137
iterator begin()
Definition: EntityMap.h:115
iterator end()
Definition: EntityMap.h:121
Deserialization interface; see serialization overview.
Definition: IDeserializer.h:40
virtual void NumberU32_Unbounded(const char *name, uint32_t &out)
Definition: IDeserializer.cpp:126
Serialization interface; see serialization overview.
Definition: ISerializer.h:126
void NumberU32_Unbounded(const char *name, uint32_t value)
Serialize a number.
Definition: ISerializer.h:176
#define debug_warn(expr)
display the error dialog with the given text.
Definition: debug.h:264
#define ENSURE(expr)
ensure the expression <expr> evaluates to non-zero.
Definition: debug.h:222
#define T(string_literal)
Definition: secure_crt.cpp:81
const entity_id_t INVALID_ENTITY
Invalid entity ID.
Definition: Entity.h:35
std::uint32_t entity_id_t
Entity ID type.
Definition: Entity.h:29
Definition: EntityMap.h:83
U * val
Definition: EntityMap.h:90
bool operator!=(_iter other)
Definition: EntityMap.h:108
_iter operator++(int)
Definition: EntityMap.h:100
std::ptrdiff_t difference_type
Definition: EntityMap.h:86
_iter(U *init)
Definition: EntityMap.h:91
U * pointer
Definition: EntityMap.h:87
std::forward_iterator_tag iterator_category
Definition: EntityMap.h:84
bool operator==(_iter other)
Definition: EntityMap.h:107
_iter & operator++()
Definition: EntityMap.h:94
U & reference
Definition: EntityMap.h:88
U * operator->()
Definition: EntityMap.h:93
U value_type
Definition: EntityMap.h:85
U & operator*()
Definition: EntityMap.h:92
Definition: EntityMap.h:47
K first_type
Definition: EntityMap.h:48
V second
Definition: EntityMap.h:51
V second_type
Definition: EntityMap.h:49
K first
Definition: EntityMap.h:50
void operator()(IDeserializer &deserialize, const char *, EntityMap< T > &value)
Definition: EntityMap.h:280
void operator()(ISerializer &serialize, const char *, EntityMap< T > &value)
Definition: EntityMap.h:264
Definition: SerializeTemplates.h:42
pthread_key_t key
Definition: wpthread.cpp:141