From 51e7a39bade7aad1657b033116e79f1900c490fa Mon Sep 17 00:00:00 2001 From: Pok <113675512+Pok27@users.noreply.github.com> Date: Fri, 9 Jan 2026 16:18:07 +0200 Subject: [PATCH] Predict DrainSystem (#41711) * DrainSystem-move-to-shared * random * review * review 2 * Apply suggestions from code review --------- Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com> --- .../Fluids/Components/DrainComponent.cs | 22 ++- .../Fluids/EntitySystems/DrainSystem.cs | 183 ++++++++++-------- Content.Shared/Fluids/SharedDrainSystem.cs | 12 -- 3 files changed, 116 insertions(+), 101 deletions(-) rename {Content.Server => Content.Shared}/Fluids/EntitySystems/DrainSystem.cs (53%) delete mode 100644 Content.Shared/Fluids/SharedDrainSystem.cs diff --git a/Content.Shared/Fluids/Components/DrainComponent.cs b/Content.Shared/Fluids/Components/DrainComponent.cs index a7d7bbb3ad..83ef676b4d 100644 --- a/Content.Shared/Fluids/Components/DrainComponent.cs +++ b/Content.Shared/Fluids/Components/DrainComponent.cs @@ -1,7 +1,10 @@ using Content.Shared.Chemistry.Components; +using Content.Shared.Fluids.EntitySystems; using Content.Shared.Tag; using Robust.Shared.Audio; +using Robust.Shared.GameStates; using Robust.Shared.Prototypes; +using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom; namespace Content.Shared.Fluids.Components; @@ -13,18 +16,25 @@ namespace Content.Shared.Fluids.Components; /// When the drain is full, it can be unclogged using a plunger (i.e. an entity with a Plunger tag attached). /// Later this can be refactored into a proper Plunger component if needed. /// -[RegisterComponent, Access(typeof(SharedDrainSystem))] +[RegisterComponent, NetworkedComponent, AutoGenerateComponentState, AutoGenerateComponentPause] +[Access(typeof(DrainSystem))] public sealed partial class DrainComponent : Component { public const string SolutionName = "drainBuffer"; public static readonly ProtoId PlungerTag = "Plunger"; + /// + /// The solution that the drain is using. + /// [ViewVariables] public Entity? Solution = null; - [DataField] - public float Accumulator = 0f; + /// + /// Next time the drain should perform its draining. + /// + [DataField(customTypeSerializer: typeof(TimeOffsetSerializer)), AutoNetworkedField, AutoPausedField] + public TimeSpan NextUpdate = TimeSpan.Zero; /// /// If true, automatically transfers solutions from nearby puddles and drains them. True for floor drains; @@ -36,7 +46,7 @@ public sealed partial class DrainComponent : Component /// /// How many units per second the drain can absorb from the surrounding puddles. /// Divided by puddles, so if there are 5 puddles this will take 1/5 from each puddle. - /// This will stay fixed to 1 second no matter what DrainFrequency is. + /// This will stay fixed to 1 second no matter what DrainInterval is. /// [DataField] public float UnitsPerSecond = 6f; @@ -55,11 +65,11 @@ public sealed partial class DrainComponent : Component public float Range = 2.5f; /// - /// How often in seconds the drain checks for puddles around it. + /// How often the drain checks for puddles around it. /// If the EntityQuery seems a bit unperformant this can be increased. /// [DataField] - public float DrainFrequency = 1f; + public TimeSpan DrainInterval = TimeSpan.FromSeconds(1); /// /// How much time it takes to unclog it with a plunger diff --git a/Content.Server/Fluids/EntitySystems/DrainSystem.cs b/Content.Shared/Fluids/EntitySystems/DrainSystem.cs similarity index 53% rename from Content.Server/Fluids/EntitySystems/DrainSystem.cs rename to Content.Shared/Fluids/EntitySystems/DrainSystem.cs index 84718add5f..a6729b1bcd 100644 --- a/Content.Server/Fluids/EntitySystems/DrainSystem.cs +++ b/Content.Shared/Fluids/EntitySystems/DrainSystem.cs @@ -1,64 +1,75 @@ -using Content.Server.DoAfter; -using Content.Server.Popups; -using Content.Shared.Chemistry.EntitySystems; using Content.Shared.Audio; using Content.Shared.Chemistry.Components.SolutionManager; +using Content.Shared.Chemistry.EntitySystems; using Content.Shared.Database; using Content.Shared.DoAfter; using Content.Shared.Examine; using Content.Shared.FixedPoint; -using Content.Shared.Fluids; using Content.Shared.Fluids.Components; using Content.Shared.Interaction; +using Content.Shared.Popups; +using Content.Shared.Random.Helpers; using Content.Shared.Tag; using Content.Shared.Verbs; using Robust.Shared.Audio.Systems; +using Robust.Shared.Containers; using Robust.Shared.Prototypes; using Robust.Shared.Random; +using Robust.Shared.Serialization; +using Robust.Shared.Timing; using Robust.Shared.Utility; -namespace Content.Server.Fluids.EntitySystems; +namespace Content.Shared.Fluids.EntitySystems; -public sealed class DrainSystem : SharedDrainSystem +/// +/// Handles the draining of solutions from containers into drains. +/// +public sealed class DrainSystem : EntitySystem { [Dependency] private readonly EntityLookupSystem _lookup = default!; - [Dependency] private readonly SharedSolutionContainerSystem _solutionContainerSystem = default!; - [Dependency] private readonly SharedAmbientSoundSystem _ambientSoundSystem = default!; - [Dependency] private readonly SharedAudioSystem _audioSystem = default!; - [Dependency] private readonly PopupSystem _popupSystem = default!; - [Dependency] private readonly TagSystem _tagSystem = default!; - [Dependency] private readonly DoAfterSystem _doAfterSystem = default!; - [Dependency] private readonly PuddleSystem _puddleSystem = default!; + [Dependency] private readonly IPrototypeManager _prototype = default!; [Dependency] private readonly IRobustRandom _random = default!; - [Dependency] private readonly IPrototypeManager _prototypeManager = default!; + [Dependency] private readonly SharedAmbientSoundSystem _ambientSound = default!; + [Dependency] private readonly SharedAudioSystem _audio = default!; + [Dependency] private readonly SharedDoAfterSystem _doAfter = default!; + [Dependency] private readonly SharedPopupSystem _popup = default!; + [Dependency] private readonly SharedPuddleSystem _puddle = default!; + [Dependency] private readonly SharedSolutionContainerSystem _solutionContainerSystem = default!; + [Dependency] private readonly TagSystem _tag = default!; + [Dependency] private readonly IGameTiming _timing = default!; - private readonly HashSet> _puddles = new(); + private readonly HashSet> _puddles = []; + /// public override void Initialize() { base.Initialize(); + SubscribeLocalEvent(OnDrainMapInit); SubscribeLocalEvent>(AddEmptyVerb); SubscribeLocalEvent(OnExamined); SubscribeLocalEvent(OnInteract); SubscribeLocalEvent(OnDoAfter); + SubscribeLocalEvent(OnEntRemoved); } private void OnDrainMapInit(Entity ent, ref MapInitEvent args) { // Randomise puddle drains so roundstart ones don't all dump at the same time. - ent.Comp.Accumulator = _random.NextFloat(ent.Comp.DrainFrequency); + ent.Comp.NextUpdate = _timing.CurTime + _random.Next(ent.Comp.DrainInterval); + Dirty(ent); } - private void AddEmptyVerb(Entity entity, ref GetVerbsEvent args) + private void AddEmptyVerb(Entity ent, ref GetVerbsEvent args) { if (!args.CanAccess || !args.CanInteract || args.Using == null) return; - if (!TryComp(args.Using, out SpillableComponent? spillable) || - !TryComp(args.Target, out DrainComponent? drain)) + if (!HasComp(args.Using) || + !TryComp(args.Target, out var drain)) return; + var user = args.User; var used = args.Using.Value; var target = args.Target; Verb verb = new() @@ -66,76 +77,68 @@ public sealed class DrainSystem : SharedDrainSystem Text = Loc.GetString("drain-component-empty-verb-inhand", ("object", Name(used))), Act = () => { - Empty(used, spillable, target, drain); + Empty((target, drain), user, used); }, Impact = LogImpact.Low, Icon = new SpriteSpecifier.Texture(new ResPath("/Textures/Interface/VerbIcons/eject.svg.192dpi.png")) - }; args.Verbs.Add(verb); } - private void Empty(EntityUid container, SpillableComponent spillable, EntityUid target, DrainComponent drain) + private void Empty(Entity ent, EntityUid user, EntityUid container) { - // Find the solution in the container that is emptied + // Find the solution in the container that is emptied. if (!_solutionContainerSystem.TryGetDrainableSolution(container, out var containerSoln, out var containerSolution) || containerSolution.Volume == FixedPoint2.Zero) { - _popupSystem.PopupEntity( + _popup.PopupClient( Loc.GetString("drain-component-empty-verb-using-is-empty-message", ("object", container)), - container); + ent.Owner, + user); return; } - // try to find the drain's solution - if (!_solutionContainerSystem.ResolveSolution(target, DrainComponent.SolutionName, ref drain.Solution, out var drainSolution)) - { + // Try to find the drain's solution. + if (!_solutionContainerSystem.ResolveSolution(ent.Owner, DrainComponent.SolutionName, ref ent.Comp.Solution, out var drainSolution)) return; - } - - // Try to transfer as much solution as possible to the drain + // Try to transfer as much solution as possible to the drain. var amountToPutInDrain = drainSolution.AvailableVolume; var amountToSpillOnGround = containerSolution.Volume - drainSolution.AvailableVolume; if (amountToPutInDrain > 0) { var solutionToPutInDrain = _solutionContainerSystem.SplitSolution(containerSoln.Value, amountToPutInDrain); - _solutionContainerSystem.TryAddSolution(drain.Solution.Value, solutionToPutInDrain); + _solutionContainerSystem.TryAddSolution(ent.Comp.Solution.Value, solutionToPutInDrain); - _audioSystem.PlayPvs(drain.ManualDrainSound, target); - _ambientSoundSystem.SetAmbience(target, true); + _audio.PlayPredicted(ent.Comp.ManualDrainSound, ent.Owner, user); + _ambientSound.SetAmbience(ent.Owner, true); } - // Spill the remainder. - if (amountToSpillOnGround > 0) { var solutionToSpill = _solutionContainerSystem.SplitSolution(containerSoln.Value, amountToSpillOnGround); - _puddleSystem.TrySpillAt(Transform(target).Coordinates, solutionToSpill, out _); - _popupSystem.PopupEntity( - Loc.GetString("drain-component-empty-verb-target-is-full-message", ("object", target)), - container); + _puddle.TrySpillAt(Transform(ent.Owner).Coordinates, solutionToSpill, out _); + _popup.PopupClient( + Loc.GetString("drain-component-empty-verb-target-is-full-message", ("object", ent.Owner)), + ent.Owner, + user); } } public override void Update(float frameTime) { base.Update(frameTime); - var managerQuery = GetEntityQuery(); - var query = EntityQueryEnumerator(); - while (query.MoveNext(out var uid, out var drain)) + var query = EntityQueryEnumerator(); + var curTime = _timing.CurTime; + while (query.MoveNext(out var uid, out var drain, out var manager)) { - drain.Accumulator += frameTime; - if (drain.Accumulator < drain.DrainFrequency) - { + if (curTime < drain.NextUpdate) continue; - } - drain.Accumulator -= drain.DrainFrequency; - if (!managerQuery.TryGetComponent(uid, out var manager)) - continue; + drain.NextUpdate += drain.DrainInterval; + Dirty(uid, drain); // Best to do this one every second rather than once every tick... if (!_solutionContainerSystem.ResolveSolution((uid, manager), DrainComponent.SolutionName, ref drain.Solution, out var drainSolution)) @@ -143,15 +146,15 @@ public sealed class DrainSystem : SharedDrainSystem if (drainSolution.Volume <= 0 && !drain.AutoDrain) { - _ambientSoundSystem.SetAmbience(uid, false); + _ambientSound.SetAmbience(uid, false); continue; } - // Remove a bit from the buffer - _solutionContainerSystem.SplitSolution(drain.Solution.Value, (drain.UnitsDestroyedPerSecond * drain.DrainFrequency)); + // Remove a bit from the buffer. + _solutionContainerSystem.SplitSolution(drain.Solution.Value, drain.UnitsDestroyedPerSecond * drain.DrainInterval.TotalSeconds); // This will ensure that UnitsPerSecond is per second... - var amount = drain.UnitsPerSecond * drain.DrainFrequency; + var amount = drain.UnitsPerSecond * drain.DrainInterval.TotalSeconds; if (drain.AutoDrain) { @@ -160,11 +163,11 @@ public sealed class DrainSystem : SharedDrainSystem if (_puddles.Count == 0 && drainSolution.Volume <= 0) { - _ambientSoundSystem.SetAmbience(uid, false); + _ambientSound.SetAmbience(uid, false); continue; } - _ambientSoundSystem.SetAmbience(uid, true); + _ambientSound.SetAmbience(uid, true); amount /= _puddles.Count; @@ -174,7 +177,7 @@ public sealed class DrainSystem : SharedDrainSystem // but queuedelete should be pretty safe. if (!_solutionContainerSystem.ResolveSolution(puddle.Owner, puddle.Comp.SolutionName, ref puddle.Comp.Solution, out var puddleSolution)) { - QueueDel(puddle); + PredictedQueueDel(puddle); continue; } @@ -185,12 +188,10 @@ public sealed class DrainSystem : SharedDrainSystem var transferSolution = _solutionContainerSystem.SplitSolution(puddle.Comp.Solution.Value, FixedPoint2.Min(FixedPoint2.New(amount), puddleSolution.Volume, drainSolution.AvailableVolume)); - drainSolution.AddSolution(transferSolution, _prototypeManager); + drainSolution.AddSolution(transferSolution, _prototype); if (puddleSolution.Volume <= 0) - { - QueueDel(puddle); - } + PredictedQueueDel(puddle); } } @@ -198,11 +199,11 @@ public sealed class DrainSystem : SharedDrainSystem } } - private void OnExamined(Entity entity, ref ExaminedEvent args) + private void OnExamined(Entity ent, ref ExaminedEvent args) { if (!args.IsInDetailsRange || - !HasComp(entity) || - !_solutionContainerSystem.ResolveSolution(entity.Owner, DrainComponent.SolutionName, ref entity.Comp.Solution, out var drainSolution)) + !HasComp(ent) || + !_solutionContainerSystem.ResolveSolution(ent.Owner, DrainComponent.SolutionName, ref ent.Comp.Solution, out var drainSolution)) { return; } @@ -213,54 +214,70 @@ public sealed class DrainSystem : SharedDrainSystem args.PushMarkup(text); } - private void OnInteract(Entity entity, ref AfterInteractUsingEvent args) + private void OnInteract(Entity ent, ref AfterInteractUsingEvent args) { if (!args.CanReach || args.Target == null || - !_tagSystem.HasTag(args.Used, DrainComponent.PlungerTag) || - !_solutionContainerSystem.ResolveSolution(args.Target.Value, DrainComponent.SolutionName, ref entity.Comp.Solution, out var drainSolution)) + !_tag.HasTag(args.Used, DrainComponent.PlungerTag) || + !_solutionContainerSystem.ResolveSolution(args.Target.Value, DrainComponent.SolutionName, ref ent.Comp.Solution, out var drainSolution)) { return; } if (drainSolution.AvailableVolume > 0) { - _popupSystem.PopupEntity(Loc.GetString("drain-component-unclog-notapplicable", ("object", args.Target.Value)), args.Target.Value); + _popup.PopupPredicted(Loc.GetString("drain-component-unclog-notapplicable", ("object", args.Target.Value)), args.Target.Value, args.User); return; } - _audioSystem.PlayPvs(entity.Comp.PlungerSound, entity); + _audio.PlayPredicted(ent.Comp.PlungerSound, ent.Owner, args.User); - - var doAfterArgs = new DoAfterArgs(EntityManager, args.User, entity.Comp.UnclogDuration, new DrainDoAfterEvent(), entity, args.Target, args.Used) + var doAfterArgs = new DoAfterArgs(EntityManager, args.User, ent.Comp.UnclogDuration, new DrainDoAfterEvent(), ent, args.Target, args.Used) { BreakOnDamage = true, BreakOnMove = true, - BreakOnHandChange = true + BreakOnHandChange = true, }; - _doAfterSystem.TryStartDoAfter(doAfterArgs); + _doAfter.TryStartDoAfter(doAfterArgs); } - private void OnDoAfter(Entity entity, ref DrainDoAfterEvent args) + private void OnDoAfter(Entity ent, ref DrainDoAfterEvent args) { if (args.Target == null) return; - if (!_random.Prob(entity.Comp.UnclogProbability)) + // TODO: Replace with RandomPredicted once the engine PR is merged + var seed = SharedRandomExtensions.HashCodeCombine((int)_timing.CurTick.Value, ent.Owner.GetHashCode()); + var rand = new System.Random(seed); + if (!rand.Prob(ent.Comp.UnclogProbability)) { - _popupSystem.PopupEntity(Loc.GetString("drain-component-unclog-fail", ("object", args.Target.Value)), args.Target.Value); + _popup.PopupPredicted(Loc.GetString("drain-component-unclog-fail", ("object", args.Target.Value)), args.Target.Value, args.User); return; } - - if (!_solutionContainerSystem.ResolveSolution(args.Target.Value, DrainComponent.SolutionName, ref entity.Comp.Solution)) - { + if (!_solutionContainerSystem.ResolveSolution(args.Target.Value, DrainComponent.SolutionName, ref ent.Comp.Solution)) return; - } + _solutionContainerSystem.RemoveAllSolution(ent.Comp.Solution.Value); + _audio.PlayPredicted(ent.Comp.UnclogSound, args.Target.Value, args.User); + _popup.PopupPredicted(Loc.GetString("drain-component-unclog-success", ("object", args.Target.Value)), args.Target.Value, args.User); + } + + // Prevent a debug assert. + // See https://github.com/space-wizards/space-station-14/pull/35314 + private void OnEntRemoved(Entity ent, ref EntRemovedFromContainerMessage args) + { + // Make sure the removed entity was our contained solution + if (ent.Comp.Solution is not { } solution || args.Entity != solution.Owner) + return; - _solutionContainerSystem.RemoveAllSolution(entity.Comp.Solution.Value); - _audioSystem.PlayPvs(entity.Comp.UnclogSound, args.Target.Value); - _popupSystem.PopupEntity(Loc.GetString("drain-component-unclog-success", ("object", args.Target.Value)), args.Target.Value); + // Cleared our cached reference to the solution entity + ent.Comp.Solution = null; } } + +/// +/// Event raised when a do-after action for unclogging a drain completes. +/// +[Serializable, NetSerializable] +public sealed partial class DrainDoAfterEvent : SimpleDoAfterEvent; diff --git a/Content.Shared/Fluids/SharedDrainSystem.cs b/Content.Shared/Fluids/SharedDrainSystem.cs deleted file mode 100644 index d65dddb0df..0000000000 --- a/Content.Shared/Fluids/SharedDrainSystem.cs +++ /dev/null @@ -1,12 +0,0 @@ -using Content.Shared.DoAfter; -using Robust.Shared.Serialization; - -namespace Content.Shared.Fluids; - -public abstract partial class SharedDrainSystem : EntitySystem -{ - [Serializable, NetSerializable] - public sealed partial class DrainDoAfterEvent : SimpleDoAfterEvent - { - } -} -- 2.52.0