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
use std::any::TypeId;
use std::collections::HashMap;
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::sync::atomic::{AtomicUsize, Ordering};
use mopa::Any;
use bitset::{AtomicBitSet, BitSet, BitSetLike, BitSetOr};
use join::Join;
use storage::{Storage, MaskedStorage, UnprotectedStorage};
use {Index, Generation, Entity};
pub trait Component: Any + Sized {
type Storage: UnprotectedStorage<Self> + Any + Send + Sync;
}
pub struct Entities<'a> {
guard: RwLockReadGuard<'a, Allocator>,
}
impl<'a> Join for &'a Entities<'a> {
type Type = Entity;
type Value = Self;
type Mask = BitSetOr<&'a BitSet, &'a AtomicBitSet>;
fn open(self) -> (Self::Mask, Self) {
(BitSetOr(&self.guard.alive, &self.guard.raised), self)
}
unsafe fn get(v: &mut Self, idx: Index) -> Entity {
let gen = v.guard.generations.get(idx as usize)
.map(|&gen| if gen.is_alive() { gen } else { gen.raised() })
.unwrap_or(Generation(1));
Entity(idx, gen)
}
}
pub struct EntityBuilder<'a>(Entity, &'a World);
impl<'a> EntityBuilder<'a> {
pub fn with<T: Component>(self, value: T) -> EntityBuilder<'a> {
self.1.write::<T>().insert(self.0, value);
self
}
pub fn build(self) -> Entity {
self.0
}
}
pub struct Allocator {
#[doc(hidden)]
pub generations: Vec<Generation>,
alive: BitSet,
raised: AtomicBitSet,
killed: AtomicBitSet,
start_from: AtomicUsize
}
impl Allocator {
#[doc(hidden)]
pub fn new() -> Allocator {
Allocator {
generations: vec![],
alive: BitSet::new(),
raised: AtomicBitSet::new(),
killed: AtomicBitSet::new(),
start_from: AtomicUsize::new(0)
}
}
fn kill(&self, e: Entity) {
self.killed.add_atomic(e.get_id());
}
pub fn is_alive(&self, e: Entity) -> bool {
e.get_gen() == match self.generations.get(e.get_id() as usize) {
Some(g) if !g.is_alive() && self.raised.contains(e.get_id()) => g.raised(),
Some(g) => *g,
None => Generation(1),
}
}
fn update_start_from(&self, start_from: usize) {
loop {
let current = self.start_from.load(Ordering::Relaxed);
if current >= start_from {
return;
}
if start_from == self.start_from.compare_and_swap(current, start_from, Ordering::Relaxed) {
return;
}
}
}
fn allocate_atomic(&self) -> Entity {
let idx = self.start_from.load(Ordering::Relaxed);
for i in idx.. {
if !self.alive.contains(i as Index) && !self.raised.add_atomic(i as Index) {
self.update_start_from(i+1);
let gen = self.generations.get(i as usize)
.map(|&gen| if gen.is_alive() { gen } else { gen.raised() })
.unwrap_or(Generation(1));
return Entity(i as Index, gen);
}
}
panic!("No entities left to allocate")
}
fn allocate(&mut self) -> Entity {
let idx = self.start_from.load(Ordering::Relaxed);
for i in idx.. {
if !self.raised.contains(i as Index) && !self.alive.add(i as Index) {
self.start_from.store(i+1, Ordering::Relaxed);
while self.generations.len() <= i as usize {
self.generations.push(Generation(0));
}
self.generations[i as usize] = self.generations[i as usize].raised();
return Entity(i as Index, self.generations[i as usize]);
}
}
panic!("No entities left to allocate")
}
fn merge(&mut self) -> Vec<Entity> {
let mut deleted = vec![];
for i in (&self.raised).iter() {
while self.generations.len() <= i as usize {
self.generations.push(Generation(0));
}
self.generations[i as usize] = self.generations[i as usize].raised();
self.alive.add(i);
}
self.raised.clear();
if let Some(lowest) = (&self.killed).iter().next() {
if lowest < self.start_from.load(Ordering::Relaxed) as Index {
self.start_from.store(lowest as usize, Ordering::Relaxed);
}
}
for i in (&self.killed).iter() {
self.alive.remove(i);
self.generations[i as usize].die();
deleted.push(Entity(i, self.generations[i as usize]))
}
self.killed.clear();
deleted
}
}
pub struct CreateEntities<'a> {
allocate: RwLockWriteGuard<'a, Allocator>,
}
impl<'a> Iterator for CreateEntities<'a> {
type Item = Entity;
fn next(&mut self) -> Option<Entity> {
Some(self.allocate.allocate())
}
}
trait StorageLock: Any + Send + Sync {
fn del_slice(&self, &[Entity]);
}
mopafy!(StorageLock);
impl<T: Component> StorageLock for RwLock<MaskedStorage<T>> {
fn del_slice(&self, entities: &[Entity]) {
let mut guard = self.write().unwrap();
for &e in entities.iter() {
guard.remove(e.get_id());
}
}
}
trait ResourceLock: Any + Send + Sync {}
mopafy!(ResourceLock);
impl<T:Any+Send+Sync> ResourceLock for RwLock<T> {}
pub struct World {
allocator: RwLock<Allocator>,
components: HashMap<TypeId, Box<StorageLock>>,
resources: HashMap<TypeId, Box<ResourceLock>>,
}
impl World {
pub fn new() -> World {
World {
components: HashMap::new(),
allocator: RwLock::new(Allocator::new()),
resources: HashMap::new()
}
}
pub fn register<T: Component>(&mut self) {
let any = RwLock::new(MaskedStorage::<T>::new());
self.components.insert(TypeId::of::<T>(), Box::new(any));
}
pub fn unregister<T: Component>(&mut self) -> Option<MaskedStorage<T>> {
self.components.remove(&TypeId::of::<T>()).map(|boxed|
match boxed.downcast::<RwLock<MaskedStorage<T>>>() {
Ok(b) => (*b).into_inner().unwrap(),
Err(_) => panic!("Unable to downcast the storage type"),
}
)
}
fn lock<T: Component>(&self) -> &RwLock<MaskedStorage<T>> {
let boxed = self.components.get(&TypeId::of::<T>())
.expect("Tried to perform an operation on type that was not registered");
boxed.downcast_ref().unwrap()
}
pub fn read<T: Component>(&self) -> Storage<T, RwLockReadGuard<Allocator>, RwLockReadGuard<MaskedStorage<T>>> {
let data = self.lock::<T>().read().unwrap();
Storage::new(self.allocator.read().unwrap(), data)
}
pub fn write<T: Component>(&self) -> Storage<T, RwLockReadGuard<Allocator>, RwLockWriteGuard<MaskedStorage<T>>> {
let data = self.lock::<T>().write().unwrap();
Storage::new(self.allocator.read().unwrap(), data)
}
pub fn entities(&self) -> Entities {
Entities {
guard: self.allocator.read().unwrap(),
}
}
pub fn create_iter(&mut self) -> CreateEntities {
CreateEntities {
allocate: self.allocator.write().unwrap(),
}
}
pub fn create_now(&mut self) -> EntityBuilder {
let id = self.allocator.write().unwrap().allocate();
EntityBuilder(id, self)
}
pub fn delete_now(&mut self, entity: Entity) {
for comp in self.components.values() {
comp.del_slice(&[entity]);
}
let mut gens = self.allocator.write().unwrap();
gens.alive.remove(entity.get_id());
gens.raised.remove(entity.get_id());
let id = entity.get_id() as usize;
gens.generations[id].die();
if id < gens.start_from.load(Ordering::Relaxed) {
gens.start_from.store(id, Ordering::Relaxed);
}
}
pub fn create_later(&self) -> Entity {
let allocator = self.allocator.read().unwrap();
allocator.allocate_atomic()
}
pub fn delete_later(&self, entity: Entity) {
let allocator = self.allocator.read().unwrap();
allocator.kill(entity);
}
pub fn is_alive(&self, entity: Entity) -> bool {
debug_assert!(entity.get_gen().is_alive());
let gens = self.allocator.read().unwrap();
gens.generations.get(entity.get_id() as usize).map(|&x| x == entity.get_gen()).unwrap_or(false)
}
pub fn maintain(&mut self) {
let mut allocator = self.allocator.write().unwrap();
let temp_list = allocator.merge();
for comp in self.components.values() {
comp.del_slice(&temp_list);
}
}
pub fn add_resource<T: Any+Send+Sync>(&mut self, resource: T) {
let resource = Box::new(RwLock::new(resource));
self.resources.insert(TypeId::of::<T>(), resource);
}
pub fn has_resource<T: Any+Send+Sync>(&self) -> bool {
self.resources.get(&TypeId::of::<T>()).is_some()
}
pub fn read_resource<T: Any+Send+Sync>(&self) -> RwLockReadGuard<T> {
self.resources.get(&TypeId::of::<T>())
.expect("Resource was not registered")
.downcast_ref::<RwLock<T>>()
.unwrap()
.read()
.unwrap()
}
pub fn write_resource<T: Any+Send+Sync>(&self) -> RwLockWriteGuard<T> {
self.resources.get(&TypeId::of::<T>())
.expect("Resource was not registered")
.downcast_ref::<RwLock<T>>()
.unwrap()
.write()
.unwrap()
}
}