Power Rework (#863)

Co-authored-by: py01 <pyronetics01@gmail.com>
This commit is contained in:
py01
2020-06-28 09:23:26 -06:00
committed by GitHub
parent ffe25de723
commit 23cc6b1d4e
154 changed files with 11253 additions and 3913 deletions

View File

@@ -0,0 +1,73 @@
using Content.Server.GameObjects.Components.NodeContainer.NodeGroups;
using Content.Server.GameObjects.Components.NodeContainer.Nodes;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
using System.Collections.Generic;
namespace Content.Server.GameObjects.Components.NodeContainer
{
/// <summary>
/// Creates and maintains a set of <see cref="Node"/>s.
/// </summary>
[RegisterComponent]
public class NodeContainerComponent : Component
{
public override string Name => "NodeContainer";
[ViewVariables]
public IReadOnlyList<Node> Nodes => _nodes;
private List<Node> _nodes = new List<Node>();
#pragma warning disable 649
[Dependency] private readonly INodeFactory _nodeFactory;
#pragma warning restore 649
/// <summary>
/// A set of <see cref="NodeGroupID"/>s and <see cref="Node"/> implementation names
/// to be created and held in this container.
/// </summary>
[ViewVariables]
private Dictionary<NodeGroupID, List<string>> _nodeTypes;
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _nodeTypes, "nodeTypes", new Dictionary<NodeGroupID, List<string>> { });
}
protected override void Startup()
{
base.Startup();
foreach (var nodeType in _nodeTypes)
{
var nodeGroupID = nodeType.Key;
foreach (var nodeName in nodeType.Value)
{
_nodes.Add(MakeNewNode(nodeName, nodeGroupID, Owner));
}
}
foreach (var node in _nodes)
{
node.OnContainerInitialize();
}
}
public override void OnRemove()
{
foreach (var node in _nodes)
{
node.OnContainerRemove();
}
_nodes = null;
base.OnRemove();
}
private Node MakeNewNode(string nodeName, NodeGroupID groupID, IEntity owner)
{
return _nodeFactory.MakeNode(nodeName, groupID, owner);
}
}
}

View File

@@ -0,0 +1,122 @@
using Content.Server.GameObjects.Components.Power;
using Content.Server.GameObjects.Components.Power.ApcNetComponents;
using Robust.Shared.ViewVariables;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
public interface IApcNet
{
void AddApc(ApcComponent apc);
void RemoveApc(ApcComponent apc);
void AddPowerProvider(PowerProviderComponent provider);
void RemovePowerProvider(PowerProviderComponent provider);
void UpdatePowerProviderReceivers(PowerProviderComponent provider);
void Update(float frameTime);
}
[NodeGroup(NodeGroupID.Apc)]
public class ApcNetNodeGroup : BaseNetConnectorNodeGroup<BaseApcNetComponent, IApcNet>, IApcNet
{
[ViewVariables]
private readonly Dictionary<ApcComponent, BatteryComponent> _apcBatteries = new Dictionary<ApcComponent, BatteryComponent>();
[ViewVariables]
private readonly Dictionary<PowerProviderComponent, List<PowerReceiverComponent>> _providerReceivers = new Dictionary<PowerProviderComponent, List<PowerReceiverComponent>>();
//Debug property
[ViewVariables]
private int TotalReceivers => _providerReceivers.SelectMany(kvp => kvp.Value).Count();
private IEnumerable<BatteryComponent> AvailableBatteries => _apcBatteries.Where(kvp => kvp.Key.MainBreakerEnabled).Select(kvp => kvp.Value);
public static readonly IApcNet NullNet = new NullApcNet();
#region IApcNet Methods
protected override void SetNetConnectorNet(BaseApcNetComponent netConnectorComponent)
{
netConnectorComponent.Net = this;
}
public void AddApc(ApcComponent apc)
{
_apcBatteries.Add(apc, apc.Battery);
}
public void RemoveApc(ApcComponent apc)
{
_apcBatteries.Remove(apc);
if (!_apcBatteries.Any())
{
foreach (var receiver in _providerReceivers.SelectMany(kvp => kvp.Value))
{
receiver.HasApcPower = false;
}
}
}
public void AddPowerProvider(PowerProviderComponent provider)
{
_providerReceivers.Add(provider, provider.LinkedReceivers.ToList());
}
public void RemovePowerProvider(PowerProviderComponent provider)
{
_providerReceivers.Remove(provider);
}
public void UpdatePowerProviderReceivers(PowerProviderComponent provider)
{
Debug.Assert(_providerReceivers.ContainsKey(provider));
_providerReceivers[provider] = provider.LinkedReceivers.ToList();
}
public void Update(float frameTime)
{
var totalCharge = 0.0;
var totalMaxCharge = 0;
foreach (var battery in AvailableBatteries)
{
totalCharge += battery.CurrentCharge;
totalMaxCharge += battery.MaxCharge;
}
var availablePowerFraction = totalCharge / totalMaxCharge;
foreach (var receiver in _providerReceivers.SelectMany(kvp => kvp.Value))
{
receiver.HasApcPower = TryUsePower(receiver.Load * frameTime);
}
}
private bool TryUsePower(float neededCharge)
{
foreach (var battery in AvailableBatteries)
{
if (battery.TryUseCharge(neededCharge)) //simplification - all power needed must come from one battery
{
return true;
}
}
return false;
}
#endregion
private class NullApcNet : IApcNet
{
public void AddApc(ApcComponent apc) { }
public void AddPowerProvider(PowerProviderComponent provider) { }
public void RemoveApc(ApcComponent apc) { }
public void RemovePowerProvider(PowerProviderComponent provider) { }
public void UpdatePowerProviderReceivers(PowerProviderComponent provider) { }
public void Update(float frameTime) { }
}
}
}

