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,124 @@
#nullable enable
using System.Collections.Generic;
using System.Threading.Tasks;
using Content.Server.Chemistry.Components;
using Content.Server.DoAfter;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Interaction;
using Content.Shared.Interaction.Helpers;
using Content.Shared.Notification;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Player;
using Robust.Shared.Serialization.Manager.Attributes;
namespace Content.Server.Fluids.Components
{
/// <summary>
/// Can a mop click on this entity and dump its fluids
/// </summary>
[RegisterComponent]
public class BucketComponent : Component, IInteractUsing
{
public override string Name => "Bucket";
private List<EntityUid> _currentlyUsing = new();
public ReagentUnit MaxVolume
{
get => Owner.TryGetComponent(out SolutionContainerComponent? solution) ? solution.MaxVolume : ReagentUnit.Zero;
set
{
if (Owner.TryGetComponent(out SolutionContainerComponent? solution))
{
solution.MaxVolume = value;
}
}
}
public ReagentUnit CurrentVolume => Owner.TryGetComponent(out SolutionContainerComponent? solution)
? solution.CurrentVolume
: ReagentUnit.Zero;
[DataField("sound")]
private string? _sound = "/Audio/Effects/Fluids/watersplash.ogg";
/// <inheritdoc />
public override void Initialize()
{
base.Initialize();
Owner.EnsureComponentWarn<SolutionContainerComponent>();
}
async Task<bool> IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs)
{
if (!Owner.TryGetComponent(out SolutionContainerComponent? contents) ||
_currentlyUsing.Contains(eventArgs.Using.Uid) ||
!eventArgs.Using.TryGetComponent(out MopComponent? mopComponent) ||
mopComponent.Mopping)
{
return false;
}
if (CurrentVolume <= 0)
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("Bucket is empty"));
return false;
}
if (mopComponent.CurrentVolume == mopComponent.MaxVolume)
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("Mop is full"));
return false;
}
_currentlyUsing.Add(eventArgs.Using.Uid);
// IMO let em move while doing it.
var doAfterArgs = new DoAfterEventArgs(eventArgs.User, 1.0f, target: eventArgs.Target)
{
BreakOnStun = true,
BreakOnDamage = true,
};
var result = await EntitySystem.Get<DoAfterSystem>().DoAfter(doAfterArgs);
_currentlyUsing.Remove(eventArgs.Using.Uid);
if (result == DoAfterStatus.Cancelled ||
Owner.Deleted ||
mopComponent.Deleted ||
CurrentVolume <= 0 ||
!Owner.InRangeUnobstructed(mopComponent.Owner))
return false;
// Top up mops solution given it needs it to annihilate puddles I guess
var transferAmount = ReagentUnit.Min(mopComponent.MaxVolume - mopComponent.CurrentVolume, CurrentVolume);
if (transferAmount == 0)
{
return false;
}
var mopContents = mopComponent.Contents;
if (mopContents == null)
{
return false;
}
var solution = contents.SplitSolution(transferAmount);
if (!mopContents.TryAddSolution(solution))
{
return false;
}
if (_sound != null)
{
SoundSystem.Play(Filter.Pvs(Owner), _sound, Owner);
}
return true;
}
}
}

View File

