Re-organize all projects (#4166)

This commit is contained in:
DrSmugleaf
2021-06-09 22:19:39 +02:00
committed by GitHub
parent 9f50e4061b
commit ff1a2d97ea
1773 changed files with 5258 additions and 5508 deletions

View File

@@ -0,0 +1,46 @@
using Content.Server.NodeContainer.Nodes;
using JetBrains.Annotations;
using Robust.Shared.GameObjects;
namespace Content.Server.NodeContainer.EntitySystems
{
[UsedImplicitly]
public class NodeContainerSystem : EntitySystem
{
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<NodeContainerComponent, PhysicsBodyTypeChangedEvent>(OnBodyTypeChanged);
SubscribeLocalEvent<NodeContainerComponent, RotateEvent>(OnRotateEvent);
}
public override void Shutdown()
{
base.Shutdown();
UnsubscribeLocalEvent<NodeContainerComponent, PhysicsBodyTypeChangedEvent>(OnBodyTypeChanged);
UnsubscribeLocalEvent<NodeContainerComponent, RotateEvent>(OnRotateEvent);
}
private void OnBodyTypeChanged(EntityUid uid, NodeContainerComponent component, PhysicsBodyTypeChangedEvent args)
{
component.AnchorUpdate();
}
private void OnRotateEvent(EntityUid uid, NodeContainerComponent container, RotateEvent ev)
{
if (ev.NewRotation == ev.OldRotation)
{
return;
}
foreach (var node in container.Nodes.Values)
{
if (node is not IRotatableNode rotatableNode) continue;
rotatableNode.RotateEvent(ev);
}
}
}
}

View File

@@ -0,0 +1,45 @@
using System.Collections.Generic;
using Content.Server.NodeContainer.NodeGroups;
using JetBrains.Annotations;
using Robust.Shared.GameObjects;
namespace Content.Server.NodeContainer.EntitySystems
{
[UsedImplicitly]
public class NodeGroupSystem : EntitySystem
{
private readonly HashSet<INodeGroup> _dirtyNodeGroups = new();
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<NodeContainerComponent, SnapGridPositionChangedEvent>(OnSnapGridPositionChanged);
}
private void OnSnapGridPositionChanged(EntityUid uid, NodeContainerComponent component, SnapGridPositionChangedEvent args)
{
foreach (var node in component.Nodes.Values)
{
node.OnSnapGridMove();
}
}
public void AddDirtyNodeGroup(INodeGroup nodeGroup)
{
_dirtyNodeGroups.Add(nodeGroup);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
foreach (var group in _dirtyNodeGroups)
{
group.RemakeGroup();
}
_dirtyNodeGroups.Clear();
}
}
}

View File

@@ -0,0 +1,110 @@
#nullable enable
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Content.Server.NodeContainer.NodeGroups;
using Content.Server.NodeContainer.Nodes;
using Content.Shared.Examine;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Server.NodeContainer
{
/// <summary>
/// Creates and maintains a set of <see cref="Node"/>s.
/// </summary>
[RegisterComponent]
public class NodeContainerComponent : Component, IExamine
{
public override string Name => "NodeContainer";
[ViewVariables]
public IReadOnlyDictionary<string, Node> Nodes => _nodes;
[DataField("nodes")]
private readonly Dictionary<string, Node> _nodes = new();
[DataField("examinable")]
private bool _examinable = false;
public override void Initialize()
{
base.Initialize();
foreach (var node in _nodes.Values)
{
node.Initialize(Owner);
}
}
protected override void Startup()
{
base.Startup();
foreach (var node in _nodes.Values)
{
node.OnContainerStartup();
}
}
protected override void Shutdown()
{
base.Shutdown();
foreach (var node in _nodes.Values)
{
node.OnContainerShutdown();
}
}
public void AnchorUpdate()
{
foreach (var node in Nodes.Values)
{
node.AnchorUpdate();
}
}
public T GetNode<T>(string identifier) where T : Node
{
return (T)_nodes[identifier];
}
public bool TryGetNode<T>(string identifier, [NotNullWhen(true)] out T? node) where T : Node
{
if (_nodes.TryGetValue(identifier, out var n) && n is T t)
{
node = t;
return true;
}
node = null;
return false;
}
public void Examine(FormattedMessage message, bool inDetailsRange)
{
if (!_examinable || !inDetailsRange) return;
foreach (var node in Nodes.Values)
{
if (node == null) continue;
switch (node.NodeGroupID)
{
case NodeGroupID.HVPower:
message.AddMarkup(
Loc.GetString("It has a connector for [color=orange]HV cables[/color].\n"));
break;
case NodeGroupID.MVPower:
message.AddMarkup(
Loc.GetString("It has a connector for [color=yellow]MV cables[/color].\n"));
break;
case NodeGroupID.Apc:
message.AddMarkup(
Loc.GetString("It has a connector for [color=green]APC cables[/color].\n"));
break;
}
}
}
}
}

