MoonTools.ECS/src/RelationDepot.cs

85 lines
2.2 KiB
C#
Raw Normal View History

2022-04-08 05:52:03 +00:00
using System;
using System.Collections.Generic;
2022-04-06 19:53:50 +00:00
namespace MoonTools.ECS
{
internal class RelationDepot
{
private Dictionary<Type, RelationStorage> storages = new Dictionary<Type, RelationStorage>();
private void Register<TRelationKind>() where TRelationKind : unmanaged
2022-04-06 19:53:50 +00:00
{
2022-04-19 19:35:21 +00:00
if (!storages.ContainsKey(typeof(TRelationKind)))
{
storages.Add(typeof(TRelationKind), new RelationStorage<TRelationKind>());
}
2022-04-06 19:53:50 +00:00
}
private RelationStorage<TRelationKind> Lookup<TRelationKind>() where TRelationKind : unmanaged
2022-04-06 19:53:50 +00:00
{
2022-04-19 19:35:21 +00:00
Register<TRelationKind>();
return (RelationStorage<TRelationKind>) storages[typeof(TRelationKind)];
2022-04-06 19:53:50 +00:00
}
public void Set<TRelationKind>(Relation relation, TRelationKind relationData) where TRelationKind : unmanaged
2022-04-06 19:53:50 +00:00
{
Lookup<TRelationKind>().Set(relation, relationData);
2022-04-06 19:53:50 +00:00
}
public void Remove<TRelationKind>(Relation relation) where TRelationKind : unmanaged
2022-04-06 19:53:50 +00:00
{
Lookup<TRelationKind>().Remove(relation);
}
2022-04-19 19:35:21 +00:00
// FIXME: optimize this
2022-04-06 19:53:50 +00:00
public void OnEntityDestroy(int entityID)
{
foreach (var storage in storages.Values)
{
storage.OnEntityDestroy(entityID);
}
}
public IEnumerable<(Entity, Entity, TRelationKind)> Relations<TRelationKind>() where TRelationKind : unmanaged
2022-04-06 19:53:50 +00:00
{
return Lookup<TRelationKind>().All();
}
public bool Related<TRelationKind>(int idA, int idB) where TRelationKind : unmanaged
2022-04-07 03:08:28 +00:00
{
return Lookup<TRelationKind>().Has(new Relation(idA, idB));
}
public IEnumerable<(Entity, TRelationKind)> RelatedToA<TRelationKind>(int entityID) where TRelationKind : unmanaged
2022-04-06 19:53:50 +00:00
{
return Lookup<TRelationKind>().RelatedToA(entityID);
}
public IEnumerable<(Entity, TRelationKind)> RelatedToB<TRelationKind>(int entityID) where TRelationKind : unmanaged
2022-04-06 19:53:50 +00:00
{
return Lookup<TRelationKind>().RelatedToB(entityID);
}
public void Save(RelationDepotState state)
{
foreach (var (type, storage) in storages)
{
if (!state.StorageStates.ContainsKey(type))
{
state.StorageStates.Add(type, storage.CreateState());
}
storage.Save(state.StorageStates[type]);
}
}
public void Load(RelationDepotState state)
{
foreach (var (type, storageState) in state.StorageStates)
{
storages[type].Load(storageState);
}
}
2022-04-06 19:53:50 +00:00
}
}