using System; using System.Collections.Generic; using System.Reflection; using System.Linq; using Encompass.Exceptions; using Encompass.Engines; namespace Encompass { public class WorldBuilder { private readonly List engines = new List(); private readonly DirectedGraph engineGraph = new DirectedGraph(); private readonly ComponentManager componentManager; private readonly EntityManager entityManager; private readonly MessageManager messageManager; private readonly DrawLayerManager drawLayerManager; private readonly RenderManager renderManager; private readonly Dictionary> typeToReaders = new Dictionary>(); private readonly HashSet senders = new HashSet(); private readonly HashSet registeredComponentTypes = new HashSet(); public WorldBuilder() { var entitiesWithAddedComponents = new HashSet(); var entitiesWithRemovedComponents = new HashSet(); drawLayerManager = new DrawLayerManager(); componentManager = new ComponentManager(drawLayerManager, entitiesWithAddedComponents, entitiesWithRemovedComponents); entityManager = new EntityManager(componentManager, entitiesWithAddedComponents, entitiesWithRemovedComponents); messageManager = new MessageManager(); renderManager = new RenderManager(entityManager, componentManager, drawLayerManager); } public Entity CreateEntity() { return entityManager.CreateEntity(); } public void EmitMessage(TMessage message) where TMessage : struct, IMessage { messageManager.AddMessage(message); } public Guid AddComponent(Entity entity, TComponent component) where TComponent : struct, IComponent { return componentManager.AddComponent(entity.ID, component); } public Guid AddDrawComponent(Entity entity, TComponent component, int layer = 0) where TComponent : struct, IComponent { return componentManager.AddDrawComponent(entity.ID, component, layer); } public void DeactivateComponent(Guid componentID) { componentManager.MarkForDeactivation(componentID); } internal void RegisterComponent(Type componentType) { registeredComponentTypes.Add(componentType); AddEngine((Engine)Activator.CreateInstance(typeof(ComponentMessageEmitter<>).MakeGenericType(componentType))); } public Engine AddEngine(TEngine engine) where TEngine : Engine { engine.AssignEntityManager(entityManager); engine.AssignComponentManager(componentManager); engine.AssignMessageManager(messageManager); engines.Add(engine); engineGraph.AddVertex(engine); foreach (var activateType in engine.activateTypes) { engine.sendTypes.Add(activateType); } var messageReadTypes = engine.readTypes; var messageSendTypes = engine.sendTypes; foreach (var messageType in messageReadTypes.Intersect(messageSendTypes)) { // ComponentMessages can safely self-cycle // this does introduce a gotcha though: if you AddComponent and then HasComponent or GetComponent you will receive a false negative // there is no point to doing this but it is a gotcha i suppose if (!(messageType.IsGenericType && messageType.GetGenericTypeDefinition() == typeof(ComponentMessage<>))) { throw new EngineMessageSelfCycleException("Engine {0} both reads and writes Message {1}", engine.GetType().Name, messageType.Name); } } if (messageSendTypes.Any()) { senders.Add(engine); } foreach (var readType in engine.readTypes) { if (readType.IsGenericType && readType.GetGenericTypeDefinition() == typeof(ComponentMessage<>)) { var componentType = readType.GetGenericArguments().Single(); if (!registeredComponentTypes.Contains(componentType)) { RegisterComponent(componentType); } } if (!typeToReaders.ContainsKey(readType)) { typeToReaders.Add(readType, new HashSet()); } typeToReaders[readType].Add(engine); } return engine; } public TRenderer AddEntityRenderer(TRenderer renderer) where TRenderer : Renderer { renderer.AssignEntityManager(entityManager); renderer.AssignComponentManager(componentManager); if (renderer is EntityRenderer) { entityManager.RegisterEntityTracker(renderer as IEntityTracker); renderManager.RegisterEntityRenderer(renderer as EntityRenderer); } return renderer; } public TRenderer AddGeneralRenderer(TRenderer renderer, int layer) where TRenderer : GeneralRenderer { renderer.AssignEntityManager(entityManager); renderer.AssignComponentManager(componentManager); renderManager.RegisterGeneralRendererWithLayer(renderer, layer); return renderer; } private void BuildEngineGraph() { foreach (var senderEngine in senders) { foreach (var messageType in senderEngine.sendTypes.Where((type) => type.GetInterfaces().Contains(typeof(IMessage)))) { if (typeToReaders.ContainsKey(messageType)) { foreach (var readerEngine in typeToReaders[messageType]) { engineGraph.AddEdge(senderEngine, readerEngine); } } } } } public World Build() { BuildEngineGraph(); if (engineGraph.Cyclic()) { var cycles = engineGraph.SimpleCycles(); var errorString = "Cycle(s) found in Engines: "; foreach (var cycle in cycles.Reverse()) { errorString += "\n" + string.Join(" -> ", cycle.Select((engine) => engine.GetType().Name)) + " -> " + cycle.First().GetType().Name; } throw new EngineCycleException(errorString); } var mutatedComponentTypes = new HashSet(); var duplicateMutations = new List(); var componentToEngines = new Dictionary>(); foreach (var engine in engines) { foreach (var updateType in engine.updateTypes) { if (updateType.GetInterfaces().Contains(typeof(IComponent))) // if our write type is a component { if (mutatedComponentTypes.Contains(updateType)) { duplicateMutations.Add(updateType); } else { mutatedComponentTypes.Add(updateType); } if (!componentToEngines.ContainsKey(updateType)) { componentToEngines[updateType] = new List(); } componentToEngines[updateType].Add(engine); } } } if (duplicateMutations.Count > 0) { var errorString = "Multiple Engines write the same Component: "; foreach (var componentType in duplicateMutations) { errorString += "\n" + componentType.Name + " written by: " + string.Join(", ", componentToEngines[componentType].Select((engine) => engine.GetType().Name)); } throw new EngineWriteConflictException(errorString); } var engineOrder = new List(); foreach (var engine in engineGraph.TopologicalSort()) { engineOrder.Add(engine); } var world = new World( engineOrder, entityManager, componentManager, messageManager, renderManager ); componentManager.PerformComponentUpdates(); componentManager.DeactivateMarkedComponents(); componentManager.RemoveMarkedComponents(); entityManager.CheckEntitiesWithAddedComponents(); entityManager.CheckEntitiesWithRemovedComponents(); return world; } } }