diff --git a/Src/Core/ECS/Entity.cs b/Src/Core/ECS/Entity.cs new file mode 100644 index 0000000..69f2869 --- /dev/null +++ b/Src/Core/ECS/Entity.cs @@ -0,0 +1,92 @@ +using System; +using System.Linq; +using System.Threading; +using Microsoft.Extensions.DependencyInjection; + +namespace BITKit.Entities +{ + public class Entity : IEntity, IDisposable + { + public Entity() + { + RegisterComponent(this); + } + public void WaitForInitializationComplete() + { + throw new NotImplementedException(); + } + public int Id { get; set; } = Guid.NewGuid().GetHashCode(); + public CancellationToken CancellationToken => _cancellationTokenSource.Token; + private readonly CancellationTokenSource _cancellationTokenSource = new(); + + public bool TryGetComponent(out T component) + { + var value = ServiceProvider.GetService(); + if (value != null) + { + component = value; + return true; + } + + component = default!; + return false; + } + + public bool TryGetComponent(Type type, out IEntityComponent component) + { + var value = ServiceProvider.GetService(type); + if (value != null) + { + component = (IEntityComponent)value; + return true; + } + + component = default!; + return false; + } + + public IEntityComponent[] Components => ServiceCollection.OfType().ToArray(); + + public bool RegisterComponent(T component) + { + _services.Add(component); + ServiceCollection.AddSingleton(typeof(T), component); + return true; + } + + public IServiceProvider ServiceProvider => _serviceProvider ??= ServiceCollection.BuildServiceProvider(); + public IServiceCollection ServiceCollection { get; } = new ServiceCollection(); + private IServiceProvider _serviceProvider; + private readonly CacheList _services = new(); + + public object[] GetServices() + { + return _services.ToArray(); + } + + public void Inject(object obj) + { + foreach (var fieldInfo in obj.GetType().GetFields(ReflectionHelper.Flags)) + { + if (Attribute.IsDefined(fieldInfo, typeof(InjectAttribute))) + { + fieldInfo.SetValue(obj, ServiceProvider.GetService(fieldInfo.FieldType)); + } + } + } + + public void Dispose() + { + _cancellationTokenSource.Cancel(); + _cancellationTokenSource.Dispose(); + + foreach (var service in _services) + { + if (service is IDisposable disposable) + { + disposable.Dispose(); + } + } + } + } +} \ No newline at end of file diff --git a/Src/Core/ECS/Entity.cs.meta b/Src/Core/ECS/Entity.cs.meta new file mode 100644 index 0000000..61c2588 --- /dev/null +++ b/Src/Core/ECS/Entity.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 881c97aa8732ace4796d97874c8f8769 \ No newline at end of file