Files
OldThink/Content.Shared/Movement/Pulling/Systems/PullingSystem.cs
Jabak 9f00d4b9aa Upstream (#148)
* Content changes for engine delta-state PR (#28134)

* Update GasTileOverlayState

* Update DecalGridState

* Update NavMapState

* poke

* poke2

* poke3

* Poke dem tests

* Update engine to v223.0.0 (#28239)

* Update RobustToolbox

* Improve InteractionSystem range & BUI checks (#27999)

* Improve InteractionSystem range & BUI checks

* Ghost fixes

* AAA

* Fix test

* fix nullable

* revert to broadcast event

* Fixes for eengine PR

* Ah buckle code

* )

* Update engine to v223.0.0

* Update engine to v223.1.0

* Update engine to v223.1.1

* Hotfix for crashes from bad item names (#28256)

* Fix weapon error logs (#28264)

* Update engine to v223.1.2 (#28273)

* Update RobustToolbox

* Update RobustToolbox

* Fix dud modular grenade visuals (#28265)

* Fix not networking whitelist and blacklist in storage component (#28238)

* fix id card console not updating records (#28237)

* fix id card console not updating records

* test

---------

Co-authored-by: deltanedas <@deltanedas:kde.org>

* Remove the network tab (#28231)

It is useless and bloat, if a user needs to change these settings they are free to modify their cvars manually via the clientconfig.toml file or via the cvar command.

* antag objective issuing refactor (#28216)

* add AntagObjectives from GenericAntag

* add AntagRandomObjectives that traitor and thief can use

* make ObjectivesSystem use initial character name which AntagSelection passes

* make thief and traitor use AntagRandomObjectives

* remove now unused locale

* make sleeper agents rule use baseTraitorRule

* restore dragon rule oop

* bandaid for genericantag

* real

* typo

---------

Co-authored-by: deltanedas <@deltanedas:kde.org>

* move nukie profile loading into its own rule (#28208)

* move profile loading out of nukeops rule

* make BaseNukeopsRule and use AntagLoadProfileRule

* untroll

---------

Co-authored-by: deltanedas <@deltanedas:kde.org>

* fix antagSelect

* Objects ordered through cargo system shouldn't start anchored (#28115)

* Order normal space heater instead of anchored variant

* Make sure ordered objects don't spawn anchored

* Order space heater flatpack instead of a regular space heater

* Remove obsolete TODO

* Remove unnecessary name

---------

Co-authored-by: Eoin Mcloughlin <helloworld@eoinrul.es>

* Move PendingZombieComponent to Shared (#28143)

* Move PendingZombieComponent to Shared

* network me boy

---------

Co-authored-by: Nemanja <98561806+EmoGarbage404@users.noreply.github.com>

* Make it possible to hide full health bars below a total damage threshold (#28127)

* Make it possible to hide full health bars below a total damage threshold

* Fix not setting state

* Fix storage UI interactions (#28291)

* Fix storage UI interactions

* Add VV support

* Fix stripping not marking interactions as handled (#28292)

* Make NetworkConfigurator use BoundUserInterfaceCheckRangeEvent (#28293)

* Fix hypodarts not injecting with people that have ANY outerclothing (#28301)

Update darts.yml

* fix borg ui mispredict opening (#28305)

move borg ui junk to shared

* Add loadout group check (#28311)

Forgot to add it back in one of the rewrites.

* fix mirror server crashes (#28318)

* Remove bogus C# finalizers (#28315)

Begging people to learn how this programming language works before throwing random syntax into a file.

None of these finalizers ever worked. I also checked whether they were memory leaks and needed *proper* shutdown logic, but they're all instantiated-once UI controls that last for the entire lifetime of the program so it's probably fine.

* Cleans up some entity-related spawnmenu stuff (#28234)

* cleans up a lot of stuff in the spawnmenu

* skibidi dode

* spawners update

* Revert "spawners update"

This reverts commit bc27d9f556b29f6fb1f89cebbe0ac37e28319fd0.

* fix antag selection being evil (#28197)

* fix antag selection being evil

* fix test

* untroll the other tests

* remove role timer troll

* Allow tests to modify antag preferences

* Fix antag selection

* Misc test fixes

* Add AntagPreferenceTest

* Fix lazy mistakes

* Test cleanup

* Try stop players in lobbies from being assigned mid-round antags

* ranting

* I am going insane

---------

Co-authored-by: deltanedas <@deltanedas:kde.org>
Co-authored-by: ElectroJr <leonsfriedrich@gmail.com>

* Revert "fix mirror server crashes (#28318)"

This reverts commit bcb0e555b058a4049d0cdb32d64eaf86c35a67be.

* fix

* Update engine to 223.2.0 (#28329)

* Update RobustToolbox

* Update RobustToolbox

---------

Co-authored-by: Leon Friedrich <60421075+ElectroJr@users.noreply.github.com>
Co-authored-by: Tayrtahn <tayrtahn@gmail.com>
Co-authored-by: DrSmugleaf <10968691+DrSmugleaf@users.noreply.github.com>
Co-authored-by: deltanedas <39013340+deltanedas@users.noreply.github.com>
Co-authored-by: Vasilis <vasilis@pikachu.systems>
Co-authored-by: eoineoineoin <github@eoinrul.es>
Co-authored-by: Eoin Mcloughlin <helloworld@eoinrul.es>
Co-authored-by: Ady4ik <141335742+Ady4ik@users.noreply.github.com>
Co-authored-by: Nemanja <98561806+EmoGarbage404@users.noreply.github.com>
Co-authored-by: Mr. 27 <45323883+Dutch-VanDerLinde@users.noreply.github.com>
Co-authored-by: metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
Co-authored-by: Pieter-Jan Briers <pieterjan.briers+git@gmail.com>
Co-authored-by: Flareguy <78941145+Flareguy@users.noreply.github.com>
Co-authored-by: ElectroJr <leonsfriedrich@gmail.com>
Co-authored-by: Kara <lunarautomaton6@gmail.com>
2024-10-22 20:47:03 +03:00

490 lines
17 KiB
C#

using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using Content.Shared.ActionBlocker;
using Content.Shared.Administration.Logs;
using Content.Shared.Alert;
using Content.Shared.Buckle.Components;
using Content.Shared.Database;
using Content.Shared.Hands;
using Content.Shared.Hands.EntitySystems;
using Content.Shared.Input;
using Content.Shared.Interaction;
using Content.Shared.Movement.Events;
using Content.Shared.Movement.Pulling.Components;
using Content.Shared.Movement.Pulling.Events;
using Content.Shared.Movement.Systems;
using Content.Shared.Pulling.Events;
using Content.Shared.Standing;
using Content.Shared.Throwing;
using Content.Shared.Verbs;
using Content.Shared.Standing.Systems;
using Robust.Shared.Containers;
using Robust.Shared.Input.Binding;
using Robust.Shared.Map;
using Robust.Shared.Physics;
using Robust.Shared.Physics.Components;
using Robust.Shared.Physics.Events;
using Robust.Shared.Physics.Systems;
using Robust.Shared.Player;
using Robust.Shared.Timing;
namespace Content.Shared.Movement.Pulling.Systems;
/// <summary>
/// Allows one entity to pull another behind them via a physics distance joint.
/// </summary>
public sealed class PullingSystem : EntitySystem
{
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly ISharedAdminLogManager _adminLogger = default!;
[Dependency] private readonly ActionBlockerSystem _blocker = default!;
[Dependency] private readonly AlertsSystem _alertsSystem = default!;
[Dependency] private readonly MovementSpeedModifierSystem _modifierSystem = default!;
[Dependency] private readonly SharedJointSystem _joints = default!;
[Dependency] private readonly SharedContainerSystem _containerSystem = default!;
[Dependency] private readonly SharedHandsSystem _handsSystem = default!;
[Dependency] private readonly SharedInteractionSystem _interaction = default!;
[Dependency] private readonly SharedPhysicsSystem _physics = default!;
[Dependency] private readonly SharedStandingStateSystem _standing = default!;
public override void Initialize()
{
base.Initialize();
UpdatesAfter.Add(typeof(SharedPhysicsSystem));
UpdatesOutsidePrediction = true;
SubscribeLocalEvent<PullableComponent, MoveInputEvent>(OnPullableMoveInput);
SubscribeLocalEvent<PullableComponent, CollisionChangeEvent>(OnPullableCollisionChange);
SubscribeLocalEvent<PullableComponent, JointRemovedEvent>(OnJointRemoved);
SubscribeLocalEvent<PullableComponent, GetVerbsEvent<Verb>>(AddPullVerbs);
SubscribeLocalEvent<PullableComponent, EntGotInsertedIntoContainerMessage>(OnPullableContainerInsert);
SubscribeLocalEvent<PullerComponent, EntGotInsertedIntoContainerMessage>(OnPullerContainerInsert);
SubscribeLocalEvent<PullerComponent, EntityUnpausedEvent>(OnPullerUnpaused);
SubscribeLocalEvent<PullerComponent, VirtualItemDeletedEvent>(OnVirtualItemDeleted);
SubscribeLocalEvent<PullerComponent, RefreshMovementSpeedModifiersEvent>(OnRefreshMovespeed);
SubscribeLocalEvent<PullerComponent, DropHandItemsEvent>(OnDropHandItems);
CommandBinds.Builder
.Bind(ContentKeyFunctions.ReleasePulledObject, InputCmdHandler.FromDelegate(OnReleasePulledObject, handle: false))
.Register<PullingSystem>();
}
private void OnDropHandItems(EntityUid uid, PullerComponent pullerComp, DropHandItemsEvent args)
{
if (pullerComp.Pulling == null || pullerComp.NeedsHands)
return;
if (!TryComp(pullerComp.Pulling, out PullableComponent? pullableComp))
return;
TryStopPull(pullerComp.Pulling.Value, pullableComp, uid);
}
private void OnPullerContainerInsert(Entity<PullerComponent> ent, ref EntGotInsertedIntoContainerMessage args)
{
if (ent.Comp.Pulling == null) return;
if (!TryComp(ent.Comp.Pulling.Value, out PullableComponent? pulling))
return;
TryStopPull(ent.Comp.Pulling.Value, pulling, ent.Owner);
}
private void OnPullableContainerInsert(Entity<PullableComponent> ent, ref EntGotInsertedIntoContainerMessage args)
{
TryStopPull(ent.Owner, ent.Comp);
}
public override void Shutdown()
{
base.Shutdown();
CommandBinds.Unregister<PullingSystem>();
}
private void OnPullerUnpaused(EntityUid uid, PullerComponent component, ref EntityUnpausedEvent args)
{
component.NextThrow += args.PausedTime;
}
private void OnVirtualItemDeleted(EntityUid uid, PullerComponent component, VirtualItemDeletedEvent args)
{
// If client deletes the virtual hand then stop the pull.
if (component.Pulling == null)
return;
if (component.Pulling != args.BlockingEntity)
return;
if (EntityManager.TryGetComponent(args.BlockingEntity, out PullableComponent? comp))
{
TryStopPull(args.BlockingEntity, comp, uid);
}
}
private void AddPullVerbs(EntityUid uid, PullableComponent component, GetVerbsEvent<Verb> args)
{
if (!args.CanAccess || !args.CanInteract)
return;
// Are they trying to pull themselves up by their bootstraps?
if (args.User == args.Target)
return;
//TODO VERB ICONS add pulling icon
if (component.Puller == args.User)
{
Verb verb = new()
{
Text = Loc.GetString("pulling-verb-get-data-text-stop-pulling"),
Act = () => TryStopPull(uid, component, user: args.User),
DoContactInteraction = false // pulling handle its own contact interaction.
};
args.Verbs.Add(verb);
}
else if (CanPull(args.User, args.Target))
{
Verb verb = new()
{
Text = Loc.GetString("pulling-verb-get-data-text"),
Act = () => TryStartPull(args.User, args.Target),
DoContactInteraction = false // pulling handle its own contact interaction.
};
args.Verbs.Add(verb);
}
}
private void OnRefreshMovespeed(EntityUid uid, PullerComponent component, RefreshMovementSpeedModifiersEvent args)
{
if (_standing.IsDown(uid))
{
args.ModifySpeed(component.WalkSpeedModifier * 0.5f, component.SprintSpeedModifier * 0.5f);
return;
}
args.ModifySpeed(component.WalkSpeedModifier, component.SprintSpeedModifier);
}
private void OnPullableMoveInput(EntityUid uid, PullableComponent component, ref MoveInputEvent args)
{
// If someone moves then break their pulling.
if (!component.BeingPulled)
return;
var entity = args.Entity;
if (!_blocker.CanMove(entity))
return;
TryStopPull(uid, component, user: uid);
}
private void OnPullableCollisionChange(EntityUid uid, PullableComponent component, ref CollisionChangeEvent args)
{
// IDK what this is supposed to be.
if (!_timing.ApplyingState && component.PullJointId != null && !args.CanCollide)
{
_joints.RemoveJoint(uid, component.PullJointId);
}
}
private void OnJointRemoved(EntityUid uid, PullableComponent component, JointRemovedEvent args)
{
// Just handles the joint getting nuked without going through pulling system (valid behavior).
// Not relevant / pullable state handle it.
if (component.Puller != args.OtherEntity ||
args.Joint.ID != component.PullJointId ||
_timing.ApplyingState)
{
return;
}
if (args.Joint.ID != component.PullJointId || component.Puller == null)
return;
StopPulling(uid, component);
}
/// <summary>
/// Forces pulling to stop and handles cleanup.
/// </summary>
private void StopPulling(EntityUid pullableUid, PullableComponent pullableComp)
{
if (!_timing.ApplyingState)
{
if (TryComp<PhysicsComponent>(pullableUid, out var pullablePhysics))
{
_physics.SetFixedRotation(pullableUid, pullableComp.PrevFixedRotation, body: pullablePhysics);
}
}
var oldPuller = pullableComp.Puller;
pullableComp.PullJointId = null;
pullableComp.Puller = null;
Dirty(pullableUid, pullableComp);
// No more joints with puller -> force stop pull.
if (TryComp<PullerComponent>(oldPuller, out var pullerComp))
{
var pullerUid = oldPuller.Value;
_alertsSystem.ClearAlert(pullerUid, AlertType.Pulling);
pullerComp.Pulling = null;
Dirty(oldPuller.Value, pullerComp);
// Messaging
var message = new PullStoppedMessage(pullerUid, pullableUid);
_modifierSystem.RefreshMovementSpeedModifiers(pullerUid);
_adminLogger.Add(LogType.Action, LogImpact.Low, $"{ToPrettyString(pullerUid):user} stopped pulling {ToPrettyString(pullableUid):target}");
RaiseLocalEvent(pullerUid, message);
RaiseLocalEvent(pullableUid, message);
}
_alertsSystem.ClearAlert(pullableUid, AlertType.Pulled);
}
public bool IsPulled(EntityUid uid, PullableComponent? component = null)
{
return Resolve(uid, ref component, false) && component.BeingPulled;
}
// WD ADDED
public bool TryGetPulledEntity(
EntityUid puller,
[NotNullWhen(true)] out EntityUid? pulled,
PullerComponent? component = null)
{
pulled = null;
if (!Resolve(puller, ref component))
{
return false;
}
pulled = component.Pulling;
return pulled is not null;
}
// WD ADDED END
public bool IsPulling(EntityUid puller, PullerComponent? component = null)
{
return Resolve(puller, ref component, false) && component.Pulling != null;
}
private void OnReleasePulledObject(ICommonSession? session)
{
if (session?.AttachedEntity is not {Valid: true} player)
{
return;
}
if (!TryComp(player, out PullerComponent? pullerComp) ||
!TryComp(pullerComp.Pulling, out PullableComponent? pullableComp))
{
return;
}
TryStopPull(pullerComp.Pulling.Value, pullableComp, user: player);
}
public bool CanPull(EntityUid puller, EntityUid pullableUid, PullerComponent? pullerComp = null)
{
if (!Resolve(puller, ref pullerComp, false))
{
return false;
}
if (pullerComp.NeedsHands
&& !_handsSystem.TryGetEmptyHand(puller, out _)
&& pullerComp.Pulling == null)
{
return false;
}
if (!_blocker.CanInteract(puller, pullableUid))
{
return false;
}
if (!EntityManager.TryGetComponent<PhysicsComponent>(pullableUid, out var physics))
{
return false;
}
if (physics.BodyType == BodyType.Static)
{
return false;
}
if (puller == pullableUid)
{
return false;
}
if (!_containerSystem.IsInSameOrNoContainer(puller, pullableUid))
{
return false;
}
if (EntityManager.TryGetComponent(puller, out BuckleComponent? buckle))
{
// Prevent people pulling the chair they're on, etc.
if (buckle is { PullStrap: false, Buckled: true } && (buckle.LastEntityBuckledTo == pullableUid))
{
return false;
}
}
var getPulled = new BeingPulledAttemptEvent(puller, pullableUid);
RaiseLocalEvent(pullableUid, getPulled, true);
var startPull = new StartPullAttemptEvent(puller, pullableUid);
RaiseLocalEvent(puller, startPull, true);
return !startPull.Cancelled && !getPulled.Cancelled;
}
public bool TogglePull(Entity<PullableComponent?> pullable, EntityUid pullerUid)
{
if (!Resolve(pullable, ref pullable.Comp, false))
return false;
if (pullable.Comp.Puller == pullerUid)
{
return TryStopPull(pullable, pullable.Comp);
}
return TryStartPull(pullerUid, pullable, pullableComp: pullable);
}
public bool TogglePull(EntityUid pullerUid, PullerComponent puller)
{
if (!TryComp<PullableComponent>(puller.Pulling, out var pullable))
return false;
return TogglePull((puller.Pulling.Value, pullable), pullerUid);
}
public bool TryStartPull(EntityUid pullerUid, EntityUid pullableUid,
PullerComponent? pullerComp = null, PullableComponent? pullableComp = null)
{
if (!Resolve(pullerUid, ref pullerComp, false) ||
!Resolve(pullableUid, ref pullableComp, false))
{
return false;
}
if (pullerComp.Pulling == pullableUid)
return true;
if (!CanPull(pullerUid, pullableUid))
return false;
if (!EntityManager.TryGetComponent<PhysicsComponent>(pullerUid, out var pullerPhysics) ||
!EntityManager.TryGetComponent<PhysicsComponent>(pullableUid, out var pullablePhysics))
{
return false;
}
// Ensure that the puller is not currently pulling anything.
if (TryComp<PullableComponent>(pullerComp.Pulling, out var oldPullable)
&& !TryStopPull(pullerComp.Pulling.Value, oldPullable, pullerUid))
return false;
// Stop anyone else pulling the entity we want to pull
if (pullableComp.Puller != null)
{
// We're already pulling this item
if (pullableComp.Puller == pullerUid)
return false;
if (!TryStopPull(pullableUid, pullableComp, pullableComp.Puller))
return false;
}
var pullAttempt = new PullAttemptEvent(pullerUid, pullableUid);
RaiseLocalEvent(pullerUid, pullAttempt);
if (pullAttempt.Cancelled)
return false;
RaiseLocalEvent(pullableUid, pullAttempt);
if (pullAttempt.Cancelled)
return false;
// Pulling confirmed
_interaction.DoContactInteraction(pullableUid, pullerUid);
// Use net entity so it's consistent across client and server.
pullableComp.PullJointId = $"pull-joint-{GetNetEntity(pullableUid)}";
pullerComp.Pulling = pullableUid;
pullableComp.Puller = pullerUid;
// joint state handling will manage its own state
if (!_timing.ApplyingState)
{
// Joint startup
var union = _physics.GetHardAABB(pullerUid).Union(_physics.GetHardAABB(pullableUid, body: pullablePhysics));
var length = Math.Max((float) union.Size.X, (float) union.Size.Y) * 0.75f;
var joint = _joints.CreateDistanceJoint(pullableUid, pullerUid, id: pullableComp.PullJointId);
joint.CollideConnected = false;
// This maximum has to be there because if the object is constrained too closely, the clamping goes backwards and asserts.
joint.MaxLength = Math.Max(1.0f, length);
joint.Length = length * 0.75f;
joint.MinLength = 0f;
joint.Stiffness = 1f;
_physics.SetFixedRotation(pullableUid, pullableComp.FixedRotationOnPull, body: pullablePhysics);
}
pullableComp.PrevFixedRotation = pullablePhysics.FixedRotation;
// Messaging
var message = new PullStartedMessage(pullerUid, pullableUid);
_alertsSystem.ShowAlert(pullerUid, AlertType.Pulling);
_alertsSystem.ShowAlert(pullableUid, AlertType.Pulled);
RaiseLocalEvent(pullerUid, message);
RaiseLocalEvent(pullableUid, message);
Dirty(pullerUid, pullerComp);
Dirty(pullableUid, pullableComp);
_adminLogger.Add(LogType.Action, LogImpact.Low,
$"{ToPrettyString(pullerUid):user} started pulling {ToPrettyString(pullableUid):target}");
return true;
}
public bool TryStopPull(EntityUid pullableUid, PullableComponent pullable, EntityUid? user = null)
{
var pullerUidNull = pullable.Puller;
if (pullerUidNull == null)
return true;
var msg = new AttemptStopPullingEvent(user);
RaiseLocalEvent(pullableUid, msg, true);
if (msg.Cancelled)
return false;
// Stop pulling confirmed!
if (!_timing.ApplyingState)
{
// Joint shutdown
if (pullable.PullJointId != null)
{
_joints.RemoveJoint(pullableUid, pullable.PullJointId);
pullable.PullJointId = null;
}
}
StopPulling(pullableUid, pullable);
return true;
}
}