encompass-cs/encompass-cs/ComponentManager.cs

97 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Encompass.Exceptions;
using Collections.Pooled;
namespace Encompass
{
internal class ComponentManager
{
private readonly DrawLayerManager drawLayerManager;
private readonly ComponentMessageManager componentMessageManager;
private readonly ComponentStore componentStore = new ComponentStore();
private readonly HashSet<Entity> entitiesMarkedForRemoval = new HashSet<Entity>();
public ComponentManager(DrawLayerManager drawLayerManager, ComponentMessageManager componentMessageManager)
{
this.drawLayerManager = drawLayerManager;
this.componentMessageManager = componentMessageManager;
}
internal void SetComponentStore(ComponentStore componentStore)
{
this.componentStore.SwapWith(componentStore);
}
internal void RegisterDrawableComponent<TComponent>(Entity entity, TComponent component, int layer) where TComponent : struct, IComponent
{
drawLayerManager.RegisterComponentWithLayer(entity, component, layer);
}
internal void AddComponent<TComponent>(Entity entity, TComponent component) where TComponent : struct, IComponent
{
componentStore.Set<TComponent>(entity, component);
}
internal void WriteComponents()
{
componentStore.SwapWith(componentMessageManager.UpToDateComponentStore);
}
internal IEnumerable<(TComponent, Entity)> GetComponentsIncludingEntity<TComponent>() where TComponent : struct, IComponent
{
return componentStore.All<TComponent>().Select(pair => (pair.Item2, pair.Item1));
}
internal IEnumerable<TComponent> GetComponentsByType<TComponent>() where TComponent : struct, IComponent
{
return componentStore.All<TComponent>().Select(pair => pair.Item2);
}
internal TComponent GetComponentByEntityAndType<TComponent>(Entity entity) where TComponent : struct, IComponent
{
return componentStore.Get<TComponent>(entity);
}
internal bool EntityHasComponentOfType<TComponent>(Entity entity) where TComponent : struct, IComponent
{
return componentStore.Has<TComponent>(entity);
}
internal bool ComponentOfTypeExists<TComponent>() where TComponent : struct, IComponent
{
return componentStore.Any<TComponent>();
}
internal void MarkAllComponentsOnEntityForRemoval(Entity entity)
{
entitiesMarkedForRemoval.Add(entity);
}
internal void RemoveMarkedComponents()
{
foreach (var entity in entitiesMarkedForRemoval)
{
componentStore.Remove(entity);
drawLayerManager.UnRegisterEntityWithLayer(entity);
}
entitiesMarkedForRemoval.Clear();
}
public void Remove<TComponent>(Entity entity) where TComponent : struct, IComponent
{
//componentStore.Remove<TComponent>(entity);
componentMessageManager.Remove<TComponent>(entity);
drawLayerManager.UnRegisterComponentWithLayer<TComponent>(entity);
}
private void Remove(Entity entity)
{
componentStore.Remove(entity);
}
}
}