View File

@@ -0,0 +1,36 @@
using Content.Server.GameObjects.Components.Power;
using Content.Server.GameObjects.Components.NodeContainer.Nodes;
using System.Collections.Generic;
using System.Linq;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
public abstract class BaseNetConnectorNodeGroup<TNetConnector, TNetType> : BaseNodeGroup where TNetConnector : BaseNetConnectorComponent<TNetType>
{
private readonly Dictionary<Node, List<TNetConnector>> _netConnectorComponents = new Dictionary<Node, List<TNetConnector>>();
protected override void OnAddNode(Node node)
{
var newNetConnectorComponents = node.Owner
.GetAllComponents<TNetConnector>()
.Where(powerComp => (NodeGroupID) powerComp.Voltage == node.NodeGroupID)
.ToList();
_netConnectorComponents.Add(node, newNetConnectorComponents);
foreach (var netConnectorComponent in newNetConnectorComponents)
{
SetNetConnectorNet(netConnectorComponent);
}
}
protected abstract void SetNetConnectorNet(TNetConnector netConnectorComponent);
protected override void OnRemoveNode(Node node)
{
foreach (var netConnectorComponent in _netConnectorComponents[node])
{
netConnectorComponent.ClearNet();
}
_netConnectorComponents.Remove(node);
}
}
}

View File