@@ -0,0 +1,173 @@
#nullable enable
using System.Threading.Tasks;
using Content.Server.Chemistry.Components;
using Content.Server.DoAfter;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Interaction;
using Content.Shared.Interaction.Helpers;
using Content.Shared.Notification;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Player;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.Fluids.Components
{
/// <summary>
/// For cleaning up puddles
/// </summary>
[RegisterComponent]
public class MopComponent : Component, IAfterInteract
{
public override string Name => "Mop";
/// <summary>
/// Used to prevent do_after spam if we're currently mopping.
/// </summary>
public bool Mopping { get; private set; }
public SolutionContainerComponent? Contents => Owner.GetComponentOrNull<SolutionContainerComponent>();
public ReagentUnit MaxVolume
{
get => Owner.GetComponentOrNull<SolutionContainerComponent>()?.MaxVolume ?? ReagentUnit.Zero;
set
{
if (Owner.TryGetComponent(out SolutionContainerComponent? solution))
{
solution.MaxVolume = value;
}
}
}
public ReagentUnit CurrentVolume =>
Owner.GetComponentOrNull<SolutionContainerComponent>()?.CurrentVolume ?? ReagentUnit.Zero;
// Currently there's a separate amount for pickup and dropoff so
// Picking up a puddle requires multiple clicks
// Dumping in a bucket requires 1 click
// Long-term you'd probably use a cooldown and start the pickup once we have some form of global cooldown
[DataField("pickup_amount")]
public ReagentUnit PickupAmount { get; } = ReagentUnit.New(5);
[DataField("pickup_sound")]
private string? _pickupSound = "/Audio/Effects/Fluids/slosh.ogg";
/// <summary>
/// Multiplier for the do_after delay for how fast the mop works.
/// </summary>
[ViewVariables]
[DataField("speed")]
private float _mopSpeed = 1;
public override void Initialize()
{
base.Initialize();
Owner.EnsureComponentWarn(out SolutionContainerComponent _);
}
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
/*
* Functionality:
* Essentially if we click on an empty tile spill our contents there
* Otherwise, try to mop up the puddle (if it is a puddle).
* It will try to destroy solution on the mop to do so, and if it is successful
* will spill some of the mop's solution onto the puddle which will evaporate eventually.
*/
if (!Owner.TryGetComponent(out SolutionContainerComponent? contents) ||
Mopping ||
!eventArgs.InRangeUnobstructed(ignoreInsideBlocker: true, popup: true))
{
return false;
}
var currentVolume = CurrentVolume;
if (eventArgs.Target == null)
{
if (currentVolume > 0)
{
// Drop the liquid on the mop on to the ground
contents.SplitSolution(CurrentVolume).SpillAt(eventArgs.ClickLocation, "PuddleSmear");
return true;
}
return false;
}
if (!eventArgs.Target.TryGetComponent(out PuddleComponent? puddleComponent))
{
return false;
}
var puddleVolume = puddleComponent.CurrentVolume;
if (currentVolume <= 0)
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("Mop needs to be wet!"));
return false;
}
Mopping = true;
// So if the puddle has 20 units we mop in 2 seconds. Don't just store CurrentVolume given it can change so need to re-calc it anyway.
var doAfterArgs = new DoAfterEventArgs(eventArgs.User, _mopSpeed * puddleVolume.Float() / 10.0f, target: eventArgs.Target)
{
BreakOnUserMove = true,
BreakOnStun = true,
BreakOnDamage = true,
};
var result = await EntitySystem.Get<DoAfterSystem>().DoAfter(doAfterArgs);
Mopping = false;
if (result == DoAfterStatus.Cancelled ||
Owner.Deleted ||
puddleComponent.Deleted)
return false;
// Annihilate the puddle
var transferAmount = ReagentUnit.Min(ReagentUnit.New(5), puddleComponent.CurrentVolume, CurrentVolume);
var puddleCleaned = puddleComponent.CurrentVolume - transferAmount <= 0;
if (transferAmount == 0)
{
if (puddleComponent.EmptyHolder) //The puddle doesn't actually *have* reagents, for example vomit because there's no "vomit" reagent.
{
puddleComponent.Owner.Delete();
transferAmount = ReagentUnit.Min(ReagentUnit.New(5), CurrentVolume);
puddleCleaned = true;
}
else
{
return true;
}
}
else
{
puddleComponent.SplitSolution(transferAmount);
}
if (puddleCleaned) //After cleaning the puddle, make a new puddle with solution from the mop as a "wet floor". Then evaporate it slowly.
{
contents.SplitSolution(transferAmount).SpillAt(eventArgs.ClickLocation, "PuddleSmear");
}
else
{
contents.SplitSolution(transferAmount);
}
if (!string.IsNullOrWhiteSpace(_pickupSound))
{
SoundSystem.Play(Filter.Pvs(Owner), _pickupSound, Owner);
}
return true;
}
}
}

View File

