DragonECS/src/EcsWorld.cs

477 lines
18 KiB
C#
Raw Normal View History

using DCFApixels.DragonECS.Internal;
using DCFApixels.DragonECS.Utils;
using System;
2023-03-02 14:42:44 +08:00
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace DCFApixels.DragonECS
{
2023-06-21 01:37:05 +08:00
public abstract partial class EcsWorld
{
public readonly short id;
private bool _isDestroyed;
private IntDispenser _entityDispenser;
private int _entitiesCount;
2023-04-18 19:35:42 +08:00
private int _entitesCapacity;
2023-05-26 00:24:38 +08:00
private short[] _gens; //старший бит указывает на то жива ли сущность
private short[] _componentCounts;
2023-04-20 11:37:27 +08:00
private EcsGroup _allEntites;
2023-04-20 18:23:23 +08:00
private int[] _delEntBuffer;
2023-04-20 11:37:27 +08:00
private int _delEntBufferCount;
private int _delEntBufferMinCount;
2023-11-22 16:08:49 +08:00
private int _freeSpace;
2023-04-18 19:35:42 +08:00
2023-06-18 00:39:25 +08:00
private List<WeakReference<EcsGroup>> _groups = new List<WeakReference<EcsGroup>>();
2023-04-18 19:35:42 +08:00
private Stack<EcsGroup> _groupsPool = new Stack<EcsGroup>(64);
2023-04-01 20:45:37 +08:00
2023-06-18 00:39:25 +08:00
private List<IEcsWorldEventListener> _listeners = new List<IEcsWorldEventListener>();
private List<IEcsEntityEventListener> _entityListeners = new List<IEcsEntityEventListener>();
2023-04-01 20:45:37 +08:00
2023-11-22 17:35:03 +08:00
internal int[][] _entitiesComponentMasks;
private readonly PoolsMediator _poolsMediator;
2023-03-02 14:42:44 +08:00
#region Properties
public bool IsDestroyed => _isDestroyed;
2023-04-18 19:35:42 +08:00
public int Count => _entitiesCount;
public int Capacity => _entitesCapacity; //_denseEntities.Length;
2023-11-22 16:08:49 +08:00
public int DelEntBufferCount => _delEntBufferCount;
2023-04-09 02:52:39 +08:00
public EcsReadonlyGroup Entities => _allEntites.Readonly;
2023-05-26 00:24:38 +08:00
public ReadOnlySpan<IEcsPoolImplementation> AllPools => _pools;// new ReadOnlySpan<IEcsPoolImplementation>(pools, 0, _poolsCount);
2023-04-23 22:55:13 +08:00
#endregion
2023-04-20 20:10:16 +08:00
#region Constructors/Destroy
public EcsWorld() : this(true) { }
internal EcsWorld(bool isIndexable)
{
_poolsMediator = new PoolsMediator(this);
2023-04-23 17:19:52 +08:00
_entitesCapacity = 512;
if (isIndexable)
{
id = (short)_worldIdDispenser.UseFree();
if (id >= Worlds.Length)
Array.Resize(ref Worlds, Worlds.Length << 1);
Worlds[id] = this;
}
2023-04-07 15:11:48 +08:00
_entityDispenser = new IntDispenser(0);
2023-05-26 00:24:38 +08:00
_pools = new IEcsPoolImplementation[512];
ArrayUtility.Fill(_pools, _nullPool);
2023-04-01 20:45:37 +08:00
2023-04-23 17:19:52 +08:00
_gens = new short[_entitesCapacity];
_componentCounts = new short[_entitesCapacity];
2023-04-23 17:19:52 +08:00
ArrayUtility.Fill(_gens, DEATH_GEN_BIT);
2023-04-20 11:37:27 +08:00
_delEntBufferCount = 0;
//_delEntBuffer = new int[_entitesCapacity >> DEL_ENT_BUFFER_SIZE_OFFSET];
_delEntBuffer = new int[_entitesCapacity];
2023-11-22 17:35:03 +08:00
_entitiesComponentMasks = new int[_entitesCapacity][];
for (int i = 0; i < _entitesCapacity; i++)
_entitiesComponentMasks[i] = new int[_pools.Length / 32 + 1];
_delEntBufferMinCount = Math.Max(_delEntBuffer.Length >> DEL_ENT_BUFFER_SIZE_OFFSET, DEL_ENT_BUFFER_MIN_SIZE);
2023-04-18 19:35:42 +08:00
2023-06-01 20:14:34 +08:00
_allEntites = GetFreeGroup();
2023-03-02 14:42:44 +08:00
}
2023-04-20 20:10:16 +08:00
public void Destroy()
{
2023-04-20 20:10:16 +08:00
_entityDispenser = null;
_gens = null;
2023-05-26 00:24:38 +08:00
_pools = null;
2023-04-20 20:10:16 +08:00
_nullPool = null;
Worlds[id] = null;
2023-06-21 15:03:33 +08:00
ReleaseData(id);
_worldIdDispenser.Release(id);
_isDestroyed = true;
_poolIds = null;
_componentIds = null;
}
2023-03-02 14:42:44 +08:00
#endregion
2023-05-30 04:32:09 +08:00
#region Getters
2023-05-28 05:53:08 +08:00
#if UNITY_2020_3_OR_NEWER
[UnityEngine.Scripting.Preserve]
#endif
2023-07-02 16:45:40 +08:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-06-22 14:31:13 +08:00
public TAspect GetAspect<TAspect>() where TAspect : EcsAspect
{
2023-06-27 05:30:45 +08:00
return Get<AspectCache<TAspect>>().instance;
}
2023-06-27 05:30:45 +08:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-05-27 15:59:46 +08:00
public TExecutor GetExecutor<TExecutor>() where TExecutor : EcsQueryExecutor, new()
{
2023-06-27 05:30:45 +08:00
return Get<ExcecutorCache<TExecutor>>().instance;
2023-05-30 15:20:27 +08:00
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-06-21 15:03:33 +08:00
public ref T Get<T>() where T : struct => ref WorldComponentPool<T>.GetForWorld(id);
2023-07-02 16:17:13 +08:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref T UncheckedGet<T>() where T : struct => ref WorldComponentPool<T>.UncheckedGetForWorld(id);
2023-07-03 02:44:35 +08:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T Get<T>(int worldID) where T : struct => ref WorldComponentPool<T>.GetForWorld(worldID);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T UncheckedGet<T>(int worldID) where T : struct => ref WorldComponentPool<T>.UncheckedGetForWorld(worldID);
2023-05-30 04:32:09 +08:00
#endregion
#region Where Query
2023-06-22 14:31:13 +08:00
public EcsReadonlyGroup WhereFor<TAspect>(EcsReadonlyGroup sourceGroup, out TAspect aspect) where TAspect : EcsAspect
{
2023-06-22 14:31:13 +08:00
var executor = GetExecutor<EcsWhereExecutor<TAspect>>();
aspect = executor.Aspect;
return executor.ExecuteFor(sourceGroup);
}
2023-06-22 14:31:13 +08:00
public EcsReadonlyGroup WhereFor<TAspect>(EcsReadonlyGroup sourceGroup) where TAspect : EcsAspect
{
2023-06-22 14:31:13 +08:00
return GetExecutor<EcsWhereExecutor<TAspect>>().ExecuteFor(sourceGroup);
}
2023-06-22 14:31:13 +08:00
public EcsReadonlyGroup Where<TAspect>(out TAspect aspect) where TAspect : EcsAspect
{
2023-06-22 14:31:13 +08:00
var executor = GetExecutor<EcsWhereExecutor<TAspect>>();
aspect = executor.Aspect;
return executor.Execute();
}
2023-06-22 14:31:13 +08:00
public EcsReadonlyGroup Where<TAspect>() where TAspect : EcsAspect
{
2023-06-22 14:31:13 +08:00
return GetExecutor<EcsWhereExecutor<TAspect>>().Execute();
}
#endregion
2023-03-26 11:19:03 +08:00
#region Entity
2023-12-20 19:06:17 +08:00
public int NewEntity()
2023-03-02 14:42:44 +08:00
{
2023-11-22 16:08:49 +08:00
if(_freeSpace <= 1 && _delEntBufferCount > _delEntBufferMinCount)
ReleaseDelEntityBuffer();
2023-03-26 11:19:03 +08:00
int entityID = _entityDispenser.GetFree();
2023-11-22 16:08:49 +08:00
_freeSpace--;
2023-04-18 19:35:42 +08:00
_entitiesCount++;
2023-04-01 20:45:37 +08:00
if (_gens.Length <= entityID)
2023-11-22 20:28:11 +08:00
Upsize();
2023-05-23 01:47:28 +08:00
2023-04-23 17:19:52 +08:00
_gens[entityID] &= GEN_BITS;
2023-04-09 02:52:39 +08:00
_allEntites.Add(entityID);
2023-06-10 18:58:43 +08:00
_entityListeners.InvokeOnNewEntity(entityID);
return entityID;
}
2023-12-20 19:06:17 +08:00
public entlong NewEntityLong()
{
2023-12-20 19:06:17 +08:00
int e = NewEntity();
return GetEntityLong(e);
2023-03-26 11:19:03 +08:00
}
public void DelEntity(int entityID)
2023-03-26 11:19:03 +08:00
{
_allEntites.Remove(entityID);
_delEntBuffer[_delEntBufferCount++] = entityID;
_gens[entityID] |= DEATH_GEN_BIT;
_entitiesCount--;
2023-06-10 18:58:43 +08:00
_entityListeners.InvokeOnDelEntity(entityID);
2023-04-20 11:37:27 +08:00
if (_delEntBufferCount >= _delEntBuffer.Length)
2023-04-24 16:48:18 +08:00
ReleaseDelEntityBuffer();
2023-04-20 11:37:27 +08:00
}
2023-04-24 16:48:18 +08:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-07-02 21:39:44 +08:00
public unsafe entlong GetEntityLong(int entityID)
{
long x = (long)id << 48 | (long)_gens[entityID] << 32 | (long)entityID;
2023-07-02 21:39:44 +08:00
return *(entlong*)&x;
}
2023-04-24 16:48:18 +08:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsAlive(int entityID, short gen) => _gens[entityID] == gen;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsUsed(int entityID) => _gens[entityID] >= 0;
2023-05-30 04:32:09 +08:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public short GetGen(int entityID) => _gens[entityID];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public short GetComponentsCount(int entityID) => _componentCounts[entityID];
public bool IsMatchesMask(EcsMask mask, int entityID)
{
2023-11-22 20:28:11 +08:00
#if (DEBUG && !DISABLE_DEBUG) || !DISABLE_DRAGONECS_ASSERT_CHEKS
if (mask.worldID != id)
throw new EcsFrameworkException("The types of the target world of the mask and this world are different.");
#endif
for (int i = 0, iMax = mask.incChunckMasks.Length; i < iMax; i++)
{
if (!_pools[mask.inc[i]].Has(entityID))
return false;
}
for (int i = 0, iMax = mask.excChunckMasks.Length; i < iMax; i++)
{
if (_pools[mask.exc[i]].Has(entityID))
return false;
}
return true;
2023-05-30 04:32:09 +08:00
}
2023-04-24 16:48:18 +08:00
public void ReleaseDelEntityBuffer()
2023-04-20 11:37:27 +08:00
{
if (_delEntBufferCount <= 0)
return;
ReadOnlySpan<int> buffser = new ReadOnlySpan<int>(_delEntBuffer, 0, _delEntBufferCount);
2023-05-26 00:24:38 +08:00
foreach (var pool in _pools)
pool.OnReleaseDelEntityBuffer(buffser);
_listeners.InvokeOnReleaseDelEntityBuffer(buffser);
2023-04-20 11:37:27 +08:00
for (int i = 0; i < _delEntBufferCount; i++)
_entityDispenser.Release(_delEntBuffer[i]);
2023-11-22 16:08:49 +08:00
_freeSpace = _entitesCapacity - _entitiesCount;
2023-04-20 11:37:27 +08:00
_delEntBufferCount = 0;
2023-03-02 14:42:44 +08:00
}
public void DeleteEmptyEntites()
{
foreach (var e in _allEntites)
{
2023-05-26 00:24:38 +08:00
if (_componentCounts[e] <= 0) DelEntity(e);
}
}
2023-05-30 04:32:09 +08:00
#region Copy/Clone
2023-05-23 01:47:28 +08:00
public void CopyEntity(int fromEntityID, int toEntityID)
{
2023-05-26 00:24:38 +08:00
foreach (var pool in _pools)
2023-05-23 01:47:28 +08:00
{
if (pool.Has(fromEntityID))
pool.Copy(fromEntityID, toEntityID);
}
}
public void CopyEntity(int fromEntityID, EcsWorld toWorld, int toEntityID)
{
foreach (var pool in _pools)
{
if (pool.Has(fromEntityID))
pool.Copy(fromEntityID, toWorld, toEntityID);
2023-05-23 01:47:28 +08:00
}
}
public int CloneEntity(int fromEntityID)
{
2023-12-20 19:06:17 +08:00
int newEntity = NewEntity();
2023-05-23 01:47:28 +08:00
CopyEntity(fromEntityID, newEntity);
return newEntity;
}
public int CloneEntity(int fromEntityID, EcsWorld toWorld)
{
2023-12-20 19:06:17 +08:00
int newEntity = NewEntity();
CopyEntity(fromEntityID, toWorld, newEntity);
return newEntity;
}
2023-05-23 01:47:28 +08:00
public void CloneEntity(int fromEntityID, int toEntityID)
{
CopyEntity(fromEntityID, toEntityID);
2023-05-26 00:24:38 +08:00
foreach (var pool in _pools)
2023-05-23 01:47:28 +08:00
{
2023-05-30 04:32:09 +08:00
if (!pool.Has(fromEntityID) && pool.Has(toEntityID))
pool.Del(toEntityID);
2023-05-23 01:47:28 +08:00
}
}
//public void CloneEntity(int fromEntityID, EcsWorld toWorld, int toEntityID)
2023-05-30 04:32:09 +08:00
#endregion
2023-05-23 01:47:28 +08:00
2023-12-06 20:45:32 +08:00
#region Pools mediation
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void RegisterEntityComponent(int entityID, int componentTypeID, EcsMaskBit maskBit)
2023-11-22 17:35:03 +08:00
{
_componentCounts[entityID]++;
_entitiesComponentMasks[entityID][maskBit.chankIndex] |= maskBit.mask;
2023-11-22 17:35:03 +08:00
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void UnregisterEntityComponent(int entityID, int componentTypeID, EcsMaskBit maskBit)
{
var count = --_componentCounts[entityID];
_entitiesComponentMasks[entityID][maskBit.chankIndex] &= ~maskBit.mask;
2023-11-22 17:35:03 +08:00
if (count == 0 && _allEntites.Has(entityID))
DelEntity(entityID);
#if (DEBUG && !DISABLE_DEBUG) || ENABLE_DRAGONECS_ASSERT_CHEKS
2023-06-26 01:57:50 +08:00
if (count < 0) Throw.World_InvalidIncrementComponentsBalance();
#endif
}
2023-12-06 20:45:32 +08:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool HasEntityComponent(int entityID, EcsMaskBit maskBit)
{
return (_entitiesComponentMasks[entityID][maskBit.chankIndex] & maskBit.mask) != maskBit.mask;
}
2023-03-02 14:42:44 +08:00
#endregion
2023-05-30 04:32:09 +08:00
#endregion
2023-11-22 20:28:11 +08:00
#region Upsize
//[MethodImpl(MethodImplOptions.NoInlining)]
private void Upsize()
{
Array.Resize(ref _gens, _gens.Length << 1);
Array.Resize(ref _componentCounts, _gens.Length);
Array.Resize(ref _delEntBuffer, _gens.Length);
Array.Resize(ref _entitiesComponentMasks, _gens.Length);
for (int i = _entitesCapacity; i < _gens.Length; i++)
_entitiesComponentMasks[i] = new int[_pools.Length / 32 + 1];
_delEntBufferMinCount = Math.Max(_delEntBuffer.Length >> DEL_ENT_BUFFER_SIZE_OFFSET, DEL_ENT_BUFFER_MIN_SIZE);
ArrayUtility.Fill(_gens, DEATH_GEN_BIT, _entitesCapacity);
_entitesCapacity = _gens.Length;
for (int i = 0; i < _groups.Count; i++)
{
if (_groups[i].TryGetTarget(out EcsGroup group))
{
group.OnWorldResize(_gens.Length);
}
else
{
int last = _groups.Count - 1;
_groups[i--] = _groups[last];
_groups.RemoveAt(last);
}
}
foreach (var item in _pools)
item.OnWorldResize(_gens.Length);
_listeners.InvokeOnWorldResize(_gens.Length);
}
#endregion
2023-05-28 06:29:04 +08:00
#region Groups Pool
internal void RegisterGroup(EcsGroup group)
{
2023-04-17 22:58:52 +08:00
_groups.Add(new WeakReference<EcsGroup>(group));
}
2023-06-01 20:14:34 +08:00
internal EcsGroup GetFreeGroup()
2023-04-18 19:35:42 +08:00
{
2023-05-28 06:29:04 +08:00
EcsGroup result = _groupsPool.Count <= 0 ? new EcsGroup(this) : _groupsPool.Pop();
result._isReleased = false;
return result;
2023-04-18 19:35:42 +08:00
}
internal void ReleaseGroup(EcsGroup group)
2023-04-18 19:35:42 +08:00
{
#if (DEBUG && !DISABLE_DEBUG) || !DISABLE_DRAGONECS_ASSERT_CHEKS
2023-06-26 01:57:50 +08:00
if (group.World != this) Throw.World_GroupDoesNotBelongWorld();
2023-04-18 19:35:42 +08:00
#endif
2023-05-28 06:29:04 +08:00
group._isReleased = true;
2023-04-18 19:35:42 +08:00
group.Clear();
_groupsPool.Push(group);
}
#endregion
2023-06-08 04:04:39 +08:00
#region Listeners
public void AddListener(IEcsWorldEventListener worldEventListener)
2023-06-08 04:04:39 +08:00
{
_listeners.Add(worldEventListener);
2023-06-08 04:04:39 +08:00
}
public void RemoveListener(IEcsWorldEventListener worldEventListener)
2023-06-08 04:04:39 +08:00
{
_listeners.Remove(worldEventListener);
2023-06-08 04:04:39 +08:00
}
public void AddListener(IEcsEntityEventListener entityEventListener)
2023-06-10 18:58:43 +08:00
{
_entityListeners.Add(entityEventListener);
2023-06-10 18:58:43 +08:00
}
public void RemoveListener(IEcsEntityEventListener entityEventListener)
2023-06-10 18:58:43 +08:00
{
_entityListeners.Remove(entityEventListener);
2023-06-10 18:58:43 +08:00
}
2023-06-08 04:04:39 +08:00
#endregion
#region Debug
2023-05-23 01:47:28 +08:00
public void GetComponents(int entityID, List<object> list)
{
list.Clear();
var itemsCount = GetComponentsCount(entityID);
2023-05-26 00:24:38 +08:00
for (var i = 0; i < _pools.Length; i++)
2023-05-23 01:47:28 +08:00
{
2023-05-26 00:24:38 +08:00
if (_pools[i].Has(entityID))
2023-05-30 18:30:10 +08:00
list.Add(_pools[i].GetRaw(entityID));
2023-05-23 01:47:28 +08:00
}
}
#endregion
public readonly struct PoolsMediator
{
private readonly EcsWorld _world;
2023-12-06 20:45:32 +08:00
internal PoolsMediator(EcsWorld world)
{
if (world == null)
{
throw new ArgumentNullException();
}
if (world._poolsMediator._world != null)
{
2023-12-06 20:45:32 +08:00
throw new MethodAccessException();
}
_world = world;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-12-06 20:45:32 +08:00
public void RegisterComponent(int entityID, int componentTypeID, EcsMaskBit maskBit)
{
_world.RegisterEntityComponent(entityID, componentTypeID, maskBit);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-12-06 20:45:32 +08:00
public void UnregisterComponent(int entityID, int componentTypeID, EcsMaskBit maskBit)
{
_world.UnregisterEntityComponent(entityID, componentTypeID, maskBit);
}
2023-12-06 20:45:32 +08:00
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool HasComponent(int entityID, EcsMaskBit maskBit)
{
return _world.HasEntityComponent(entityID, maskBit);
}
}
2023-05-30 04:32:09 +08:00
}
2023-05-28 05:53:08 +08:00
2023-05-26 00:24:38 +08:00
#region Callbacks Interface
public interface IEcsWorldEventListener
{
void OnWorldResize(int newSize);
void OnReleaseDelEntityBuffer(ReadOnlySpan<int> buffer);
void OnWorldDestroy();
2023-06-10 18:58:43 +08:00
}
public interface IEcsEntityEventListener
{
void OnNewEntity(int entityID);
void OnDelEntity(int entityID);
}
2023-05-26 00:24:38 +08:00
internal static class WorldEventListExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void InvokeOnWorldResize(this List<IEcsWorldEventListener> self, int newSize)
{
for (int i = 0, iMax = self.Count; i < iMax; i++) self[i].OnWorldResize(newSize);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void InvokeOnReleaseDelEntityBuffer(this List<IEcsWorldEventListener> self, ReadOnlySpan<int> buffer)
{
for (int i = 0, iMax = self.Count; i < iMax; i++) self[i].OnReleaseDelEntityBuffer(buffer);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void InvokeOnWorldDestroy(this List<IEcsWorldEventListener> self)
{
for (int i = 0, iMax = self.Count; i < iMax; i++) self[i].OnWorldDestroy();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-06-10 18:58:43 +08:00
public static void InvokeOnNewEntity(this List<IEcsEntityEventListener> self, int entityID)
{
for (int i = 0, iMax = self.Count; i < iMax; i++) self[i].OnNewEntity(entityID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-06-10 18:58:43 +08:00
public static void InvokeOnDelEntity(this List<IEcsEntityEventListener> self, int entityID)
{
for (int i = 0, iMax = self.Count; i < iMax; i++) self[i].OnDelEntity(entityID);
}
}
#endregion
2023-05-28 06:35:33 +08:00
#region Extensions
public static class IntExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static entlong ToEntityLong(this int self, EcsWorld world) => world.GetEntityLong(self);
}
#endregion
2023-03-02 14:42:44 +08:00
}