encompass-cs/src/Engine.cs

61 lines
2.5 KiB
C#
Raw Normal View History

2019-06-15 07:39:08 +00:00
using System;
using System.Reflection;
2019-06-15 00:51:06 +00:00
using System.Collections.Generic;
namespace Encompass {
public abstract class Engine {
2019-06-15 07:39:08 +00:00
public readonly List<Type> mutateComponentTypes = new List<Type>();
2019-06-15 00:51:06 +00:00
private EntityManager entityManager;
private ComponentManager componentManager;
2019-06-15 07:39:08 +00:00
public Engine() {
var mutatesAttribute = this.GetType().GetCustomAttribute<Mutates>(false);
if (mutatesAttribute != null) {
mutateComponentTypes = mutatesAttribute.mutateComponentTypes;
}
}
2019-06-15 00:51:06 +00:00
internal void AssignEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
internal void AssignComponentManager(ComponentManager componentManager) {
this.componentManager = componentManager;
}
public abstract void Update(float dt);
protected Entity CreateEntity() {
return this.entityManager.CreateEntity();
}
protected IEnumerable<TComponent> ReadComponents<TComponent>() where TComponent : struct, IComponent {
return this.componentManager.GetActiveComponentsByType<TComponent>();
}
protected TComponent ReadComponent<TComponent>() where TComponent : struct, IComponent {
return this.componentManager.GetActiveComponentByType<TComponent>();
}
2019-06-15 07:39:08 +00:00
2019-06-15 18:40:42 +00:00
internal void UpdateComponentInWorld<TComponent>(TComponent originalComponent, TComponent newComponent) where TComponent : struct, IComponent {
2019-06-15 07:39:08 +00:00
if (mutateComponentTypes.Contains(typeof(TComponent))) {
this.componentManager.UpdateComponent(originalComponent, newComponent);
} else {
2019-06-15 18:40:42 +00:00
throw new IllegalComponentMutationException("Engine {0} tried to mutate undeclared Component {1}", this.GetType().Name, typeof(TComponent).Name);
}
}
protected void UpdateComponent<TComponent>(TComponent component, Func<TComponent, TComponent> updateFunction) where TComponent : struct, IComponent {
var updatedComponent = updateFunction(component);
this.UpdateComponentInWorld(component, updatedComponent);
}
protected void UpdateComponents<TComponent>(IEnumerable<TComponent> components, Func<TComponent, TComponent> updateFunction) where TComponent : struct, IComponent {
foreach (var component in components) {
this.UpdateComponent(component, updateFunction);
2019-06-15 07:39:08 +00:00
}
}
2019-06-15 00:51:06 +00:00
}
}