@@ -0,0 +1,413 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Content.Server.Chemistry.Components;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Chemistry.Solution;
using Content.Shared.Directions;
using Content.Shared.Examine;
using Content.Shared.Maps;
using Content.Shared.Physics;
using Content.Shared.Slippery;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Player;
using Robust.Shared.Random;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
namespace Content.Server.Fluids.Components
{
/// <summary>
/// Puddle on a floor
/// </summary>
[RegisterComponent]
public class PuddleComponent : Component, IExamine, IMapInit
{
// Current design: Something calls the SpillHelper.Spill, that will either
// A) Add to an existing puddle at the location (normalised to tile-center) or
// B) add a new one
// From this every time a puddle is spilt on it will try and overflow to its neighbours if possible,
// and also update its appearance based on volume level (opacity) and chemistry color
// Small puddles will evaporate after a set delay
// TODO: 'leaves fluidtracks', probably in a separate component for stuff like gibb chunks?;
// based on behaviour (e.g. someone being punched vs slashed with a sword would have different blood sprite)
// to check for low volumes for evaporation or whatever
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly IRobustRandom _random = default!;
public override string Name => "Puddle";
private CancellationTokenSource? _evaporationToken;
[DataField("evaporate_threshold")]
private ReagentUnit _evaporateThreshold = ReagentUnit.New(20); // How few <Solution Quantity> we can hold prior to self-destructing
public ReagentUnit EvaporateThreshold
{
get => _evaporateThreshold;
set => _evaporateThreshold = value;
}
private ReagentUnit _slipThreshold = ReagentUnit.New(3);
public ReagentUnit SlipThreshold
{
get => _slipThreshold;
set => _slipThreshold = value;
}
/// <summary>
/// The time that it will take this puddle to evaporate, in seconds.
/// </summary>
[DataField("evaporate_time")]
public float EvaporateTime { get; private set; } = 5f;
[DataField("spill_sound")]
private string _spillSound = "/Audio/Effects/Fluids/splat.ogg";
/// <summary>
/// Whether or not this puddle is currently overflowing onto its neighbors
/// </summary>
private bool _overflown;
private SpriteComponent _spriteComponent = default!;
public ReagentUnit MaxVolume
{
get => _contents.MaxVolume;
set => _contents.MaxVolume = value;
}
[ViewVariables]
public ReagentUnit CurrentVolume => _contents.CurrentVolume;
// Volume at which the fluid will try to spill to adjacent components
// Currently a random number, potentially change
public ReagentUnit OverflowVolume => _overflowVolume;
[ViewVariables]
[DataField("overflow_volume")]
private ReagentUnit _overflowVolume = ReagentUnit.New(20);
private ReagentUnit OverflowLeft => CurrentVolume - OverflowVolume;
private SolutionContainerComponent _contents = default!;
public bool EmptyHolder => _contents.ReagentList.Count == 0;
[DataField("variants")]
private int _spriteVariants = 1;
// Whether the underlying solution color should be used
[DataField("recolor")]
private bool _recolor = default;
[DataField("state")]
private string _spriteState = "puddle";
private bool Slippery => Owner.TryGetComponent(out SlipperyComponent? slippery) && slippery.Slippery;
public override void Initialize()
{
base.Initialize();
_contents = Owner.EnsureComponentWarn<SolutionContainerComponent>();
// Smaller than 1m^3 for now but realistically this shouldn't be hit
MaxVolume = ReagentUnit.New(1000);
// Random sprite state set server-side so it's consistent across all clients
_spriteComponent = Owner.EnsureComponent<SpriteComponent>();
var randomVariant = _random.Next(0, _spriteVariants - 1);
if (_spriteComponent.BaseRSIPath != null)
{
_spriteComponent.LayerSetState(0, $"{_spriteState}-{randomVariant}");
}
// UpdateAppearance should get called soon after this so shouldn't need to call Dirty() here
UpdateStatus();
}
void IMapInit.MapInit()
{
var robustRandom = IoCManager.Resolve<IRobustRandom>();
_spriteComponent.Rotation = Angle.FromDegrees(robustRandom.Next(0, 359));
}
void IExamine.Examine(FormattedMessage message, bool inDetailsRange)
{
if(Slippery)
{
message.AddText(Loc.GetString("It looks slippery."));
}
}
/// <summary>
/// Whether adding this solution to this puddle would overflow.
/// </summary>
/// <param name="solution"></param>
/// <returns></returns>
public bool WouldOverflow(Solution solution)
{
return (CurrentVolume + solution.TotalVolume > _overflowVolume);
}
// Flow rate should probably be controlled globally so this is it for now
internal bool TryAddSolution(Solution solution, bool sound = true, bool checkForEvaporate = true, bool checkForOverflow = true)
{
if (solution.TotalVolume == 0)
{
return false;
}
var result = _contents.TryAddSolution(solution);
if (!result)
{
return false;
}
UpdateStatus();
if (checkForOverflow)
{
CheckOverflow();
}
if (checkForEvaporate)
{
CheckEvaporate();
}
UpdateAppearance();
if (!sound)
{
return true;
}
SoundSystem.Play(Filter.Pvs(Owner), _spillSound, Owner.Transform.Coordinates);
return true;
}
internal Solution SplitSolution(ReagentUnit quantity)
{
var split = _contents.SplitSolution(quantity);
CheckEvaporate();
UpdateAppearance();
return split;
}
public void CheckEvaporate()
{
if (CurrentVolume == 0)
{
Owner.Delete();
}
}
public void Evaporate()
{
_contents.SplitSolution(ReagentUnit.Min(ReagentUnit.New(1), _contents.CurrentVolume));
if (CurrentVolume == 0)
{
Owner.Delete();
}
else
{
UpdateStatus();
}
}
public void UpdateStatus()
{
_evaporationToken?.Cancel();
if(Owner.Deleted) return;
UpdateAppearance();
UpdateSlip();
if (_evaporateThreshold == ReagentUnit.New(-1) || CurrentVolume > _evaporateThreshold)
{
return;
}
_evaporationToken = new CancellationTokenSource();
// KYS to evaporate
Owner.SpawnTimer(TimeSpan.FromSeconds(EvaporateTime), Evaporate, _evaporationToken.Token);
}
private void UpdateSlip()
{
if ((_slipThreshold == ReagentUnit.New(-1) || CurrentVolume < _slipThreshold) &&
Owner.TryGetComponent(out SlipperyComponent? oldSlippery))
{
oldSlippery.Slippery = false;
}
else if (CurrentVolume >= _slipThreshold)
{
var newSlippery = Owner.EnsureComponent<SlipperyComponent>();
newSlippery.Slippery = true;
}
}
private void UpdateAppearance()
{
if (Owner.Deleted || EmptyHolder)
{
return;
}
// Opacity based on level of fullness to overflow
// Hard-cap lower bound for visibility reasons
var volumeScale = (CurrentVolume.Float() / OverflowVolume.Float()) * 0.75f + 0.25f;
var cappedScale = Math.Min(1.0f, volumeScale);
// Color based on the underlying solutioncomponent
Color newColor;
if (_recolor)
{
newColor = _contents.Color.WithAlpha(cappedScale);
}
else
{
newColor = _spriteComponent.Color.WithAlpha(cappedScale);
}
_spriteComponent.Color = newColor;
_spriteComponent.Dirty();
}
/// <summary>
/// Will overflow this entity to neighboring entities if required
/// </summary>
private void CheckOverflow()
{
if (CurrentVolume <= _overflowVolume || _overflown)
{
return;
}
var nextPuddles = new List<PuddleComponent>() {this};
var overflownPuddles = new List<PuddleComponent>();
while (OverflowLeft > ReagentUnit.Zero && nextPuddles.Count > 0)
{
foreach (var next in nextPuddles.ToArray())
{
nextPuddles.Remove(next);
next._overflown = true;
overflownPuddles.Add(next);
var adjacentPuddles = next.GetAllAdjacentOverflow().ToArray();
if (OverflowLeft <= ReagentUnit.Epsilon * adjacentPuddles.Length)
{
break;
}
if (adjacentPuddles.Length == 0)
{
continue;
}
var numberOfAdjacent = ReagentUnit.New(adjacentPuddles.Length);
var overflowSplit = OverflowLeft / numberOfAdjacent;
foreach (var adjacent in adjacentPuddles)
{
var adjacentPuddle = adjacent();
var quantity = ReagentUnit.Min(overflowSplit, adjacentPuddle.OverflowVolume);
var spillAmount = _contents.SplitSolution(quantity);
adjacentPuddle.TryAddSolution(spillAmount, false, false, false);
nextPuddles.Add(adjacentPuddle);
}
}
}
foreach (var puddle in overflownPuddles)
{
puddle._overflown = false;
}
}
/// <summary>
/// Tries to get an adjacent coordinate to overflow to, unless it is blocked by a wall on the
/// same tile or the tile is empty
/// </summary>
/// <param name="direction">The direction to get the puddle from, respective to this one</param>
/// <param name="puddle">The puddle that was found or is to be created, or null if there
/// is a wall in the way</param>
/// <returns>true if a puddle was found or created, false otherwise</returns>
private bool TryGetAdjacentOverflow(Direction direction, [NotNullWhen(true)] out Func<PuddleComponent>? puddle)
{
puddle = default;
// We're most likely in space, do nothing.
if (!Owner.Transform.GridID.IsValid())
return false;
var mapGrid = _mapManager.GetGrid(Owner.Transform.GridID);
var coords = Owner.Transform.Coordinates;
if (!coords.Offset(direction).TryGetTileRef(out var tile))
{
return false;
}
// If space return early, let that spill go out into the void
if (tile.Value.Tile.IsEmpty)
{
return false;
}
if (!Owner.Transform.Anchored)
return false;
foreach (var entity in mapGrid.GetInDir(coords, direction))
{
if (Owner.EntityManager.ComponentManager.TryGetComponent(entity, out IPhysBody? physics) &&
(physics.CollisionLayer & (int) CollisionGroup.Impassable) != 0)
{
puddle = default;
return false;
}
if (Owner.EntityManager.ComponentManager.TryGetComponent(entity, out PuddleComponent? existingPuddle))
{
if (existingPuddle._overflown)
{
return false;
}
puddle = () => existingPuddle;
}
}
if (puddle == default)
{
puddle = () => Owner.EntityManager.SpawnEntity(Owner.Prototype?.ID, mapGrid.DirectionToGrid(coords, direction)).GetComponent<PuddleComponent>();
}
return true;
}
/// <summary>
/// Finds or creates adjacent puddles in random directions from this one
/// </summary>
/// <returns>Enumerable of the puddles found or to be created</returns>
private IEnumerable<Func<PuddleComponent>> GetAllAdjacentOverflow()
{
foreach (var direction in SharedDirectionExtensions.RandomDirections())
{
if (TryGetAdjacentOverflow(direction, out var puddle))
{
yield return puddle;
}
}
}
}
}

