encompass-cs/encompass-cs/WorldBuilder.cs

350 lines
15 KiB
C#
Raw Normal View History

2019-06-17 00:56:36 +00:00
using System;
2019-06-15 00:03:56 +00:00
using System.Collections.Generic;
2019-06-17 00:56:36 +00:00
using System.Reflection;
using System.Linq;
using Encompass.Exceptions;
2019-07-18 21:02:57 +00:00
using Encompass.Engines;
using MoonTools.Core.Graph;
using MoonTools.Core.Graph.Extensions;
2019-06-15 00:03:56 +00:00
2019-06-16 01:05:56 +00:00
namespace Encompass
{
/// <summary>
/// WorldBuilder is used to construct a World from Engines, Renderers, and an initial state of Entities, Components, and Messages.
/// </summary>
/// <remarks>
/// WorldBuilder enforces certain rules about Engine structure. It is forbidden to have messages create cycles between Engines,
/// and no Component may be written by more than one Engine.
/// The WorldBuilder uses Engines and their Message read/emit information to determine a valid ordering of the Engines, which is given to the World.
/// </remarks>
2019-06-16 01:05:56 +00:00
public class WorldBuilder
{
2019-06-20 17:46:15 +00:00
private readonly List<Engine> engines = new List<Engine>();
private readonly DirectedGraph<Engine, Unit> engineGraph = GraphBuilder.DirectedGraph<Engine>();
2019-06-15 00:51:06 +00:00
2019-06-20 17:46:15 +00:00
private readonly ComponentManager componentManager;
private readonly EntityManager entityManager;
private readonly MessageManager messageManager;
2019-08-01 23:24:57 +00:00
private readonly ComponentMessageManager componentMessageManager;
2019-06-20 17:46:15 +00:00
private readonly DrawLayerManager drawLayerManager;
private readonly RenderManager renderManager;
2019-06-15 00:03:56 +00:00
private readonly Dictionary<Type, HashSet<Engine>> typeToReaders = new Dictionary<Type, HashSet<Engine>>();
2019-06-17 00:56:36 +00:00
2019-07-18 21:02:57 +00:00
private readonly HashSet<Engine> senders = new HashSet<Engine>();
private readonly HashSet<Type> registeredComponentTypes = new HashSet<Type>();
2019-06-16 01:05:56 +00:00
public WorldBuilder()
{
drawLayerManager = new DrawLayerManager();
componentManager = new ComponentManager(drawLayerManager);
2019-06-16 01:55:35 +00:00
messageManager = new MessageManager();
2019-08-01 23:24:57 +00:00
componentMessageManager = new ComponentMessageManager();
entityManager = new EntityManager(componentManager, componentMessageManager);
2019-08-10 02:29:08 +00:00
renderManager = new RenderManager(componentManager, drawLayerManager);
2019-06-15 00:03:56 +00:00
}
/// <summary>
/// Creates and returns a new empty Entity.
/// </summary>
2019-06-16 01:05:56 +00:00
public Entity CreateEntity()
{
2019-06-19 21:14:44 +00:00
return entityManager.CreateEntity();
2019-06-15 00:03:56 +00:00
}
/// <summary>
/// Specifies that the given Message should be sent immediately on the first World Update.
/// </summary>
public void SendMessage<TMessage>(TMessage message) where TMessage : struct, IMessage
2019-06-29 05:07:48 +00:00
{
messageManager.AddMessage(message);
}
/// <summary>
/// Specifies that the given Message should be sent after the specified number of seconds after the first World Update.
/// </summary>
2019-08-20 02:05:18 +00:00
public void SendMessageDelayed<TMessage>(TMessage message, double time) where TMessage : struct, IMessage
{
messageManager.AddMessageDelayed(message, time);
}
/// <summary>
/// Sets Component data for the specified Component Type on the specified Entity.
/// </summary>
public Guid SetComponent<TComponent>(Entity entity, TComponent component, int priority = 0) where TComponent : struct, IComponent
2019-07-17 18:24:21 +00:00
{
return componentManager.MarkComponentForWrite(entity, component, priority);
2019-07-17 18:24:21 +00:00
}
/// <summary>
/// Sets Draw Component data for the specified Component Type on the specified Entity.
/// This method must be used for the Draw Component to be readable by an OrderedRenderer.
/// </summary>
public Guid SetDrawComponent<TComponent>(Entity entity, TComponent component, int priority = 0, int layer = 0) where TComponent : struct, IComponent, IDrawComponent
2019-07-17 18:24:21 +00:00
{
return componentManager.MarkDrawComponentForWrite(entity, component, priority, layer);
2019-07-17 18:24:21 +00:00
}
2019-07-18 21:02:57 +00:00
internal void RegisterComponent(Type componentType)
{
registeredComponentTypes.Add(componentType);
AddEngine((Engine)Activator.CreateInstance(typeof(ComponentMessageEmitter<>).MakeGenericType(componentType)));
}
/// <summary>
/// Adds the specified Engine to the World.
/// </summary>
/// <param name="engine">An instance of an Engine.</param>
public Engine AddEngine<TEngine>(TEngine engine) where TEngine : Engine
2019-06-16 01:05:56 +00:00
{
engine.AssignEntityManager(entityManager);
engine.AssignComponentManager(componentManager);
engine.AssignMessageManager(messageManager);
2019-08-01 23:24:57 +00:00
engine.AssignComponentMessageManager(componentMessageManager);
2019-06-15 00:51:06 +00:00
engines.Add(engine);
engineGraph.AddNode(engine);
2019-06-17 00:56:36 +00:00
2019-07-19 19:47:17 +00:00
var messageReceiveTypes = engine.receiveTypes;
2019-07-19 01:20:38 +00:00
var messageSendTypes = engine.sendTypes;
2019-06-17 00:56:36 +00:00
2019-07-29 02:17:00 +00:00
foreach (var messageType in messageReceiveTypes.Union(messageSendTypes))
{
messageManager.RegisterMessageType(messageType);
}
2019-07-19 19:47:17 +00:00
foreach (var messageType in messageReceiveTypes.Intersect(messageSendTypes))
2019-07-18 21:02:57 +00:00
{
2019-07-19 23:15:48 +00:00
if ((messageType.IsGenericType && messageType.GetGenericTypeDefinition() == typeof(PendingComponentMessage<>)))
{
2019-07-19 23:15:48 +00:00
var componentType = messageType.GetGenericArguments().Single();
throw new EngineSelfCycleException("Engine {0} both activates and reads pending Component {1}", engine.GetType().Name, componentType.Name);
}
2019-07-19 23:15:48 +00:00
throw new EngineSelfCycleException("Engine {0} both receives and sends Message {1}", engine.GetType().Name, messageType.Name);
2019-07-18 21:02:57 +00:00
}
2019-06-17 00:56:36 +00:00
2019-07-18 21:02:57 +00:00
if (messageSendTypes.Any())
{
senders.Add(engine);
}
2019-07-19 19:47:17 +00:00
foreach (var receiveType in engine.receiveTypes)
2019-07-18 21:02:57 +00:00
{
2019-07-19 19:47:17 +00:00
if (receiveType.IsGenericType)
2019-06-29 05:57:18 +00:00
{
2019-07-19 19:47:17 +00:00
var genericTypeDefinition = receiveType.GetGenericTypeDefinition();
2019-07-19 23:15:48 +00:00
if (genericTypeDefinition == typeof(ComponentMessage<>) || genericTypeDefinition == typeof(PendingComponentMessage<>))
2019-06-17 00:56:36 +00:00
{
2019-07-19 19:47:17 +00:00
var componentType = receiveType.GetGenericArguments().Single();
if (!registeredComponentTypes.Contains(componentType))
{
RegisterComponent(componentType);
}
2019-06-17 00:56:36 +00:00
}
}
2019-07-19 19:47:17 +00:00
if (!typeToReaders.ContainsKey(receiveType))
2019-06-17 00:56:36 +00:00
{
2019-07-19 19:47:17 +00:00
typeToReaders.Add(receiveType, new HashSet<Engine>());
2019-06-29 05:57:18 +00:00
}
2019-06-17 00:56:36 +00:00
2019-07-19 19:47:17 +00:00
typeToReaders[receiveType].Add(engine);
}
2019-06-15 00:51:06 +00:00
return engine;
}
/// <summary>
/// Adds the specified OrderedRenderer to the World.
/// </summary>
public OrderedRenderer<TComponent> AddOrderedRenderer<TComponent>(OrderedRenderer<TComponent> renderer) where TComponent : struct, IComponent, IDrawComponent
2019-06-19 21:14:44 +00:00
{
renderer.AssignEntityManager(entityManager);
renderer.AssignComponentManager(componentManager);
renderManager.RegisterOrderedRenderer<TComponent>(renderer.InternalRender);
return renderer;
}
/// <summary>
/// Adds the specified GeneralRenderer to the World at the specified layer.
/// Higher layer numbers draw on top of lower layer numbers.
/// </summary>
/// <param name="renderer">An instance of a GeneralRenderer.</param>
/// <param name="layer">The layer at which the GeneralRenderer should render. Higher numbers draw over lower numbers.</param>
public TRenderer AddGeneralRenderer<TRenderer>(TRenderer renderer, int layer) where TRenderer : GeneralRenderer
{
renderer.AssignEntityManager(entityManager);
renderer.AssignComponentManager(componentManager);
renderManager.RegisterGeneralRendererWithLayer(renderer, layer);
2019-06-19 21:14:44 +00:00
return renderer;
}
2019-07-18 21:02:57 +00:00
private void BuildEngineGraph()
{
foreach (var senderEngine in senders)
{
2019-07-19 01:20:38 +00:00
foreach (var messageType in senderEngine.sendTypes.Where((type) => type.GetInterfaces().Contains(typeof(IMessage))))
2019-07-18 21:02:57 +00:00
{
if (typeToReaders.ContainsKey(messageType))
{
foreach (var readerEngine in typeToReaders[messageType])
{
if (senderEngine != readerEngine)
{
engineGraph.AddEdge(senderEngine, readerEngine);
}
2019-07-18 21:02:57 +00:00
}
}
}
}
}
/// <summary>
/// Builds the World out of the state specified on the WorldBuilder.
/// Validates and constructs an ordering of the given Engines.
/// </summary>
/// <returns>An instance of World.</returns>
2019-06-16 01:05:56 +00:00
public World Build()
{
2019-07-18 21:02:57 +00:00
BuildEngineGraph();
2019-06-17 00:56:36 +00:00
if (engineGraph.Cyclic())
{
var cycles = engineGraph.SimpleCycles();
var errorString = "Cycle(s) found in Engines: ";
2019-07-19 23:15:48 +00:00
foreach (var cycle in cycles)
2019-06-17 00:56:36 +00:00
{
2019-07-19 23:15:48 +00:00
var reversed = cycle.Reverse();
2019-06-17 00:56:36 +00:00
errorString += "\n" +
2019-07-19 23:15:48 +00:00
string.Join(" -> ", reversed.Select((engine) => engine.GetType().Name)) +
2019-06-17 00:56:36 +00:00
" -> " +
2019-07-19 23:15:48 +00:00
reversed.First().GetType().Name;
2019-06-17 00:56:36 +00:00
}
throw new EngineCycleException(errorString);
}
var writtenComponentTypesWithoutPriority = new HashSet<Type>();
var writtenComponentTypesWithPriority = new HashSet<Type>();
var duplicateWritesWithoutPriority = new List<Type>();
2019-08-22 00:54:43 +00:00
var duplicateWritesWithSamePriority = new List<Type>();
var writePriorities = new Dictionary<Type, HashSet<int>>();
var writeMessageToEngines = new Dictionary<Type, List<Engine>>();
2019-06-17 00:56:36 +00:00
foreach (var engine in engines)
{
var defaultWritePriorityAttribute = engine.GetType().GetCustomAttribute<DefaultWritePriority>(false);
var writeTypes = engine.sendTypes.Where((type) => type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ComponentWriteMessage<>));
2019-07-20 00:50:13 +00:00
foreach (var writeType in writeTypes)
2019-06-17 00:56:36 +00:00
{
var componentType = writeType.GetGenericArguments()[0];
int? priority = null;
2019-08-22 00:54:43 +00:00
if (engine.writePriorities.ContainsKey(componentType))
2019-06-17 00:56:36 +00:00
{
priority = engine.writePriorities[componentType];
}
else if (defaultWritePriorityAttribute != null)
{
priority = defaultWritePriorityAttribute.writePriority;
}
2019-08-22 00:54:43 +00:00
if (priority.HasValue)
{
2019-08-22 00:54:43 +00:00
writtenComponentTypesWithPriority.Add(componentType);
if (!writePriorities.ContainsKey(componentType))
{
writePriorities[componentType] = new HashSet<int>();
}
if (writePriorities[componentType].Contains(priority.Value))
2019-08-22 00:54:43 +00:00
{
duplicateWritesWithSamePriority.Add(componentType);
}
else if (writtenComponentTypesWithoutPriority.Contains(componentType))
{
duplicateWritesWithoutPriority.Add(componentType);
}
else
{
writePriorities[componentType].Add(priority.Value);
}
2019-07-19 23:15:48 +00:00
}
else
{
2019-08-22 00:54:43 +00:00
if (writtenComponentTypesWithoutPriority.Contains(componentType) || writtenComponentTypesWithPriority.Contains(componentType))
{
duplicateWritesWithoutPriority.Add(componentType);
}
else
{
writtenComponentTypesWithoutPriority.Add(componentType);
}
2019-07-19 23:15:48 +00:00
}
2019-07-19 01:20:38 +00:00
if (!writeMessageToEngines.ContainsKey(componentType))
2019-07-19 23:15:48 +00:00
{
writeMessageToEngines[componentType] = new List<Engine>();
2019-06-17 00:56:36 +00:00
}
2019-07-19 23:15:48 +00:00
writeMessageToEngines[componentType].Add(engine);
2019-06-17 00:56:36 +00:00
}
}
if (duplicateWritesWithoutPriority.Count > 0)
2019-06-17 00:56:36 +00:00
{
var errorString = "Multiple Engines write the same Component without declaring priority: ";
foreach (var componentType in duplicateWritesWithoutPriority)
2019-06-17 00:56:36 +00:00
{
errorString += "\n" +
componentType.Name + " written by: " +
string.Join(", ", writeMessageToEngines[componentType].Select((engine) => engine.GetType().Name));
2019-06-17 00:56:36 +00:00
}
errorString += "\nTo resolve the conflict, add priority arguments to the Writes declarations or use a DefaultWritePriority attribute.";
2019-06-17 00:56:36 +00:00
throw new EngineWriteConflictException(errorString);
2019-06-17 00:56:36 +00:00
}
2019-08-22 00:54:43 +00:00
if (duplicateWritesWithSamePriority.Count > 0)
2019-06-17 00:56:36 +00:00
{
2019-08-22 00:54:43 +00:00
var errorString = "Multiple Engines write the same Component with the same priority: ";
foreach (var componentType in duplicateWritesWithSamePriority)
2019-06-17 00:56:36 +00:00
{
errorString += "\n" +
2019-08-22 00:54:43 +00:00
componentType.Name + " written by: " +
string.Join(", ", writeMessageToEngines[componentType].Select(engine => engine.GetType().Name));
2019-06-17 00:56:36 +00:00
}
errorString += "\nTo resolve the conflict, add priority arguments to the Writes declarations or use a DefaultWritePriority attribute.";
2019-06-17 00:56:36 +00:00
2019-08-22 00:54:43 +00:00
throw new EngineWriteConflictException(errorString);
2019-06-17 00:56:36 +00:00
}
var engineOrder = new List<Engine>();
foreach (var engine in engineGraph.TopologicalSort())
{
engineOrder.Add(engine);
}
2019-06-15 00:51:06 +00:00
var world = new World(
2019-06-17 00:56:36 +00:00
engineOrder,
2019-06-19 21:14:44 +00:00
entityManager,
componentManager,
messageManager,
2019-08-01 23:24:57 +00:00
componentMessageManager,
2019-06-19 21:14:44 +00:00
renderManager
2019-06-15 00:51:06 +00:00
);
2019-06-15 00:03:56 +00:00
componentManager.RemoveMarkedComponents();
componentManager.WriteComponents();
2019-07-18 01:53:31 +00:00
2019-06-15 00:03:56 +00:00
return world;
}
}
}