Refactor disposals to ECS (#4418)

* ECS up disposals

Also significantly reduced its CPU usage.

* Make update significantly less S L O W

* Start units pressurised

* Client-side flush lerping

* Fix powered not toggling UI

* Fix flush button

* InteractUsing

* Minor optimisations

* Fix collisions

* Make visual state ECS

* Almost done with shared

* Most stuff moved

* Optimise item sleeping
This commit is contained in:
metalgearsloth
2021-08-12 13:40:38 +10:00
committed by GitHub
parent b17555903f
commit 4da74d0ee4
21 changed files with 756 additions and 1856 deletions

View File

@@ -4,11 +4,8 @@ using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Content.Server.Atmos;
using Content.Server.Atmos.EntitySystems;
using Content.Server.Construction.Components;
using Content.Server.Disposal.Tube.Components;
using Content.Server.Disposal.Unit.EntitySystems;
using Content.Server.DoAfter;
using Content.Server.Hands.Components;
using Content.Server.Power.Components;
using Content.Server.UserInterface;
using Content.Shared.ActionBlocker;
@@ -16,49 +13,27 @@ using Content.Shared.Acts;
using Content.Shared.Atmos;
using Content.Shared.Disposal.Components;
using Content.Shared.DragDrop;
using Content.Shared.Interaction;
using Content.Shared.Movement;
using Content.Shared.Notification.Managers;
using Content.Shared.Sound;
using Content.Shared.Throwing;
using Content.Shared.Verbs;
using Robust.Server.GameObjects;
using Robust.Shared.Audio;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Player;
using Robust.Shared.Random;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
namespace Content.Server.Disposal.Unit.Components
{
[RegisterComponent]
[ComponentReference(typeof(SharedDisposalUnitComponent))]
[ComponentReference(typeof(IActivate))]
[ComponentReference(typeof(IInteractUsing))]
public class DisposalUnitComponent : SharedDisposalUnitComponent, IInteractHand, IActivate, IInteractUsing, IThrowCollide, IGasMixtureHolder, IDestroyAct
public class DisposalUnitComponent : SharedDisposalUnitComponent, IGasMixtureHolder, IDestroyAct
{
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly IMapManager _mapManager = default!;
public override string Name => "DisposalUnit";
/// <summary>
/// The delay for an entity trying to move out of this unit.
/// </summary>
private static readonly TimeSpan ExitAttemptDelay = TimeSpan.FromSeconds(0.5);
/// <summary>
/// Last time that an entity tried to exit this disposal unit.
/// </summary>
[ViewVariables]
private TimeSpan _lastExitAttempt;
public TimeSpan LastExitAttempt;
/// <summary>
/// The current pressure of this disposal unit.
@@ -66,19 +41,15 @@ namespace Content.Server.Disposal.Unit.Components
/// </summary>
[ViewVariables]
[DataField("pressure")]
private float _pressure;
private bool _engaged;
public float Pressure = 1f;
[ViewVariables(VVAccess.ReadWrite)]
[DataField("autoEngageTime")]
private readonly TimeSpan _automaticEngageTime = TimeSpan.FromSeconds(30);
public readonly TimeSpan _automaticEngageTime = TimeSpan.FromSeconds(30);
[ViewVariables(VVAccess.ReadWrite)]
[DataField("flushDelay")]
private readonly TimeSpan _flushDelay = TimeSpan.FromSeconds(3);
[DataField("clickSound")] private SoundSpecifier _clickSound = new SoundPathSpecifier("/Audio/Machines/machine_switch.ogg");
public readonly TimeSpan FlushDelay = TimeSpan.FromSeconds(3);
/// <summary>
/// Delay from trying to enter disposals ourselves.
@@ -97,88 +68,33 @@ namespace Content.Server.Disposal.Unit.Components
/// Token used to cancel the automatic engage of a disposal unit
/// after an entity enters it.
/// </summary>
private CancellationTokenSource? _automaticEngageToken;
public CancellationTokenSource? AutomaticEngageToken;
/// <summary>
/// Container of entities inside this disposal unit.
/// </summary>
[ViewVariables]
private Container _container = default!;
[ViewVariables] public Container Container = default!;
[ViewVariables] public IReadOnlyList<IEntity> ContainedEntities => _container.ContainedEntities;
[ViewVariables] public IReadOnlyList<IEntity> ContainedEntities => Container.ContainedEntities;
[ViewVariables]
public bool Powered =>
!Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver) ||
receiver.Powered;
[ViewVariables]
private PressureState State => _pressure >= 1 ? PressureState.Ready : PressureState.Pressurizing;
[ViewVariables] public PressureState State => Pressure >= 1 ? PressureState.Ready : PressureState.Pressurizing;
[ViewVariables(VVAccess.ReadWrite)]
private bool Engaged
{
get => _engaged;
set
{
var oldEngaged = _engaged;
_engaged = value;
public bool Engaged { get; set; }
if (oldEngaged == value)
{
return;
}
UpdateVisualState();
}
}
[ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(DisposalUnitUiKey.Key);
[ViewVariables] public BoundUserInterface? UserInterface => Owner.GetUIOrNull(DisposalUnitUiKey.Key);
[DataField("air")]
public GasMixture Air { get; set; } = new GasMixture(Atmospherics.CellVolume);
public override bool CanInsert(IEntity entity)
{
if (!base.CanInsert(entity))
return false;
return _container.CanInsert(entity);
}
private void TryQueueEngage()
{
if (!Powered && ContainedEntities.Count == 0)
{
return;
}
_automaticEngageToken = new CancellationTokenSource();
Owner.SpawnTimer(_automaticEngageTime, () =>
{
if (!TryFlush())
{
TryQueueEngage();
}
}, _automaticEngageToken.Token);
}
private void AfterInsert(IEntity entity)
{
TryQueueEngage();
if (entity.TryGetComponent(out ActorComponent? actor))
{
UserInterface?.Close(actor.PlayerSession);
}
UpdateVisualState();
}
public async Task<bool> TryInsert(IEntity entity, IEntity? user = default)
{
if (!CanInsert(entity))
if (!EntitySystem.Get<DisposalUnitSystem>().CanInsert(this, entity))
return false;
var delay = user == entity ? _entryDelay : _draggedEntryDelay;
@@ -204,130 +120,14 @@ namespace Content.Server.Disposal.Unit.Components
return false;
}
if (!_container.Insert(entity))
if (!Container.Insert(entity))
return false;
AfterInsert(entity);
EntitySystem.Get<DisposalUnitSystem>().AfterInsert(this, entity);
return true;
}
private bool TryDrop(IEntity user, IEntity entity)
{
if (!user.TryGetComponent(out HandsComponent? hands))
{
return false;
}
if (!CanInsert(entity) || !hands.Drop(entity, _container))
{
return false;
}
AfterInsert(entity);
return true;
}
private void Remove(IEntity entity)
{
_container.Remove(entity);
if (ContainedEntities.Count == 0)
{
_automaticEngageToken?.Cancel();
_automaticEngageToken = null;
}
UpdateVisualState();
}
private bool CanFlush()
{
return _pressure >= 1 && Powered && Anchored;
}
private void ToggleEngage()
{
Engaged ^= true;
if (Engaged && CanFlush())
{
Owner.SpawnTimer(_flushDelay, () => TryFlush());
}
}
public bool TryFlush()
{
if (!CanFlush())
{
return false;
}
var grid = _mapManager.GetGrid(Owner.Transform.GridID);
var coords = Owner.Transform.Coordinates;
var entry = grid.GetLocal(coords)
.FirstOrDefault(entity => Owner.EntityManager.ComponentManager.HasComponent<DisposalEntryComponent>(entity));
if (entry == default)
{
return false;
}
var entryComponent = Owner.EntityManager.ComponentManager.GetComponent<DisposalEntryComponent>(entry);
var atmosphereSystem = EntitySystem.Get<AtmosphereSystem>();
if (atmosphereSystem.GetTileMixture(Owner.Transform.Coordinates, true) is {Temperature: > 0} environment)
{
var transferMoles = 0.1f * (0.05f * Atmospherics.OneAtmosphere * 1.01f - Air.Pressure) * Air.Volume / (environment.Temperature * Atmospherics.R);
Air = environment.Remove(transferMoles);
}
entryComponent.TryInsert(this);
_automaticEngageToken?.Cancel();
_automaticEngageToken = null;
_pressure = 0;
Engaged = false;
UpdateVisualState(true);
UpdateInterface();
return true;
}
public void TryEjectContents()
{
foreach (var entity in _container.ContainedEntities.ToArray())
{
Remove(entity);
}
}
private void TogglePower()
{
if (!Owner.TryGetComponent(out ApcPowerReceiverComponent? receiver))
{
return;
}
receiver.PowerDisabled = !receiver.PowerDisabled;
UpdateInterface();
}
private void UpdateInterface()
{
string stateString;
stateString = Loc.GetString($"{State}");
var state = new DisposalUnitBoundUserInterfaceState(Owner.Name, stateString, _pressure, Powered, Engaged);
UserInterface?.SetState(state);
}
private bool PlayerCanUse(IEntity? player)
{
if (player == null)
@@ -346,7 +146,7 @@ namespace Content.Server.Disposal.Unit.Components
return true;
}
private void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj)
public void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj)
{
if (obj.Session.AttachedEntity == null)
{
@@ -366,259 +166,25 @@ namespace Content.Server.Disposal.Unit.Components
switch (message.Button)
{
case UiButton.Eject:
TryEjectContents();
EntitySystem.Get<DisposalUnitSystem>().TryEjectContents(this);
break;
case UiButton.Engage:
ToggleEngage();
EntitySystem.Get<DisposalUnitSystem>().ToggleEngage(this);
break;
case UiButton.Power:
TogglePower();
SoundSystem.Play(Filter.Pvs(Owner), _clickSound.GetSound(), Owner, AudioParams.Default.WithVolume(-2f));
EntitySystem.Get<DisposalUnitSystem>().TogglePower(this);
SoundSystem.Play(Filter.Pvs(Owner), "/Audio/Machines/machine_switch.ogg", Owner, AudioParams.Default.WithVolume(-2f));
break;
default:
throw new ArgumentOutOfRangeException();
}
}
public void UpdateVisualState()
{
UpdateVisualState(false);
}
private void UpdateVisualState(bool flush)
{
if (!Owner.TryGetComponent(out AppearanceComponent? appearance))
{
return;
}
if (!Anchored)
{
appearance.SetData(Visuals.VisualState, VisualState.UnAnchored);
appearance.SetData(Visuals.Handle, HandleState.Normal);
appearance.SetData(Visuals.Light, LightState.Off);
return;
}
else if (_pressure < 1)
{
appearance.SetData(Visuals.VisualState, VisualState.Charging);
}
else
{
appearance.SetData(Visuals.VisualState, VisualState.Anchored);
}
appearance.SetData(Visuals.Handle, Engaged
? HandleState.Engaged
: HandleState.Normal);
if (!Powered)
{
appearance.SetData(Visuals.Light, LightState.Off);
return;
}
if (flush)
{
appearance.SetData(Visuals.VisualState, VisualState.Flushing);
appearance.SetData(Visuals.Light, LightState.Off);
return;
}
if (ContainedEntities.Count > 0)
{
appearance.SetData(Visuals.Light, LightState.Full);
return;
}
appearance.SetData(Visuals.Light, _pressure < 1
? LightState.Charging
: LightState.Ready);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
if (!Powered)
{
return;
}
var oldPressure = _pressure;
_pressure = _pressure + frameTime > 1
? 1
: _pressure + 0.05f * frameTime;
if (oldPressure < 1 && _pressure >= 1)
{
UpdateVisualState();
if (Engaged)
{
TryFlush();
}
}
// TODO: Ideally we'd just send the start and end and client could lerp as the bandwidth would be way lower
if (_pressure < 1.0f || oldPressure < 1.0f && _pressure >= 1.0f)
{
UpdateInterface();
}
}
private void PowerStateChanged(PowerChangedMessage args)
{
if (!args.Powered)
{
_automaticEngageToken?.Cancel();
_automaticEngageToken = null;
}
UpdateVisualState();
if (Engaged && !TryFlush())
{
TryQueueEngage();
}
}
protected override void Initialize()
{
base.Initialize();
_container = ContainerHelpers.EnsureContainer<Container>(Owner, Name);
if (UserInterface != null)
{
UserInterface.OnReceiveMessage += OnUiReceiveMessage;
}
UpdateInterface();
}
protected override void Startup()
{
base.Startup();
if(!Owner.HasComponent<AnchorableComponent>())
{
Logger.WarningS("VitalComponentMissing", $"Disposal unit {Owner.Uid} is missing an {nameof(AnchorableComponent)}");
}
UpdateVisualState();
UpdateInterface();
}
protected override void OnRemove()
{
foreach (var entity in _container.ContainedEntities.ToArray())
{
_container.ForceRemove(entity);
}
UserInterface?.CloseAll();
_automaticEngageToken?.Cancel();
_automaticEngageToken = null;
_container = null!;
base.OnRemove();
}
public override void HandleMessage(ComponentMessage message, IComponent? component)
{
base.HandleMessage(message, component);
switch (message)
{
case RelayMovementEntityMessage msg:
if (!msg.Entity.TryGetComponent(out HandsComponent? hands) ||
hands.Count == 0 ||
_gameTiming.CurTime < _lastExitAttempt + ExitAttemptDelay)
{
break;
}
_lastExitAttempt = _gameTiming.CurTime;
Remove(msg.Entity);
break;
case PowerChangedMessage powerChanged:
PowerStateChanged(powerChanged);
break;
}
}
bool IsValidInteraction(ITargetedInteractEventArgs eventArgs)
{
if (!EntitySystem.Get<ActionBlockerSystem>().CanInteract(eventArgs.User))
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("ui-disposal-unit-is-valid-interaction-cannot=interact"));
return false;
}
if (eventArgs.User.IsInContainer())
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("ui-disposal-unit-is-valid-interaction-cannot-reach"));
return false;
}
// This popup message doesn't appear on clicks, even when code was seperate. Unsure why.
if (!eventArgs.User.HasComponent<IHandsComponent>())
{
Owner.PopupMessage(eventArgs.User, Loc.GetString("ui-disposal-unit-is-valid-interaction-no-hands"));
return false;
}
return true;
}
bool IInteractHand.InteractHand(InteractHandEventArgs eventArgs)
{
if (!eventArgs.User.TryGetComponent(out ActorComponent? actor))
{
return false;
}
// Duplicated code here, not sure how else to get actor inside to make UserInterface happy.
if (IsValidInteraction(eventArgs))
{
UserInterface?.Open(actor.PlayerSession);
return true;
}
return false;
}
void IActivate.Activate(ActivateEventArgs eventArgs)
{
if (!eventArgs.User.TryGetComponent(out ActorComponent? actor))
{
return;
}
if (IsValidInteraction(eventArgs))
{
UserInterface?.Open(actor.PlayerSession);
}
return;
}
async Task<bool> IInteractUsing.InteractUsing(InteractUsingEventArgs eventArgs)
{
return TryDrop(eventArgs.User, eventArgs.Using);
}
public override bool CanDragDropOn(DragDropEvent eventArgs)
{
// Base is redundant given this already calls the base CanInsert
// If that changes then update this
return CanInsert(eventArgs.Dragged);
return EntitySystem.Get<DisposalUnitSystem>().CanInsert(this, eventArgs.Dragged);
}
public override bool DragDropOn(DragDropEvent eventArgs)
@@ -627,18 +193,6 @@ namespace Content.Server.Disposal.Unit.Components
return true;
}
void IThrowCollide.HitBy(ThrowCollideEventArgs eventArgs)
{
if (!CanInsert(eventArgs.Thrown) ||
IoCManager.Resolve<IRobustRandom>().NextDouble() > 0.75 ||
!_container.Insert(eventArgs.Thrown))
{
return;
}
AfterInsert(eventArgs.Thrown);
}
[Verb]
private sealed class SelfInsertVerb : Verb<DisposalUnitComponent>
{
@@ -682,14 +236,13 @@ namespace Content.Server.Disposal.Unit.Components
protected override void Activate(IEntity user, DisposalUnitComponent component)
{
component.Engaged = true;
component.TryFlush();
EntitySystem.Get<DisposalUnitSystem>().Engage(component);
}
}
void IDestroyAct.OnDestroy(DestructionEventArgs eventArgs)
{
TryEjectContents();
EntitySystem.Get<DisposalUnitSystem>().TryEjectContents(this);
}
}
}

