encompass-cs/encompass-cs/EntityManager.cs

93 lines
2.5 KiB
C#
Raw Normal View History

2019-12-20 20:52:38 +00:00
using System.Collections.Generic;
using Encompass.Exceptions;
2019-06-16 01:05:56 +00:00
namespace Encompass
{
internal class EntityManager
{
2019-12-20 20:52:38 +00:00
private readonly int entityCapacity;
private readonly IDManager idManager = new IDManager();
2019-12-29 21:54:08 +00:00
private readonly HashSet<int> IDs = new HashSet<int>();
2019-12-29 21:54:08 +00:00
private readonly HashSet<int> entitiesMarkedForDestroy = new HashSet<int>();
2019-06-19 23:13:02 +00:00
2019-06-20 17:46:15 +00:00
private readonly ComponentManager componentManager;
2019-12-29 21:54:08 +00:00
public IEnumerable<int> EntityIDs
2019-12-22 09:15:58 +00:00
{
2019-12-29 21:54:08 +00:00
get { return IDs; }
2019-12-22 09:15:58 +00:00
}
2019-12-20 20:52:38 +00:00
public EntityManager(ComponentManager componentManager, int entityCapacity)
2019-06-16 01:05:56 +00:00
{
this.componentManager = componentManager;
2019-12-20 20:52:38 +00:00
this.entityCapacity = entityCapacity;
}
private int NextID()
{
return idManager.NextID();
}
2019-06-16 01:05:56 +00:00
public Entity CreateEntity()
{
2019-12-20 20:52:38 +00:00
if (IDs.Count < entityCapacity)
{
var id = NextID();
var entity = new Entity(id);
2019-12-29 21:54:08 +00:00
IDs.Add(id);
2019-12-20 20:52:38 +00:00
return entity;
}
else
{
throw new EntityOverflowException("The number of entities has exceeded the entity capacity of {0}", entityCapacity);
}
}
2019-12-20 20:52:38 +00:00
public bool EntityExists(int id)
{
2019-12-29 21:54:08 +00:00
return IDs.Contains(id);
}
public Entity GetEntity(int id)
{
if (!EntityExists(id))
{
throw new Encompass.Exceptions.EntityNotFoundException("Entity with id {0} does not exist.", id);
}
2019-12-29 21:54:08 +00:00
return new Entity(id);
}
2019-12-29 21:54:08 +00:00
public void MarkForDestroy(int entityID)
2019-06-16 01:05:56 +00:00
{
2019-12-29 21:54:08 +00:00
entitiesMarkedForDestroy.Add(entityID);
}
2019-12-29 00:16:21 +00:00
public void DestroyMarkedEntities(IEnumerable<Engine> engines)
2019-06-16 01:05:56 +00:00
{
2019-12-29 21:54:08 +00:00
foreach (var entityID in entitiesMarkedForDestroy)
2019-06-16 01:05:56 +00:00
{
2019-12-29 21:54:08 +00:00
foreach (var engine in engines) { engine.RegisterDestroyedEntity(entityID); }
componentManager.MarkAllComponentsOnEntityForRemoval(entityID);
IDs.Remove(entityID);
idManager.Free(entityID);
}
2019-06-19 23:13:02 +00:00
entitiesMarkedForDestroy.Clear();
}
2020-03-18 00:40:11 +00:00
// NOTE: this is very suboptimal
public void PruneEmptyEntities()
{
foreach (var id in EntityIDs)
{
if (componentManager.UpToDateEntityIsEmpty(id))
{
MarkForDestroy(id);
}
}
}
}
}