update world/add WorldComponentPoolAbstract

This commit is contained in:
DCFApixels 2024-12-04 16:09:52 +08:00
parent dd5a81334c
commit d107d29482
5 changed files with 321 additions and 50 deletions

View File

@ -236,7 +236,7 @@ namespace DCFApixels.DragonECS
#endregion
#region Builder
private readonly struct WorldMaskComponent : IEcsWorldComponent<WorldMaskComponent>
internal readonly struct WorldMaskComponent : IEcsWorldComponent<WorldMaskComponent>
{
private readonly EcsWorld _world;
private readonly Dictionary<OpMaskKey, EcsMask> _opMasks;

View File

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
#if ENABLE_IL2CPP
using Unity.IL2CPP.CompilerServices;
#endif
@ -16,14 +17,17 @@ namespace DCFApixels.DragonECS
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
#endif
[Serializable]
[DataContract]
public class EcsWorldConfig
{
public static readonly EcsWorldConfig Default = new EcsWorldConfig();
public readonly int EntitiesCapacity;
public readonly int GroupCapacity;
public readonly int PoolsCapacity;
public readonly int PoolComponentsCapacity;
public readonly int PoolRecycledComponentsCapacity;
[DataMember] public int EntitiesCapacity;
[DataMember] public int GroupCapacity;
[DataMember] public int PoolsCapacity;
[DataMember] public int PoolComponentsCapacity;
[DataMember] public int PoolRecycledComponentsCapacity;
public EcsWorldConfig() : this(512) { }
public EcsWorldConfig(int entitiesCapacity = 512, int groupCapacity = 512, int poolsCapacity = 512, int poolComponentsCapacity = 512, int poolRecycledComponentsCapacity = 512 / 2)
{
EntitiesCapacity = entitiesCapacity;
@ -40,7 +44,7 @@ namespace DCFApixels.DragonECS
#endif
[MetaColor(MetaColor.DragonRose)]
[MetaGroup(EcsConsts.PACK_GROUP, EcsConsts.WORLDS_GROUP)]
[MetaDescription(EcsConsts.AUTHOR, "It is a container for entities and components.")]
[MetaDescription(EcsConsts.AUTHOR, "Container for entities and components.")]
[MetaID("AEF3557C92019C976FC48F90E95A9DA6")]
[DebuggerTypeProxy(typeof(DebuggerProxy))]
public partial class EcsWorld : IEntityStorage, IEcsMember, INamedMember
@ -70,8 +74,8 @@ namespace DCFApixels.DragonECS
//обновляется в NewEntity и в DelEntity
private long _version = 0;
private List<IEcsWorldEventListener> _listeners = new List<IEcsWorldEventListener>();
private List<IEcsEntityEventListener> _entityListeners = new List<IEcsEntityEventListener>();
private StructList<IEcsWorldEventListener> _listeners = new StructList<IEcsWorldEventListener>(2);
private StructList<IEcsEntityEventListener> _entityListeners = new StructList<IEcsEntityEventListener>(2);
#region Properties
EcsWorld IEntityStorage.World
@ -160,6 +164,14 @@ namespace DCFApixels.DragonECS
_configs = configs;
EcsWorldConfig config = configs.GetWorldConfigOrDefault();
// тут сложно однозначно посчитать, так как нужно еще место под аспекты и запросы
int controllersCount = config.PoolsCapacity * 4;
_worldComponentPools = new StructList<WorldComponentPoolAbstract>(controllersCount);
if (controllersCount < _allWorldComponentPools.Capacity)
{
_allWorldComponentPools.Capacity = controllersCount;
}
if (worldID < 0 || (worldID == NULL_WORLD_ID && nullWorld == false))
{
worldID = (short)_worldIdDispenser.UseFree();
@ -261,12 +273,12 @@ namespace DCFApixels.DragonECS
return ref WorldComponentPool<T>.GetForWorldUnchecked(ID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T Get<T>(int worldID) where T : struct
public static ref T Get<T>(short worldID) where T : struct
{
return ref WorldComponentPool<T>.GetForWorld(worldID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T GetUnchecked<T>(int worldID) where T : struct
public static ref T GetUnchecked<T>(short worldID) where T : struct
{
return ref WorldComponentPool<T>.GetForWorldUnchecked(worldID);
}
@ -1078,11 +1090,7 @@ namespace DCFApixels.DragonECS
#endregion
#region DebuggerProxy
private EcsSpan GetSpan_Debug()
{
return _entityDispenser.UsedToEcsSpan(ID);
}
protected class DebuggerProxy
protected partial class DebuggerProxy
{
private EcsWorld _world;
private List<MaskQueryExecutor> _queries;
@ -1129,7 +1137,7 @@ namespace DCFApixels.DragonECS
internal static class WorldEventListExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void InvokeOnWorldResize(this List<IEcsWorldEventListener> self, int newSize)
public static void InvokeOnWorldResize(this ref StructList<IEcsWorldEventListener> self, int newSize)
{
for (int i = 0, iMax = self.Count; i < iMax; i++)
{
@ -1137,7 +1145,7 @@ namespace DCFApixels.DragonECS
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void InvokeOnReleaseDelEntityBuffer(this List<IEcsWorldEventListener> self, ReadOnlySpan<int> buffer)
public static void InvokeOnReleaseDelEntityBuffer(this ref StructList<IEcsWorldEventListener> self, ReadOnlySpan<int> buffer)
{
for (int i = 0, iMax = self.Count; i < iMax; i++)
{
@ -1145,7 +1153,7 @@ namespace DCFApixels.DragonECS
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void InvokeOnWorldDestroy(this List<IEcsWorldEventListener> self)
public static void InvokeOnWorldDestroy(this ref StructList<IEcsWorldEventListener> self)
{
for (int i = 0, iMax = self.Count; i < iMax; i++)
{
@ -1153,7 +1161,7 @@ namespace DCFApixels.DragonECS
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void InvokeOnNewEntity(this List<IEcsEntityEventListener> self, int entityID)
public static void InvokeOnNewEntity(this ref StructList<IEcsEntityEventListener> self, int entityID)
{
for (int i = 0, iMax = self.Count; i < iMax; i++)
{
@ -1161,7 +1169,7 @@ namespace DCFApixels.DragonECS
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void InvokeOnDelEntity(this List<IEcsEntityEventListener> self, int entityID)
public static void InvokeOnDelEntity(this ref StructList<IEcsEntityEventListener> self, int entityID)
{
for (int i = 0, iMax = self.Count; i < iMax; i++)
{

View File

@ -71,7 +71,7 @@ namespace DCFApixels.DragonECS
[UnityEngine.Scripting.Preserve]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TPool GetPoolInstance<TPool>(int worldID) where TPool : IEcsPoolImplementation, new()
public static TPool GetPoolInstance<TPool>(short worldID) where TPool : IEcsPoolImplementation, new()
{
return Get<PoolCache<TPool>>(worldID).Instance;
}
@ -79,7 +79,7 @@ namespace DCFApixels.DragonECS
[UnityEngine.Scripting.Preserve]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TPool GetPoolInstanceUnchecked<TPool>(int worldID) where TPool : IEcsPoolImplementation, new()
public static TPool GetPoolInstanceUnchecked<TPool>(short worldID) where TPool : IEcsPoolImplementation, new()
{
return GetUnchecked<PoolCache<TPool>>(worldID).Instance;
}

View File

@ -2,12 +2,14 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
namespace DCFApixels.DragonECS
{
public partial class EcsWorld
{
#region Consts
private const short NULL_WORLD_ID = 0;
private const short GEN_STATUS_SEPARATOR = 0;
@ -16,50 +18,84 @@ namespace DCFApixels.DragonECS
private const int DEL_ENT_BUFFER_SIZE_OFFSET = 5;
private const int DEL_ENT_BUFFER_MIN_SIZE = 64;
#endregion
private static EcsWorld[] _worlds = Array.Empty<EcsWorld>();
private static IdDispenser _worldIdDispenser = new IdDispenser(4, 0, n => Array.Resize(ref _worlds, n));
private static List<DataReleaser> _dataReleaseres = new List<DataReleaser>();
//public static int Copacity => Worlds.Length;
private static StructList<WorldComponentPoolAbstract> _allWorldComponentPools = new StructList<WorldComponentPoolAbstract>(64);
private StructList<WorldComponentPoolAbstract> _worldComponentPools;
private int _builtinWorldComponentsCount = 0;
private static readonly object _worldLock = new object();
static EcsWorld()
{
_worlds[NULL_WORLD_ID] = new NullWorld();
}
private static void ReleaseData(int worldID)
{// ts
lock (_worldLock)
{
for (int i = 0, iMax = _dataReleaseres.Count; i < iMax; i++)
{
_dataReleaseres[i].Release(worldID);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static EcsWorld GetWorld(short worldID)
{// ts
return _worlds[worldID];
}
private void ReleaseData(short worldID)
{// ts
lock (_worldLock)
{
foreach (var controller in _worldComponentPools)
{
controller.Release(worldID);
}
_worldComponentPools.Clear();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T GetData<T>(int worldID)
public static ref T GetData<T>(short worldID)
{
return ref WorldComponentPool<T>.GetForWorld(worldID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T GetDataUnchecked<T>(int worldID)
public static bool HasData<T>(short worldID)
{
return WorldComponentPool<T>.Has(worldID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T GetDataUnchecked<T>(short worldID)
{
return ref WorldComponentPool<T>.GetForWorldUnchecked(worldID);
}
private abstract class DataReleaser
#region WorldComponentPool
public ReadOnlySpan<WorldComponentPoolAbstract> GetWorldComponents()
{
public abstract void Release(int worldID);
return new ReadOnlySpan<WorldComponentPoolAbstract>(_worldComponentPools._items, 0, _builtinWorldComponentsCount);
}
public ReadOnlySpan<WorldComponentPoolAbstract> GetAllWorldComponents()
{
return _worldComponentPools.ToReadOnlySpan();
}
public abstract class WorldComponentPoolAbstract
{
protected static readonly Type[] _builtinTypes = new Type[]
{
typeof(AspectCache<>),
typeof(PoolCache<>),
typeof(WhereQueryCache<,>),
typeof(EcsMask.WorldMaskComponent),
};
internal readonly bool _isBuiltin;
protected WorldComponentPoolAbstract()
{
Type type = ComponentType;
if (type.IsGenericType) { type = type.GetGenericTypeDefinition(); }
_isBuiltin = Array.IndexOf(_builtinTypes, type) >= 0;
}
public abstract Type ComponentType { get; }
public abstract void Has(short worldID);
public abstract void Release(short worldID);
public abstract object GetRaw(short worldID);
public abstract void SetRaw(short worldID, object raw);
}
private static class WorldComponentPool<T>
{
@ -69,26 +105,30 @@ namespace DCFApixels.DragonECS
private static short[] _recycledItems = new short[4];
private static short _recycledItemsCount;
private static IEcsWorldComponent<T> _interface = EcsWorldComponentHandler<T>.instance;
private static Abstract _controller = new Abstract();
static WorldComponentPool()
{
_allWorldComponentPools.Add(_controller);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T GetItem(int itemIndex)
{// ts
return ref _items[itemIndex];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T GetForWorld(int worldID)
public static ref T GetForWorld(short worldID)
{// зависит от GetItemIndex
return ref GetItem(GetItemIndex(worldID));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T GetForWorldUnchecked(int worldID)
public static ref T GetForWorldUnchecked(short worldID)
{// ts
#if (DEBUG && !DISABLE_DEBUG) || ENABLE_DRAGONECS_ASSERT_CHEKS
if (_mapping[worldID] <= 0) { Throw.ArgumentOutOfRange(); }
#endif
return ref _items[_mapping[worldID]];
}
public static int GetItemIndex(int worldID)
public static int GetItemIndex(short worldID)
{// ts
if (_mapping.Length < _worlds.Length)
{
@ -126,13 +166,22 @@ namespace DCFApixels.DragonECS
}
_interface.Init(ref _items[itemIndex], _worlds[worldID]);
_dataReleaseres.Add(new Releaser());
var world = GetWorld(worldID);
world._worldComponentPools.Add(_controller);
if (_controller._isBuiltin)
{
world._builtinWorldComponentsCount++;
world._worldComponentPools.SwapAt(
world._worldComponentPools.Count - 1,
world._builtinWorldComponentsCount - 1);
}
}
}
}
return itemIndex;
}
private static void Release(int worldID)
private static void Release(short worldID)
{// ts
lock (_worldLock)
{
@ -153,19 +202,75 @@ namespace DCFApixels.DragonECS
}
}
}
private sealed class Releaser : DataReleaser
public static bool Has(short worldID)
{// ts
if (_mapping.Length < _worlds.Length)
{
lock (_worldLock)
{
if (_mapping.Length < _worlds.Length)
{
Array.Resize(ref _mapping, _worlds.Length);
}
}
}
short itemIndex = _mapping[worldID];
return itemIndex > 0;
}
private sealed class Abstract : WorldComponentPoolAbstract
{
public sealed override void Release(int worldID)
public sealed override Type ComponentType
{
get { return typeof(T); }
}
public override void SetRaw(short worldID, object raw)
{
WorldComponentPool<T>.GetItem(worldID) = (T)raw;
}
public sealed override void Has(short worldID)
{
WorldComponentPool<T>.Has(worldID);
}
public sealed override object GetRaw(short worldID)
{
return WorldComponentPool<T>.GetItem(worldID);
}
public sealed override void Release(short worldID)
{
WorldComponentPool<T>.Release(worldID);
}
}
}
#endregion
private sealed class NullWorld : EcsWorld
{
internal NullWorld() : base(new EcsWorldConfig(4, 4, 4, 4, 4), null, 0) { }
}
#region DebuggerProxy
protected partial class DebuggerProxy
{
private short _worldID;
public IEnumerable<object> WorldComponents
{
get
{
_worldID = _world.ID;
return _world._worldComponentPools.ToEnumerable().Skip(_world._builtinWorldComponentsCount).Select(o => o.GetRaw(_worldID));
}
}
public IEnumerable<object> AllWorldComponents
{
get
{
_worldID = _world.ID;
return _world._worldComponentPools.ToEnumerable().Select(o => o.GetRaw(_worldID));
}
}
}
#endregion
#region Obsolete
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Use EcsWorld.ID")]

View File

@ -0,0 +1,158 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
namespace DCFApixels.DragonECS.Internal
{
[DebuggerDisplay("Count: {Count}")]
internal struct StructList<T>
{
internal T[] _items;
internal int _count;
public int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _count; }
}
public int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _items.Length; }
set
{
if (value <= _items.Length) { return; }
value = ArrayUtility.NormalizeSizeToPowerOfTwo(value);
Array.Resize(ref _items, value);
}
}
public T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
#if DEBUG
if (index < 0 || index >= _count) { Throw.ArgumentOutOfRange(); }
#endif
return _items[index];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
#if DEBUG
if (index < 0 || index >= _count) { Throw.ArgumentOutOfRange(); }
#endif
_items[index] = value;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public StructList(int capacity)
{
_items = new T[ArrayUtility.NormalizeSizeToPowerOfTwo(capacity)];
_count = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(T item)
{
if (_count >= _items.Length)
{
Array.Resize(ref _items, _items.Length << 1);
}
_items[_count++] = item;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int IndexOf(T item)
{
return Array.IndexOf(_items, item, 0, _count);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SwapAt(int idnex1, int idnex2)
{
T tmp = _items[idnex1];
_items[idnex1] = _items[idnex2];
_items[idnex2] = tmp;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void FastRemoveAt(int index)
{
#if DEBUG
if (index < 0 || index >= _count) { Throw.ArgumentOutOfRange(); }
#endif
_items[index] = _items[--_count];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RemoveAt(int index)
{
#if DEBUG
if (index < 0 || index >= _count) { Throw.ArgumentOutOfRange(); }
#endif
_items[index] = _items[--_count];
_items[_count] = default;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RemoveAtWithOrder(int index)
{
#if DEBUG
if (index < 0 || index >= _count) { Throw.ArgumentOutOfRange(); }
#endif
for (int i = index; i < _count;)
{
_items[i++] = _items[i];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Remove(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool RemoveWithOrder(T item)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAtWithOrder(index);
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void FastClear()
{
_count = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
{
for (int i = 0; i < _count; i++)
{
_items[i] = default;
}
_count = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T>.Enumerator GetEnumerator()
{
return new ReadOnlySpan<T>(_items, 0, _count).GetEnumerator();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> ToReadOnlySpan()
{
return new ReadOnlySpan<T>(_items, 0, _count);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IEnumerable<T> ToEnumerable()
{
return _items.Take(_count);
}
}
}