/
GroupManager.cs
88 lines (77 loc) · 2.31 KB
/
GroupManager.cs
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
using System;
using System.Collections.Generic;
namespace Artemis
{
public sealed class GroupManager {
private EntityWorld world;
private Bag<Entity> EMPTY_BAG = new Bag<Entity>();
private Dictionary<String, Bag<Entity>> entitiesByGroup = new Dictionary<String, Bag<Entity>>();
private Bag<String> groupByEntity = new Bag<String>();
public GroupManager(EntityWorld world) {
this.world = world;
}
/**
* Set the group of the entity.
*
* @param group group to set the entity into.
* @param e entity to set into the group.
*/
public void Set(String group, Entity e) {
Remove(e); // Entity can only belong to one group.
Bag<Entity> entities;
if(!entitiesByGroup.TryGetValue(group,out entities)) {
entities = new Bag<Entity>();
entitiesByGroup.Add(group, entities);
}
entities.Add(e);
groupByEntity.Set(e.Id, group);
}
/**
* Get all entities that belong to the provided group.
* @param group name of the group.
* @return read-only bag of entities belonging to the group.
*/
public Bag<Entity> GetEntities(String group) {
Bag<Entity> bag;
if(!entitiesByGroup.TryGetValue(group,out bag))
return EMPTY_BAG;
return bag;
}
/// <summary>
/// Removes an entity from the group it is assigned to, if any.
/// </summary>
/// <param name="e">The entity to be removed</param>
public void Remove(Entity e) {
int entityId = e.Id;
if(entityId < groupByEntity.Capacity) {
String group = groupByEntity.Get(entityId);
if(group != null) {
groupByEntity.Set(entityId, null);
Bag<Entity> entities;
if(entitiesByGroup.TryGetValue(group,out entities)) {
entities.Remove(e);
}
}
}
}
/**
* @param e entity
* @return the name of the group that this entity belongs to, null if none.
*/
public String GetGroupOf(Entity e) {
int entityId = e.Id;
if(entityId < groupByEntity.Capacity) {
return groupByEntity.Get(entityId);
}
return null;
}
/**
* Checks if the entity belongs to any group.
* @param e the entity to check.
* @return true if it is in any group, false if none.
*/
public bool IsGrouped(Entity e) {
return GetGroupOf(e) != null;
}
}
}