View File

@@ -0,0 +1,37 @@
#nullable enable
using System.Collections.Generic;
using System.Linq;
using Content.Server.NodeContainer.Nodes;
using Content.Server.Power.Components;
namespace Content.Server.NodeContainer.NodeGroups
{
public abstract class BaseNetConnectorNodeGroup<TNetConnector, TNetType> : BaseNodeGroup where TNetConnector : BaseNetConnectorComponent<TNetType>
{
private readonly Dictionary<Node, List<TNetConnector>> _netConnectorComponents = new();
protected override void OnAddNode(Node node)
{
var newNetConnectorComponents = node.Owner
.GetAllComponents<TNetConnector>()
.Where(powerComp => (NodeGroupID) powerComp.Voltage == node.NodeGroupID)
.ToList();
_netConnectorComponents[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,125 @@
#nullable enable
using System.Collections.Generic;
using Content.Server.NodeContainer.EntitySystems;
using Content.Server.NodeContainer.Nodes;
using Robust.Shared.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.ViewVariables;
namespace Content.Server.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
{
IReadOnlyList<Node> Nodes { get; }
void Initialize(Node sourceNode);
void AddNode(Node node);
void RemoveNode(Node node);
void CombineGroup(INodeGroup newGroup);
void RemakeGroup();
}
[NodeGroup(NodeGroupID.Default, NodeGroupID.WireNet)]
public class BaseNodeGroup : INodeGroup
{
[ViewVariables]
public IReadOnlyList<Node> Nodes => _nodes;
private readonly List<Node> _nodes = new();
[ViewVariables]
public int NodeCount => Nodes.Count;
/// <summary>
/// Debug variable to indicate that this NodeGroup should not be being used by anything.
/// </summary>
[ViewVariables]
public bool Removed { get; private set; } = false;
public static readonly INodeGroup NullGroup = new NullNodeGroup();
protected GridId GridId { get; private set;}
public virtual void Initialize(Node sourceNode)
{
GridId = sourceNode.Owner.Transform.GridID;
}
public void AddNode(Node node)
{
_nodes.Add(node);
OnAddNode(node);
}
public void RemoveNode(Node node)
{
_nodes.Remove(node);
OnRemoveNode(node);
EntitySystem.Get<NodeGroupSystem>().AddDirtyNodeGroup(this);
}
public void CombineGroup(INodeGroup newGroup)
{
if (newGroup.Nodes.Count < Nodes.Count)
{
newGroup.CombineGroup(this);
return;
}
OnGivingNodesForCombine(newGroup);
foreach (var node in Nodes)
{
node.NodeGroup = newGroup;
}
Removed = true;
}
/// <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>
public void RemakeGroup()
{
foreach (var node in Nodes)
{
node.ClearNodeGroup();
}
var newGroups = new List<INodeGroup>();
foreach (var node in Nodes)
{
if (node.TryAssignGroupIfNeeded())
{
node.SpreadGroup();
newGroups.Add(node.NodeGroup);
}
}
AfterRemake(newGroups);
Removed = true;
}
protected virtual void OnAddNode(Node node) { }
protected virtual void OnRemoveNode(Node node) { }
protected virtual void OnGivingNodesForCombine(INodeGroup newGroup) { }
protected virtual void AfterRemake(IEnumerable<INodeGroup> newGroups) { }
private class NullNodeGroup : INodeGroup
{
public IReadOnlyList<Node> Nodes => _nodes;
private readonly List<Node> _nodes = new();
public void Initialize(Node sourceNode) { }
public void AddNode(Node node) { }
public void CombineGroup(INodeGroup newGroup) { }
public void RemoveNode(Node node) { }
public void RemakeGroup() { }
}
}
}

View File

@@ -0,0 +1,102 @@
#nullable enable
using System.Collections.Generic;
using Content.Server.Atmos;
using Content.Server.GameObjects.EntitySystems;
using Content.Server.Interfaces;
using Content.Server.NodeContainer.Nodes;
using Robust.Shared.GameObjects;
using Robust.Shared.ViewVariables;
namespace Content.Server.NodeContainer.NodeGroups
{
public interface IPipeNet : IGasMixtureHolder
{
/// <summary>
/// Causes gas in the PipeNet to react.
/// </summary>
void Update();
}
[NodeGroup(NodeGroupID.Pipe)]
public class PipeNet : BaseNodeGroup, IPipeNet
{
[ViewVariables]
public GasMixture Air { get; set; } = new();
public static readonly IPipeNet NullNet = new NullPipeNet();
[ViewVariables]
private readonly List<PipeNode> _pipes = new();
[ViewVariables] private AtmosphereSystem? _atmosphereSystem;
[ViewVariables] private IGridAtmosphereComponent? GridAtmos => _atmosphereSystem?.GetGridAtmosphere(GridId);
public override void Initialize(Node sourceNode)
{
base.Initialize(sourceNode);
_atmosphereSystem = EntitySystem.Get<AtmosphereSystem>();
GridAtmos?.AddPipeNet(this);
}
public void Update()
{
Air.React(this);
}
protected override void OnAddNode(Node node)
{
if (node is not PipeNode pipeNode)
return;
_pipes.Add(pipeNode);
pipeNode.JoinPipeNet(this);
Air.Volume += pipeNode.Volume;
Air.Merge(pipeNode.LocalAir);
pipeNode.LocalAir.Clear();
}
protected override void OnRemoveNode(Node node)
{
RemoveFromGridAtmos();
if (node is not PipeNode pipeNode)
return;
var pipeAir = pipeNode.LocalAir;
pipeAir.Merge(Air);
pipeAir.Multiply(pipeNode.Volume / Air.Volume);
_pipes.Remove(pipeNode);
}
protected override void OnGivingNodesForCombine(INodeGroup newGroup)
{
if (newGroup is not IPipeNet newPipeNet)
return;
newPipeNet.Air.Merge(Air);
Air.Clear();
}
protected override void AfterRemake(IEnumerable<INodeGroup> newGroups)
{
foreach (var newGroup in newGroups)
{
if (newGroup is not IPipeNet newPipeNet)
continue;
newPipeNet.Air.Merge(Air);
var newPipeNetGas = newPipeNet.Air;
newPipeNetGas.Multiply(newPipeNetGas.Volume / Air.Volume);
}
RemoveFromGridAtmos();
}
private void RemoveFromGridAtmos()
{
GridAtmos?.RemovePipeNet(this);
}
private class NullPipeNet : IPipeNet
{
GasMixture IGasMixtureHolder.Air { get; set; } = new();
public void Update() { }
}
}
}

View File

@@ -0,0 +1,21 @@
#nullable enable
using System;
namespace Content.Server.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,70 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Reflection;
using Content.Server.NodeContainer.Nodes;
using Robust.Shared.IoC;
using Robust.Shared.Reflection;
namespace Content.Server.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(Node sourceNode);
}
public class NodeGroupFactory : INodeGroupFactory
{
[Dependency] private readonly IReflectionManager _reflectionManager = default!;
[Dependency] private readonly IDynamicTypeFactory _typeFactory = default!;
private readonly Dictionary<NodeGroupID, Type> _groupTypes = new();
public void Initialize()
{
var nodeGroupTypes = _reflectionManager.GetAllChildren<INodeGroup>();
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(Node sourceNode)
{
if (_groupTypes.TryGetValue(sourceNode.NodeGroupID, out var type))
{
var nodeGroup = _typeFactory.CreateInstance<INodeGroup>(type);
nodeGroup.Initialize(sourceNode);
return nodeGroup;
}
throw new ArgumentException($"{sourceNode.NodeGroupID} did not have an associated {nameof(INodeGroup)}.");
}
}
public enum NodeGroupID
{
Default,
HVPower,
MVPower,
Apc,
AMEngine,
Pipe,
WireNet
}
}

View File

@@ -0,0 +1,164 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Content.Server.Power.Components;
using Robust.Shared.IoC;
using Robust.Shared.ViewVariables;
namespace Content.Server.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);
void UpdateConsumerReceivedPower();
}
[NodeGroup(NodeGroupID.HVPower, NodeGroupID.MVPower)]
public class PowerNetNodeGroup : BaseNetConnectorNodeGroup<BasePowerNetComponent, IPowerNet>, IPowerNet
{
private static readonly Priority[] CachedPriorities = (Priority[]) Enum.GetValues(typeof(Priority));
[Dependency] private readonly IPowerNetManager _powerNetManager = default!;
[ViewVariables]
private readonly List<PowerSupplierComponent> _suppliers = new();
[ViewVariables]
private int _totalSupply = 0;
[ViewVariables]
private readonly Dictionary<Priority, List<PowerConsumerComponent>> _consumersByPriority = new();
[ViewVariables]
private readonly Dictionary<Priority, int> _drawByPriority = new();
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);
}
}
protected override void SetNetConnectorNet(BasePowerNetComponent netConnectorComponent)
{
netConnectorComponent.Net = this;
}
#region IPowerNet Methods
public void AddSupplier(PowerSupplierComponent supplier)
{
_suppliers.Add(supplier);
_totalSupply += supplier.SupplyRate;
_powerNetManager.AddDirtyPowerNet(this);
}
public void RemoveSupplier(PowerSupplierComponent supplier)
{
Debug.Assert(_suppliers.Contains(supplier));
_suppliers.Remove(supplier);
_totalSupply -= supplier.SupplyRate;
_powerNetManager.AddDirtyPowerNet(this);
}
public void UpdateSupplierSupply(PowerSupplierComponent supplier, int oldSupplyRate, int newSupplyRate)
{
Debug.Assert(_suppliers.Contains(supplier));
_totalSupply -= oldSupplyRate;
_totalSupply += newSupplyRate;
_powerNetManager.AddDirtyPowerNet(this);
}
public void AddConsumer(PowerConsumerComponent consumer)
{
_consumersByPriority[consumer.Priority].Add(consumer);
_drawByPriority[consumer.Priority] += consumer.DrawRate;
_powerNetManager.AddDirtyPowerNet(this);
}
public void RemoveConsumer(PowerConsumerComponent consumer)
{
Debug.Assert(_consumersByPriority[consumer.Priority].Contains(consumer));
consumer.ReceivedPower = 0;
_consumersByPriority[consumer.Priority].Remove(consumer);
_drawByPriority[consumer.Priority] -= consumer.DrawRate;
_powerNetManager.AddDirtyPowerNet(this);
}
public void UpdateConsumerDraw(PowerConsumerComponent consumer, int oldDrawRate, int newDrawRate)
{
Debug.Assert(_consumersByPriority[consumer.Priority].Contains(consumer));
_drawByPriority[consumer.Priority] -= oldDrawRate;
_drawByPriority[consumer.Priority] += newDrawRate;
_powerNetManager.AddDirtyPowerNet(this);
}
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;
_powerNetManager.AddDirtyPowerNet(this);
}
public void UpdateConsumerReceivedPower()
{
var remainingSupply = _totalSupply;
foreach (var priority in CachedPriorities)
{
var categoryPowerDemand = _drawByPriority[priority];
if (remainingSupply >= categoryPowerDemand) //can fully power all in category
{
remainingSupply -= categoryPowerDemand;
foreach (var consumer in _consumersByPriority[priority])
{
consumer.ReceivedPower = consumer.DrawRate;
}
}
else //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) { }
public void UpdateConsumerReceivedPower() { }
}
}
}

