using System.Collections.Generic; using Encompass.Exceptions; namespace Encompass { internal class EntityManager { private readonly int entityCapacity; private readonly IDManager idManager = new IDManager(); private readonly Dictionary IDs = new Dictionary(32768); private readonly HashSet entitiesMarkedForDestroy = new HashSet(); private readonly ComponentManager componentManager; public IEnumerable Entities { get { return IDs.Values; } } public EntityManager(ComponentManager componentManager, int entityCapacity) { this.componentManager = componentManager; this.entityCapacity = entityCapacity; } private int NextID() { return idManager.NextID(); } public Entity CreateEntity() { if (IDs.Count < entityCapacity) { var id = NextID(); var entity = new Entity(id); IDs.Add(id, entity); return entity; } else { throw new EntityOverflowException("The number of entities has exceeded the entity capacity of {0}", entityCapacity); } } public bool EntityExists(int id) { return IDs.ContainsKey(id); } public Entity GetEntity(int id) { if (!EntityExists(id)) { throw new Encompass.Exceptions.EntityNotFoundException("Entity with id {0} does not exist.", id); } return IDs[id]; } public void MarkForDestroy(Entity entity) { entitiesMarkedForDestroy.Add(entity); } public void DestroyMarkedEntities(IEnumerable engines) { foreach (var entity in entitiesMarkedForDestroy) { foreach (var engine in engines) { engine.RegisterDestroyedEntity(entity); } componentManager.MarkAllComponentsOnEntityForRemoval(entity); IDs.Remove(entity.ID); idManager.Free(entity.ID); } entitiesMarkedForDestroy.Clear(); } } }