using System; using Unity.Collections; using Unity.Mathematics; namespace GameCore.TinyECS { public struct EntityDatabase : IDisposable where TEnum : unmanaged, IConvertible where TData : unmanaged, IEntityDataStruct { public TData dataStruct; public EntityGenerator generator; public EntityCollection collection; public int Count => collection.Count; internal EntityDatabase(TEnum type, TData dataStruct, int initCapacity, AllocatorManager.AllocatorHandle allocator) { generator = new(type, initCapacity, allocator); collection = new(type, initCapacity, allocator); this.dataStruct = dataStruct; } public Entity AddEntity() { var entity = generator.Create(); collection.Add(entity); dataStruct.Add(); return entity; } public void RemoveEntity(Entity entity) { generator.Delete(entity); if (collection.Remove(entity, out var index, out var _)) dataStruct.Remove(index); } public T GetData(Entity entity) where T : unmanaged { var index = collection.GetIndex(entity); return dataStruct.GetData(index); } public ref T GetDataRef(Entity entity) where T : unmanaged { var index = collection.GetIndex(entity); return ref dataStruct.GetDataRef(index); } public void Dispose() { generator.Dispose(); collection.Dispose(); dataStruct.Dispose(); } } public static class EntityDataBaseExtensions { public static EntityDatabase CreateEntityDatabase(this TData dataStruct, TEnum type, int initCapacity) where TEnum : unmanaged, IConvertible where TData : unmanaged, IEntityDataStruct { return new EntityDatabase(type, dataStruct, initCapacity, dataStruct.Allocator); } } }