MoonTools.ECS/src/ComponentStorage.cs

107 lines
2.4 KiB
C#
Raw Normal View History

2022-03-05 02:01:44 +00:00
namespace MoonTools.ECS;
internal abstract class ComponentStorage
{
2022-03-06 06:12:27 +00:00
public abstract bool Has(int entityID);
2022-03-05 02:01:44 +00:00
public abstract void Remove(int entityID);
2022-03-25 19:32:35 +00:00
public abstract object Debug_Get(int entityID);
2022-03-05 02:01:44 +00:00
}
// FIXME: we can probably get rid of this weird entity storage system by using filters
2022-03-05 02:01:44 +00:00
internal class ComponentStorage<TComponent> : ComponentStorage where TComponent : struct
{
private int nextID;
private readonly Dictionary<int, int> entityIDToStorageIndex = new Dictionary<int, int>(16);
private int[] entityIDs = new int[16];
private TComponent[] components = new TComponent[16];
2022-03-05 02:01:44 +00:00
public bool Any()
{
return nextID > 0;
}
2022-03-06 06:12:27 +00:00
public override bool Has(int entityID)
2022-03-05 02:01:44 +00:00
{
return entityIDToStorageIndex.ContainsKey(entityID);
}
public ref readonly TComponent Get(int entityID)
{
return ref components[entityIDToStorageIndex[entityID]];
}
2022-03-25 19:32:35 +00:00
public override object Debug_Get(int entityID)
{
return components[entityIDToStorageIndex[entityID]];
}
2022-03-21 23:21:42 +00:00
public ref readonly TComponent Get()
{
#if DEBUG
if (nextID == 0)
{
throw new ArgumentOutOfRangeException("Component storage is empty!");
}
#endif
return ref components[0];
}
2022-03-05 02:01:44 +00:00
public void Set(int entityID, in TComponent component)
{
if (!entityIDToStorageIndex.ContainsKey(entityID))
{
var index = nextID;
nextID += 1;
if (index >= components.Length)
{
Array.Resize(ref components, components.Length * 2);
Array.Resize(ref entityIDs, entityIDs.Length * 2);
2022-03-05 02:01:44 +00:00
}
entityIDToStorageIndex[entityID] = index;
entityIDs[index] = entityID;
2022-03-05 02:01:44 +00:00
}
components[entityIDToStorageIndex[entityID]] = component;
}
public override void Remove(int entityID)
{
if (entityIDToStorageIndex.ContainsKey(entityID))
{
var storageIndex = entityIDToStorageIndex[entityID];
entityIDToStorageIndex.Remove(entityID);
var lastElementIndex = nextID - 1;
// move a component into the hole to maintain contiguous memory
if (lastElementIndex != storageIndex)
2022-03-05 02:01:44 +00:00
{
var lastEntityID = entityIDs[lastElementIndex];
entityIDToStorageIndex[lastEntityID] = storageIndex;
2022-03-05 02:01:44 +00:00
components[storageIndex] = components[lastElementIndex];
entityIDs[storageIndex] = lastEntityID;
2022-03-05 02:01:44 +00:00
}
nextID -= 1;
}
}
public void Clear()
{
nextID = 0;
entityIDToStorageIndex.Clear();
}
public ReadOnlySpan<TComponent> AllComponents()
{
return new ReadOnlySpan<TComponent>(components, 0, nextID);
}
2022-03-21 23:21:42 +00:00
public Entity FirstEntity()
2022-03-21 23:21:42 +00:00
{
return new Entity(entityIDs[0]);
2022-03-21 23:21:42 +00:00
}
2022-03-05 02:01:44 +00:00
}