Makes tools and welders ECS, add ToolQualityPrototype. (#4741)

This commit is contained in:
Vera Aguilera Puerto
2021-10-07 13:01:27 +02:00
committed by GitHub
parent f2760d0002
commit 365c7da4dc
44 changed files with 1144 additions and 863 deletions

View File

@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using Content.Shared.Sound;
using Content.Shared.Tools;
using Content.Shared.Tools.Components;
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.Tools.Components
{
/// <summary>
/// Not to be confused with Multitool (power)
/// </summary>
[RegisterComponent]
public class MultipleToolComponent : SharedMultipleToolComponent
{
[DataDefinition]
public class ToolEntry
{
[DataField("behavior", required:true)]
public PrototypeFlags<ToolQualityPrototype> Behavior { get; } = new();
[DataField("useSound")]
public SoundSpecifier? Sound { get; } = null;
[DataField("changeSound")]
public SoundSpecifier? ChangeSound { get; } = null;
[DataField("sprite")]
public SpriteSpecifier? Sprite { get; } = null;
}
[DataField("entries", required:true)]
public ToolEntry[] Entries { get; } = Array.Empty<ToolEntry>();
[ViewVariables]
public int CurrentEntry = 0;
[ViewVariables]
public string CurrentQualityName = string.Empty;
}
}

View File

@@ -1,99 +0,0 @@
using System.Collections.Generic;
using Content.Shared.Interaction;
using Content.Shared.Sound;
using Content.Shared.Tool;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.Player;
using Robust.Shared.Players;
using Robust.Shared.Serialization.Manager.Attributes;
namespace Content.Server.Tools.Components
{
/// <summary>
/// Not to be confused with Multitool (power)
/// </summary>
[RegisterComponent]
[NetworkedComponent()]
public class MultiToolComponent : Component, IUse
{
[DataDefinition]
public class ToolEntry
{
[DataField("behavior")] public ToolQuality Behavior { get; private set; } = ToolQuality.None;
[DataField("state")]
public string State { get; } = string.Empty;
[DataField("texture")]
public string Texture { get; } = string.Empty;
[DataField("sprite")]
public string Sprite { get; } = string.Empty;
[DataField("useSound", required: true)]
public SoundSpecifier Sound { get; } = default!;
[DataField("changeSound", required: true)]
public SoundSpecifier ChangeSound { get; } = default!;
}
public override string Name => "MultiTool";
[DataField("tools")] private List<ToolEntry> _tools = new();
private int _currentTool = 0;
private ToolComponent? _tool;
private SpriteComponent? _sprite;
protected override void Initialize()
{
base.Initialize();
Owner.TryGetComponent(out _tool);
Owner.TryGetComponent(out _sprite);
SetTool();
}
public void Cycle()
{
_currentTool = (_currentTool + 1) % _tools.Count;
SetTool();
var current = _tools[_currentTool];
SoundSystem.Play(Filter.Pvs(Owner), current.ChangeSound.GetSound(), Owner);
}
private void SetTool()
{
if (_tool == null) return;
var current = _tools[_currentTool];
_tool.UseSound = current.Sound;
_tool.Qualities = current.Behavior;
if (_sprite == null) return;
if (string.IsNullOrEmpty(current.Texture))
if (!string.IsNullOrEmpty(current.Sprite))
_sprite.LayerSetState(0, current.State, current.Sprite);
else
_sprite.LayerSetState(0, current.State);
else
_sprite.LayerSetTexture(0, current.Texture);
Dirty();
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
Cycle();
return true;
}
public override ComponentState GetComponentState(ICommonSession player)
{
return new MultiToolComponentState(_tool?.Qualities ?? ToolQuality.None);
}
}
}

View File

@@ -2,11 +2,13 @@
using Content.Shared.Interaction;
using Content.Shared.Interaction.Helpers;
using Content.Shared.Maps;
using Content.Shared.Tool;
using Content.Shared.Tools;
using Content.Shared.Tools.Components;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
namespace Content.Server.Tools.Components
{
@@ -17,9 +19,13 @@ namespace Content.Server.Tools.Components
[Dependency] private readonly IMapManager _mapManager = default!;
public override string Name => "TilePrying";
[DataField("toolComponentNeeded")]
private bool _toolComponentNeeded = true;
[DataField("qualityNeeded", customTypeSerializer:typeof(PrototypeIdSerializer<ToolQualityPrototype>))]
private string _qualityNeeded = "Prying";
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
TryPryTile(eventArgs.User, eventArgs.ClickLocation);
@@ -43,9 +49,10 @@ namespace Content.Server.Tools.Components
var tileDef = (ContentTileDefinition)_tileDefinitionManager[tile.Tile.TypeId];
if (!tileDef.CanCrowbar) return;
if (!tileDef.CanCrowbar)
return;
if (_toolComponentNeeded && !await tool!.UseTool(user, null, 0f, ToolQuality.Prying))
if (_toolComponentNeeded && !await EntitySystem.Get<ToolSystem>().UseTool(Owner.Uid, user.Uid, null, 0f, 0f, _qualityNeeded))
return;
coordinates.PryTile(Owner.EntityManager, _mapManager);

View File

@@ -1,40 +1,20 @@
using System;
using System.Threading.Tasks;
using Content.Server.DoAfter;
using Content.Shared.ActionBlocker;
using Content.Shared.Audio;
using Content.Shared.Sound;
using Content.Shared.Tool;
using Robust.Shared.Audio;
using Content.Shared.Tools;
using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
using Robust.Shared.Player;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Server.Tools.Components
{
public interface IToolComponent
[RegisterComponent, Friend(typeof(ToolSystem))]
public class ToolComponent : Component
{
ToolQuality Qualities { get; set; }
}
public override string Name => "Tool";
[RegisterComponent]
[ComponentReference(typeof(IToolComponent))]
public class ToolComponent : SharedToolComponent, IToolComponent
{
[DataField("qualities")]
protected ToolQuality _qualities = ToolQuality.None;
[ViewVariables]
public override ToolQuality Qualities
{
get => _qualities;
set
{
_qualities = value;
Dirty();
}
}
public PrototypeFlags<ToolQualityPrototype> Qualities { get; set; } = new();
/// <summary>
/// For tool interactions that have a delay before action this will modify the rate, time to wait is divided by this value
@@ -43,63 +23,7 @@ namespace Content.Server.Tools.Components
[DataField("speed")]
public float SpeedModifier { get; set; } = 1;
// Some tools don't play a sound on use.
[DataField("useSound")]
public SoundSpecifier? UseSound { get; set; }
public void AddQuality(ToolQuality quality)
{
_qualities |= quality;
Dirty();
}
public void RemoveQuality(ToolQuality quality)
{
_qualities &= ~quality;
Dirty();
}
public bool HasQuality(ToolQuality quality)
{
return _qualities.HasFlag(quality);
}
public virtual async Task<bool> UseTool(IEntity user, IEntity? target, float doAfterDelay, ToolQuality toolQualityNeeded, Func<bool>? doAfterCheck = null)
{
if (!HasQuality(toolQualityNeeded) || !EntitySystem.Get<ActionBlockerSystem>().CanInteract(user))
return false;
if (doAfterDelay > 0f)
{
var doAfterSystem = EntitySystem.Get<DoAfterSystem>();
var doAfterArgs = new DoAfterEventArgs(user, doAfterDelay / SpeedModifier, default, target)
{
ExtraCheck = doAfterCheck,
BreakOnDamage = false, // TODO: Change this to true once breathing is fixed.
BreakOnStun = true,
BreakOnTargetMove = true,
BreakOnUserMove = true,
NeedHand = true,
};
var result = await doAfterSystem.WaitDoAfter(doAfterArgs);
if (result == DoAfterStatus.Cancelled)
return false;
}
PlayUseSound();
return true;
}
public void PlayUseSound(float volume = -5f)
{
if (UseSound == null)
return;
SoundSystem.Play(Filter.Pvs(Owner), UseSound.GetSound(), Owner, AudioHelpers.WithVariation(0.15f).WithVolume(volume));
}
}
}

View File

@@ -1,328 +1,52 @@
using System;
using System.Threading.Tasks;
using Content.Server.Act;
using Content.Server.Atmos.EntitySystems;
using Content.Server.Chat.Managers;
using Content.Server.Chemistry.Components;
using Content.Server.Explosion;
using Content.Server.Items;
using Content.Server.Popups;
using Content.Shared.Audio;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Interaction;
using Content.Shared.Popups;
using Content.Shared.Sound;
using Content.Shared.Tool;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Content.Shared.Tools.Components;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Player;
using Robust.Shared.Players;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
namespace Content.Server.Tools.Components
{
[RegisterComponent]
[ComponentReference(typeof(ToolComponent))]
[ComponentReference(typeof(IToolComponent))]
[NetworkedComponent()]
public class WelderComponent : ToolComponent, IUse, ISuicideAct, IAfterInteract
public class WelderComponent : SharedWelderComponent
{
[Dependency] private readonly IEntitySystemManager _entitySystemManager = default!;
public override string Name => "Welder";
public const string SolutionName = "welder";
/// <summary>
/// Solution on the entity that contains the fuel.
/// </summary>
[DataField("fuelSolution")]
public string FuelSolution { get; } = "Welder";
/// <summary>
/// Default Cost of using the welder fuel for an action
/// Reagent that will be used as fuel for welding.
/// </summary>
public const float DefaultFuelCost = 10;
[DataField("fuelReagent", customTypeSerializer:typeof(PrototypeIdSerializer<ReagentPrototype>))]
public string FuelReagent { get; } = "WeldingFuel";
/// <summary>
/// Rate at which we expunge fuel from ourselves when activated
/// Fuel consumption per second, while the welder is active.
/// </summary>
public const float FuelLossRate = 0.5f;
[DataField("fuelConsumption")]
public ReagentUnit FuelConsumption { get; } = ReagentUnit.New(0.05f);
private bool _welderLit;
private WelderSystem _welderSystem = default!;
private SpriteComponent? _spriteComponent;
private PointLightComponent? _pointLightComponent;
[DataField("weldSounds")]
private SoundSpecifier WeldSounds { get; set; } = new SoundCollectionSpecifier("Welder");
/// <summary>
/// A fuel amount to be consumed when the welder goes from being unlit to being lit.
/// </summary>
[DataField("welderOnConsume")]
public ReagentUnit FuelLitCost { get; } = ReagentUnit.New(0.5f);
/// <summary>
/// Sound played when the welder is turned off.
/// </summary>
[DataField("welderOffSounds")]
private SoundSpecifier WelderOffSounds { get; set; } = new SoundCollectionSpecifier("WelderOff");
public SoundSpecifier WelderOffSounds { get; } = new SoundCollectionSpecifier("WelderOff");
/// <summary>
/// Sound played when the tool is turned on.
/// </summary>
[DataField("welderOnSounds")]
private SoundSpecifier WelderOnSounds { get; set; } = new SoundCollectionSpecifier("WelderOn");
public SoundSpecifier WelderOnSounds { get; } = new SoundCollectionSpecifier("WelderOn");
[DataField("welderRefill")]
private SoundSpecifier WelderRefill { get; set; } = new SoundPathSpecifier("/Audio/Effects/refill.ogg");
[ViewVariables] public float Fuel => WelderSolution?.GetReagentQuantity("WeldingFuel").Float() ?? 0f;
[ViewVariables] public float FuelCapacity => WelderSolution?.MaxVolume.Float() ?? 0f;
private Solution? WelderSolution
{
get
{
Owner.EntityManager.EntitySysManager.GetEntitySystem<SolutionContainerSystem>()
.TryGetSolution(Owner, SolutionName, out var solution);
return solution;
}
}
/// <summary>
/// Status of welder, whether it is ignited
/// </summary>
[ViewVariables]
public bool WelderLit
{
get => _welderLit;
private set
{
_welderLit = value;
Dirty();
}
}
protected override void Initialize()
{
base.Initialize();
AddQuality(ToolQuality.Welding);
_welderSystem = _entitySystemManager.GetEntitySystem<WelderSystem>();
Owner.EnsureComponent<SolutionContainerManagerComponent>();
Owner.TryGetComponent(out _spriteComponent);
Owner.TryGetComponent(out _pointLightComponent);
EntitySystem.Get<SolutionContainerSystem>().EnsureSolution(Owner, "welder");
}
public override ComponentState GetComponentState(ICommonSession player)
{
return new WelderComponentState(FuelCapacity, Fuel, WelderLit);
}
public override async Task<bool> UseTool(IEntity user, IEntity? target, float doAfterDelay,
ToolQuality toolQualityNeeded, Func<bool>? doAfterCheck = null)
{
bool ExtraCheck()
{
var extraCheck = doAfterCheck?.Invoke() ?? true;
if (!CanWeld(DefaultFuelCost))
{
target?.PopupMessage(user, "Can't weld!");
return false;
}
return extraCheck;
}
var canUse = await base.UseTool(user, target, doAfterDelay, toolQualityNeeded, ExtraCheck);
return toolQualityNeeded.HasFlag(ToolQuality.Welding) ? canUse && TryWeld(DefaultFuelCost, user) : canUse;
}
public async Task<bool> UseTool(IEntity user, IEntity target, float doAfterDelay, ToolQuality toolQualityNeeded,
float fuelConsumed, Func<bool>? doAfterCheck = null)
{
bool ExtraCheck()
{
var extraCheck = doAfterCheck?.Invoke() ?? true;
return extraCheck && CanWeld(fuelConsumed);
}
return await base.UseTool(user, target, doAfterDelay, toolQualityNeeded, ExtraCheck) &&
TryWeld(fuelConsumed, user);
}
private bool TryWeld(float value, IEntity? user = null, bool silent = false)
{
if (!WelderLit)
{
if (!silent && user != null)
Owner.PopupMessage(user, Loc.GetString("welder-component-welder-not-lit-message"));
return false;
}
if (!CanWeld(value))
{
if (!silent && user != null)
Owner.PopupMessage(user, Loc.GetString("welder-component-cannot-weld-message"));
return false;
}
if (WelderSolution == null)
return false;
var succeeded = EntitySystem.Get<SolutionContainerSystem>()
.TryRemoveReagent(Owner.Uid, WelderSolution, "WeldingFuel", ReagentUnit.New(value));
if (succeeded && !silent)
{
PlaySound(WeldSounds);
}
return succeeded;
}
private bool CanWeld(float value)
{
return Fuel > value || Qualities != ToolQuality.Welding;
}
private bool CanLitWelder()
{
return Fuel > 0 || Qualities != ToolQuality.Welding;
}
/// <summary>
/// Deactivates welding tool if active, activates welding tool if possible
/// </summary>
private bool ToggleWelderStatus(IEntity? user = null)
{
var item = Owner.GetComponent<ItemComponent>();
if (WelderLit)
{
WelderLit = false;
// Layer 1 is the flame.
item.EquippedPrefix = "off";
_spriteComponent?.LayerSetVisible(1, false);
if (_pointLightComponent != null) _pointLightComponent.Enabled = false;
PlaySound(WelderOffSounds, -5);
_welderSystem.Unsubscribe(this);
return true;
}
if (!CanLitWelder() && user != null)
{
Owner.PopupMessage(user, Loc.GetString("welder-component-no-fuel-message"));
return false;
}
WelderLit = true;
item.EquippedPrefix = "on";
_spriteComponent?.LayerSetVisible(1, true);
if (_pointLightComponent != null) _pointLightComponent.Enabled = true;
PlaySound(WelderOnSounds, -5);
_welderSystem.Subscribe(this);
EntitySystem.Get<AtmosphereSystem>().HotspotExpose(Owner.Transform.Coordinates, 700, 50, true);
return true;
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
return ToggleWelderStatus(eventArgs.User);
}
protected override void Shutdown()
{
base.Shutdown();
_welderSystem.Unsubscribe(this);
}
public void OnUpdate(float frameTime)
{
if (!HasQuality(ToolQuality.Welding) || !WelderLit || Owner.Deleted)
return;
EntitySystem.Get<SolutionContainerSystem>().TryRemoveReagent(Owner.Uid, WelderSolution, "WeldingFuel",
ReagentUnit.New(FuelLossRate * frameTime));
EntitySystem.Get<AtmosphereSystem>().HotspotExpose(Owner.Transform.Coordinates, 700, 50, true);
if (Fuel == 0)
ToggleWelderStatus();
}
SuicideKind ISuicideAct.Suicide(IEntity victim, IChatManager chat)
{
string othersMessage;
string selfMessage;
if (TryWeld(5, victim, silent: true))
{
PlaySound(WeldSounds);
othersMessage =
Loc.GetString("welder-component-suicide-lit-others-message",
("victim", victim));
victim.PopupMessageOtherClients(othersMessage);
selfMessage = Loc.GetString("welder-component-suicide-lit-message");
victim.PopupMessage(selfMessage);
return SuicideKind.Heat;
}
othersMessage = Loc.GetString("welder-component-suicide-unlit-others-message", ("victim", victim));
victim.PopupMessageOtherClients(othersMessage);
selfMessage = Loc.GetString("welder-component-suicide-unlit-message");
victim.PopupMessage(selfMessage);
return SuicideKind.Blunt;
}
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
if (eventArgs.Target == null || !eventArgs.CanReach)
{
return false;
}
if (eventArgs.Target.TryGetComponent(out ReagentTankComponent? tank)
&& tank.TankType == ReagentTankType.Fuel
&& EntitySystem.Get<SolutionContainerSystem>()
.TryGetDrainableSolution(eventArgs.Target.Uid, out var targetSolution)
&& WelderSolution != null)
{
var trans = ReagentUnit.Min(WelderSolution.AvailableVolume, targetSolution.DrainAvailable);
if (trans > 0)
{
var drained = EntitySystem.Get<SolutionContainerSystem>().Drain(eventArgs.Target.Uid, targetSolution, trans);
EntitySystem.Get<SolutionContainerSystem>().TryAddSolution(Owner.Uid, WelderSolution, drained);
SoundSystem.Play(Filter.Pvs(Owner), WelderRefill.GetSound(), Owner);
eventArgs.Target.PopupMessage(eventArgs.User,
Loc.GetString("welder-component-after-interact-refueled-message"));
}
else
{
eventArgs.Target.PopupMessage(eventArgs.User,
Loc.GetString("welder-component-no-fuel-in-tank", ("owner", eventArgs.Target)));
}
}
return true;
}
private void PlaySound(SoundSpecifier sound, float volume = -5f)
{
SoundSystem.Play(Filter.Pvs(Owner), sound.GetSound(), Owner, AudioHelpers.WithVariation(0.15f).WithVolume(volume));
}
public SoundSpecifier WelderRefill { get; } = new SoundPathSpecifier("/Audio/Effects/refill.ogg");
}
}

View File

@@ -0,0 +1,108 @@
using System;
using System.Linq;
using Content.Server.Tools.Components;
using Content.Shared.Interaction;
using Content.Shared.Tools;
using Content.Shared.Tools.Components;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Player;
using Robust.Shared.Prototypes;
namespace Content.Server.Tools
{
public partial class ToolSystem
{
private void InitializeMultipleTools()
{
SubscribeLocalEvent<MultipleToolComponent, ComponentStartup>(OnMultipleToolStartup);
SubscribeLocalEvent<MultipleToolComponent, UseInHandEvent>(OnMultipleToolUsedInHand);
SubscribeLocalEvent<MultipleToolComponent, ActivateInWorldEvent>(OnMultipleToolActivated);
SubscribeLocalEvent<MultipleToolComponent, ComponentGetState>(OnMultipleToolGetState);
}
private void OnMultipleToolStartup(EntityUid uid, MultipleToolComponent multiple, ComponentStartup args)
{
// Only set the multiple tool if we have a tool component.
if(EntityManager.TryGetComponent(uid, out ToolComponent? tool))
SetMultipleTool(uid, multiple, tool);
}
private void OnMultipleToolUsedInHand(EntityUid uid, MultipleToolComponent multiple, UseInHandEvent args)
{
if (args.Handled)
return;
args.Handled = CycleMultipleTool(uid, multiple);
}
private void OnMultipleToolActivated(EntityUid uid, MultipleToolComponent multiple, ActivateInWorldEvent args)
{
if (args.Handled)
return;
args.Handled = CycleMultipleTool(uid, multiple);
}
private void OnMultipleToolGetState(EntityUid uid, MultipleToolComponent multiple, ref ComponentGetState args)
{
args.State = new MultipleToolComponentState(multiple.CurrentQualityName);
}
public bool CycleMultipleTool(EntityUid uid, MultipleToolComponent? multiple = null)
{
if (!Resolve(uid, ref multiple))
return false;
if (multiple.Entries.Length == 0)
return false;
multiple.CurrentEntry = (multiple.CurrentEntry + 1) % multiple.Entries.Length;
SetMultipleTool(uid, multiple);
var current = multiple.Entries[multiple.CurrentEntry];
if(current.ChangeSound is {} changeSound)
SoundSystem.Play(Filter.Pvs(uid), changeSound.GetSound(), uid);
return true;
}
public void SetMultipleTool(EntityUid uid, MultipleToolComponent? multiple = null, ToolComponent? tool = null, SpriteComponent? sprite = null)
{
if (!Resolve(uid, ref multiple, ref tool))
return;
// Sprite is optional.
Resolve(uid, ref sprite);
if (multiple.Entries.Length == 0)
{
multiple.CurrentQualityName = Loc.GetString("multiple-tool-component-no-behavior");
multiple.Dirty();
return;
}
var current = multiple.Entries[multiple.CurrentEntry];
tool.UseSound = current.Sound;
tool.Qualities = current.Behavior;
if (_prototypeManager.TryIndex(current.Behavior.First(), out ToolQualityPrototype? quality))
{
multiple.CurrentQualityName = Loc.GetString(quality.Name);
}
multiple.Dirty();
if (current.Sprite == null || sprite == null)
return;
sprite.LayerSetSprite(0, current.Sprite);
}
}
}

View File

@@ -0,0 +1,332 @@
using System.Collections.Generic;
using System.Linq;
using Content.Server.Chemistry.Components;
using Content.Server.Items;
using Content.Server.Tools.Components;
using Content.Shared.Audio;
using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Examine;
using Content.Shared.Interaction;
using Content.Shared.Popups;
using Content.Shared.Temperature;
using Content.Shared.Tools.Components;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.GameStates;
using Robust.Shared.Localization;
using Robust.Shared.Player;
namespace Content.Server.Tools
{
public partial class ToolSystem
{
private readonly HashSet<EntityUid> _activeWelders = new();
private const float WelderUpdateTimer = 1f;
private float _welderTimer = 0f;
public void InitializeWelders()
{
SubscribeLocalEvent<WelderComponent, ComponentStartup>(OnWelderStartup);
SubscribeLocalEvent<WelderComponent, IsHotEvent>(OnWelderIsHotEvent);
SubscribeLocalEvent<WelderComponent, ExaminedEvent>(OnWelderExamine);
SubscribeLocalEvent<WelderComponent, SolutionChangedEvent>(OnWelderSolutionChange);
SubscribeLocalEvent<WelderComponent, UseInHandEvent>(OnWelderUseInHand);
SubscribeLocalEvent<WelderComponent, ActivateInWorldEvent>(OnWelderActivate);
SubscribeLocalEvent<WelderComponent, AfterInteractEvent>(OnWelderAfterInteract);
SubscribeLocalEvent<WelderComponent, ToolUseAttemptEvent>(OnWelderToolUseAttempt);
SubscribeLocalEvent<WelderComponent, ToolUseFinishAttemptEvent>(OnWelderToolUseFinishAttempt);
SubscribeLocalEvent<WelderComponent, ComponentShutdown>(OnWelderShutdown);
SubscribeLocalEvent<WelderComponent, ComponentGetState>(OnWelderGetState);
}
public (ReagentUnit fuel, ReagentUnit capacity) GetWelderFuelAndCapacity(EntityUid uid, WelderComponent? welder = null, SolutionContainerManagerComponent? solutionContainer = null)
{
if (!Resolve(uid, ref welder, ref solutionContainer)
|| !_solutionContainerSystem.TryGetSolution(uid, welder.FuelSolution, out var fuelSolution, solutionContainer))
return (ReagentUnit.Zero, ReagentUnit.Zero);
return (_solutionContainerSystem.GetReagentQuantity(uid, welder.FuelReagent), fuelSolution.MaxVolume);
}
public bool TryToggleWelder(EntityUid uid, EntityUid? user,
WelderComponent? welder = null,
SolutionContainerManagerComponent? solutionContainer = null,
ItemComponent? item = null,
PointLightComponent? light = null,
SpriteComponent? sprite = null)
{
// Right now, we only need the welder.
// So let's not unnecessarily resolve components
if (!Resolve(uid, ref welder))
return false;
return !welder.Lit
? TryTurnWelderOn(uid, user, welder, solutionContainer, item, light, sprite)
: TryTurnWelderOff(uid, user, welder, item, light, sprite);
}
public bool TryTurnWelderOn(EntityUid uid, EntityUid? user,
WelderComponent? welder = null,
SolutionContainerManagerComponent? solutionContainer = null,
ItemComponent? item = null,
PointLightComponent? light = null,
SpriteComponent? sprite = null)
{
if (!Resolve(uid, ref welder, ref solutionContainer))
return false;
// Optional components.
Resolve(uid, ref item, ref light, ref sprite);
if (!_solutionContainerSystem.TryGetSolution(uid, welder.FuelSolution, out var solution, solutionContainer))
return false;
var fuel = solution.GetReagentQuantity(welder.FuelReagent);
// Not enough fuel to lit welder.
if (fuel == ReagentUnit.Zero || fuel < welder.FuelLitCost)
{
if(user != null)
_popupSystem.PopupEntity(Loc.GetString("welder-component-no-fuel-message"), uid, Filter.Entities(user.Value));
return false;
}
if (user != null && !_actionBlockerSystem.CanInteract(user.Value))
return false;
solution.RemoveReagent(welder.FuelReagent, welder.FuelLitCost);
welder.Lit = true;
if(item != null)
item.EquippedPrefix = "on";
sprite?.LayerSetVisible(1, true);
if (light != null)
light.Enabled = true;
SoundSystem.Play(Filter.Pvs(uid), welder.WelderOnSounds.GetSound(), uid, AudioHelpers.WithVariation(0.125f).WithVolume(-5f));
// TODO: Use ITransformComponent directly.
_atmosphereSystem.HotspotExpose(welder.Owner.Transform.Coordinates, 700, 50, true);
welder.Dirty();
_activeWelders.Add(uid);
return true;
}
public bool TryTurnWelderOff(EntityUid uid, EntityUid? user,
WelderComponent? welder = null,
ItemComponent? item = null,
PointLightComponent? light = null,
SpriteComponent? sprite = null)
{
if (!Resolve(uid, ref welder))
return false;
// Optional components.
Resolve(uid, ref item, ref light, ref sprite);
if (user != null && !_actionBlockerSystem.CanInteract(user.Value))
return false;
welder.Lit = false;
// TODO: Make all this use visualizers.
if (item != null)
item.EquippedPrefix = "off";
// Layer 1 is the flame.
sprite?.LayerSetVisible(1, false);
if (light != null)
light.Enabled = false;
SoundSystem.Play(Filter.Pvs(uid), welder.WelderOffSounds.GetSound(), uid, AudioHelpers.WithVariation(0.125f).WithVolume(-5f));
welder.Dirty();
_activeWelders.Remove(uid);
return true;
}
private void OnWelderStartup(EntityUid uid, WelderComponent component, ComponentStartup args)
{
component.Dirty();
}
private void OnWelderIsHotEvent(EntityUid uid, WelderComponent welder, IsHotEvent args)
{
args.IsHot = welder.Lit;
}
private void OnWelderExamine(EntityUid uid, WelderComponent welder, ExaminedEvent args)
{
if (welder.Lit)
{
args.PushMarkup(Loc.GetString("welder-component-on-examine-welder-lit-message"));
}
else
{
args.PushMarkup(Loc.GetString("welder-component-on-examine-welder-not-lit-message"));
}
if (args.IsInDetailsRange)
{
var (fuel, capacity) = GetWelderFuelAndCapacity(uid, welder);
args.PushMarkup(Loc.GetString("welder-component-on-examine-detailed-message",
("colorName", fuel < capacity / ReagentUnit.New(4f) ? "darkorange" : "orange"),
("fuelLeft", fuel),
("fuelCapacity", capacity)));
}
}
private void OnWelderSolutionChange(EntityUid uid, WelderComponent welder, SolutionChangedEvent args)
{
welder.Dirty();
}
private void OnWelderActivate(EntityUid uid, WelderComponent welder, ActivateInWorldEvent args)
{
args.Handled = TryToggleWelder(uid, args.User.Uid, welder);
}
private void OnWelderAfterInteract(EntityUid uid, WelderComponent welder, AfterInteractEvent args)
{
if (args.Handled)
return;
if (args.Target == null || !args.CanReach)
return;
// TODO: Clean up this inherited oldcode.
if (args.Target.TryGetComponent(out ReagentTankComponent? tank)
&& tank.TankType == ReagentTankType.Fuel
&& _solutionContainerSystem.TryGetDrainableSolution(args.Target.Uid, out var targetSolution)
&& _solutionContainerSystem.TryGetSolution(uid, welder.FuelSolution, out var welderSolution))
{
var trans = ReagentUnit.Min(welderSolution.AvailableVolume, targetSolution.DrainAvailable);
if (trans > 0)
{
var drained = _solutionContainerSystem.Drain(args.Target.Uid, targetSolution, trans);
_solutionContainerSystem.TryAddSolution(uid, welderSolution, drained);
SoundSystem.Play(Filter.Pvs(uid), welder.WelderRefill.GetSound(), uid);
args.Target.PopupMessage(args.User, Loc.GetString("welder-component-after-interact-refueled-message"));
}
else
{
args.Target.PopupMessage(args.User, Loc.GetString("welder-component-no-fuel-in-tank", ("owner", args.Target)));
}
}
args.Handled = true;
}
private void OnWelderUseInHand(EntityUid uid, WelderComponent welder, UseInHandEvent args)
{
args.Handled = TryToggleWelder(uid, args.User.Uid, welder);
}
private void OnWelderToolUseAttempt(EntityUid uid, WelderComponent welder, ToolUseAttemptEvent args)
{
if (args.Cancelled)
return;
if (!welder.Lit)
{
_popupSystem.PopupEntity(Loc.GetString("welder-component-welder-not-lit-message"), uid, Filter.Entities(args.User));
args.Cancel();
return;
}
var (fuel, _) = GetWelderFuelAndCapacity(uid, welder);
if (ReagentUnit.New(args.Fuel) > fuel)
{
_popupSystem.PopupEntity(Loc.GetString("welder-component-cannot-weld-message"), uid, Filter.Entities(args.User));
args.Cancel();
return;
}
}
private void OnWelderToolUseFinishAttempt(EntityUid uid, WelderComponent welder, ToolUseFinishAttemptEvent args)
{
if (args.Cancelled)
return;
if (!welder.Lit)
{
_popupSystem.PopupEntity(Loc.GetString("welder-component-welder-not-lit-message"), uid, Filter.Entities(args.User));
args.Cancel();
return;
}
var (fuel, _) = GetWelderFuelAndCapacity(uid, welder);
var neededFuel = ReagentUnit.New(args.Fuel);
if (neededFuel > fuel)
{
args.Cancel();
}
if (!_solutionContainerSystem.TryGetSolution(uid, welder.FuelSolution, out var solution))
{
args.Cancel();
return;
}
solution.RemoveReagent(welder.FuelReagent, neededFuel);
welder.Dirty();
}
private void OnWelderShutdown(EntityUid uid, WelderComponent welder, ComponentShutdown args)
{
_activeWelders.Remove(uid);
}
private void OnWelderGetState(EntityUid uid, WelderComponent welder, ref ComponentGetState args)
{
var (fuel, capacity) = GetWelderFuelAndCapacity(uid, welder);
args.State = new WelderComponentState(capacity.Float(), fuel.Float(), welder.Lit);
}
private void UpdateWelders(float frameTime)
{
_welderTimer += frameTime;
if (_welderTimer < WelderUpdateTimer)
return;
foreach (var tool in _activeWelders.ToArray())
{
if (!EntityManager.TryGetComponent(tool, out WelderComponent? welder)
|| !EntityManager.TryGetComponent(tool, out SolutionContainerManagerComponent? solutionContainer))
continue;
if (!_solutionContainerSystem.TryGetSolution(tool, welder.FuelSolution, out var solution, solutionContainer))
continue;
// TODO: Use ITransformComponent directly.
_atmosphereSystem.HotspotExpose(welder.Owner.Transform.Coordinates, 700, 50, true);
solution.RemoveReagent(welder.FuelReagent, welder.FuelConsumption * _welderTimer);
if (solution.GetReagentQuantity(welder.FuelReagent) <= ReagentUnit.Zero)
TryTurnWelderOff(tool, null, welder);
welder.Dirty();
}
_welderTimer -= WelderUpdateTimer;
}
}
}

View File

@@ -0,0 +1,142 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Content.Server.Atmos.EntitySystems;
using Content.Server.DoAfter;
using Content.Server.Popups;
using Content.Server.Tools.Components;
using Content.Shared.ActionBlocker;
using Content.Shared.Audio;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.Tools;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Player;
using Robust.Shared.Prototypes;
namespace Content.Server.Tools
{
public partial class ToolSystem : EntitySystem
{
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly ActionBlockerSystem _actionBlockerSystem = default!;
[Dependency] private readonly DoAfterSystem _doAfterSystem = default!;
[Dependency] private readonly SolutionContainerSystem _solutionContainerSystem = default!;
[Dependency] private readonly AtmosphereSystem _atmosphereSystem = default!;
[Dependency] private readonly PopupSystem _popupSystem = default!;
public override void Initialize()
{
base.Initialize();
InitializeWelders();
InitializeMultipleTools();
}
public async Task<bool> UseTool(EntityUid tool, EntityUid user, EntityUid? target, float fuel,
float doAfterDelay, IEnumerable<string> toolQualitiesNeeded, Func<bool>? doAfterCheck = null,
ToolComponent? toolComponent = null)
{
if (!Resolve(tool, ref toolComponent))
return false;
if (!toolComponent.Qualities.ContainsAll(toolQualitiesNeeded) || !_actionBlockerSystem.CanInteract(user))
return false;
var beforeAttempt = new ToolUseAttemptEvent(fuel, user);
RaiseLocalEvent(tool, beforeAttempt, false);
if (beforeAttempt.Cancelled)
return false;
if (doAfterDelay > 0f)
{
var doAfterArgs = new DoAfterEventArgs(user, doAfterDelay / toolComponent.SpeedModifier, default, target)
{
ExtraCheck = doAfterCheck,
BreakOnDamage = true,
BreakOnStun = true,
BreakOnTargetMove = true,
BreakOnUserMove = true,
NeedHand = true,
};
var result = await _doAfterSystem.WaitDoAfter(doAfterArgs);
if (result == DoAfterStatus.Cancelled)
return false;
}
var afterAttempt = new ToolUseFinishAttemptEvent(fuel, user);
RaiseLocalEvent(tool, afterAttempt, false);
if (afterAttempt.Cancelled)
return false;
if (toolComponent.UseSound != null)
PlayToolSound(tool, toolComponent);
return true;
}
public Task<bool> UseTool(EntityUid tool, EntityUid user, EntityUid? target, float fuel,
float doAfterDelay, string toolQualityNeeded, Func<bool>? doAfterCheck = null,
ToolComponent? toolComponent = null)
{
return UseTool(tool, user, target, fuel, doAfterDelay, new [] {toolQualityNeeded}, doAfterCheck, toolComponent);
}
public void PlayToolSound(EntityUid uid, ToolComponent? tool = null)
{
if (!Resolve(uid, ref tool))
return;
if (tool.UseSound is not {} sound)
return;
// Pass tool.Owner to Filter.Pvs to avoid a TryGetEntity call.
SoundSystem.Play(Filter.Pvs(tool.Owner), sound.GetSound(), uid,
AudioHelpers.WithVariation(0.175f).WithVolume(-5f));
}
public override void Update(float frameTime)
{
base.Update(frameTime);
UpdateWelders(frameTime);
}
}
/// <summary>
/// Attempt event called *before* any do afters to see if the tool usage should succeed or not.
/// You can change the fuel consumption by changing the Fuel property.
/// </summary>
public class ToolUseAttemptEvent : CancellableEntityEventArgs
{
public float Fuel { get; set; }
public EntityUid User { get; }
public ToolUseAttemptEvent(float fuel, EntityUid user)
{
Fuel = fuel;
User = user;
}
}
/// <summary>
/// Attempt event called *after* any do afters to see if the tool usage should succeed or not.
/// You can use this event to consume any fuel needed.
/// </summary>
public class ToolUseFinishAttemptEvent : CancellableEntityEventArgs
{
public float Fuel { get; }
public EntityUid User { get; }
public ToolUseFinishAttemptEvent(float fuel, EntityUid user)
{
Fuel = fuel;
}
}
}

View File

@@ -1,77 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Server.Tools.Components;
using Content.Shared.Chemistry.EntitySystems;
using Content.Shared.Examine;
using Content.Shared.Temperature;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
namespace Content.Server.Tools
{
/// <summary>
/// Despite the name, it's only really used for the welder logic in tools. Go figure.
/// </summary>
public class WelderSystem : EntitySystem
{
private readonly HashSet<WelderComponent> _activeWelders = new();
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<WelderComponent, SolutionChangedEvent>(OnSolutionChange);
SubscribeLocalEvent<WelderComponent, IsHotEvent>(OnIsHotEvent);
SubscribeLocalEvent<WelderComponent, ExaminedEvent>(OnExamine);
}
private void OnIsHotEvent(EntityUid uid, WelderComponent component, IsHotEvent args)
{
args.IsHot = component.WelderLit;
}
private void OnExamine(EntityUid uid, WelderComponent component, ExaminedEvent args)
{
if (component.WelderLit)
{
args.PushMarkup(Loc.GetString("welder-component-on-examine-welder-lit-message"));
}
else
{
args.PushMarkup(Loc.GetString("welder-component-on-examine-welder-not-lit-message"));
}
if (args.IsInDetailsRange)
{
args.PushMarkup(Loc.GetString("welder-component-on-examine-detailed-message",
("colorName", component.Fuel < component.FuelCapacity / 4f ? "darkorange" : "orange"),
("fuelLeft", Math.Round(component.Fuel)),
("fuelCapacity", component.FuelCapacity)));
}
}
private void OnSolutionChange(EntityUid uid, WelderComponent component, SolutionChangedEvent args)
{
component.Dirty();
}
public bool Subscribe(WelderComponent welder)
{
return _activeWelders.Add(welder);
}
public bool Unsubscribe(WelderComponent welder)
{
return _activeWelders.Remove(welder);
}
public override void Update(float frameTime)
{
foreach (var tool in _activeWelders.ToArray())
{
tool.OnUpdate(frameTime);
}
}
}
}