DragonECS/src/EcsQuery.cs

109 lines
3.4 KiB
C#
Raw Normal View History

using DCFApixels.DragonECS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace DCFApixels.DragonECS
{
2023-04-07 14:03:29 +08:00
public abstract class EcsQueryBuilder
{
public abstract inc<TComponent> Include<TComponent>() where TComponent : struct;
public abstract exc<TComponent> Exclude<TComponent>() where TComponent : struct;
public abstract opt<TComponent> Optional<TComponent>() where TComponent : struct;
}
2023-04-07 14:03:29 +08:00
public interface IEcsQuery
{
internal void AddEntity(int entityID);
internal void RemoveEntity(int entityID);
}
2023-04-07 14:03:29 +08:00
public class EcsQuery<TWorldArchetype> : IEcsQuery
where TWorldArchetype : EcsWorld<TWorldArchetype>
{
private int _id;
internal EcsGroup group;
public int ID => _id;
public EcsReadonlyGroup entities
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => group.Readonly;
}
2023-04-07 14:03:29 +08:00
public EcsQuery(Builder b)
{
}
public EcsGroup.Enumerator GetEnumerator() => group.GetEnumerator();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-04-07 14:03:29 +08:00
void IEcsQuery.AddEntity(int entityID) => group.Add(entityID);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
2023-04-07 14:03:29 +08:00
void IEcsQuery.RemoveEntity(int entityID) => group.Remove(entityID);
#region Builder
2023-04-07 14:03:29 +08:00
public sealed class Builder : EcsQueryBuilder
{
private IEcsWorld _world;
private List<int> _inc;
private List<int> _exc;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Builder(IEcsWorld world)
{
_world = world;
_inc = new List<int>(8);
_exc = new List<int>(4);
}
public override inc<TComponent> Include<TComponent>() where TComponent : struct
{
_inc.Add(_world.GetComponentID<TComponent>());
return new inc<TComponent>(_world.GetPool<TComponent>());
}
public override exc<TComponent> Exclude<TComponent>() where TComponent : struct
{
_exc.Add(_world.GetComponentID<TComponent>());
return new exc<TComponent>(_world.GetPool<TComponent>());
}
public override opt<TComponent> Optional<TComponent>() where TComponent : struct
{
return new opt<TComponent>(_world.GetPool<TComponent>());
}
2023-04-07 14:03:29 +08:00
internal void End(out EcsQueryMask mask)
{
_inc.Sort();
_exc.Sort();
2023-04-07 14:03:29 +08:00
mask = new EcsQueryMask(_world.ArchetypeType, _inc.ToArray(), _exc.ToArray());
_world = null;
_inc.Clear();
_inc = null;
_exc.Clear();
_exc = null;
}
}
#endregion
}
2023-04-07 14:03:29 +08:00
public class EcsQueryMask
{
internal readonly Type WorldArchetypeType;
internal readonly int[] Inc;
internal readonly int[] Exc;
public int IncCount => Inc.Length;
public int ExcCount => Exc.Length;
2023-04-07 14:03:29 +08:00
public EcsQueryMask(Type worldArchetypeType, int[] inc, int[] exc)
{
WorldArchetypeType = worldArchetypeType;
Inc = inc;
Exc = exc;
}
}
}