1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::sync::atomic::{AtomicU32, Ordering};
use core::{fmt, mem};
#[cfg(feature = "std")]
use std::error::Error;
#[derive(Clone, Copy, Hash, Eq, Ord, PartialEq, PartialOrd)]
pub struct Entity {
pub(crate) generation: u32,
pub(crate) id: u32,
}
impl Entity {
pub fn to_bits(self) -> u64 {
u64::from(self.generation) << 32 | u64::from(self.id)
}
pub fn from_bits(bits: u64) -> Self {
Self {
generation: (bits >> 32) as u32,
id: bits as u32,
}
}
pub fn id(self) -> u32 {
self.id
}
}
impl fmt::Debug for Entity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}v{}", self.id, self.generation)
}
}
#[derive(Default)]
pub(crate) struct Entities {
pub meta: Box<[EntityMeta]>,
pending: AtomicU32,
free: Box<[u32]>,
free_cursor: AtomicU32,
reserved: Box<[AtomicU32]>,
reserved_cursor: AtomicU32,
}
impl Entities {
pub fn reserve_entity(&self) -> Entity {
loop {
let index = self.free_cursor.load(Ordering::Relaxed);
match index.checked_sub(1) {
None => {
let n = self.pending.fetch_add(1, Ordering::Relaxed);
return Entity {
generation: 0,
id: u32::try_from(self.meta.len())
.ok()
.and_then(|x| x.checked_add(n))
.expect("too many entities"),
};
}
Some(next) => {
if self
.free_cursor
.compare_exchange_weak(index, next, Ordering::Relaxed, Ordering::Relaxed)
.is_err()
{
continue;
}
let id = self.free[next as usize];
let reservation = self.reserved_cursor.fetch_add(1, Ordering::Relaxed);
self.reserved[reservation as usize].store(id, Ordering::Relaxed);
return Entity {
generation: self.meta[id as usize].generation,
id,
};
}
}
}
}
pub fn alloc(&mut self) -> Entity {
debug_assert_eq!(
self.pending.load(Ordering::Relaxed),
0,
"allocator must be flushed before potentially growing"
);
let index = self.free_cursor.load(Ordering::Relaxed);
match index.checked_sub(1) {
None => {
self.grow(0);
let cursor = self.free_cursor.fetch_sub(1, Ordering::Relaxed);
let id = self.free[(cursor - 1) as usize];
Entity {
generation: self.meta[id as usize].generation,
id,
}
}
Some(next) => {
self.free_cursor.store(next, Ordering::Relaxed);
let id = self.free[next as usize];
Entity {
generation: self.meta[id as usize].generation,
id,
}
}
}
}
pub fn free(&mut self, entity: Entity) -> Result<Location, NoSuchEntity> {
let meta = &mut self.meta[entity.id as usize];
if meta.generation != entity.generation {
return Err(NoSuchEntity);
}
meta.generation += 1;
let loc = mem::replace(
&mut meta.location,
Location {
archetype: 0,
index: u32::max_value(),
},
);
let index = self.free_cursor.fetch_add(1, Ordering::Relaxed);
self.free[index as usize] = entity.id;
debug_assert!(
loc.index != u32::max_value(),
"free called on reserved entity without flush"
);
Ok(loc)
}
pub fn reserve(&mut self, additional: u32) {
debug_assert_eq!(
self.pending.load(Ordering::Relaxed),
0,
"allocator must be flushed before potentially growing"
);
let free = self.free_cursor.load(Ordering::Relaxed);
if additional > free {
self.grow(additional - free);
}
}
pub fn contains(&self, entity: Entity) -> bool {
if entity.id >= self.meta.len() as u32 {
return true;
}
self.meta[entity.id as usize].generation == entity.generation
}
pub fn clear(&mut self) {
self.free_cursor
.store(self.meta.len() as u32, Ordering::Relaxed);
for (i, x) in self.free.iter_mut().enumerate() {
*x = i as u32;
}
self.pending.store(0, Ordering::Relaxed);
self.reserved_cursor.store(0, Ordering::Relaxed);
}
pub fn get_mut(&mut self, entity: Entity) -> Result<&mut Location, NoSuchEntity> {
let meta = &mut self.meta[entity.id as usize];
if meta.generation == entity.generation {
Ok(&mut meta.location)
} else {
Err(NoSuchEntity)
}
}
pub fn get(&self, entity: Entity) -> Result<Location, NoSuchEntity> {
if self.meta.len() <= entity.id as usize {
return Ok(Location {
archetype: 0,
index: u32::max_value(),
});
}
let meta = &self.meta[entity.id as usize];
if meta.generation != entity.generation {
return Err(NoSuchEntity);
}
if meta.location.archetype == 0 {
return Ok(Location {
archetype: 0,
index: u32::max_value(),
});
}
Ok(meta.location)
}
#[allow(clippy::reversed_empty_ranges)]
pub fn flush(&mut self) -> impl Iterator<Item = u32> {
let pending = self.pending.load(Ordering::Relaxed);
if pending != 0 {
let first = self.meta.len() as u32;
self.grow(0);
first..(first + pending)
} else {
0..0
}
}
pub fn reserved_len(&self) -> u32 {
self.reserved_cursor.load(Ordering::Relaxed)
}
pub fn reserved(&self, i: u32) -> u32 {
debug_assert!(i < self.reserved_len());
self.reserved[i as usize].load(Ordering::Relaxed)
}
pub fn clear_reserved(&mut self) {
self.reserved_cursor.store(0, Ordering::Relaxed);
}
fn grow(&mut self, increment: u32) {
let pending = self.pending.swap(0, Ordering::Relaxed);
let new_len = (self.meta.len() + pending as usize + increment as usize)
.max(self.meta.len() * 2)
.max(1024);
let mut new_meta = Vec::with_capacity(new_len);
new_meta.extend_from_slice(&self.meta);
new_meta.resize(
new_len,
EntityMeta {
generation: 0,
location: Location {
archetype: 0,
index: u32::max_value(),
},
},
);
let free_cursor = self.free_cursor.load(Ordering::Relaxed);
let mut new_free = Vec::with_capacity(new_len);
new_free.extend_from_slice(&self.free[0..free_cursor as usize]);
new_free.extend(((self.meta.len() as u32 + pending)..new_len as u32).rev());
debug_assert!(new_free.len() <= new_len);
self.free_cursor
.store(new_free.len() as u32, Ordering::Relaxed);
new_free.resize(new_len, 0);
self.meta = new_meta.into();
self.free = new_free.into();
let mut new_reserved = Vec::with_capacity(new_len);
let reserved_cursor = self.reserved_cursor.load(Ordering::Relaxed);
for x in &self.reserved[..reserved_cursor as usize] {
new_reserved.push(AtomicU32::new(x.load(Ordering::Relaxed)));
}
new_reserved.resize_with(new_len, || AtomicU32::new(0));
self.reserved = new_reserved.into();
}
}
#[derive(Copy, Clone)]
pub(crate) struct EntityMeta {
pub generation: u32,
pub location: Location,
}
#[derive(Copy, Clone)]
pub(crate) struct Location {
pub archetype: u32,
pub index: u32,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct NoSuchEntity;
impl fmt::Display for NoSuchEntity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("no such entity")
}
}
#[cfg(feature = "std")]
impl Error for NoSuchEntity {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn entity_bits_roundtrip() {
let e = Entity {
generation: 0xDEADBEEF,
id: 0xBAADF00D,
};
assert_eq!(Entity::from_bits(e.to_bits()), e);
}
}