@@ -0,0 +1,121 @@
using Content.Server.GameObjects.Components.NodeContainer.Nodes;
using Robust.Shared.ViewVariables;
using System.Collections.Generic;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
/// <summary>
/// Maintains a collection of <see cref="Node"/>s, and performs operations requiring a list of
/// all connected <see cref="Node"/>s.
/// </summary>
public interface INodeGroup
{
public IReadOnlyList<Node> Nodes { get; }
void AddNode(Node node);
void RemoveNode(Node node);
void CombineGroup(INodeGroup newGroup);
void BeforeCombine();
void AfterCombine();
void BeforeRemakeSpread();
void AfterRemakeSpread();
}
[NodeGroup(NodeGroupID.Default)]
public class BaseNodeGroup : INodeGroup
{
[ViewVariables]
public IReadOnlyList<Node> Nodes => _nodes;
private readonly List<Node> _nodes = new List<Node>();
[ViewVariables]
public int NodeCount => Nodes.Count;
public static readonly INodeGroup NullGroup = new NullNodeGroup();
public void AddNode(Node node)
{
_nodes.Add(node);
OnAddNode(node);
}
public void RemoveNode(Node node)
{
_nodes.Remove(node);
OnRemoveNode(node);
RemakeGroup();
}
public void CombineGroup(INodeGroup newGroup)
{
if (newGroup.Nodes.Count < Nodes.Count)
{
newGroup.CombineGroup(this);
return;
}
BeforeCombine();
newGroup.BeforeCombine();
foreach (var node in Nodes)
{
node.NodeGroup = newGroup;
}
AfterCombine();
newGroup.AfterCombine();
}
/// <summary>
/// Causes all <see cref="Node"/>s to remake their groups. Called when a <see cref="Node"/> is removed
/// and may have split a group in two, so multiple new groups may need to be formed.
/// </summary>
private void RemakeGroup()
{
BeforeRemake();
foreach (var node in Nodes)
{
node.ClearNodeGroup();
}
foreach (var node in Nodes)
{
if (node.TryAssignGroupIfNeeded())
{
node.StartSpreadingGroup();
}
}
}
protected virtual void OnAddNode(Node node) { }
protected virtual void OnRemoveNode(Node node) { }
protected virtual void BeforeRemake() { }
protected virtual void AfterRemake() { }
public virtual void BeforeCombine() { }
public virtual void AfterCombine() { }
public virtual void BeforeRemakeSpread() { }
public virtual void AfterRemakeSpread() { }
private class NullNodeGroup : INodeGroup
{
public IReadOnlyList<Node> Nodes => _nodes;
private readonly List<Node> _nodes = new List<Node>();
public void AddNode(Node node) { }
public void CombineGroup(INodeGroup newGroup) { }
public void RemoveNode(Node node) { }
public void BeforeCombine() { }
public void AfterCombine() { }
public void BeforeRemakeSpread() { }
public void AfterRemakeSpread() { }
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
/// <summary>
/// Associates a <see cref="INodeGroup"/> implementation with a <see cref="NodeGroupID"/>.
/// This is used to gurantee all <see cref="INode"/>s of the same <see cref="INode.NodeGroupID"/>
/// have the same type of <see cref="INodeGroup"/>. Used by <see cref="INodeGroupFactory"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class NodeGroupAttribute : Attribute
{
public NodeGroupID[] NodeGroupIDs { get; }
public NodeGroupAttribute(params NodeGroupID[] nodeGroupTypes)
{
NodeGroupIDs = nodeGroupTypes;
}
}
}

View File

@@ -0,0 +1,65 @@
using Robust.Shared.Interfaces.Reflection;
using Robust.Shared.IoC;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
public interface INodeGroupFactory
{
/// <summary>
/// Performs reflection to associate <see cref="INodeGroup"/> implementations with the
/// string specified in their <see cref="NodeGroupAttribute"/>.
/// </summary>
void Initialize();
/// <summary>
/// Returns a new <see cref="INodeGroup"/> instance.
/// </summary>
INodeGroup MakeNodeGroup(NodeGroupID nodeGroupType);
}
public class NodeGroupFactory : INodeGroupFactory
{
private readonly Dictionary<NodeGroupID, Type> _groupTypes = new Dictionary<NodeGroupID, Type>();
#pragma warning disable 649
[Dependency] private readonly IReflectionManager _reflectionManager;
[Dependency] private readonly IDynamicTypeFactory _typeFactory;
#pragma warning restore 649
public void Initialize()
{
var nodeGroupTypes = _reflectionManager.GetAllChildren<BaseNodeGroup>();
foreach (var nodeGroupType in nodeGroupTypes)
{
var att = nodeGroupType.GetCustomAttribute<NodeGroupAttribute>();
if (att != null)
{
foreach (var groupID in att.NodeGroupIDs)
{
_groupTypes.Add(groupID, nodeGroupType);
}
}
}
}
public INodeGroup MakeNodeGroup(NodeGroupID nodeGroupType)
{
if (_groupTypes.TryGetValue(nodeGroupType, out var type))
{
return _typeFactory.CreateInstance<INodeGroup>(type);
}
throw new ArgumentException($"{nodeGroupType} did not have an associated {nameof(INodeGroup)}.");
}
}
public enum NodeGroupID
{
Default,
HVPower,
MVPower,
Apc,
}
}

View File

