Files
Delta-v/Content.Shared/DeviceLinking/SharedDeviceLinkSystem.cs
T
29e55b9464 Upstream Merge (June / July) attempt 2 electric boogaloo (#4607)
* Fix the sensor monitoring console forcing a GC every 3 seconds (#38146)

* Optimize sensor monitoring window graph drawing

* Add shared static Vector2 pool for all GraphView instances

* Address requested changes

* remove lock

* Update submodule to 264.0.0 (#38629)

* Toy/Plushie Inhands and Wearables (#38514)

* Fixed dependency injection and some other issues in a few places.

* More issue fixes

* patchfor broken NetworkConfiguratorLinkMenu (#38632)

fix

* Fix solutions flickering when transferring contents (#34838)

* Use Solution clones when applying SolutionComponent states

* Revert "Use Solution clones when applying SolutionComponent states"

This reverts commit 013fd111cf92b22562e00f98a7aaa49bc4b4ed62.

* Make Solution implement ICloneable and rename Clone method.

* Copy CanReact value when cloning a Solution

* Convert to IRobustCloneable

* Fix typos in guidebook: Buisness → Business (#38636)

* Fix typo in `MinorAntagonists.xml`

Buisness → Business

* Fix typo in `YourFirstCharacter.xml`

Buisness → Business

* Various Headphones Fixes and Tweaks (#38479)

* sprites, wearables

* neck

* icon-on sprite

* Cleanup prototype instantiation in `DamageTest` (#38639)

Cleanup prototype instantiation in DamageTest

* Cleanup prototype instantiation in `ExplosionSystem` (#38642)

Cleanup prototype instantiation in ExplosionSystem

* AddBodyPartCommand localization. (#38612)

commit

* fix ItemSlotsSystem debug assert (#38655)

* Allow the Command & Super door remotes to use the access of their user. (Re-creation of PR due to changes to game balance) (#35536)

* Added directional beacons (#38284)

* Added directional beacons

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

* Fixed names

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

---------

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

* Power stat and nuke codes commands get some LEC love. (#38585)

* commit

* requested changes.

* Dsay Dirty and Follow commands converted to LEC and localized. (#38666)

* commit

* whoopwhoopwhoop

* Retro laser sprite fix (#38676)

* Fixed everything except the icon

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

* fixed icon

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

---------

Signed-off-by: Nox38 <nebulousnox38@gmail.com>

* fix water coolers (#38681)

* Monochromacy typo fix (#38686)

* fixes the typo

* Fixed cloning looking for the trait, not the component, RE https://github.com/space-wizards/space-station-14/pull/38686#issuecomment-3025093504

* Apply suggestions from code review

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Validate `CloningSettingsPrototype`s (#38688)

* Validate CloningSettingsPrototypes

* Update Content.IntegrationTests/Tests/Cloning/CloningSettingsPrototypeTest.cs

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Check EventComponents too

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Add test of objective-related console commands (#36400)

* Add test of objective add/list/remove commands

* Not sure why we're validating test prototypes, but sure

* We don't need a map

* Improvements and fixups for New Status Effect API (#38660)

* Predict healing and bloodstream (#38690)

* initial commit

* reapply 38126

* fix rootable

* someone missed an important minus sign here

* try this

* fix

* fix

* reenable crit hits

* cleanup

* fix status time dirtying

* fix

* camelCase

* Healing and bloodstream prediction fixes.

* Resolving Wizard casting recall on nuke disk making it impossible to disarm (#38661)

* Resolving Wizard Recall on Nuke disk making it impossible to disarm
- Adding a DisarmBomb case to nuke status update loop
- Changing a few methods and parameters to properly follow formatting standards
- Updating some names to follow camelCase

* Updating missed tag

* Reverting DataField change

Should prevent this preventative bugfix being a breaking change.

* Switch HSV to the default colorspace for character customization (#38434)

* Made HSV default for character editor

* Adds/fixes comments to HSV defaulting

* Added dropbox fix, potentially cursed

* Revert "Added dropbox fix, potentially cursed"

This reverts commit a709883366fbee813e839742125e70844672af29.

---------

Co-authored-by: TrixxedHeart <46364955+TrixxedBit@users.noreply.github.com>

* Fix: Don't deploy foldables when clicking on items inside containers (#38709)

* Fix

* Apply suggestions from code review

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Pressure Relief Valve (#36708)

* initial system (this math is probably WRONG)

* General code cleanup and OnExamined support
(holy moly this code sucks)

* UICode and related events foundation
TODO:
- Actually write the XAML UI and the underlying system
- Un-shitcode the entire thing
- Actually test everything...

* Working UI code
TODO: Make predicted, as this certainly isn't predicted. Even though I said it was. It isn't.

* Remove one TODO for unshitcoding the examine code

* Add reminder
yea

* Make predicted (defenitely isn't)
(also defenitely isn't a copypaste from pressure pump code)

* It's predicted!
TODO:
- Give it snazzy predicted visuals!
- Have a different field for pressure entry, lest it gets bulldozed every UI update.

* Improve gas pressure relief valve UI
TODO: Reminder to reduce amount of dirties using deltafields

* Implement DirtyField prediction

* Entity<T> cleanup
A lot of Entity<T> conversions and lukewarm cleanup.

Also got caught copy pasting code in 4K UHD but it's not like you couldn't tell.

* More cleanup and comments

* Remove TODO comment on bulldozing window title

* """refactoring"""
- Move appearance out of shared and finally fix it. Pointless to predict appearance in this instance.
- More Entity<T> conversions because I like them.
- Move UI creation handling over entirely to the ActivatableUI system.
- Fix a hardcoded locale string (why????).

* Add visuals

* Revert debugging variable replacememt
yea

* Revert skissue

* Remove unused using directives and remove TODO

* Localize, cleanup, document

* Fix adminlogging discrepancy

* Add ability to construct, add guidebook entry

* Clear up comment

* Add guidebook tooltip to valve

* Convert GasPressureReliefValveBoundUserInterface declaration into primary constructor

* Adds more input handling and adds autofill on open

* Un-deepfry input validator shitcode
Genuinely what was I smoking

* improve visuals logic

* Refactor again
- Update math to the correct implementation
- Moved code that could be re-used in the future into a helper method under AtmosphereSystem.Gases.cs

* I'm sorry but I hate warnings

* Remove unused using directive in AtmosphereSystem.Gases.cs

* Review and cleanup

* Lukewarm UI glossup

* Maintainer for the upstream project btw

* Remove redundant state sets and messy logic

* Unduplicate valve updater code

* Redo UI (im sorry Slarti)

* run tests

* Test refactored UI messaging

* Second round of UI improvements
- God please find a way to improve this system. Feels bad.

* Update loop implementation

* Further predict UI

* Clear up SetToCurrentThreshold

* cleanup

* Update to master + pipe layers and bug fixes
want to run tests

* fixes

* Deploy rename pipebomb

* Documentation and requested changes

* Rename the method that wiggled away

* Undo rounding changes

* Fix comment

* Rename and cleanup

* Apply suggestions from code review

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Fix TextLinkTag (#32203)

* Adjust uplink buy button to be under item icon (#38596)

* Adjusted uplink buy button to be under item icon

* Put the discount subtext under the icon

* Indent fixes, added margin

---------

Co-authored-by: TrixxedHeart <46364955+TrixxedBit@users.noreply.github.com>

* Scurrets - Audio Improvements (#38482)

* Scurret audio tuning

* Add new sfx

* Update sneezing sfx

* YAML support

* Rename a folder

* make telesci wreck easier (#37569)

rel

* Validate `ShaderPrototype` IDs (#38728)

* Convert all shader prototype string literals to protoids in overlays

* Convert more shader prototype literal strings to protoids

* Convert ValidatePrototypeId to ProtoId

* Later

* [BUGFIX] Fixed revenant malfunction ability not working properly only MediBots and Stasis bed (#38664)

* fixed

* clean up

* orks fix smart

* review fix 1

* more requested changes

* less cursed

* more descriptive description

* better wording

* Tiny Tiny Cleanup of the EyeClosingSystem. (#38734)

Update EyeClosingSystem.cs

* Fix human skin tone distribution (#38701)

* fix: Use PredictedQueueDel for gib spell (#38729)

* fix: don't default to uncharged sprite state for cells (#38730)

* Fix Hristov description - remove inaccurate technical specs (#38746)

- Removes inaccurate 'armor piercing 14.5mm shells' reference
- Replaces it with a more funny description, matching the style of the other snipers and guns
- Keeps ammunition type '.60 anti-materiel ammo' specification
- Fixes issue #38590

Co-authored-by: Arthur Fiorese de Andrade <aandrade@cmcxs.gov.br>

* feat: allow mopping evaporating puddles (#38743)

* Validate remaining `ProtoId` strings (#38747)

Validate remaining ProtoId strings

* Validate `ProtoId`s in tests (#38745)

* Convert string literals to protoids in Content.Tests

* Convert string literals to protoids or consts in Content.IntegrationTests

* Fix linter failures
Tricksy static using misled me

* Cleanup warning in StomachSystem (#38748)

you did not see this

* Vox scars (#38592)

* Added vox scars n'stuff, renamed vox_tattoos.ftl to just vox.ftl

* Revert "Added vox scars n'stuff, renamed vox_tattoos.ftl to just vox.ftl"

This reverts commit c73da55ba3b39ddf93b493aecd85604c54dd8a15.

* locale key fix

* Changed top surgery scar names to be more generalized

* Adjusted face scars

* Formatting fixes

---------

Co-authored-by: TrixxedHeart <46364955+TrixxedBit@users.noreply.github.com>

* UnlockNode command to LEC. (#38751)

* commit

* Update UnlockNodeCommand.cs

* commit

* move command locale to its own file.

* Update Content.Server/Xenoarchaeology/Artifact/UnlockNodeCommand.cs

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Typofixes for figurine dialogue (#38737)

* Typofixes for figurine dialogue

* Forgot two

* Janitor Tool: Wire Brush (#38667)

* Wow! It's -brush-

* spacing.

* Update Resources/Prototypes/Entities/Objects/Specific/Janitorial/janitor.yml

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Update Resources/Prototypes/Entities/Objects/Specific/Janitorial/janitor.yml

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* fixed changes

---------

Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>

* Minor escape menu UX improvements (#38650)

* fix: spellbooks can have infinite charges (#38376)

* fix: spellbooks can have infinite charges

* refactor: indicate infinite spellbook charges with null

Not sure if I like this much better...
2025-11-06 18:22:39 +00:00

594 lines
22 KiB
C#

using System.Linq;
using Content.Shared.Administration.Logs;
using Content.Shared.Database;
using Content.Shared.DeviceLinking.Events;
using Content.Shared.DeviceNetwork;
using Content.Shared.Popups;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
using Robust.Shared.Utility;
namespace Content.Shared.DeviceLinking;
public abstract class SharedDeviceLinkSystem : EntitySystem
{
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly ISharedAdminLogManager _adminLogger = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
public const string InvokedPort = "link_port";
/// <inheritdoc/>
public override void Initialize()
{
SubscribeLocalEvent<DeviceLinkSourceComponent, ComponentStartup>(OnSourceStartup);
SubscribeLocalEvent<DeviceLinkSourceComponent, ComponentRemove>(OnSourceRemoved);
SubscribeLocalEvent<DeviceLinkSinkComponent, ComponentRemove>(OnSinkRemoved);
}
#region Link Validation
/// <summary>
/// Removes invalid links where the saved sink doesn't exist/have a sink component for example
/// </summary>
private void OnSourceStartup(Entity<DeviceLinkSourceComponent> source, ref ComponentStartup args)
{
List<EntityUid> invalidSinks = new();
List<(string, string)> invalidLinks = new();
foreach (var (sink, links) in source.Comp.LinkedPorts)
{
if (!TryComp(sink, out DeviceLinkSinkComponent? sinkComponent))
{
invalidSinks.Add(sink);
continue;
}
foreach (var link in links)
{
if (sinkComponent.Ports.Contains(link.Sink) && source.Comp.Ports.Contains(link.Source))
source.Comp.Outputs.GetOrNew(link.Source).Add(sink);
else
invalidLinks.Add(link);
}
foreach (var link in invalidLinks)
{
Log.Warning($"Device source {ToPrettyString(source)} contains invalid links to entity {ToPrettyString(sink)}: {link.Item1}->{link.Item2}");
links.Remove(link);
}
if (links.Count == 0)
{
invalidSinks.Add(sink);
continue;
}
invalidLinks.Clear();
sinkComponent.LinkedSources.Add(source.Owner);
}
foreach (var sink in invalidSinks)
{
source.Comp.LinkedPorts.Remove(sink);
Log.Warning($"Device source {ToPrettyString(source)} contains invalid sink: {ToPrettyString(sink)}");
}
}
#endregion
/// <summary>
/// Ensures that its links get deleted when a source gets removed
/// </summary>
private void OnSourceRemoved(Entity<DeviceLinkSourceComponent> source, ref ComponentRemove args)
{
var query = GetEntityQuery<DeviceLinkSinkComponent>();
foreach (var sinkUid in source.Comp.LinkedPorts.Keys)
{
if (query.TryGetComponent(sinkUid, out var sink))
RemoveSinkFromSourceInternal(source, sinkUid, source, sink);
else
Log.Error($"Device source {ToPrettyString(source)} links to invalid entity: {ToPrettyString(sinkUid)}");
}
}
/// <summary>
/// Ensures that its links get deleted when a sink gets removed
/// </summary>
private void OnSinkRemoved(Entity<DeviceLinkSinkComponent> sink, ref ComponentRemove args)
{
foreach (var sourceUid in sink.Comp.LinkedSources)
{
if (TryComp(sourceUid, out DeviceLinkSourceComponent? source))
RemoveSinkFromSourceInternal(sourceUid, sink, source, sink);
else
Log.Error($"Device sink {ToPrettyString(sink)} source list contains invalid entity: {ToPrettyString(sourceUid)}");
}
}
#region Ports
/// <summary>
/// Convenience function to add several ports to an entity
/// </summary>
public void EnsureSourcePorts(EntityUid uid, params ProtoId<SourcePortPrototype>[] ports)
{
if (ports.Length == 0)
return;
var comp = EnsureComp<DeviceLinkSourceComponent>(uid);
foreach (var port in ports)
{
if (!_prototypeManager.HasIndex(port))
Log.Error($"Attempted to add invalid port {port} to {ToPrettyString(uid)}");
else
comp.Ports.Add(port);
}
}
/// <summary>
/// Convenience function to add several ports to an entity.
/// </summary>
public void EnsureSinkPorts(EntityUid uid, params ProtoId<SinkPortPrototype>[] ports)
{
if (ports.Length == 0)
return;
var comp = EnsureComp<DeviceLinkSinkComponent>(uid);
foreach (var port in ports)
{
if (!_prototypeManager.HasIndex(port))
Log.Error($"Attempted to add invalid port {port} to {ToPrettyString(uid)}");
else
comp.Ports.Add(port);
}
}
public ProtoId<SourcePortPrototype>[] GetSourcePortIds(Entity<DeviceLinkSourceComponent> source)
{
return source.Comp.Ports.ToArray();
}
/// <summary>
/// Retrieves the available ports from a source
/// </summary>
/// <returns>A list of source port prototypes</returns>
public List<SourcePortPrototype> GetSourcePorts(EntityUid sourceUid, DeviceLinkSourceComponent? sourceComponent = null)
{
if (!Resolve(sourceUid, ref sourceComponent))
return new List<SourcePortPrototype>();
var sourcePorts = new List<SourcePortPrototype>();
foreach (var port in sourceComponent.Ports)
{
sourcePorts.Add(_prototypeManager.Index(port));
}
return sourcePorts;
}
public ProtoId<SinkPortPrototype>[] GetSinkPortIds(Entity<DeviceLinkSinkComponent> source)
{
return source.Comp.Ports.ToArray();
}
/// <summary>
/// Retrieves the available ports from a sink
/// </summary>
/// <returns>A list of sink port prototypes</returns>
public List<SinkPortPrototype> GetSinkPorts(EntityUid sinkUid, DeviceLinkSinkComponent? sinkComponent = null)
{
if (!Resolve(sinkUid, ref sinkComponent))
return new List<SinkPortPrototype>();
var sinkPorts = new List<SinkPortPrototype>();
foreach (var port in sinkComponent.Ports)
{
sinkPorts.Add(_prototypeManager.Index(port));
}
return sinkPorts;
}
/// <summary>
/// Convenience function to retrieve the name of a port prototype
/// </summary>
public string PortName<TPort>(string port) where TPort : DevicePortPrototype, IPrototype
{
if (!_prototypeManager.TryIndex<TPort>(port, out var proto))
return port;
return Loc.GetString(proto.Name);
}
/// <summary>
/// Goobstation - Removes a port from a source.
/// </summary>
public void RemoveSourcePort(EntityUid uid, ProtoId<SourcePortPrototype> port)
{
if (!TryComp<DeviceLinkSourceComponent>(uid, out var comp))
return;
comp.Ports.Remove(port);
if (comp.Ports.Count == 0)
RemCompDeferred<DeviceLinkSourceComponent>(uid);
}
/// <summary>
/// Goobstation - Removes a port from a sink.
/// </summary>
public void RemoveSinkPort(EntityUid uid, ProtoId<SinkPortPrototype> port)
{
if (!TryComp<DeviceLinkSinkComponent>(uid, out var comp))
return;
comp.Ports.Remove(port);
if (comp.Ports.Count == 0)
RemCompDeferred<DeviceLinkSinkComponent>(uid);
}
#endregion
#region Links
/// <summary>
/// Returns the links of a source
/// </summary>
/// <returns>A list of sink and source port ids that are linked together</returns>
public HashSet<(ProtoId<SourcePortPrototype> source, ProtoId<SinkPortPrototype> sink)> GetLinks(EntityUid sourceUid, EntityUid sinkUid, DeviceLinkSourceComponent? sourceComponent = null)
{
if (!Resolve(sourceUid, ref sourceComponent) || !sourceComponent.LinkedPorts.TryGetValue(sinkUid, out var links))
return new HashSet<(ProtoId<SourcePortPrototype>, ProtoId<SinkPortPrototype>)>();
return links;
}
/// <summary>
/// Returns the default links for the given list of source port prototypes
/// </summary>
/// <param name="sources">The list of source port prototypes to get the default links for</param>
/// <returns>A list of sink and source port ids</returns>
public List<(string source, string sink)> GetDefaults(List<SourcePortPrototype> sources)
{
var defaults = new List<(string, string)>();
foreach (var source in sources)
{
if (source.DefaultLinks == null)
return new List<(string, string)>();
foreach (var defaultLink in source.DefaultLinks)
{
defaults.Add((source.ID, defaultLink));
}
}
return defaults;
}
/// <summary>
/// Links the given source and sink by their default links
/// </summary>
/// <param name="userId">Optinal user uid for displaying popups</param>
/// <param name="sourceUid">The source uid</param>
/// <param name="sinkUid">The sink uid</param>
/// <param name="sourceComponent"></param>
/// <param name="sinkComponent"></param>
public void LinkDefaults(
EntityUid? userId,
EntityUid sourceUid,
EntityUid sinkUid,
DeviceLinkSourceComponent? sourceComponent = null,
DeviceLinkSinkComponent? sinkComponent = null)
{
if (!Resolve(sourceUid, ref sourceComponent) || !Resolve(sinkUid, ref sinkComponent))
return;
if (userId != null)
_adminLogger.Add(LogType.DeviceLinking, LogImpact.Low, $"{ToPrettyString(userId.Value):actor} is linking defaults between {ToPrettyString(sourceUid):source} and {ToPrettyString(sinkUid):sink}");
else
_adminLogger.Add(LogType.DeviceLinking, LogImpact.Low, $"linking defaults between {ToPrettyString(sourceUid):source} and {ToPrettyString(sinkUid):sink}");
var sourcePorts = GetSourcePorts(sourceUid, sourceComponent);
var defaults = GetDefaults(sourcePorts);
SaveLinks(userId, sourceUid, sinkUid, defaults, sourceComponent, sinkComponent);
if (userId != null)
_popupSystem.PopupCursor(Loc.GetString("signal-linking-verb-success", ("machine", sourceUid)), userId.Value);
}
/// <summary>
/// Saves multiple links between a source and a sink device.
/// Ignores links where either the source or sink port aren't present
/// </summary>
/// <param name="userId">Optinal user uid for displaying popups</param>
/// <param name="sourceUid">The source uid</param>
/// <param name="sinkUid">The sink uid</param>
/// <param name="links">List of source and sink ids to link</param>
/// <param name="sourceComponent"></param>
/// <param name="sinkComponent"></param>
public void SaveLinks(
EntityUid? userId,
EntityUid sourceUid,
EntityUid sinkUid,
List<(string source, string sink)> links,
DeviceLinkSourceComponent? sourceComponent = null,
DeviceLinkSinkComponent? sinkComponent = null)
{
if (!Resolve(sourceUid, ref sourceComponent) || !Resolve(sinkUid, ref sinkComponent))
return;
if (!InRange(sourceUid, sinkUid, sourceComponent.Range))
{
if (userId != null)
_popupSystem.PopupCursor(Loc.GetString("signal-linker-component-out-of-range"), userId.Value);
return;
}
RemoveSinkFromSource(sourceUid, sinkUid, sourceComponent);
foreach (var (source, sink) in links)
{
DebugTools.Assert(_prototypeManager.HasIndex<SourcePortPrototype>(source));
DebugTools.Assert(_prototypeManager.HasIndex<SinkPortPrototype>(sink));
if (!sourceComponent.Ports.Contains(source) || !sinkComponent.Ports.Contains(sink))
continue;
if (!CanLink(userId, sourceUid, sinkUid, source, sink, false, sourceComponent))
continue;
sourceComponent.Outputs.GetOrNew(source).Add(sinkUid);
sourceComponent.LinkedPorts.GetOrNew(sinkUid).Add((source, sink));
SendNewLinkEvent(userId, sourceUid, source, sinkUid, sink);
}
if (links.Count > 0)
sinkComponent.LinkedSources.Add(sourceUid);
}
/// <summary>
/// Removes every link from the given sink
/// </summary>
public void RemoveAllFromSink(EntityUid sinkUid, DeviceLinkSinkComponent? sinkComponent = null)
{
if (!Resolve(sinkUid, ref sinkComponent))
return;
foreach (var sourceUid in sinkComponent.LinkedSources)
{
RemoveSinkFromSource(sourceUid, sinkUid, null, sinkComponent);
}
}
/// <summary>
/// Removes all links between a source and a sink
/// </summary>
public void RemoveSinkFromSource(
EntityUid sourceUid,
EntityUid sinkUid,
DeviceLinkSourceComponent? sourceComponent = null,
DeviceLinkSinkComponent? sinkComponent = null)
{
if (Resolve(sourceUid, ref sourceComponent, false) && Resolve(sinkUid, ref sinkComponent, false))
{
RemoveSinkFromSourceInternal(sourceUid, sinkUid, sourceComponent, sinkComponent);
return;
}
if (sourceComponent == null && sinkComponent == null)
{
// Both were deleted?
return;
}
if (sourceComponent == null)
{
Log.Error($"Attempted to remove link between {ToPrettyString(sourceUid)} and {ToPrettyString(sinkUid)}, but the source component was missing.");
sinkComponent!.LinkedSources.Remove(sourceUid);
}
else
{
Log.Error($"Attempted to remove link between {ToPrettyString(sourceUid)} and {ToPrettyString(sinkUid)}, but the sink component was missing.");
sourceComponent.LinkedPorts.Remove(sinkUid);
}
}
private void RemoveSinkFromSourceInternal(
EntityUid sourceUid,
EntityUid sinkUid,
DeviceLinkSourceComponent sourceComponent,
DeviceLinkSinkComponent sinkComponent)
{
// This function gets called on component removal. Beware that TryComp & Resolve may return false.
if (sourceComponent.LinkedPorts.TryGetValue(sinkUid, out var ports))
{
foreach (var (sourcePort, sinkPort) in ports)
{
RaiseLocalEvent(sourceUid, new PortDisconnectedEvent(sourcePort));
RaiseLocalEvent(sinkUid, new PortDisconnectedEvent(sinkPort));
}
}
sinkComponent.LinkedSources.Remove(sourceUid);
sourceComponent.LinkedPorts.Remove(sinkUid);
foreach (var outputList in sourceComponent.Outputs.Values)
{
outputList.Remove(sinkUid);
}
}
/// <summary>
/// Adds or removes a link depending on if it's already present
/// </summary>
/// <returns>True if the link was successfully added or removed</returns>
public bool ToggleLink(
EntityUid? userId,
EntityUid sourceUid,
EntityUid sinkUid,
string source,
string sink,
DeviceLinkSourceComponent? sourceComponent = null,
DeviceLinkSinkComponent? sinkComponent = null)
{
if (!Resolve(sourceUid, ref sourceComponent) || !Resolve(sinkUid, ref sinkComponent))
return false;
var outputs = sourceComponent.Outputs.GetOrNew(source);
var linkedPorts = sourceComponent.LinkedPorts.GetOrNew(sinkUid);
if (linkedPorts.Contains((source, sink)))
{
if (userId != null)
_adminLogger.Add(LogType.DeviceLinking, LogImpact.Low, $"{ToPrettyString(userId.Value):actor} unlinked {ToPrettyString(sourceUid):source} {source} and {ToPrettyString(sinkUid):sink} {sink}");
else
_adminLogger.Add(LogType.DeviceLinking, LogImpact.Low, $"unlinked {ToPrettyString(sourceUid):source} {source} and {ToPrettyString(sinkUid):sink} {sink}");
RaiseLocalEvent(sourceUid, new PortDisconnectedEvent(source));
RaiseLocalEvent(sinkUid, new PortDisconnectedEvent(sink));
outputs.Remove(sinkUid);
linkedPorts.Remove((source, sink));
if (linkedPorts.Count != 0)
return true;
sourceComponent.LinkedPorts.Remove(sinkUid);
sinkComponent.LinkedSources.Remove(sourceUid);
CreateLinkPopup(userId, sourceUid, source, sinkUid, sink, true);
}
else
{
if (!sourceComponent.Ports.Contains(source) || !sinkComponent.Ports.Contains(sink))
return false;
if (!CanLink(userId, sourceUid, sinkUid, source, sink, true, sourceComponent))
return false;
outputs.Add(sinkUid);
linkedPorts.Add((source, sink));
sinkComponent.LinkedSources.Add(sourceUid);
SendNewLinkEvent(userId, sourceUid, source, sinkUid, sink);
CreateLinkPopup(userId, sourceUid, source, sinkUid, sink, false);
}
return true;
}
/// <summary>
/// Checks if a source and a sink can be linked by allowing other systems to veto the link
/// and by optionally checking if they are in range of each other
/// </summary>
/// <returns></returns>
private bool CanLink(
EntityUid? userId,
EntityUid sourceUid,
EntityUid sinkUid,
string source,
string sink,
bool checkRange = true,
DeviceLinkSourceComponent? sourceComponent = null)
{
if (!Resolve(sourceUid, ref sourceComponent))
return false;
if (checkRange && !InRange(sourceUid, sinkUid, sourceComponent.Range))
{
if (userId.HasValue)
_popupSystem.PopupCursor(Loc.GetString("signal-linker-component-out-of-range"), userId.Value);
return false;
}
var linkAttemptEvent = new LinkAttemptEvent(userId, sourceUid, source, sinkUid, sink);
RaiseLocalEvent(sourceUid, linkAttemptEvent, true);
if (linkAttemptEvent.Cancelled && userId.HasValue)
{
_popupSystem.PopupCursor(Loc.GetString("signal-linker-component-connection-refused", ("machine", source)), userId.Value);
return false;
}
RaiseLocalEvent(sinkUid, linkAttemptEvent, true);
if (linkAttemptEvent.Cancelled && userId.HasValue)
{
_popupSystem.PopupCursor(Loc.GetString("signal-linker-component-connection-refused", ("machine", source)), userId.Value);
return false;
}
return !linkAttemptEvent.Cancelled;
}
private bool InRange(EntityUid sourceUid, EntityUid sinkUid, float range)
{
// TODO: This should be using an existing method and also coordinates inrange instead.
return _transform.GetMapCoordinates(sourceUid).InRange(_transform.GetMapCoordinates(sinkUid), range);
}
private void SendNewLinkEvent(EntityUid? user, EntityUid sourceUid, string source, EntityUid sinkUid, string sink)
{
if (user != null)
_adminLogger.Add(LogType.DeviceLinking, LogImpact.Low, $"{ToPrettyString(user.Value):actor} linked {ToPrettyString(sourceUid):source} {source} and {ToPrettyString(sinkUid):sink} {sink}");
else
_adminLogger.Add(LogType.DeviceLinking, LogImpact.Low, $"linked {ToPrettyString(sourceUid):source} {source} and {ToPrettyString(sinkUid):sink} {sink}");
var newLinkEvent = new NewLinkEvent(user, sourceUid, source, sinkUid, sink);
RaiseLocalEvent(sourceUid, newLinkEvent);
RaiseLocalEvent(sinkUid, newLinkEvent);
}
private void CreateLinkPopup(EntityUid? userId, EntityUid sourceUid, string source, EntityUid sinkUid, string sink, bool removed)
{
if (!userId.HasValue)
return;
var locString = removed ? "signal-linker-component-unlinked-port" : "signal-linker-component-linked-port";
_popupSystem.PopupCursor(Loc.GetString(locString, ("machine1", sourceUid), ("port1", PortName<SourcePortPrototype>(source)),
("machine2", sinkUid), ("port2", PortName<SinkPortPrototype>(sink))), userId.Value, PopupType.Medium);
}
#endregion
#region Sending & Receiving
/// <summary>
/// Sends a network payload directed at the sink entity.
/// Just raises a <see cref="SignalReceivedEvent"/> without data if the source or the sink doesn't have a <see cref="DeviceNetworkComponent"/>
/// </summary>
/// <param name="uid">The source uid that invokes the port</param>
/// <param name="port">The port to invoke</param>
/// <param name="data">Optional data to send along</param>
/// <param name="sourceComponent"></param>
public virtual void InvokePort(EntityUid uid, string port, NetworkPayload? data = null,
DeviceLinkSourceComponent? sourceComponent = null)
{
// NOOP on client for the moment.
}
#endregion
/// <summary>
/// Gets how many times a <see cref="DeviceLinkSinkComponent"/> has been invoked recently.
/// </summary>
/// <remarks>
/// The return value of this function goes up by one every time a sink is invoked, and goes down by one every tick.
/// </remarks>
public int GetEffectiveInvokeCounter(DeviceLinkSinkComponent sink)
{
// Shouldn't be possible but just to be safe.
var curTick = _gameTiming.CurTick;
if (curTick < sink.InvokeCounterTick)
return 0;
var tickDelta = curTick.Value - sink.InvokeCounterTick.Value;
if (tickDelta >= sink.InvokeCounter)
return 0;
return Math.Max(0, sink.InvokeCounter - (int)tickDelta);
}
protected void SetInvokeCounter(DeviceLinkSinkComponent sink, int value)
{
sink.InvokeCounterTick = _gameTiming.CurTick;
sink.InvokeCounter = value;
}
}