View File

@@ -0,0 +1,156 @@
#nullable enable
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Content.Server.Coordinates.Helpers;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Chemistry.Solution;
using Content.Shared.Chemistry.Solution.Components;
using Robust.Server.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
namespace Content.Server.Fluids.Components
{
public static class SpillExtensions
{
/// <summary>
/// Spills the specified solution at the entity's location if possible.
/// </summary>
/// <param name="entity">
/// The entity to use as a location to spill the solution at.
/// </param>
/// <param name="solution">Initial solution for the prototype.</param>
/// <param name="prototype">The prototype to use.</param>
/// <param name="sound">Play the spill sound.</param>
/// <returns>The puddle if one was created, null otherwise.</returns>
public static PuddleComponent? SpillAt(this Solution solution, IEntity entity, string prototype, bool sound = true)
{
return solution.SpillAt(entity.Transform.Coordinates, prototype, sound);
}
/// <summary>
/// Spills the specified solution at the entity's location if possible.
/// </summary>
/// <param name="entity">
/// The entity to use as a location to spill the solution at.
/// </param>
/// <param name="solution">Initial solution for the prototype.</param>
/// <param name="prototype">The prototype to use.</param>
/// <param name="puddle">The puddle if one was created, null otherwise.</param>
/// <param name="sound">Play the spill sound.</param>
/// <returns>True if a puddle was created, false otherwise.</returns>
public static bool TrySpillAt(this Solution solution, IEntity entity, string prototype, [NotNullWhen(true)] out PuddleComponent? puddle, bool sound = true)
{
puddle = solution.SpillAt(entity, prototype, sound);
return puddle != null;
}
/// <summary>
/// Spills solution at the specified grid coordinates.
/// </summary>
/// <param name="solution">Initial solution for the prototype.</param>
/// <param name="coordinates">The coordinates to spill the solution at.</param>
/// <param name="prototype">The prototype to use.</param>
/// <param name="sound">Whether or not to play the spill sound.</param>
/// <returns>The puddle if one was created, null otherwise.</returns>
public static PuddleComponent? SpillAt(this Solution solution, EntityCoordinates coordinates, string prototype, bool overflow = true, bool sound = true)
{
if (solution.TotalVolume == 0) return null;
var mapManager = IoCManager.Resolve<IMapManager>();
var entityManager = IoCManager.Resolve<IEntityManager>();
if (!mapManager.TryGetGrid(coordinates.GetGridId(entityManager), out var mapGrid)) return null; // Let's not spill to space.
return SpillAt(mapGrid.GetTileRef(coordinates), solution, prototype, overflow, sound);
}
/// <summary>
/// Spills the specified solution at the entity's location if possible.
/// </summary>
/// <param name="coordinates">The coordinates to spill the solution at.</param>
/// <param name="solution">Initial solution for the prototype.</param>
/// <param name="prototype">The prototype to use.</param>
/// <param name="puddle">The puddle if one was created, null otherwise.</param>
/// <param name="sound">Play the spill sound.</param>
/// <returns>True if a puddle was created, false otherwise.</returns>
public static bool TrySpillAt(this Solution solution, EntityCoordinates coordinates, string prototype, [NotNullWhen(true)] out PuddleComponent? puddle, bool sound = true)
{
puddle = solution.SpillAt(coordinates, prototype, sound);
return puddle != null;
}
public static bool TryGetPuddle(this TileRef tileRef, GridTileLookupSystem? gridTileLookupSystem, [NotNullWhen(true)] out PuddleComponent? puddle)
{
foreach (var entity in tileRef.GetEntitiesInTileFast(gridTileLookupSystem))
{
if (entity.TryGetComponent(out PuddleComponent? p))
{
puddle = p;
return true;
}
}
puddle = null;
return false;
}
public static PuddleComponent? SpillAt(this TileRef tileRef, Solution solution, string prototype, bool overflow = true, bool sound = true)
{
if (solution.TotalVolume <= 0) return null;
var mapManager = IoCManager.Resolve<IMapManager>();
var entityManager = IoCManager.Resolve<IEntityManager>();
var serverEntityManager = IoCManager.Resolve<IServerEntityManager>();
// If space return early, let that spill go out into the void
if (tileRef.Tile.IsEmpty) return null;
var gridId = tileRef.GridIndex;
if (!mapManager.TryGetGrid(gridId, out var mapGrid)) return null; // Let's not spill to invalid grids.
// Get normalized co-ordinate for spill location and spill it in the centre
// TODO: Does SnapGrid or something else already do this?
var spillGridCoords = mapGrid.GridTileToLocal(tileRef.GridIndices);
PuddleComponent? puddle = null;
var spilt = false;
var spillEntities = IoCManager.Resolve<IEntityLookup>().GetEntitiesIntersecting(mapGrid.ParentMapId, spillGridCoords.Position).ToArray();
foreach (var spillEntity in spillEntities)
{
if (spillEntity.TryGetComponent(out ISolutionInteractionsComponent? solutionContainerComponent) &&
solutionContainerComponent.CanRefill)
{
solutionContainerComponent.Refill(
solution.SplitSolution(ReagentUnit.Min(solutionContainerComponent.RefillSpaceAvailable, solutionContainerComponent.MaxSpillRefill))
);
}
}
foreach (var spillEntity in spillEntities)
{
if (!spillEntity.TryGetComponent(out PuddleComponent? puddleComponent)) continue;
if (!overflow && puddleComponent.WouldOverflow(solution)) return null;
if (!puddleComponent.TryAddSolution(solution, sound)) continue;
puddle = puddleComponent;
spilt = true;
break;
}
// Did we add to an existing puddle
if (spilt) return puddle;
var puddleEnt = serverEntityManager.SpawnEntity(prototype, spillGridCoords);
var newPuddleComponent = puddleEnt.GetComponent<PuddleComponent>();
newPuddleComponent.TryAddSolution(solution, sound);
return newPuddleComponent;
}
}
}

