Entitas  0.40.0
Entitas is a super fast Entity Component System (ECS) Framework specifically made for C# and Unity
EntityIndex.cs
1 using System;
2 using System.Collections.Generic;
3 
4 namespace Entitas {
5 
6  public class EntityIndex<TEntity, TKey> : AbstractEntityIndex<TEntity, TKey> where TEntity : class, IEntity, new() {
7 
8  readonly Dictionary<TKey, HashSet<TEntity>> _index;
9 
10  public EntityIndex(string name, IGroup<TEntity> group, Func<TEntity, IComponent, TKey> getKey) : base(name, group, getKey) {
11  _index = new Dictionary<TKey, HashSet<TEntity>>();
12  Activate();
13  }
14 
15  public EntityIndex(string name, IGroup<TEntity> group, Func<TEntity, IComponent, TKey[]> getKeys) : base(name, group, getKeys) {
16  _index = new Dictionary<TKey, HashSet<TEntity>>();
17  Activate();
18  }
19 
20  public EntityIndex(string name, IGroup<TEntity> group, Func<TEntity, IComponent, TKey> getKey, IEqualityComparer<TKey> comparer) : base(name, group, getKey) {
21  _index = new Dictionary<TKey, HashSet<TEntity>>(comparer);
22  Activate();
23  }
24 
25  public EntityIndex(string name, IGroup<TEntity> group, Func<TEntity, IComponent, TKey[]> getKeys, IEqualityComparer<TKey> comparer) : base(name, group, getKeys) {
26  _index = new Dictionary<TKey, HashSet<TEntity>>(comparer);
27  Activate();
28  }
29 
30  public override void Activate() {
31  base.Activate();
32  indexEntities(_group);
33  }
34 
35  public HashSet<TEntity> GetEntities(TKey key) {
36  HashSet<TEntity> entities;
37  if(!_index.TryGetValue(key, out entities)) {
38  entities = new HashSet<TEntity>(EntityEqualityComparer<TEntity>.comparer);
39  _index.Add(key, entities);
40  }
41 
42  return entities;
43  }
44 
45  public override string ToString() {
46  return "EntityIndex(" + name + ")";
47  }
48 
49  protected override void clear() {
50  foreach(var entities in _index.Values) {
51  foreach(var entity in entities) {
52 
53 #if ENTITAS_FAST_AND_UNSAFE
54  entity.Release(this);
55 #else
56  if(entity.owners.Contains(this)) {
57  entity.Release(this);
58  }
59 #endif
60  }
61  }
62 
63  _index.Clear();
64  }
65 
66  protected override void addEntity(TKey key, TEntity entity) {
67  GetEntities(key).Add(entity);
68 
69 #if ENTITAS_FAST_AND_UNSAFE
70  entity.Retain(this);
71 #else
72  if(!entity.owners.Contains(this)) {
73  entity.Retain(this);
74  }
75 #endif
76  }
77 
78  protected override void removeEntity(TKey key, TEntity entity) {
79  GetEntities(key).Remove(entity);
80 
81 #if ENTITAS_FAST_AND_UNSAFE
82  entity.Release(this);
83 #else
84  if(entity.owners.Contains(this)) {
85  entity.Release(this);
86  }
87 #endif
88  }
89  }
90 }