FollowerSystem.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. using System.Linq;
  2. using System.Numerics;
  3. using Content.Shared.Administration.Managers;
  4. using Content.Shared.Database;
  5. using Content.Shared.Follower.Components;
  6. using Content.Shared.Ghost;
  7. using Content.Shared.Hands;
  8. using Content.Shared.Movement.Events;
  9. using Content.Shared.Movement.Pulling.Events;
  10. using Content.Shared.Polymorph;
  11. using Content.Shared.Tag;
  12. using Content.Shared.Verbs;
  13. using Robust.Shared.Containers;
  14. using Robust.Shared.GameStates;
  15. using Robust.Shared.Map;
  16. using Robust.Shared.Map.Events;
  17. using Robust.Shared.Network;
  18. using Robust.Shared.Physics;
  19. using Robust.Shared.Physics.Systems;
  20. using Robust.Shared.Player;
  21. using Robust.Shared.Utility;
  22. namespace Content.Shared.Follower;
  23. public sealed class FollowerSystem : EntitySystem
  24. {
  25. [Dependency] private readonly SharedTransformSystem _transform = default!;
  26. [Dependency] private readonly TagSystem _tagSystem = default!;
  27. [Dependency] private readonly SharedContainerSystem _containerSystem = default!;
  28. [Dependency] private readonly SharedJointSystem _jointSystem = default!;
  29. [Dependency] private readonly SharedPhysicsSystem _physicsSystem = default!;
  30. [Dependency] private readonly INetManager _netMan = default!;
  31. [Dependency] private readonly ISharedAdminManager _adminManager = default!;
  32. public override void Initialize()
  33. {
  34. base.Initialize();
  35. SubscribeLocalEvent<GetVerbsEvent<AlternativeVerb>>(OnGetAlternativeVerbs);
  36. SubscribeLocalEvent<FollowerComponent, MoveInputEvent>(OnFollowerMove);
  37. SubscribeLocalEvent<FollowerComponent, PullStartedMessage>(OnPullStarted);
  38. SubscribeLocalEvent<FollowerComponent, EntityTerminatingEvent>(OnFollowerTerminating);
  39. SubscribeLocalEvent<FollowerComponent, AfterAutoHandleStateEvent>(OnAfterHandleState);
  40. SubscribeLocalEvent<FollowedComponent, ComponentGetStateAttemptEvent>(OnFollowedAttempt);
  41. SubscribeLocalEvent<FollowerComponent, GotEquippedHandEvent>(OnGotEquippedHand);
  42. SubscribeLocalEvent<FollowedComponent, EntityTerminatingEvent>(OnFollowedTerminating);
  43. SubscribeLocalEvent<BeforeSerializationEvent>(OnBeforeSave);
  44. SubscribeLocalEvent<FollowedComponent, PolymorphedEvent>(OnFollowedPolymorphed);
  45. }
  46. private void OnFollowedAttempt(Entity<FollowedComponent> ent, ref ComponentGetStateAttemptEvent args)
  47. {
  48. if (args.Cancelled)
  49. return;
  50. // Clientside VV stay losing
  51. var playerEnt = args.Player?.AttachedEntity;
  52. if (playerEnt == null ||
  53. !ent.Comp.Following.Contains(playerEnt.Value) && !HasComp<GhostComponent>(playerEnt.Value))
  54. {
  55. args.Cancelled = true;
  56. }
  57. }
  58. private void OnBeforeSave(BeforeSerializationEvent ev)
  59. {
  60. // Some followers will not be map savable. This ensures that maps don't get saved with some entities that have
  61. // empty/invalid followers, by just stopping any following happening on the map being saved.
  62. // I hate this so much.
  63. // TODO WeakEntityReference
  64. // We need some way to store entity references in a way that doesn't imply that the entity still exists.
  65. // Then we wouldn't have to deal with this shit.
  66. var maps = ev.Entities.Select(x => Transform(x).MapUid).ToHashSet();
  67. var query = AllEntityQuery<FollowerComponent, TransformComponent, MetaDataComponent>();
  68. while (query.MoveNext(out var uid, out var follower, out var xform, out var meta))
  69. {
  70. if (meta.EntityPrototype == null || meta.EntityPrototype.MapSavable)
  71. continue;
  72. if (!maps.Contains(xform.MapUid))
  73. continue;
  74. StopFollowingEntity(uid, follower.Following);
  75. }
  76. }
  77. private void OnGetAlternativeVerbs(GetVerbsEvent<AlternativeVerb> ev)
  78. {
  79. if (ev.User == ev.Target || IsClientSide(ev.Target))
  80. return;
  81. if (HasComp<GhostComponent>(ev.User))
  82. {
  83. var verb = new AlternativeVerb()
  84. {
  85. Priority = 10,
  86. Act = () => StartFollowingEntity(ev.User, ev.Target),
  87. Impact = LogImpact.Low,
  88. Text = Loc.GetString("verb-follow-text"),
  89. Icon = new SpriteSpecifier.Texture(new("/Textures/Interface/VerbIcons/open.svg.192dpi.png"))
  90. };
  91. ev.Verbs.Add(verb);
  92. }
  93. if (_tagSystem.HasTag(ev.Target, "ForceableFollow"))
  94. {
  95. if (!ev.CanAccess || !ev.CanInteract)
  96. return;
  97. var verb = new AlternativeVerb
  98. {
  99. Priority = 10,
  100. Act = () => StartFollowingEntity(ev.Target, ev.User),
  101. Impact = LogImpact.Low,
  102. Text = Loc.GetString("verb-follow-me-text"),
  103. Icon = new SpriteSpecifier.Texture(new ("/Textures/Interface/VerbIcons/close.svg.192dpi.png")),
  104. };
  105. ev.Verbs.Add(verb);
  106. }
  107. }
  108. private void OnFollowerMove(EntityUid uid, FollowerComponent component, ref MoveInputEvent args)
  109. {
  110. if (args.HasDirectionalMovement)
  111. StopFollowingEntity(uid, component.Following);
  112. }
  113. private void OnPullStarted(EntityUid uid, FollowerComponent component, PullStartedMessage args)
  114. {
  115. StopFollowingEntity(uid, component.Following);
  116. }
  117. private void OnGotEquippedHand(EntityUid uid, FollowerComponent component, GotEquippedHandEvent args)
  118. {
  119. StopFollowingEntity(uid, component.Following, deparent:false);
  120. }
  121. private void OnFollowerTerminating(EntityUid uid, FollowerComponent component, ref EntityTerminatingEvent args)
  122. {
  123. StopFollowingEntity(uid, component.Following, deparent: false);
  124. }
  125. private void OnAfterHandleState(Entity<FollowerComponent> entity, ref AfterAutoHandleStateEvent args)
  126. {
  127. StartFollowingEntity(entity, entity.Comp.Following);
  128. }
  129. // Since we parent our observer to the followed entity, we need to detach
  130. // before they get deleted so that we don't get recursively deleted too.
  131. private void OnFollowedTerminating(EntityUid uid, FollowedComponent component, ref EntityTerminatingEvent args)
  132. {
  133. StopAllFollowers(uid, component);
  134. }
  135. private void OnFollowedPolymorphed(Entity<FollowedComponent> entity, ref PolymorphedEvent args)
  136. {
  137. foreach (var follower in entity.Comp.Following)
  138. {
  139. // Stop following the target's old entity and start following the new one
  140. StartFollowingEntity(follower, args.NewEntity);
  141. }
  142. }
  143. /// <summary>
  144. /// Makes an entity follow another entity, by parenting to it.
  145. /// </summary>
  146. /// <param name="follower">The entity that should follow</param>
  147. /// <param name="entity">The entity to be followed</param>
  148. public void StartFollowingEntity(EntityUid follower, EntityUid entity)
  149. {
  150. // No recursion for you
  151. var targetXform = Transform(entity);
  152. while (targetXform.ParentUid.IsValid())
  153. {
  154. if (targetXform.ParentUid == follower)
  155. return;
  156. targetXform = Transform(targetXform.ParentUid);
  157. }
  158. // Cleanup old following.
  159. if (TryComp<FollowerComponent>(follower, out var followerComp))
  160. {
  161. // Already following you goob
  162. if (followerComp.Following == entity)
  163. return;
  164. StopFollowingEntity(follower, followerComp.Following, deparent: false, removeComp: false);
  165. }
  166. else
  167. {
  168. followerComp = AddComp<FollowerComponent>(follower);
  169. }
  170. followerComp.Following = entity;
  171. var followedComp = EnsureComp<FollowedComponent>(entity);
  172. if (!followedComp.Following.Add(follower))
  173. return;
  174. if (TryComp<JointComponent>(follower, out var joints))
  175. _jointSystem.ClearJoints(follower, joints);
  176. var xform = Transform(follower);
  177. _containerSystem.AttachParentToContainerOrGrid((follower, xform));
  178. // If we didn't get to parent's container.
  179. if (xform.ParentUid != Transform(xform.ParentUid).ParentUid)
  180. {
  181. _transform.SetCoordinates(follower, xform, new EntityCoordinates(entity, Vector2.Zero), rotation: Angle.Zero);
  182. }
  183. _physicsSystem.SetLinearVelocity(follower, Vector2.Zero);
  184. EnsureComp<OrbitVisualsComponent>(follower);
  185. var followerEv = new StartedFollowingEntityEvent(entity, follower);
  186. var entityEv = new EntityStartedFollowingEvent(entity, follower);
  187. RaiseLocalEvent(follower, followerEv);
  188. RaiseLocalEvent(entity, entityEv);
  189. Dirty(entity, followedComp);
  190. Dirty(follower, followerComp);
  191. }
  192. /// <summary>
  193. /// Forces an entity to stop following another entity, if it is doing so.
  194. /// </summary>
  195. /// <param name="deparent">Should the entity deparent itself</param>
  196. public void StopFollowingEntity(EntityUid uid, EntityUid target, FollowedComponent? followed = null, bool deparent = true, bool removeComp = true)
  197. {
  198. if (!Resolve(target, ref followed, false))
  199. return;
  200. if (!TryComp<FollowerComponent>(uid, out var followerComp) || followerComp.Following != target)
  201. return;
  202. followed.Following.Remove(uid);
  203. if (followed.Following.Count == 0)
  204. RemComp<FollowedComponent>(target);
  205. if (removeComp)
  206. {
  207. RemComp<FollowerComponent>(uid);
  208. RemComp<OrbitVisualsComponent>(uid);
  209. }
  210. var uidEv = new StoppedFollowingEntityEvent(target, uid);
  211. var targetEv = new EntityStoppedFollowingEvent(target, uid);
  212. RaiseLocalEvent(uid, uidEv, true);
  213. RaiseLocalEvent(target, targetEv, false);
  214. Dirty(target, followed);
  215. RaiseLocalEvent(uid, uidEv);
  216. RaiseLocalEvent(target, targetEv);
  217. if (!deparent || !TryComp(uid, out TransformComponent? xform))
  218. return;
  219. _transform.AttachToGridOrMap(uid, xform);
  220. if (xform.MapUid != null)
  221. return;
  222. if (_netMan.IsClient)
  223. {
  224. _transform.DetachEntity(uid, xform);
  225. return;
  226. }
  227. Log.Warning($"A follower has been detached to null-space and will be deleted. Follower: {ToPrettyString(uid)}. Followed: {ToPrettyString(target)}");
  228. QueueDel(uid);
  229. }
  230. /// <summary>
  231. /// Forces all of an entity's followers to stop following it.
  232. /// </summary>
  233. public void StopAllFollowers(EntityUid uid,
  234. FollowedComponent? followed=null)
  235. {
  236. if (!Resolve(uid, ref followed))
  237. return;
  238. foreach (var player in followed.Following)
  239. {
  240. StopFollowingEntity(player, uid, followed);
  241. }
  242. }
  243. /// <summary>
  244. /// Gets the entity with the most non-admin ghosts following it.
  245. /// </summary>
  246. public EntityUid? GetMostGhostFollowed()
  247. {
  248. EntityUid? picked = null;
  249. var most = 0;
  250. // Keep a tally of how many ghosts are following each entity
  251. var followedEnts = new Dictionary<EntityUid, int>();
  252. // Look for followers that are ghosts and are player controlled
  253. var query = EntityQueryEnumerator<FollowerComponent, GhostComponent, ActorComponent>();
  254. while (query.MoveNext(out _, out var follower, out _, out var actor))
  255. {
  256. // Exclude admins
  257. if (_adminManager.IsAdmin(actor.PlayerSession))
  258. continue;
  259. var followed = follower.Following;
  260. // Add new entry or increment existing
  261. followedEnts.TryGetValue(followed, out var currentValue);
  262. followedEnts[followed] = currentValue + 1;
  263. if (followedEnts[followed] > most)
  264. {
  265. picked = followed;
  266. most = followedEnts[followed];
  267. }
  268. }
  269. return picked;
  270. }
  271. }
  272. public abstract class FollowEvent : EntityEventArgs
  273. {
  274. public EntityUid Following;
  275. public EntityUid Follower;
  276. protected FollowEvent(EntityUid following, EntityUid follower)
  277. {
  278. Following = following;
  279. Follower = follower;
  280. }
  281. }
  282. /// <summary>
  283. /// Raised on an entity when it start following another entity.
  284. /// </summary>
  285. public sealed class StartedFollowingEntityEvent : FollowEvent
  286. {
  287. public StartedFollowingEntityEvent(EntityUid following, EntityUid follower) : base(following, follower)
  288. {
  289. }
  290. }
  291. /// <summary>
  292. /// Raised on an entity when it stops following another entity.
  293. /// </summary>
  294. public sealed class StoppedFollowingEntityEvent : FollowEvent
  295. {
  296. public StoppedFollowingEntityEvent(EntityUid following, EntityUid follower) : base(following, follower)
  297. {
  298. }
  299. }
  300. /// <summary>
  301. /// Raised on an entity when it start following another entity.
  302. /// </summary>
  303. public sealed class EntityStartedFollowingEvent : FollowEvent
  304. {
  305. public EntityStartedFollowingEvent(EntityUid following, EntityUid follower) : base(following, follower)
  306. {
  307. }
  308. }
  309. /// <summary>
  310. /// Raised on an entity when it starts being followed by another entity.
  311. /// </summary>
  312. public sealed class EntityStoppedFollowingEvent : FollowEvent
  313. {
  314. public EntityStoppedFollowingEvent(EntityUid following, EntityUid follower) : base(following, follower)
  315. {
  316. }
  317. }