@@ -0,0 +1,192 @@
using Content.Server.GameObjects.Components.Power.PowerNetComponents;
using Robust.Shared.ViewVariables;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups
{
public interface IPowerNet
{
void AddSupplier(PowerSupplierComponent supplier);
void RemoveSupplier(PowerSupplierComponent supplier);
void UpdateSupplierSupply(PowerSupplierComponent supplier, int oldSupplyRate, int newSupplyRate);
void AddConsumer(PowerConsumerComponent consumer);
void RemoveConsumer(PowerConsumerComponent consumer);
void UpdateConsumerDraw(PowerConsumerComponent consumer, int oldDrawRate, int newDrawRate);
void UpdateConsumerPriority(PowerConsumerComponent consumer, Priority oldPriority, Priority newPriority);
}
[NodeGroup(NodeGroupID.HVPower, NodeGroupID.MVPower)]
public class PowerNetNodeGroup : BaseNetConnectorNodeGroup<BasePowerNetComponent, IPowerNet>, IPowerNet
{
[ViewVariables]
private readonly List<PowerSupplierComponent> _suppliers = new List<PowerSupplierComponent>();
[ViewVariables]
private int _totalSupply = 0;
[ViewVariables]
private readonly Dictionary<Priority, List<PowerConsumerComponent>> _consumersByPriority = new Dictionary<Priority, List<PowerConsumerComponent>>();
[ViewVariables]
private readonly Dictionary<Priority, int> _drawByPriority = new Dictionary<Priority, int>();
[ViewVariables]
private bool _supressPowerRecalculation = false;
public static readonly IPowerNet NullNet = new NullPowerNet();
public PowerNetNodeGroup()
{
foreach(Priority priority in Enum.GetValues(typeof(Priority)))
{
_consumersByPriority.Add(priority, new List<PowerConsumerComponent>());
_drawByPriority.Add(priority, 0);
}
}
#region BaseNodeGroup Overrides
protected override void SetNetConnectorNet(BasePowerNetComponent netConnectorComponent)
{
netConnectorComponent.Net = this;
}
public override void BeforeCombine()
{
_supressPowerRecalculation = true;
}
public override void AfterCombine()
{
_supressPowerRecalculation = false;
UpdateConsumerReceivedPower();
}
protected override void BeforeRemake()
{
_supressPowerRecalculation = true;
}
public override void BeforeRemakeSpread()
{
_supressPowerRecalculation = true;
}
public override void AfterRemakeSpread()
{
_supressPowerRecalculation = false;
UpdateConsumerReceivedPower();
}
#endregion
#region IPowerNet Methods
public void AddSupplier(PowerSupplierComponent supplier)
{
_suppliers.Add(supplier);
_totalSupply += supplier.SupplyRate;
UpdateConsumerReceivedPower();
}
public void RemoveSupplier(PowerSupplierComponent supplier)
{
Debug.Assert(_suppliers.Contains(supplier));
_suppliers.Remove(supplier);
_totalSupply -= supplier.SupplyRate;
UpdateConsumerReceivedPower();
}
public void UpdateSupplierSupply(PowerSupplierComponent supplier, int oldSupplyRate, int newSupplyRate)
{
Debug.Assert(_suppliers.Contains(supplier));
_totalSupply -= oldSupplyRate;
_totalSupply += newSupplyRate;
UpdateConsumerReceivedPower();
}
public void AddConsumer(PowerConsumerComponent consumer)
{
_consumersByPriority[consumer.Priority].Add(consumer);
_drawByPriority[consumer.Priority] += consumer.DrawRate;
UpdateConsumerReceivedPower();
}
public void RemoveConsumer(PowerConsumerComponent consumer)
{
Debug.Assert(_consumersByPriority[consumer.Priority].Contains(consumer));
_consumersByPriority[consumer.Priority].Add(consumer);
_drawByPriority[consumer.Priority] -= consumer.DrawRate;
UpdateConsumerReceivedPower();
}
public void UpdateConsumerDraw(PowerConsumerComponent consumer, int oldDrawRate, int newDrawRate)
{
Debug.Assert(_consumersByPriority[consumer.Priority].Contains(consumer));
_drawByPriority[consumer.Priority] -= oldDrawRate;
_drawByPriority[consumer.Priority] += newDrawRate;
UpdateConsumerReceivedPower();
}
public void UpdateConsumerPriority(PowerConsumerComponent consumer, Priority oldPriority, Priority newPriority)
{
Debug.Assert(_consumersByPriority[oldPriority].Contains(consumer));
_consumersByPriority[oldPriority].Remove(consumer);
_drawByPriority[oldPriority] -= consumer.DrawRate;
_consumersByPriority[newPriority].Add(consumer);
_drawByPriority[newPriority] += consumer.DrawRate;
UpdateConsumerReceivedPower();
}
private void UpdateConsumerReceivedPower()
{
if (_supressPowerRecalculation)
{
return;
}
var remainingSupply = _totalSupply;
foreach (Priority priority in Enum.GetValues(typeof(Priority)))
{
var categoryPowerDemand = _drawByPriority[priority];
if (remainingSupply - categoryPowerDemand >= 0) //can fully power all in category
{
remainingSupply -= categoryPowerDemand;
foreach (var consumer in _consumersByPriority[priority])
{
consumer.ReceivedPower = consumer.DrawRate;
}
}
else if (remainingSupply - categoryPowerDemand < 0) //cannot fully power all, split power
{
var availiablePowerFraction = (float) remainingSupply / categoryPowerDemand;
remainingSupply = 0;
foreach (var consumer in _consumersByPriority[priority])
{
consumer.ReceivedPower = (int) (consumer.DrawRate * availiablePowerFraction); //give each consumer a fraction of what they requested (rounded down to nearest int)
}
}
}
}
#endregion
private class NullPowerNet : IPowerNet
{
public void AddConsumer(PowerConsumerComponent consumer) { }
public void AddSupplier(PowerSupplierComponent supplier) { }
public void UpdateSupplierSupply(PowerSupplierComponent supplier, int oldSupplyRate, int newSupplyRate) { }
public void RemoveConsumer(PowerConsumerComponent consumer) { }
public void RemoveSupplier(PowerSupplierComponent supplier) { }
public void UpdateConsumerDraw(PowerConsumerComponent consumer, int oldDrawRate, int newDrawRate) { }
public void UpdateConsumerPriority(PowerConsumerComponent consumer, Priority oldPriority, Priority newPriority) { }
}
}
}

