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
351
352
353
354
355
356
use std::collections::{HashSet, HashMap};
use std::collections::hash_map::{Iter as HIter, IterMut as HIterMut};
use std::any::{TypeId, Any};
use std::hash::Hash;
use std::fmt;
use std::fmt::Debug;
trait CompList<E> : Any {
fn remove(&mut self, &E) -> bool;
fn as_any_mut(&mut self) -> &mut Any;
fn as_any(&self) -> &Any;
fn debug(&self, &mut fmt::Formatter, &E, &str) -> Option<fmt::Result>;
}
impl<C: Any, E: Hash + Eq + Any> CompList<E> for CList<C, E> {
fn remove(&mut self, a: &E) -> bool { self.0.remove(a).is_some() }
fn as_any_mut(&mut self) -> &mut Any { self }
fn as_any(&self) -> &Any { self }
fn debug(&self, f: &mut fmt::Formatter, a: &E, prefix: &str) -> Option<fmt::Result> {
self.1.as_ref().and_then(|b| self.0.get(a).map(|c| {
try!(f.write_str(prefix));
b(c, f)
}))
}
}
struct CList<C: Any, E: Hash + Eq>(HashMap<E, C>, Option<Box<Fn(&C, &mut fmt::Formatter) -> fmt::Result>>);
impl<C: Any, E: Hash + Eq> CList<C, E> {
fn new_nodbg() -> CList<C, E> { CList(HashMap::new(), None) }
}
impl<C: Any + Debug, E: Hash + Eq> CList<C, E> {
fn new_dbg() -> CList<C, E> { CList(HashMap::new(), Some(Box::new(
|c: &C, f: &mut fmt::Formatter| (c as &Debug).fmt(f)))) }
}
pub struct Iter<'a, E: 'a, C: 'a>(Option<HIter<'a, E, C>>);
impl<'a, E: 'a, C: 'a> Iterator for Iter<'a, E, C> {
type Item = (&'a E, &'a C);
fn next(&mut self) -> Option<(&'a E, &'a C)> { self.0.as_mut().and_then(|s| s.next()) }
}
pub struct IterMut<'a, E: 'a, C: 'a>(Option<HIterMut<'a, E, C>>);
impl<'a, E: 'a, C: 'a> Iterator for IterMut<'a, E, C> {
type Item = (&'a E, &'a mut C);
fn next(&mut self) -> Option<(&'a E, &'a mut C)> { self.0.as_mut().and_then(|s| s.next()) }
}
#[derive(Default)]
pub struct ECMap<E: Hash + Eq = u32> {
entities: HashSet<E>,
components: HashMap<TypeId, Box<CompList<E>>>,
last_entity: E,
}
impl<E: Hash + Eq + Default> ECMap<E> {
pub fn new_custom() -> ECMap<E> { Default::default() }
}
impl<E: Hash + Eq + Any + Copy> ECMap<E> {
fn clist<C: Any>(&self) -> Option<&CList<C, E>> {
self.components.get(&TypeId::of::<C>()).map(|c|
c.as_any().downcast_ref::<CList<C, E>>().unwrap())
}
fn clist_mut<C: Any>(&mut self) -> Option<&mut CList<C, E>> {
self.components.get_mut(&TypeId::of::<C>()).map(|c|
c.as_any_mut().downcast_mut::<CList<C, E>>().unwrap())
}
pub fn insert<C: Any>(&mut self, e: E, c: C) -> Option<C> {
self.entities.insert(e);
let q = self.components.entry(TypeId::of::<C>())
.or_insert_with(|| Box::new(CList::<C, E>::new_nodbg()));
q.as_any_mut().downcast_mut::<CList<C, E>>().unwrap().0.insert(e, c)
}
pub fn insert_component<C: Any + Debug>(&mut self) -> bool {
if self.contains_component::<C>() { return false }
self.components.insert(TypeId::of::<C>(), Box::new(CList::<C, E>::new_dbg()));
true
}
pub fn get<C: Any>(&self, e: E) -> Option<&C> {
self.clist::<C>().and_then(|s| s.0.get(&e))
}
pub fn get_mut<C: Any>(&mut self, e: E) -> Option<&mut C> {
self.clist_mut::<C>().and_then(|s| s.0.get_mut(&e))
}
pub fn contains<C: Any>(&self, e: E) -> bool {
self.get::<C>(e).is_some()
}
pub fn contains_entity(&self, e: E) -> bool {
self.entities.contains(&e)
}
pub fn contains_component<C: Any>(&self) -> bool {
self.components.contains_key(&TypeId::of::<C>())
}
pub fn remove<C: Any>(&mut self, e: E) -> bool {
self.components.get_mut(&TypeId::of::<C>()).map(
|s| s.remove(&e)).unwrap_or(false)
}
pub fn remove_entity(&mut self, e: E) -> bool {
if !self.entities.remove(&e) { return false };
for (_, c) in self.components.iter_mut() { c.remove(&e); }
true
}
pub fn remove_component<C: Any>(&mut self) -> bool {
self.components.remove(&TypeId::of::<C>()).is_some()
}
pub fn clone_with<C: Any + Clone>(&self) -> Vec<(E, C)> {
self.iter_with::<C>().map(|(k, v)| (*k, v.clone())).collect()
}
pub fn iter_with<C: Any>(&self) -> Iter<E, C> {
let c = if let Some(s) = self.clist::<C>() { s } else { return Iter(None) };
Iter(Some(c.0.iter()))
}
pub fn iter_mut_with<C: Any>(&mut self) -> IterMut<E, C> {
let c = if let Some(s) = self.clist_mut::<C>() { s } else { return IterMut(None) };
IterMut(Some(c.0.iter_mut()))
}
}
impl<E: Hash + Eq + Debug> Debug for ECMap<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(f.write_str("ECMap {"));
let mut fent = true;
for e in self.entities.iter() {
if !fent { try!(f.write_str(",\n")) };
fent = false;
try!(write!(f, "{:?}: (", e));
let mut fcomp = true;
for c in self.components.values() {
match c.debug(f, e, if fcomp {""} else {", "}) {
Some(Err(fe)) => return Err(fe),
Some(_) => fcomp = false,
None => {},
}
}
try!(f.write_str(")"));
}
f.write_str("}")
}
}
impl ECMap<u32> {
pub fn new() -> ECMap<u32> { Default::default() }
pub fn new_u32() -> ECMap<u32> { Default::default() }
pub fn insert_entity(&mut self) -> u32 {
self.last_entity += 1;
self.entities.insert(self.last_entity);
self.last_entity
}
}
impl ECMap<usize> {
pub fn new_usize() -> ECMap<usize> { Default::default() }
pub fn insert_entity(&mut self) -> usize {
self.last_entity += 1;
self.entities.insert(self.last_entity);
self.last_entity
}
}
impl ECMap<u64> {
pub fn new_u64() -> ECMap<u64> { Default::default() }
pub fn insert_entity(&mut self) -> u64 {
self.last_entity += 1;
self.entities.insert(self.last_entity);
self.last_entity
}
}
#[test]
fn do_test() {
let mut e = ECMap::new_usize();
let id = e.insert_entity();
assert_eq!(e.insert(id, 6u16), None);
assert_eq!(e.insert(id, 10u32), None);
assert_eq!(e.insert(id, 7u16), Some(6u16));
{
let q: &mut u32 = e.get_mut(id).unwrap();
*q += 1;
}
assert_eq!(e.get::<u32>(id), Some(&11u32));
assert_eq!(e.get::<i32>(id), None);
assert_eq!(&*e.clone_with::<u16>(), &[(id, 7u16)][..]);
e.remove_entity(id);
assert_eq!(&*e.clone_with::<u16>(), &[][..]);
}
#[test]
fn debug_test() {
let mut e = ECMap::new();
#[derive(Debug)]
struct Name(&'static str);
e.insert_component::<Name>();
e.insert_component::<u32>();
let id1 = e.insert_entity();
e.insert(id1, Name("Test"));
e.insert(id1, 7u32);
let id2 = e.insert_entity();
e.insert(id2, 5u16);
let s1 = "ECMap {1: (7, Name(\"Test\")),\n2: ()}";
let s2 = "ECMap {2: (),\n1: (7, Name(\"Test\"))}";
let s3 = "ECMap {1: (Name(\"Test\"), 7),\n2: ()}";
let s4 = "ECMap {2: (),\n1: (Name(\"Test\"), 7)}";
let s = format!("{:?}", e);
println!("{}", s);
assert!(s == s1 || s == s2 || s == s3 || s == s4);
}
#[test]
fn str_as_id() {
let mut e = ECMap::new_custom();
#[derive(Debug, Eq, PartialEq, Hash)]
struct Sound(&'static str);
e.insert("Cat", Sound("Meow"));
assert_eq!(e.get::<Sound>("Cat"), Some(&Sound("Meow")));
}
#[test]
fn same_as_doc() {
#[derive(Debug, Clone)]
struct Sound(String);
let mut map = ECMap::new();
map.insert_component::<Sound>();
let cat = map.insert_entity();
map.insert(cat, Sound("Meow".into()));
println!("{:?}", map);
println!("{:?}", map.get::<Sound>(cat));
map.get_mut::<Sound>(cat).unwrap().0 = "Voof!".into();
let computer = map.insert_entity();
map.insert(computer, Sound("Hello world".into()));
for (id, sound) in map.iter_with::<Sound>() {
println!("{} says {}!", id, sound.0);
}
map.remove_entity(cat);
}