View File

@@ -0,0 +1,41 @@
#nullable enable
using System.Collections.Generic;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Serialization.Manager.Attributes;
namespace Content.Server.NodeContainer.Nodes
{
/// <summary>
/// A <see cref="Node"/> that can reach other <see cref="AdjacentNode"/>s that are directly adjacent to it.
/// </summary>
[DataDefinition]
public class AdjacentNode : Node
{
protected override IEnumerable<Node> GetReachableNodes()
{
if (!Owner.Transform.Anchored)
yield break;
var grid = IoCManager.Resolve<IMapManager>().GetGrid(Owner.Transform.GridID);
var coords = Owner.Transform.Coordinates;
foreach (var cell in grid.GetCardinalNeighborCells(coords))
{
foreach (var entity in grid.GetLocal(Owner.EntityManager.GetEntity(cell).Transform.Coordinates))
{
if (!Owner.EntityManager.GetEntity(entity).TryGetComponent<NodeContainerComponent>(out var container))
continue;
foreach (var node in container.Nodes.Values)
{
if (node != null && node != this)
{
yield return node;
}
}
}
}
}
}
}

View File

@@ -0,0 +1,16 @@
using Robust.Shared.GameObjects;
namespace Content.Server.NodeContainer.Nodes
{
/// <summary>
/// A <see cref="Node"/> that implements this will have its <see cref="RotateEvent(RotateEvent)"/> called when its
/// <see cref="NodeContainerComponent"/> is rotated.
/// </summary>
public interface IRotatableNode
{
/// <summary>
/// Rotates this <see cref="Node"/>.
/// </summary>
void RotateEvent(RotateEvent ev);
}
}

