using System;
using Godot;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using BITKit.Core.Entites;
// ReSharper disable All
namespace BITKit;
///
/// 基于Godot.Node的IEntitiesService实现
///
public partial class GodotEntitiesService : Node,IEntitiesService
{
public GodotEntitiesService()
{
DI.Register(this);
}
private readonly Dictionary _entities=new ();
private CancellationTokenSource _cancellationTokenSource;
public event Action OnAdd;
public event Action OnRemove;
public IEntity[] Entities => _entities.Values.ToArray();
public bool Register(IEntity entity)
{
return _entities.TryAdd(entity.Id, entity);
}
public bool UnRegister(IEntity entity)
{
return _entities.TryRemove(entity.Id);
}
public override void _Ready()
{
_cancellationTokenSource = new();
}
protected override void Dispose(bool disposing)
{
if(disposing)_cancellationTokenSource.Cancel();
}
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
public IEntity Get(ulong id)
{
throw new NotImplementedException();
}
public IEntity[] Query()
{
return _entities.Values.Where(x => x.TryGetComponent(out _)).ToArray();
}
T[] IEntitiesService.QueryComponents()
{
return _entities.Values
.Where(x => x.TryGetComponent(out _))
.Select(x =>
{
var component = x.Components.Single(x => x is T);
return (T)component;
})
.ToArray();
}
public ValueTuple[] QueryComponents() where T : IEntityComponent
{
return _entities.Values
.Where(x => x.TryGetComponent(out _))
.Select(x =>
{
var component = x.Components.Single(x => x is T);
return (T)component;
})
.Select(x => new ValueTuple(x))
.ToArray();
}
public (T, T1)[] QueryComponents()
{
var entities = _entities.Values.Where(x => x.TryGetComponent(out _) && x.TryGetComponent(out _));
var result = new List<(T, T1)>();
foreach (var entity in entities)
{
var t = (T)entity.Components.Single(x => x is T);
var t1 = (T1)entity.Components.Single(x => x is T1);
result.Add(new(t,t1));
}
return result.ToArray();
}
public (T, T1, T2)[] QueryComponents()
{
return _entities.Values
.Where(x => x.TryGetComponent(out _) && x.TryGetComponent(out _) && x.TryGetComponent(out _))
.Select(x =>
{
var component = (T)x.Components.Single(x => x is T);
var component1 = (T1)x.Components.Single(x => x is T1);
var component2 = (T2)x.Components.Single(x => x is T2);
(T, T1, T2) value = new(component, component1, component2);
return value;
})
.ToArray();
}
}