continued implementing ECS

This commit is contained in:
2025-09-08 19:36:15 +02:00
parent 161a166141
commit 97207ab2a3
5 changed files with 92 additions and 5 deletions

View File

@ -0,0 +1,6 @@
namespace EngineSharp.Core.ECS;
public abstract class DataComponent : IComponent
{
}

View File

@ -1,11 +1,33 @@
namespace EngineSharp.Core.ECS;
using System.ComponentModel;
namespace EngineSharp.Core.ECS;
// Maybe look at this C# ECS to get an idea of how to implement one myself
// https://github.com/friflo/Friflo.Engine.ECS/tree/main
// OR: https://github.com/genaray/Arch
public struct Entity
{
public readonly long Id;
private List<LogicComponent> _logicComponents;
private Scene _scene;
internal Entity(long id, Scene scene)
{
this.Id = id;
_scene = scene;
}
/// <summary>
/// If the component already exists on the entity, it will not be added.
/// </summary>
public void AddComponent(IComponent component)
{
_scene.AddComponent(this, component);
}
public IComponent? GetComponent(IComponent component)
{
return _scene.GetComponent(this, component);
}
}

View File

@ -0,0 +1,6 @@
namespace EngineSharp.Core.ECS;
public interface IComponent
{
}

View File

@ -2,10 +2,8 @@
// TODO: A LogicComponent would have a list of Components. A LogicComponent is basically what will be stored in the scene graph and all components of all LogicComponents will have their Update methods etc. be called
public abstract class LogicComponent
public abstract class LogicComponent : IComponent
{
internal Entity _entity; // the entity this component belongs to
public abstract void Start();
public abstract void OnUpdate(double deltaTime);
}

View File

@ -0,0 +1,55 @@
using System.ComponentModel;
namespace EngineSharp.Core.ECS;
public class Scene
{
private Dictionary<long, LogicComponent> _logicComponents = new();
private Dictionary<long, DataComponent> _dataComponents = new();
internal void AddComponent(Entity entity, IComponent component)
{
switch (component)
{
case LogicComponent logic:
_logicComponents.TryAdd(entity.Id, logic);
break;
case DataComponent data:
_dataComponents.TryAdd(entity.Id, data);
break;
}
}
internal IComponent? GetComponent(Entity entity, IComponent component)
{
switch (component)
{
case LogicComponent logic:
return GetComponent(entity.Id, logic);
case DataComponent data:
return GetComponent(entity.Id, data);
default:
return null;
}
}
private LogicComponent? GetComponent(long id, LogicComponent component)
{
if (_logicComponents.TryGetValue(id, out var logic))
{
return logic;
}
return null;
}
private DataComponent? GetComponent(long id, DataComponent component)
{
if (_dataComponents.TryGetValue(id, out var data))
{
return data;
}
return null;
}
}