View File

@@ -0,0 +1,182 @@
#nullable enable
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Content.Server.NodeContainer.NodeGroups;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Physics;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.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>
[ImplicitDataDefinitionForInheritors]
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]
[DataField("nodeGroupID")]
public NodeGroupID NodeGroupID { get; private set; } = NodeGroupID.Default;
[ViewVariables]
public INodeGroup NodeGroup { get => _nodeGroup; set => SetNodeGroup(value); }
private INodeGroup _nodeGroup = BaseNodeGroup.NullGroup;
[ViewVariables]
public IEntity Owner { get; private set; } = default!;
[ViewVariables]
private bool _needsGroup = true;
/// <summary>
/// If this node should be considered for connection by other nodes.
/// </summary>
public bool Connectable => !_deleting && Anchored;
private bool Anchored => !Owner.TryGetComponent<IPhysBody>(out var physics) || physics.BodyType == BodyType.Static;
/// <summary>
/// Prevents a node from being used by other nodes while midway through removal.
/// </summary>
private bool _deleting;
public virtual void Initialize(IEntity owner)
{
Owner = owner;
}
public virtual void OnContainerStartup()
{
TryAssignGroupIfNeeded();
CombineGroupWithReachable();
}
public void AnchorUpdate()
{
if (Anchored)
{
TryAssignGroupIfNeeded();
CombineGroupWithReachable();
}
else
{
RemoveSelfFromGroup();
}
}
public virtual void OnSnapGridMove()
{
}
public virtual void OnContainerShutdown()
{
_deleting = true;
NodeGroup.RemoveNode(this);
}
public bool TryAssignGroupIfNeeded()
{
if (!_needsGroup || !Connectable)
{
return false;
}
NodeGroup = GetReachableCompatibleGroups().FirstOrDefault() ?? MakeNewGroup();
return true;
}
public void SpreadGroup()
{
Debug.Assert(!_needsGroup);
foreach (var node in GetReachableCompatibleNodes())
{
if (node._needsGroup)
{
node.NodeGroup = NodeGroup;
node.SpreadGroup();
}
}
}
public void ClearNodeGroup()
{
_nodeGroup = BaseNodeGroup.NullGroup;
_needsGroup = true;
}
protected void RefreshNodeGroup()
{
RemoveSelfFromGroup();
TryAssignGroupIfNeeded();
CombineGroupWithReachable();
}
/// <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()
{
foreach (var node in GetReachableNodes())
{
if (node.NodeGroupID == NodeGroupID && node.Connectable)
{
yield return node;
}
}
}
private IEnumerable<INodeGroup> GetReachableCompatibleGroups()
{
foreach (var node in GetReachableCompatibleNodes())
{
if (!node._needsGroup)
{
var group = node.NodeGroup;
if (group != NodeGroup)
{
yield return group;
}
}
}
}
private void CombineGroupWithReachable()
{
if (_needsGroup || !Connectable)
return;
foreach (var group in GetReachableCompatibleGroups())
{
NodeGroup.CombineGroup(group);
}
}
private void SetNodeGroup(INodeGroup newGroup)
{
_nodeGroup = newGroup;
NodeGroup.AddNode(this);
_needsGroup = false;
}
private INodeGroup MakeNewGroup()
{
return IoCManager.Resolve<INodeGroupFactory>().MakeNodeGroup(this);
}
private void RemoveSelfFromGroup()
{
NodeGroup.RemoveNode(this);
ClearNodeGroup();
}
}
}

