AnchorableSystem.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. using Content.Shared.Administration.Logs;
  2. using Content.Shared.Examine;
  3. using Content.Shared.Construction.Components;
  4. using Content.Shared.Containers.ItemSlots;
  5. using Content.Shared.Coordinates.Helpers;
  6. using Content.Shared.Database;
  7. using Content.Shared.DoAfter;
  8. using Content.Shared.Interaction;
  9. using Content.Shared.Movement.Pulling.Components;
  10. using Content.Shared.Movement.Pulling.Systems;
  11. using Content.Shared.Popups;
  12. using Content.Shared.Tools;
  13. using Content.Shared.Tools.Components;
  14. using Robust.Shared.Map;
  15. using Robust.Shared.Map.Components;
  16. using Robust.Shared.Physics.Components;
  17. using Content.Shared.Tag;
  18. using Robust.Shared.Prototypes;
  19. using Robust.Shared.Serialization;
  20. using Robust.Shared.Utility;
  21. using SharedToolSystem = Content.Shared.Tools.Systems.SharedToolSystem;
  22. namespace Content.Shared.Construction.EntitySystems;
  23. public sealed partial class AnchorableSystem : EntitySystem
  24. {
  25. [Dependency] private readonly IMapManager _mapManager = default!;
  26. [Dependency] private readonly ISharedAdminLogManager _adminLogger = default!;
  27. [Dependency] private readonly SharedPopupSystem _popup = default!;
  28. [Dependency] private readonly PullingSystem _pulling = default!;
  29. [Dependency] private readonly SharedToolSystem _tool = default!;
  30. [Dependency] private readonly SharedTransformSystem _transformSystem = default!;
  31. [Dependency] private readonly TagSystem _tagSystem = default!;
  32. [Dependency] private readonly SharedAppearanceSystem _appearance = default!;
  33. private EntityQuery<PhysicsComponent> _physicsQuery;
  34. public readonly ProtoId<TagPrototype> Unstackable = "Unstackable";
  35. public override void Initialize()
  36. {
  37. base.Initialize();
  38. _physicsQuery = GetEntityQuery<PhysicsComponent>();
  39. SubscribeLocalEvent<AnchorableComponent, InteractUsingEvent>(OnInteractUsing,
  40. before: new[] { typeof(ItemSlotsSystem) }, after: new[] { typeof(SharedConstructionSystem) });
  41. SubscribeLocalEvent<AnchorableComponent, TryAnchorCompletedEvent>(OnAnchorComplete);
  42. SubscribeLocalEvent<AnchorableComponent, TryUnanchorCompletedEvent>(OnUnanchorComplete);
  43. SubscribeLocalEvent<AnchorableComponent, ExaminedEvent>(OnAnchoredExamine);
  44. SubscribeLocalEvent<AnchorableComponent, ComponentStartup>(OnAnchorStartup);
  45. SubscribeLocalEvent<AnchorableComponent, AnchorStateChangedEvent>(OnAnchorStateChange);
  46. }
  47. private void OnAnchorStartup(EntityUid uid, AnchorableComponent comp, ComponentStartup args)
  48. {
  49. _appearance.SetData(uid, AnchorVisuals.Anchored, Transform(uid).Anchored);
  50. }
  51. private void OnAnchorStateChange(EntityUid uid, AnchorableComponent comp, AnchorStateChangedEvent args)
  52. {
  53. _appearance.SetData(uid, AnchorVisuals.Anchored, args.Anchored);
  54. }
  55. /// <summary>
  56. /// Tries to unanchor the entity.
  57. /// </summary>
  58. /// <returns>true if unanchored, false otherwise</returns>
  59. private void TryUnAnchor(EntityUid uid, EntityUid userUid, EntityUid usingUid,
  60. AnchorableComponent? anchorable = null,
  61. TransformComponent? transform = null,
  62. ToolComponent? usingTool = null)
  63. {
  64. if (!Resolve(uid, ref anchorable, ref transform))
  65. return;
  66. if (!Resolve(usingUid, ref usingTool))
  67. return;
  68. if (!Valid(uid, userUid, usingUid, false))
  69. return;
  70. // Log unanchor attempt (server only)
  71. _adminLogger.Add(LogType.Anchor, LogImpact.Low, $"{ToPrettyString(userUid):user} is trying to unanchor {ToPrettyString(uid):entity} from {transform.Coordinates:targetlocation}");
  72. _tool.UseTool(usingUid, userUid, uid, anchorable.Delay, usingTool.Qualities, new TryUnanchorCompletedEvent());
  73. }
  74. private void OnInteractUsing(EntityUid uid, AnchorableComponent anchorable, InteractUsingEvent args)
  75. {
  76. if (args.Handled)
  77. return;
  78. // If the used entity doesn't have a tool, return early.
  79. if (!TryComp(args.Used, out ToolComponent? usedTool) || !_tool.HasQuality(args.Used, anchorable.Tool, usedTool))
  80. return;
  81. args.Handled = true;
  82. TryToggleAnchor(uid, args.User, args.Used, anchorable, usingTool: usedTool);
  83. }
  84. private void OnAnchoredExamine(EntityUid uid, AnchorableComponent component, ExaminedEvent args)
  85. {
  86. var isAnchored = Comp<TransformComponent>(uid).Anchored;
  87. var messageId = isAnchored ? "examinable-anchored" : "examinable-unanchored";
  88. args.PushMarkup(Loc.GetString(messageId, ("target", uid)));
  89. }
  90. private void OnUnanchorComplete(EntityUid uid, AnchorableComponent component, TryUnanchorCompletedEvent args)
  91. {
  92. if (args.Cancelled || args.Used is not { } used)
  93. return;
  94. var xform = Transform(uid);
  95. RaiseLocalEvent(uid, new BeforeUnanchoredEvent(args.User, used));
  96. _transformSystem.Unanchor(uid, xform);
  97. RaiseLocalEvent(uid, new UserUnanchoredEvent(args.User, used));
  98. _popup.PopupClient(Loc.GetString("anchorable-unanchored"), uid, args.User);
  99. _adminLogger.Add(
  100. LogType.Unanchor,
  101. LogImpact.Low,
  102. $"{EntityManager.ToPrettyString(args.User):user} unanchored {EntityManager.ToPrettyString(uid):anchored} using {EntityManager.ToPrettyString(used):using}"
  103. );
  104. }
  105. private void OnAnchorComplete(EntityUid uid, AnchorableComponent component, TryAnchorCompletedEvent args)
  106. {
  107. if (args.Cancelled || args.Used is not { } used)
  108. return;
  109. var xform = Transform(uid);
  110. if (TryComp<PhysicsComponent>(uid, out var anchorBody) &&
  111. !TileFree(xform.Coordinates, anchorBody))
  112. {
  113. _popup.PopupClient(Loc.GetString("anchorable-occupied"), uid, args.User);
  114. return;
  115. }
  116. // Snap rotation to cardinal (multiple of 90)
  117. var rot = xform.LocalRotation;
  118. xform.LocalRotation = Math.Round(rot / (Math.PI / 2)) * (Math.PI / 2);
  119. if (TryComp<PullableComponent>(uid, out var pullable) && pullable.Puller != null)
  120. {
  121. _pulling.TryStopPull(uid, pullable);
  122. }
  123. // TODO: Anchoring snaps rn anyway!
  124. if (component.Snap)
  125. {
  126. var coordinates = xform.Coordinates.SnapToGrid(EntityManager, _mapManager);
  127. if (AnyUnstackable(uid, coordinates))
  128. {
  129. _popup.PopupClient(Loc.GetString("construction-step-condition-no-unstackable-in-tile"), uid, args.User);
  130. return;
  131. }
  132. _transformSystem.SetCoordinates(uid, coordinates);
  133. }
  134. RaiseLocalEvent(uid, new BeforeAnchoredEvent(args.User, used));
  135. if (!xform.Anchored)
  136. _transformSystem.AnchorEntity(uid, xform);
  137. RaiseLocalEvent(uid, new UserAnchoredEvent(args.User, used));
  138. _popup.PopupClient(Loc.GetString("anchorable-anchored"), uid, args.User);
  139. _adminLogger.Add(
  140. LogType.Anchor,
  141. LogImpact.Low,
  142. $"{EntityManager.ToPrettyString(args.User):user} anchored {EntityManager.ToPrettyString(uid):anchored} using {EntityManager.ToPrettyString(used):using}"
  143. );
  144. }
  145. /// <summary>
  146. /// Tries to toggle the anchored status of this component's owner.
  147. /// override is used due to popup and adminlog being server side systems in this case.
  148. /// </summary>
  149. /// <returns>true if toggled, false otherwise</returns>
  150. public void TryToggleAnchor(EntityUid uid, EntityUid userUid, EntityUid usingUid,
  151. AnchorableComponent? anchorable = null,
  152. TransformComponent? transform = null,
  153. PullableComponent? pullable = null,
  154. ToolComponent? usingTool = null)
  155. {
  156. if (!Resolve(uid, ref transform))
  157. return;
  158. if (transform.Anchored)
  159. {
  160. TryUnAnchor(uid, userUid, usingUid, anchorable, transform, usingTool);
  161. }
  162. else
  163. {
  164. TryAnchor(uid, userUid, usingUid, anchorable, transform, pullable, usingTool);
  165. }
  166. }
  167. /// <summary>
  168. /// Tries to anchor the entity.
  169. /// </summary>
  170. /// <returns>true if anchored, false otherwise</returns>
  171. private void TryAnchor(EntityUid uid, EntityUid userUid, EntityUid usingUid,
  172. AnchorableComponent? anchorable = null,
  173. TransformComponent? transform = null,
  174. PullableComponent? pullable = null,
  175. ToolComponent? usingTool = null)
  176. {
  177. if (!Resolve(uid, ref anchorable, ref transform))
  178. return;
  179. // Optional resolves.
  180. Resolve(uid, ref pullable, false);
  181. if (!Resolve(usingUid, ref usingTool))
  182. return;
  183. if (!Valid(uid, userUid, usingUid, true, anchorable, usingTool))
  184. return;
  185. // Log anchor attempt (server only)
  186. _adminLogger.Add(LogType.Anchor, LogImpact.Low, $"{ToPrettyString(userUid):user} is trying to anchor {ToPrettyString(uid):entity} to {transform.Coordinates:targetlocation}");
  187. if (TryComp<PhysicsComponent>(uid, out var anchorBody) &&
  188. !TileFree(transform.Coordinates, anchorBody))
  189. {
  190. _popup.PopupClient(Loc.GetString("anchorable-occupied"), uid, userUid);
  191. return;
  192. }
  193. if (AnyUnstackable(uid, transform.Coordinates))
  194. {
  195. _popup.PopupClient(Loc.GetString("construction-step-condition-no-unstackable-in-tile"), uid, userUid);
  196. return;
  197. }
  198. _tool.UseTool(usingUid, userUid, uid, anchorable.Delay, usingTool.Qualities, new TryAnchorCompletedEvent());
  199. }
  200. private bool Valid(
  201. EntityUid uid,
  202. EntityUid userUid,
  203. EntityUid usingUid,
  204. bool anchoring,
  205. AnchorableComponent? anchorable = null,
  206. ToolComponent? usingTool = null)
  207. {
  208. if (!Resolve(uid, ref anchorable))
  209. return false;
  210. if (!Resolve(usingUid, ref usingTool))
  211. return false;
  212. if (anchoring && (anchorable.Flags & AnchorableFlags.Anchorable) == 0x0)
  213. return false;
  214. if (!anchoring && (anchorable.Flags & AnchorableFlags.Unanchorable) == 0x0)
  215. return false;
  216. BaseAnchoredAttemptEvent attempt =
  217. anchoring ? new AnchorAttemptEvent(userUid, usingUid) : new UnanchorAttemptEvent(userUid, usingUid);
  218. // Need to cast the event or it will be raised as BaseAnchoredAttemptEvent.
  219. if (anchoring)
  220. RaiseLocalEvent(uid, (AnchorAttemptEvent) attempt);
  221. else
  222. RaiseLocalEvent(uid, (UnanchorAttemptEvent) attempt);
  223. anchorable.Delay += attempt.Delay;
  224. return !attempt.Cancelled;
  225. }
  226. private bool TileFree(EntityCoordinates coordinates, PhysicsComponent anchorBody)
  227. {
  228. // Probably ignore CanCollide on the anchoring body?
  229. var gridUid = coordinates.GetGridUid(EntityManager);
  230. if (!TryComp<MapGridComponent>(gridUid, out var grid))
  231. return false;
  232. var tileIndices = grid.TileIndicesFor(coordinates);
  233. return TileFree(grid, tileIndices, anchorBody.CollisionLayer, anchorBody.CollisionMask);
  234. }
  235. /// <summary>
  236. /// Returns true if no hard anchored entities match the collision layer or mask specified.
  237. /// </summary>
  238. /// <param name="grid"></param>
  239. public bool TileFree(MapGridComponent grid, Vector2i gridIndices, int collisionLayer = 0, int collisionMask = 0)
  240. {
  241. var enumerator = grid.GetAnchoredEntitiesEnumerator(gridIndices);
  242. while (enumerator.MoveNext(out var ent))
  243. {
  244. if (!_physicsQuery.TryGetComponent(ent, out var body) ||
  245. !body.CanCollide ||
  246. !body.Hard)
  247. {
  248. continue;
  249. }
  250. if ((body.CollisionMask & collisionLayer) != 0x0 ||
  251. (body.CollisionLayer & collisionMask) != 0x0)
  252. {
  253. return false;
  254. }
  255. }
  256. return true;
  257. }
  258. /// <summary>
  259. /// Returns true if any unstackables are also on the corresponding tile.
  260. /// </summary>
  261. public bool AnyUnstackable(EntityUid uid, EntityCoordinates location)
  262. {
  263. DebugTools.Assert(!Transform(uid).Anchored);
  264. // If we are unstackable, iterate through any other entities anchored on the current square
  265. return _tagSystem.HasTag(uid, Unstackable) && AnyUnstackablesAnchoredAt(location);
  266. }
  267. public bool AnyUnstackablesAnchoredAt(EntityCoordinates location)
  268. {
  269. var gridUid = location.GetGridUid(EntityManager);
  270. if (!TryComp<MapGridComponent>(gridUid, out var grid))
  271. return false;
  272. var enumerator = grid.GetAnchoredEntitiesEnumerator(grid.LocalToTile(location));
  273. while (enumerator.MoveNext(out var entity))
  274. {
  275. // If we find another unstackable here, return true.
  276. if (_tagSystem.HasTag(entity.Value, Unstackable))
  277. return true;
  278. }
  279. return false;
  280. }
  281. [Serializable, NetSerializable]
  282. private sealed partial class TryUnanchorCompletedEvent : SimpleDoAfterEvent
  283. {
  284. }
  285. [Serializable, NetSerializable]
  286. private sealed partial class TryAnchorCompletedEvent : SimpleDoAfterEvent
  287. {
  288. }
  289. }
  290. [Serializable, NetSerializable]
  291. public enum AnchorVisuals : byte
  292. {
  293. Anchored
  294. }