View File

@@ -0,0 +1,68 @@
using Content.Shared.ActionBlocker;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Chemistry.Solution.Components;
using Content.Shared.DragDrop;
using Content.Shared.Notification;
using Content.Shared.Verbs;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
namespace Content.Server.Fluids.Components
{
[RegisterComponent]
public class SpillableComponent : Component, IDropped
{
public override string Name => "Spillable";
/// <summary>
/// Transfers solution from the held container to the floor.
/// </summary>
[Verb]
private sealed class SpillTargetVerb : Verb<SpillableComponent>
{
protected override void GetData(IEntity user, SpillableComponent component, VerbData data)
{
if (!ActionBlockerSystem.CanInteract(user) ||
!component.Owner.TryGetComponent(out ISolutionInteractionsComponent? solutionComponent) ||
!solutionComponent.CanDrain)
{
data.Visibility = VerbVisibility.Invisible;
return;
}
data.Text = Loc.GetString("Spill liquid");
data.Visibility = solutionComponent.DrainAvailable > ReagentUnit.Zero
? VerbVisibility.Visible
: VerbVisibility.Disabled;
}
protected override void Activate(IEntity user, SpillableComponent component)
{
if (component.Owner.TryGetComponent<ISolutionInteractionsComponent>(out var solutionComponent))
{
if (!solutionComponent.CanDrain)
{
user.PopupMessage(user,
Loc.GetString("You can't pour anything from {0:theName}!", component.Owner));
}
if (solutionComponent.DrainAvailable <= 0)
{
user.PopupMessage(user, Loc.GetString("{0:theName} is empty!", component.Owner));
}
// Need this as when we split the component's owner may be deleted
solutionComponent.Drain(solutionComponent.DrainAvailable).SpillAt(component.Owner.Transform.Coordinates, "PuddleSmear");
}
}
}
void IDropped.Dropped(DroppedEventArgs eventArgs)
{
if (!eventArgs.Intentional && Owner.TryGetComponent(out ISolutionInteractionsComponent? solutionComponent))
{
solutionComponent.Drain(solutionComponent.DrainAvailable).SpillAt(Owner.Transform.Coordinates, "PuddleSmear");
}
}
}
}