View File

@@ -0,0 +1,25 @@
using Content.Server.GameObjects.Components.NodeContainer.NodeGroups;
using Robust.Shared.GameObjects.Components.Transform;
using System.Collections.Generic;
using System.Linq;
namespace Content.Server.GameObjects.Components.NodeContainer.Nodes
{
/// <summary>
/// A <see cref="Node"/> that can reach other <see cref="AdjacentNode"/>s that are directly adjacent to it.
/// </summary>
[Node("AdjacentNode")]
public class AdjacentNode : Node
{
protected override IEnumerable<Node> GetReachableNodes()
{
return Owner.GetComponent<SnapGridComponent>()
.GetCardinalNeighborCells()
.SelectMany(sgc => sgc.GetLocal())
.Select(entity => entity.TryGetComponent<NodeContainerComponent>(out var container) ? container : null)
.Where(container => container != null)
.SelectMany(container => container.Nodes)
.Where(node => node != null && node != this);
}
}
}

View File

@@ -0,0 +1,131 @@
using Content.Server.GameObjects.Components.NodeContainer.NodeGroups;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.ViewVariables;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Content.Server.GameObjects.Components.NodeContainer.Nodes
{
/// <summary>
/// Organizes themselves into distinct <see cref="INodeGroup"/>s with other <see cref="Node"/>s
/// that they can "reach" and have the same <see cref="Node.NodeGroupID"/>.
/// </summary>
public abstract class Node
{
/// <summary>
/// An ID used as a criteria for combining into groups. Determines which <see cref="INodeGroup"/>
/// implementation is used as a group, detailed in <see cref="INodeGroupFactory"/>.
/// </summary>
[ViewVariables]
public NodeGroupID NodeGroupID { get; private set; }
[ViewVariables]
public INodeGroup NodeGroup { get => _nodeGroup; set => SetNodeGroup(value); }
private INodeGroup _nodeGroup = BaseNodeGroup.NullGroup;
[ViewVariables]
public IEntity Owner { get; private set; }
private bool _needsGroup = true;
private bool _deleting = false;
#pragma warning disable 649
[Dependency] private readonly INodeGroupFactory _nodeGroupFactory;
#pragma warning restore 649
public void Initialize(NodeGroupID nodeGroupID, IEntity owner)
{
NodeGroupID = nodeGroupID;
Owner = owner;
}
public void OnContainerInitialize()
{
TryAssignGroupIfNeeded();
CombineGroupWithReachable();
}
public void OnContainerRemove()
{
_deleting = true;
NodeGroup.RemoveNode(this);
}
public bool TryAssignGroupIfNeeded()
{
if (!_needsGroup)
{
return false;
}
NodeGroup = GetReachableCompatibleGroups().FirstOrDefault() ?? MakeNewGroup();
return true;
}
public void StartSpreadingGroup()
{
NodeGroup.BeforeRemakeSpread();
SpreadGroup();
NodeGroup.AfterRemakeSpread();
}
public void SpreadGroup()
{
Debug.Assert(!_needsGroup);
foreach (var node in GetReachableCompatibleNodes().Where(node => node._needsGroup == true))
{
node.NodeGroup = NodeGroup;
node.SpreadGroup();
}
}
public void ClearNodeGroup()
{
_nodeGroup = BaseNodeGroup.NullGroup;
_needsGroup = true;
}
/// <summary>
/// How this node will attempt to find other reachable <see cref="Node"/>s to group with.
/// Returns a set of <see cref="Node"/>s to consider grouping with. Should not return this current <see cref="Node"/>.
/// </summary>
protected abstract IEnumerable<Node> GetReachableNodes();
private IEnumerable<Node> GetReachableCompatibleNodes()
{
return GetReachableNodes().Where(node => node.NodeGroupID == NodeGroupID)
.Where(node => node._deleting == false);
}
private IEnumerable<INodeGroup> GetReachableCompatibleGroups()
{
return GetReachableCompatibleNodes().Where(node => node._needsGroup == false)
.Select(node => node.NodeGroup)
.Where(group => group != NodeGroup);
}
private void CombineGroupWithReachable()
{
Debug.Assert(!_needsGroup);
foreach (var group in GetReachableCompatibleGroups())
{
NodeGroup.CombineGroup(group);
}
}
private void SetNodeGroup(INodeGroup newGroup)
{
_nodeGroup = newGroup;
NodeGroup.AddNode(this);
_needsGroup = false;
}
private INodeGroup MakeNewGroup()
{
return _nodeGroupFactory.MakeNodeGroup(NodeGroupID);
}
}
}

