pooling bit arrays

pull/5/head
Evan Hemsley 2019-12-20 11:28:56 -08:00
parent 494a583240
commit 642f8df4d5
3 changed files with 47 additions and 5 deletions

View File

@ -0,0 +1,33 @@
using System.Collections;
using System.Collections.Generic;
namespace Encompass
{
internal class BitArrayPool
{
private Stack<BitArray> bitArrays;
public BitArrayPool(int capacity)
{
bitArrays = new Stack<BitArray>(capacity);
for (var i = 0; i < capacity; i++)
{
bitArrays.Push(new BitArray(128));
}
}
public BitArray Obtain(int size)
{
var bitArray = bitArrays.Pop();
bitArray.Length = size;
bitArray.SetAll(false);
return bitArray;
}
public void Free(BitArray bitArray)
{
bitArrays.Push(bitArray);
}
}
}

View File

@ -81,7 +81,7 @@ namespace Encompass
{
entry.Remove(entity);
}
componentBitSet.DestroyEntity(entity);
componentBitSet.RemoveEntity(entity);
}
public bool Any<TComponent>() where TComponent : struct, IComponent

View File

@ -6,6 +6,7 @@ namespace Encompass
{
internal class ComponentBitSet
{
BitArrayPool bitArrayPool = new BitArrayPool(32768); // todo: set entity cap
Dictionary<Entity, BitArray> entities = new Dictionary<Entity, BitArray>();
Dictionary<Type, int> typeToIndex = new Dictionary<Type, int>();
BitArray queryArray;
@ -26,13 +27,17 @@ namespace Encompass
public void Clear()
{
foreach (var kvp in entities)
{
bitArrayPool.Free(kvp.Value);
}
entities.Clear();
}
public void AddEntity(Entity entity)
{
var bitArray = new BitArray(typeToIndex.Count);
entities.Add(entity, bitArray); // this is gonna create garbage!! fuck!!
var bitArray = bitArrayPool.Obtain(typeToIndex.Count);
entities.Add(entity, bitArray);
}
public void Set<TComponent>(Entity entity) where TComponent : struct, IComponent
@ -46,10 +51,14 @@ namespace Encompass
entities[entity].Set(typeToIndex[typeof(TComponent)], false);
}
public void DestroyEntity(Entity entity)
public void RemoveEntity(Entity entity)
{
if (entities.ContainsKey(entity))
{
bitArrayPool.Free(entities[entity]);
entities.Remove(entity);
}
}
public IEnumerable<Entity> EntitiesWithComponents(IEnumerable<Type> types)
{