View File

@@ -0,0 +1,224 @@
using System;
using System.Threading.Tasks;
using Content.Server.Chemistry.Components;
using Content.Shared.ActionBlocker;
using Content.Shared.Audio;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.Cooldown;
using Content.Shared.DragDrop;
using Content.Shared.Fluids;
using Content.Shared.Interaction;
using Content.Shared.Notification;
using Content.Shared.Vapor;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Player;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Server.Fluids.Components
{
[RegisterComponent]
class SprayComponent : SharedSprayComponent, IAfterInteract, IUse, IActivate, IDropped
{
public const float SprayDistance = 3f;
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly IServerEntityManager _serverEntityManager = default!;
[DataField("transferAmount")]
private ReagentUnit _transferAmount = ReagentUnit.New(10);
[DataField("spraySound")]
private string? _spraySound;
[DataField("sprayVelocity")]
private float _sprayVelocity = 1.5f;
[DataField("sprayAliveTime")]
private float _sprayAliveTime = 0.75f;
private TimeSpan _lastUseTime;
private TimeSpan _cooldownEnd;
[DataField("cooldownTime")]
private float _cooldownTime = 0.5f;
[DataField("sprayedPrototype")]
private string _vaporPrototype = "Vapor";
[DataField("vaporAmount")]
private int _vaporAmount = 1;
[DataField("vaporSpread")]
private float _vaporSpread = 90f;
[DataField("hasSafety")]
private bool _hasSafety;
[DataField("safety")]
private bool _safety = true;
[DataField("impulse")]
private float _impulse = 0f;
/// <summary>
/// The amount of solution to be sprayer from this solution when using it
/// </summary>
[ViewVariables]
public ReagentUnit TransferAmount
{
get => _transferAmount;
set => _transferAmount = value;
}
/// <summary>
/// The speed at which the vapor starts when sprayed
/// </summary>
[ViewVariables]
public float Velocity
{
get => _sprayVelocity;
set => _sprayVelocity = value;
}
public string? SpraySound => _spraySound;
public ReagentUnit CurrentVolume => Owner.GetComponentOrNull<SolutionContainerComponent>()?.CurrentVolume ?? ReagentUnit.Zero;
public override void Initialize()
{
base.Initialize();
Owner.EnsureComponentWarn(out SolutionContainerComponent _);
if (_hasSafety)
{
SetSafety(Owner, _safety);
}
}
async Task<bool> IAfterInteract.AfterInteract(AfterInteractEventArgs eventArgs)
{
if (!ActionBlockerSystem.CanInteract(eventArgs.User))
return false;
if (_hasSafety && _safety)
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("Its safety is on!"));
return true;
}
if (CurrentVolume <= 0)
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("It's empty!"));
return true;
}
var curTime = _gameTiming.CurTime;
if(curTime < _cooldownEnd)
return true;
var playerPos = eventArgs.User.Transform.Coordinates;
if (eventArgs.ClickLocation.GetGridId(_serverEntityManager) != playerPos.GetGridId(_serverEntityManager))
return true;
if (!Owner.TryGetComponent(out SolutionContainerComponent? contents))
return true;
var direction = (eventArgs.ClickLocation.Position - playerPos.Position).Normalized;
var threeQuarters = direction * 0.75f;
var quarter = direction * 0.25f;
var amount = Math.Max(Math.Min((contents.CurrentVolume / _transferAmount).Int(), _vaporAmount), 1);
var spread = _vaporSpread / amount;
for (var i = 0; i < amount; i++)
{
var rotation = new Angle(direction.ToAngle() + Angle.FromDegrees(spread * i) - Angle.FromDegrees(spread * (amount-1)/2));
var (_, diffPos) = eventArgs.ClickLocation - playerPos;
var diffNorm = diffPos.Normalized;
var diffLength = diffPos.Length;
var target = eventArgs.User.Transform.Coordinates.Offset((diffNorm + rotation.ToVec()).Normalized * diffLength + quarter);
if (target.TryDistance(Owner.EntityManager, playerPos, out var distance) && distance > SprayDistance)
target = eventArgs.User.Transform.Coordinates.Offset(diffNorm * SprayDistance);
var solution = contents.SplitSolution(_transferAmount);
if (solution.TotalVolume <= ReagentUnit.Zero)
break;
var vapor = _serverEntityManager.SpawnEntity(_vaporPrototype, playerPos.Offset(distance < 1 ? quarter : threeQuarters));
vapor.Transform.LocalRotation = rotation;
if (vapor.TryGetComponent(out AppearanceComponent? appearance)) // Vapor sprite should face down.
{
appearance.SetData(VaporVisuals.Rotation, -Angle.South + rotation);
appearance.SetData(VaporVisuals.Color, contents.Color.WithAlpha(1f));
appearance.SetData(VaporVisuals.State, true);
}
// Add the solution to the vapor and actually send the thing
var vaporComponent = vapor.GetComponent<VaporComponent>();
vaporComponent.TryAddSolution(solution);
vaporComponent.Start(rotation.ToVec(), _sprayVelocity, target, _sprayAliveTime);
if (_impulse > 0f && eventArgs.User.TryGetComponent(out IPhysBody? body))
{
body.ApplyLinearImpulse(-direction * _impulse);
}
}
//Play sound
if (!string.IsNullOrEmpty(_spraySound))
{
SoundSystem.Play(Filter.Pvs(Owner), _spraySound, Owner, AudioHelpers.WithVariation(0.125f));
}
_lastUseTime = curTime;
_cooldownEnd = _lastUseTime + TimeSpan.FromSeconds(_cooldownTime);
if (Owner.TryGetComponent(out ItemCooldownComponent? cooldown))
{
cooldown.CooldownStart = _lastUseTime;
cooldown.CooldownEnd = _cooldownEnd;
}
return true;
}
bool IUse.UseEntity(UseEntityEventArgs eventArgs)
{
ToggleSafety(eventArgs.User);
return true;
}
void IActivate.Activate(ActivateEventArgs eventArgs)
{
ToggleSafety(eventArgs.User);
}
private void ToggleSafety(IEntity user)
{
SetSafety(user, !_safety);
}
private void SetSafety(IEntity user, bool state)
{
if (!ActionBlockerSystem.CanInteract(user) || !_hasSafety)
return;
_safety = state;
if(Owner.TryGetComponent(out AppearanceComponent? appearance))
appearance.SetData(SprayVisuals.Safety, _safety);
}
void IDropped.Dropped(DroppedEventArgs eventArgs)
{
if(_hasSafety && Owner.TryGetComponent(out AppearanceComponent? appearance))
appearance.SetData(SprayVisuals.Safety, _safety);
}
}
}