View File

@@ -1,28 +1,537 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Content.Server.Atmos.EntitySystems;
using Content.Server.Disposal.Unit.Components;
using Content.Server.Construction.Components;
using Content.Server.Disposal.Tube.Components;
using Content.Server.Hands.Components;
using Content.Server.Items;
using Content.Server.Power.Components;
using Content.Shared.ActionBlocker;
using Content.Shared.Atmos;
using Content.Shared.Disposal;
using Content.Shared.Disposal.Components;
using Content.Shared.Interaction;
using Content.Shared.Movement;
using Content.Shared.Notification.Managers;
using Content.Shared.Throwing;
using Robust.Server.GameObjects;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Random;
namespace Content.Server.Disposal.Unit.EntitySystems
{
public sealed class DisposalUnitSystem : EntitySystem
public sealed class DisposalUnitSystem : SharedDisposalUnitSystem
{
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly IRobustRandom _robustRandom = default!;
[Dependency] private readonly AtmosphereSystem _atmosSystem = default!;
private readonly List<DisposalUnitComponent> _activeDisposals = new();
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<DisposalUnitComponent, AnchoredEvent>(OnAnchored);
SubscribeLocalEvent<DisposalUnitComponent, UnanchoredEvent>(OnUnanchored);
// TODO: Predict me when hands predicted
SubscribeLocalEvent<DisposalUnitComponent, RelayMovementEntityEvent>(HandleMovement);
SubscribeLocalEvent<DisposalUnitComponent, PowerChangedEvent>(HandlePowerChange);
// Component lifetime
SubscribeLocalEvent<DisposalUnitComponent, ComponentInit>(HandleDisposalInit);
SubscribeLocalEvent<DisposalUnitComponent, ComponentShutdown>(HandleDisposalShutdown);
SubscribeLocalEvent<DisposalUnitComponent, ThrowCollideEvent>(HandleThrowCollide);
// Interactions
SubscribeLocalEvent<DisposalUnitComponent, ActivateInWorldEvent>(HandleActivate);
SubscribeLocalEvent<DisposalUnitComponent, InteractHandEvent>(HandleInteractHand);
SubscribeLocalEvent<DisposalUnitComponent, InteractUsingEvent>(HandleInteractUsing);
}
private static void OnAnchored(EntityUid uid, DisposalUnitComponent component, AnchoredEvent args)
public override void Update(float frameTime)
{
component.UpdateVisualState();
base.Update(frameTime);
for (var i = _activeDisposals.Count - 1; i >= 0; i--)
{
var comp = _activeDisposals[i];
if (!Update(comp, frameTime)) continue;
_activeDisposals.RemoveAt(i);
}
}
private static void OnUnanchored(EntityUid uid, DisposalUnitComponent component, UnanchoredEvent args)
#region UI Handlers
public void ToggleEngage(DisposalUnitComponent component)
{
component.UpdateVisualState();
component.TryEjectContents();
component.Engaged ^= true;
if (component.Engaged)
{
Engage(component);
}
else
{
Disengage(component);
}
}
public void TogglePower(DisposalUnitComponent component)
{
if (!ComponentManager.TryGetComponent(component.Owner.Uid, out ApcPowerReceiverComponent? receiver))
{
return;
}
receiver.PowerDisabled = !receiver.PowerDisabled;
UpdateInterface(component, receiver.Powered);
}
#endregion
#region Eventbus Handlers
private void HandleActivate(EntityUid uid, DisposalUnitComponent component, ActivateInWorldEvent args)
{
if (!args.User.TryGetComponent(out ActorComponent? actor))
{
return;
}
args.Handled = true;
if (IsValidInteraction(args))
{
component.UserInterface?.Open(actor.PlayerSession);
}
}
private void HandleInteractHand(EntityUid uid, DisposalUnitComponent component, InteractHandEvent args)
{
if (!args.User.TryGetComponent(out ActorComponent? actor)) return;
// Duplicated code here, not sure how else to get actor inside to make UserInterface happy.
if (!IsValidInteraction(args)) return;
component.UserInterface?.Open(actor.PlayerSession);
args.Handled = true;
}
private void HandleInteractUsing(EntityUid uid, DisposalUnitComponent component, InteractUsingEvent args)
{
if (!args.User.TryGetComponent(out HandsComponent? hands))
{
return;
}
if (!CanInsert(component, args.Used) || !hands.Drop(args.Used, component.Container))
{
return;
}
AfterInsert(component, args.Used);
args.Handled = true;
}
/// <summary>
/// Thrown items have a chance of bouncing off the unit and not going in.
/// </summary>
private void HandleThrowCollide(EntityUid uid, DisposalUnitComponent component, ThrowCollideEvent args)
{
if (!CanInsert(component, args.Thrown) ||
_robustRandom.NextDouble() > 0.75 ||
!component.Container.Insert(args.Thrown))
{
return;
}
AfterInsert(component, args.Thrown);
}
private void HandleDisposalInit(EntityUid uid, DisposalUnitComponent component, ComponentInit args)
{
component.Container = component.Owner.EnsureContainer<Container>(component.Name);
if (component.UserInterface != null)
{
component.UserInterface.OnReceiveMessage += component.OnUiReceiveMessage;
}
UpdateInterface(component, component.Powered);
if (!component.Owner.HasComponent<AnchorableComponent>())
{
Logger.WarningS("VitalComponentMissing", $"Disposal unit {uid} is missing an {nameof(AnchorableComponent)}");
}
}
private void HandleDisposalShutdown(EntityUid uid, DisposalUnitComponent component, ComponentShutdown args)
{
foreach (var entity in component.Container.ContainedEntities.ToArray())
{
component.Container.ForceRemove(entity);
}
component.UserInterface?.CloseAll();
component.AutomaticEngageToken?.Cancel();
component.AutomaticEngageToken = null;
component.Container = null!;
_activeDisposals.Remove(component);
}
private void HandlePowerChange(EntityUid uid, DisposalUnitComponent component, PowerChangedEvent args)
{
// TODO: Need to check the other stuff.
if (!args.Powered)
{
component.AutomaticEngageToken?.Cancel();
component.AutomaticEngageToken = null;
}
HandleStateChange(component, args.Powered && component.State == SharedDisposalUnitComponent.PressureState.Pressurizing);
UpdateVisualState(component);
UpdateInterface(component, args.Powered);
if (component.Engaged && !TryFlush(component))
{
TryQueueEngage(component);
}
}
/// <summary>
/// Add or remove this disposal from the active ones for updating.
/// </summary>
public void HandleStateChange(DisposalUnitComponent component, bool active)
{
if (active)
{
if (!_activeDisposals.Contains(component))
_activeDisposals.Add(component);
}
else
{
_activeDisposals.Remove(component);
}
}
private void HandleMovement(EntityUid uid, DisposalUnitComponent component, RelayMovementEntityEvent args)
{
var currentTime = GameTiming.CurTime;
if (!args.Entity.TryGetComponent(out HandsComponent? hands) ||
hands.Count == 0 ||
currentTime < component.LastExitAttempt + ExitAttemptDelay)
{
return;
}
component.LastExitAttempt = currentTime;
Remove(component, args.Entity);
}
private void OnAnchored(EntityUid uid, DisposalUnitComponent component, AnchoredEvent args)
{
UpdateVisualState(component);
}
private void OnUnanchored(EntityUid uid, DisposalUnitComponent component, UnanchoredEvent args)
{
UpdateVisualState(component);
TryEjectContents(component);
}
#endregion
/// <summary>
/// Work out if we can stop updating this disposals component i.e. full pressure and nothing colliding.
/// </summary>
private bool Update(DisposalUnitComponent component, float frameTime)
{
var oldPressure = component.Pressure;
component.Pressure = MathF.Min(1.0f, component.Pressure + PressurePerSecond * frameTime);
var state = component.State;
if (oldPressure < 1 && state == SharedDisposalUnitComponent.PressureState.Ready)
{
UpdateVisualState(component);
if (component.Engaged)
{
TryFlush(component);
}
}
Box2? disposalsBounds = null;
var count = component.RecentlyEjected.Count;
if (count > 0)
{
if (!component.Owner.TryGetComponent(out PhysicsComponent? disposalsBody))
{
component.RecentlyEjected.Clear();
}
else
{
disposalsBounds = disposalsBody.GetWorldAABB();
}
}
for (var i = component.RecentlyEjected.Count - 1; i >= 0; i--)
{
var uid = component.RecentlyEjected[i];
if (EntityManager.EntityExists(uid) &&
ComponentManager.TryGetComponent(uid, out PhysicsComponent? body))
{
// TODO: We need to use a specific collision method (which sloth hasn't coded yet) for actual bounds overlaps.
// Check for itemcomp as we won't just block the disposal unit "sleeping" for something it can't collide with anyway.
if (!ComponentManager.HasComponent<ItemComponent>(uid) && body.GetWorldAABB().Intersects(disposalsBounds!.Value)) continue;
component.RecentlyEjected.RemoveAt(i);
}
}
if (count != component.RecentlyEjected.Count)
component.Dirty();
return state == SharedDisposalUnitComponent.PressureState.Ready && component.RecentlyEjected.Count == 0;
}
private bool IsValidInteraction(ITargetedInteractEventArgs eventArgs)
{
if (!Get<ActionBlockerSystem>().CanInteract(eventArgs.User))
{
eventArgs.Target.PopupMessage(eventArgs.User, Loc.GetString("ui-disposal-unit-is-valid-interaction-cannot=interact"));
return false;
}
if (eventArgs.User.IsInContainer())
{
eventArgs.Target.PopupMessage(eventArgs.User, Loc.GetString("ui-disposal-unit-is-valid-interaction-cannot-reach"));
return false;
}
// This popup message doesn't appear on clicks, even when code was seperate. Unsure why.
if (!eventArgs.User.HasComponent<IHandsComponent>())
{
eventArgs.Target.PopupMessage(eventArgs.User, Loc.GetString("ui-disposal-unit-is-valid-interaction-no-hands"));
return false;
}
return true;
}
public bool TryFlush(DisposalUnitComponent component)
{
if (component.Deleted || !CanFlush(component))
{
return false;
}
var grid = _mapManager.GetGrid(component.Owner.Transform.GridID);
var coords = component.Owner.Transform.Coordinates;
var entry = grid.GetLocal(coords)
.FirstOrDefault(entity => EntityManager.ComponentManager.HasComponent<DisposalEntryComponent>(entity));
if (entry == default)
{
return false;
}
var air = component.Air;
var entryComponent = EntityManager.ComponentManager.GetComponent<DisposalEntryComponent>(entry);
if (_atmosSystem.GetTileMixture(component.Owner.Transform.Coordinates, true) is {Temperature: > 0} environment)
{
var transferMoles = 0.1f * (0.05f * Atmospherics.OneAtmosphere * 1.01f - air.Pressure) * air.Volume / (environment.Temperature * Atmospherics.R);
component.Air = environment.Remove(transferMoles);
}
entryComponent.TryInsert(component);
component.AutomaticEngageToken?.Cancel();
component.AutomaticEngageToken = null;
component.Pressure = 0;
component.Engaged = false;
HandleStateChange(component, true);
UpdateVisualState(component, true);
UpdateInterface(component, component.Powered);
return true;
}
public void UpdateInterface(DisposalUnitComponent component, bool powered)
{
var stateString = Loc.GetString($"{component.State}");
var state = new SharedDisposalUnitComponent.DisposalUnitBoundUserInterfaceState(component.Owner.Name, stateString, EstimatedFullPressure(component), powered, component.Engaged);
component.UserInterface?.SetState(state);
}
private TimeSpan EstimatedFullPressure(DisposalUnitComponent component)
{
if (component.State == SharedDisposalUnitComponent.PressureState.Ready) return TimeSpan.Zero;
var currentTime = GameTiming.CurTime;
var pressure = component.Pressure;
return TimeSpan.FromSeconds(currentTime.TotalSeconds + (1.0f - pressure) / PressurePerSecond);
}
public void UpdateVisualState(DisposalUnitComponent component)
{
UpdateVisualState(component, false);
}
public void UpdateVisualState(DisposalUnitComponent component, bool flush)
{
if (!component.Owner.TryGetComponent(out SharedAppearanceComponent? appearance))
{
return;
}
if (!component.Owner.Transform.Anchored)
{
appearance.SetData(SharedDisposalUnitComponent.Visuals.VisualState, SharedDisposalUnitComponent.VisualState.UnAnchored);
appearance.SetData(SharedDisposalUnitComponent.Visuals.Handle, SharedDisposalUnitComponent.HandleState.Normal);
appearance.SetData(SharedDisposalUnitComponent.Visuals.Light, SharedDisposalUnitComponent.LightState.Off);
return;
}
appearance.SetData(SharedDisposalUnitComponent.Visuals.VisualState, component.Pressure < 1 ? SharedDisposalUnitComponent.VisualState.Charging : SharedDisposalUnitComponent.VisualState.Anchored);
appearance.SetData(SharedDisposalUnitComponent.Visuals.Handle, component.Engaged
? SharedDisposalUnitComponent.HandleState.Engaged
: SharedDisposalUnitComponent.HandleState.Normal);
if (!component.Powered)
{
appearance.SetData(SharedDisposalUnitComponent.Visuals.Light, SharedDisposalUnitComponent.LightState.Off);
return;
}
if (flush)
{
appearance.SetData(SharedDisposalUnitComponent.Visuals.VisualState, SharedDisposalUnitComponent.VisualState.Flushing);
appearance.SetData(SharedDisposalUnitComponent.Visuals.Light, SharedDisposalUnitComponent.LightState.Off);
return;
}
if (component.ContainedEntities.Count > 0)
{
appearance.SetData(SharedDisposalUnitComponent.Visuals.Light, SharedDisposalUnitComponent.LightState.Full);
return;
}
appearance.SetData(SharedDisposalUnitComponent.Visuals.Light, component.Pressure < 1
? SharedDisposalUnitComponent.LightState.Charging
: SharedDisposalUnitComponent.LightState.Ready);
}
public void Remove(DisposalUnitComponent component, IEntity entity)
{
component.Container.Remove(entity);
if (component.ContainedEntities.Count == 0)
{
component.AutomaticEngageToken?.Cancel();
component.AutomaticEngageToken = null;
}
if (!component.RecentlyEjected.Contains(entity.Uid))
component.RecentlyEjected.Add(entity.Uid);
component.Dirty();
HandleStateChange(component, true);
UpdateVisualState(component);
}
public bool CanFlush(DisposalUnitComponent component)
{
return component.State == SharedDisposalUnitComponent.PressureState.Ready && component.Powered && component.Owner.Transform.Anchored;
}
public void Engage(DisposalUnitComponent component)
{
component.Engaged = true;
UpdateVisualState(component);
UpdateInterface(component, component.Powered);
if (CanFlush(component))
{
component.Owner.SpawnTimer(component.FlushDelay, () => TryFlush(component));
}
}
public void Disengage(DisposalUnitComponent component)
{
component.Engaged = false;
UpdateVisualState(component);
UpdateInterface(component, component.Powered);
}
/// <summary>
/// Remove all entities currently in the disposal unit.
/// </summary>
public void TryEjectContents(DisposalUnitComponent component)
{
foreach (var entity in component.Container.ContainedEntities.ToArray())
{
Remove(component, entity);
}
}
public override bool CanInsert(SharedDisposalUnitComponent component, IEntity entity)
{
if (!base.CanInsert(component, entity) || component is not DisposalUnitComponent serverComp)
return false;
return serverComp.Container.CanInsert(entity);
}
/// <summary>
/// If something is inserted (or the likes) then we'll queue up a flush in the future.
/// </summary>
public void TryQueueEngage(DisposalUnitComponent component)
{
if (component.Deleted || !component.Powered && component.ContainedEntities.Count == 0)
{
return;
}
component.AutomaticEngageToken = new CancellationTokenSource();
component.Owner.SpawnTimer(component._automaticEngageTime, () =>
{
if (!TryFlush(component))
{
TryQueueEngage(component);
}
}, component.AutomaticEngageToken.Token);
}
public void AfterInsert(DisposalUnitComponent component, IEntity entity)
{
TryQueueEngage(component);
if (entity.TryGetComponent(out ActorComponent? actor))
{
component.UserInterface?.Close(actor.PlayerSession);
}
UpdateVisualState(component);
}
}
}