View File

@@ -0,0 +1,291 @@
#nullable enable
using System.Collections.Generic;
using Content.Server.Atmos;
using Content.Server.Interfaces;
using Content.Server.NodeContainer.NodeGroups;
using Content.Shared.GameObjects.Components.Atmos;
using Robust.Server.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.NodeContainer.Nodes
{
/// <summary>
/// Connects with other <see cref="PipeNode"/>s whose <see cref="PipeDirection"/>
/// correctly correspond.
/// </summary>
[DataDefinition]
public class PipeNode : Node, IGasMixtureHolder, IRotatableNode
{
/// <summary>
/// Modifies the <see cref="PipeDirection"/> of this pipe, and ensures the sprite is correctly rotated.
/// This is a property for the sake of calling the method via ViewVariables.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public PipeDirection SetPipeDirectionAndSprite { get => PipeDirection; set => AdjustPipeDirectionAndSprite(value); }
/// <summary>
/// The directions in which this pipe can connect to other pipes around it.
/// Used to check if this pipe can connect to another pipe in a given direction.
/// </summary>
[ViewVariables]
[DataField("pipeDirection")]
public PipeDirection PipeDirection { get; private set; }
/// <summary>
/// The directions in which this node is connected to other nodes.
/// Used by <see cref="PipeVisualState"/>.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
private PipeDirection ConnectedDirections { get => _connectedDirections; set { _connectedDirections = value; UpdateAppearance(); } }
private PipeDirection _connectedDirections;
/// <summary>
/// The <see cref="IPipeNet"/> this pipe is a part of. Set to <see cref="PipeNet.NullNet"/> when not in an <see cref="IPipeNet"/>.
/// </summary>
[ViewVariables]
private IPipeNet _pipeNet = PipeNet.NullNet;
/// <summary>
/// If <see cref="_pipeNet"/> is set to <see cref="PipeNet.NullNet"/>.
/// When true, this pipe may be storing gas in <see cref="LocalAir"/>.
/// </summary>
[ViewVariables]
private bool _needsPipeNet = true;
/// <summary>
/// Prevents rotation events from re-calculating the <see cref="IPipeNet"/>.
/// Used while rotating the sprite to the correct orientation while not affecting the pipe.
/// </summary>
private bool IgnoreRotation { get; set; }
/// <summary>
/// The gases in this pipe.
/// </summary>
[ViewVariables]
public GasMixture Air
{
get => _needsPipeNet ? LocalAir : _pipeNet.Air;
set
{
if (_needsPipeNet)
LocalAir = value;
else
_pipeNet.Air = value;
}
}
/// <summary>
/// Stores gas in this pipe when disconnected from a <see cref="IPipeNet"/>.
/// Only for usage by <see cref="IPipeNet"/>s.
/// </summary>
[ViewVariables]
[DataField("gasMixture")]
public GasMixture LocalAir { get; set; } = new(DefaultVolume);
[ViewVariables]
public float Volume => LocalAir.Volume;
private AppearanceComponent? _appearance;
private const float DefaultVolume = 1;
public override void Initialize(IEntity owner)
{
base.Initialize(owner);
Owner.TryGetComponent(out _appearance);
}
public override void OnContainerStartup()
{
base.OnContainerStartup();
OnConnectedDirectionsNeedsUpdating();
UpdateAppearance();
}
public override void OnContainerShutdown()
{
base.OnContainerShutdown();
UpdateAdjacentConnectedDirections();
}
public void JoinPipeNet(IPipeNet pipeNet)
{
_pipeNet = pipeNet;
_needsPipeNet = false;
}
public void ClearPipeNet()
{
_pipeNet = PipeNet.NullNet;
_needsPipeNet = true;
}
/// <summary>
/// Rotates the <see cref="PipeDirection"/> when the entity is rotated, and re-calculates the <see cref="IPipeNet"/>.
/// </summary>
void IRotatableNode.RotateEvent(RotateEvent ev)
{
if (IgnoreRotation)
return;
var diff = ev.NewRotation - ev.OldRotation;
PipeDirection = PipeDirection.RotatePipeDirection(diff);
RefreshNodeGroup();
OnConnectedDirectionsNeedsUpdating();
UpdateAppearance();
}
protected override IEnumerable<Node> GetReachableNodes()
{
for (var i = 0; i < PipeDirectionHelpers.PipeDirections; i++)
{
var pipeDir = (PipeDirection) (1 << i);
if (!PipeDirection.HasDirection(pipeDir))
continue;
foreach (var pipe in LinkableNodesInDirection(pipeDir))
yield return pipe;
}
}
/// <summary>
/// Gets the pipes that can connect to us from entities on the tile adjacent in a direction.
/// </summary>
private IEnumerable<PipeNode> LinkableNodesInDirection(PipeDirection pipeDir)
{
foreach (var pipe in PipesInDirection(pipeDir))
{
if (pipe.PipeDirection.HasDirection(pipeDir.GetOpposite()))
yield return pipe;
}
}
/// <summary>
/// Gets the pipes from entities on the tile adjacent in a direction.
/// </summary>
private IEnumerable<PipeNode> PipesInDirection(PipeDirection pipeDir)
{
if (!Owner.Transform.Anchored)
yield break;
var grid = IoCManager.Resolve<IMapManager>().GetGrid(Owner.Transform.GridID);
var position = Owner.Transform.Coordinates;
foreach (var entity in grid.GetInDir(position, pipeDir.ToDirection()))
{
if (!Owner.EntityManager.ComponentManager.TryGetComponent<NodeContainerComponent>(entity, out var container))
continue;
foreach (var node in container.Nodes.Values)
{
if (node is PipeNode pipe)
yield return pipe;
}
}
}
/// <summary>
/// Updates the <see cref="ConnectedDirections"/> of this and all sorrounding pipes.
/// </summary>
private void OnConnectedDirectionsNeedsUpdating()
{
UpdateConnectedDirections();
UpdateAdjacentConnectedDirections();
}
/// <summary>
/// Checks what directions there are connectable pipes in, to update <see cref="ConnectedDirections"/>.
/// </summary>
private void UpdateConnectedDirections()
{
ConnectedDirections = PipeDirection.None;
for (var i = 0; i < PipeDirectionHelpers.PipeDirections; i++)
{
var pipeDir = (PipeDirection) (1 << i);
if (!PipeDirection.HasDirection(pipeDir))
continue;
foreach (var pipe in LinkableNodesInDirection(pipeDir))
{
if (pipe.Connectable && pipe.NodeGroupID == NodeGroupID)
{
ConnectedDirections |= pipeDir;
break;
}
}
}
}
/// <summary>
/// Calls <see cref="UpdateConnectedDirections"/> on all adjacent pipes,
/// to update their <see cref="ConnectedDirections"/> when this pipe is changed.
/// </summary>
private void UpdateAdjacentConnectedDirections()
{
for (var i = 0; i < PipeDirectionHelpers.PipeDirections; i++)
{
var pipeDir = (PipeDirection) (1 << i);
foreach (var pipe in LinkableNodesInDirection(pipeDir))
pipe.UpdateConnectedDirections();
}
}
/// <summary>
/// Updates the <see cref="AppearanceComponent"/>.
/// Gets the combined <see cref="ConnectedDirections"/> of every pipe on this entity, so the visualizer on this entity can draw the pipe connections.
/// </summary>
private void UpdateAppearance()
{
var netConnectedDirections = PipeDirection.None;
if (Owner.TryGetComponent<NodeContainerComponent>(out var container))
{
foreach (var node in container.Nodes.Values)
{
if (node is PipeNode pipe)
{
netConnectedDirections |= pipe.ConnectedDirections;
}
}
}
_appearance?.SetData(PipeVisuals.VisualState, new PipeVisualState(PipeDirection.PipeDirectionToPipeShape(), netConnectedDirections));
}
/// <summary>
/// Changes the directions of this pipe while ensuring the sprite is correctly rotated.
/// </summary>
public void AdjustPipeDirectionAndSprite(PipeDirection newDir)
{
IgnoreRotation = true;
var baseDir = newDir.PipeDirectionToPipeShape().ToBaseDirection();
var newAngle = Angle.FromDegrees(0);
for (var i = 0; i < PipeDirectionHelpers.PipeDirections; i++)
{
var pipeDir = (PipeDirection) (1 << i);
var angle = pipeDir.ToAngle();
if (baseDir.RotatePipeDirection(angle) == newDir) //finds what angle the entity needs to be rotated from the base to be set to the correct direction
{
newAngle = angle;
break;
}
}
Owner.Transform.LocalRotation = newAngle; //rotate the entity so the sprite's new state will be of the correct direction
PipeDirection = newDir;
RefreshNodeGroup();
OnConnectedDirectionsNeedsUpdating();
UpdateAppearance();
IgnoreRotation = false;
}
}
}