View File

@@ -0,0 +1,20 @@
using System;
namespace Content.Server.GameObjects.Components.NodeContainer.Nodes
{
/// <summary>
/// Associates a <see cref="Node"/> implementation with a string. This is used
/// to specify an <see cref="Node"/>'s strategy in yaml. Used by <see cref="INodeFactory"/>.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class
NodeAttribute : Attribute
{
public string Name { get; }
public NodeAttribute(string name)
{
Name = name;
}
}
}

View File

@@ -0,0 +1,58 @@
using Content.Server.GameObjects.Components.NodeContainer.NodeGroups;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.Reflection;
using Robust.Shared.IoC;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Content.Server.GameObjects.Components.NodeContainer.Nodes
{
public interface INodeFactory
{
/// <summary>
/// Performs reflection to associate <see cref="Node"/> implementations with the
/// string specified in their <see cref="NodeAttribute"/>.
/// </summary>
void Initialize();
/// <summary>
/// Returns a new <see cref="Node"/> instance.
/// </summary>
Node MakeNode(string nodeName, NodeGroupID groupID, IEntity owner);
}
public class NodeFactory : INodeFactory
{
private readonly Dictionary<string, Type> _groupTypes = new Dictionary<string, Type>();
#pragma warning disable 649
[Dependency] private readonly IReflectionManager _reflectionManager;
[Dependency] private readonly IDynamicTypeFactory _typeFactory;
#pragma warning restore 649
public void Initialize()
{
var nodeTypes = _reflectionManager.GetAllChildren<Node>();
foreach (var nodeType in nodeTypes)
{
var att = nodeType.GetCustomAttribute<NodeAttribute>();
if (att != null)
{
_groupTypes.Add(att.Name, nodeType);
}
}
}
public Node MakeNode(string nodeName, NodeGroupID groupID, IEntity owner)
{
if (_groupTypes.TryGetValue(nodeName, out var type))
{
var newNode = _typeFactory.CreateInstance<Node>(type);
newNode.Initialize(groupID, owner);
return newNode;
}
throw new ArgumentException($"{nodeName} did not have an associated {nameof(Node)}.");
}
}
}