View File

@@ -0,0 +1,48 @@
using Content.Server.Fluids.Components;
using JetBrains.Annotations;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Map;
namespace Content.Server.Fluids
{
[UsedImplicitly]
internal sealed class PuddleSystem : EntitySystem
{
[Dependency] private readonly IMapManager _mapManager = default!;
public override void Initialize()
{
base.Initialize();
_mapManager.TileChanged += HandleTileChanged;
}
public override void Shutdown()
{
base.Shutdown();
_mapManager.TileChanged -= HandleTileChanged;
}
//TODO: Replace all this with an Unanchored event that deletes the puddle
private void HandleTileChanged(object? sender, TileChangedEventArgs eventArgs)
{
// If this gets hammered you could probably queue up all the tile changes every tick but I doubt that would ever happen.
foreach (var puddle in ComponentManager.EntityQuery<PuddleComponent>(true))
{
// If the tile becomes space then delete it (potentially change by design)
var puddleTransform = puddle.Owner.Transform;
if(!puddleTransform.Anchored)
continue;
var grid = _mapManager.GetGrid(puddleTransform.GridID);
if (eventArgs.NewTile.GridIndex == puddle.Owner.Transform.GridID &&
grid.TileIndicesFor(puddleTransform.Coordinates) == eventArgs.NewTile.GridIndices &&
eventArgs.NewTile.Tile.IsEmpty)
{
puddle.Owner.QueueDelete();
break; // Currently it's one puddle per tile, if that changes remove this
}
}
}
}
}