91 lines
2.6 KiB
C#
91 lines
2.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace Encompass
|
|
{
|
|
internal abstract class TypedComponentStore
|
|
{
|
|
public abstract int Count { get; }
|
|
public abstract IEnumerable<(Entity, Type, IComponent)> AllInterfaceTyped();
|
|
public abstract bool Has(Entity entity);
|
|
public abstract bool Remove(Entity entity, int priority);
|
|
public abstract void ForceRemove(Entity entity);
|
|
public abstract void Clear();
|
|
}
|
|
|
|
internal class TypedComponentStore<TComponent> : TypedComponentStore where TComponent : struct, IComponent
|
|
{
|
|
private readonly Dictionary<Entity, TComponent> store = new Dictionary<Entity, TComponent>(128);
|
|
private readonly Dictionary<Entity, int> priorities = new Dictionary<Entity, int>(128);
|
|
|
|
public override int Count { get => store.Count; }
|
|
|
|
public TComponent Get(Entity entity)
|
|
{
|
|
return store[entity];
|
|
}
|
|
|
|
public void Set(Entity entity, TComponent component)
|
|
{
|
|
store[entity] = component;
|
|
}
|
|
|
|
public bool Set(Entity entity, TComponent component, int priority)
|
|
{
|
|
if (!priorities.ContainsKey(entity) || priority < priorities[entity]) {
|
|
store[entity] = component;
|
|
priorities[entity] = priority;
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public override bool Remove(Entity entity, int priority)
|
|
{
|
|
if (!priorities.ContainsKey(entity) || priority < priorities[entity])
|
|
{
|
|
priorities[entity] = priority;
|
|
store.Remove(entity);
|
|
priorities.Remove(entity);
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public override void ForceRemove(Entity entity)
|
|
{
|
|
store.Remove(entity);
|
|
priorities.Remove(entity);
|
|
}
|
|
|
|
public override bool Has(Entity entity)
|
|
{
|
|
return store.ContainsKey(entity);
|
|
}
|
|
|
|
public override void Clear()
|
|
{
|
|
store.Clear();
|
|
priorities.Clear();
|
|
}
|
|
|
|
public IEnumerable<(TComponent, Entity)> All()
|
|
{
|
|
foreach (var kvp in store)
|
|
{
|
|
yield return (kvp.Value, kvp.Key);
|
|
}
|
|
}
|
|
|
|
public override IEnumerable<(Entity, Type, IComponent)> AllInterfaceTyped()
|
|
{
|
|
foreach (var kvp in store)
|
|
{
|
|
yield return (kvp.Key, typeof(TComponent), (IComponent)kvp.Value);
|
|
}
|
|
}
|
|
}
|
|
}
|