ConstructionSystem.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. using System.Diagnostics.CodeAnalysis;
  2. using Content.Client.Popups;
  3. using Content.Shared.Construction;
  4. using Content.Shared.Construction.Prototypes;
  5. using Content.Shared.Construction.Steps;
  6. using Content.Shared.Examine;
  7. using Content.Shared.Input;
  8. using Content.Shared.Interaction;
  9. using Content.Shared.Wall;
  10. using JetBrains.Annotations;
  11. using Robust.Client.GameObjects;
  12. using Robust.Client.Player;
  13. using Robust.Shared.Input;
  14. using Robust.Shared.Input.Binding;
  15. using Robust.Shared.Map;
  16. using Robust.Shared.Player;
  17. using Robust.Shared.Prototypes;
  18. namespace Content.Client.Construction
  19. {
  20. /// <summary>
  21. /// The client-side implementation of the construction system, which is used for constructing entities in game.
  22. /// </summary>
  23. [UsedImplicitly]
  24. public sealed class ConstructionSystem : SharedConstructionSystem
  25. {
  26. [Dependency] private readonly IPlayerManager _playerManager = default!;
  27. [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
  28. [Dependency] private readonly ExamineSystemShared _examineSystem = default!;
  29. [Dependency] private readonly SharedTransformSystem _transformSystem = default!;
  30. [Dependency] private readonly PopupSystem _popupSystem = default!;
  31. private readonly Dictionary<int, EntityUid> _ghosts = new();
  32. private readonly Dictionary<string, ConstructionGuide> _guideCache = new();
  33. public bool CraftingEnabled { get; private set; }
  34. /// <inheritdoc />
  35. public override void Initialize()
  36. {
  37. base.Initialize();
  38. UpdatesOutsidePrediction = true;
  39. SubscribeLocalEvent<LocalPlayerAttachedEvent>(HandlePlayerAttached);
  40. SubscribeNetworkEvent<AckStructureConstructionMessage>(HandleAckStructure);
  41. SubscribeNetworkEvent<ResponseConstructionGuide>(OnConstructionGuideReceived);
  42. CommandBinds.Builder
  43. .Bind(ContentKeyFunctions.OpenCraftingMenu,
  44. new PointerInputCmdHandler(HandleOpenCraftingMenu, outsidePrediction: true))
  45. .Bind(EngineKeyFunctions.Use,
  46. new PointerInputCmdHandler(HandleUse, outsidePrediction: true))
  47. .Bind(ContentKeyFunctions.EditorFlipObject,
  48. new PointerInputCmdHandler(HandleFlip, outsidePrediction: true))
  49. .Register<ConstructionSystem>();
  50. SubscribeLocalEvent<ConstructionGhostComponent, ExaminedEvent>(HandleConstructionGhostExamined);
  51. SubscribeLocalEvent<ConstructionGhostComponent, ComponentShutdown>(HandleGhostComponentShutdown);
  52. }
  53. private void HandleGhostComponentShutdown(EntityUid uid, ConstructionGhostComponent component, ComponentShutdown args)
  54. {
  55. ClearGhost(component.GhostId);
  56. }
  57. private void OnConstructionGuideReceived(ResponseConstructionGuide ev)
  58. {
  59. _guideCache[ev.ConstructionId] = ev.Guide;
  60. ConstructionGuideAvailable?.Invoke(this, ev.ConstructionId);
  61. }
  62. /// <inheritdoc />
  63. public override void Shutdown()
  64. {
  65. base.Shutdown();
  66. CommandBinds.Unregister<ConstructionSystem>();
  67. }
  68. public ConstructionGuide? GetGuide(ConstructionPrototype prototype)
  69. {
  70. if (_guideCache.TryGetValue(prototype.ID, out var guide))
  71. return guide;
  72. RaiseNetworkEvent(new RequestConstructionGuide(prototype.ID));
  73. return null;
  74. }
  75. private void HandleConstructionGhostExamined(EntityUid uid, ConstructionGhostComponent component, ExaminedEvent args)
  76. {
  77. if (component.Prototype == null)
  78. return;
  79. using (args.PushGroup(nameof(ConstructionGhostComponent)))
  80. {
  81. args.PushMarkup(Loc.GetString(
  82. "construction-ghost-examine-message",
  83. ("name", component.Prototype.Name)));
  84. if (!_prototypeManager.TryIndex(component.Prototype.Graph, out ConstructionGraphPrototype? graph))
  85. return;
  86. var startNode = graph.Nodes[component.Prototype.StartNode];
  87. if (!graph.TryPath(component.Prototype.StartNode, component.Prototype.TargetNode, out var path) ||
  88. !startNode.TryGetEdge(path[0].Name, out var edge))
  89. {
  90. return;
  91. }
  92. foreach (var step in edge.Steps)
  93. {
  94. step.DoExamine(args);
  95. }
  96. }
  97. }
  98. public event EventHandler<CraftingAvailabilityChangedArgs>? CraftingAvailabilityChanged;
  99. public event EventHandler<string>? ConstructionGuideAvailable;
  100. public event EventHandler? ToggleCraftingWindow;
  101. public event EventHandler? FlipConstructionPrototype;
  102. private void HandleAckStructure(AckStructureConstructionMessage msg)
  103. {
  104. // We get sent a NetEntity but it actually corresponds to our local Entity.
  105. ClearGhost(msg.GhostId);
  106. }
  107. private void HandlePlayerAttached(LocalPlayerAttachedEvent msg)
  108. {
  109. var available = IsCraftingAvailable(msg.Entity);
  110. UpdateCraftingAvailability(available);
  111. }
  112. private bool HandleOpenCraftingMenu(in PointerInputCmdHandler.PointerInputCmdArgs args)
  113. {
  114. if (args.State == BoundKeyState.Down)
  115. ToggleCraftingWindow?.Invoke(this, EventArgs.Empty);
  116. return true;
  117. }
  118. private bool HandleFlip(in PointerInputCmdHandler.PointerInputCmdArgs args)
  119. {
  120. if (args.State == BoundKeyState.Down)
  121. FlipConstructionPrototype?.Invoke(this, EventArgs.Empty);
  122. return true;
  123. }
  124. private void UpdateCraftingAvailability(bool available)
  125. {
  126. if (CraftingEnabled == available)
  127. return;
  128. CraftingAvailabilityChanged?.Invoke(this, new CraftingAvailabilityChangedArgs(available));
  129. CraftingEnabled = available;
  130. }
  131. private static bool IsCraftingAvailable(EntityUid? entity)
  132. {
  133. if (entity == default)
  134. return false;
  135. // TODO: Decide if entity can craft, using capabilities or something
  136. return true;
  137. }
  138. private bool HandleUse(in PointerInputCmdHandler.PointerInputCmdArgs args)
  139. {
  140. if (!args.EntityUid.IsValid() || !IsClientSide(args.EntityUid))
  141. return false;
  142. if (!HasComp<ConstructionGhostComponent>(args.EntityUid))
  143. return false;
  144. TryStartConstruction(args.EntityUid);
  145. return true;
  146. }
  147. /// <summary>
  148. /// Creates a construction ghost at the given location.
  149. /// </summary>
  150. public void SpawnGhost(ConstructionPrototype prototype, EntityCoordinates loc, Direction dir)
  151. => TrySpawnGhost(prototype, loc, dir, out _);
  152. /// <summary>
  153. /// Creates a construction ghost at the given location.
  154. /// </summary>
  155. public bool TrySpawnGhost(
  156. ConstructionPrototype prototype,
  157. EntityCoordinates loc,
  158. Direction dir,
  159. [NotNullWhen(true)] out EntityUid? ghost)
  160. {
  161. ghost = null;
  162. if (_playerManager.LocalEntity is not { } user ||
  163. !user.IsValid())
  164. {
  165. return false;
  166. }
  167. if (GhostPresent(loc))
  168. return false;
  169. var predicate = GetPredicate(prototype.CanBuildInImpassable, _transformSystem.ToMapCoordinates(loc));
  170. if (!_examineSystem.InRangeUnOccluded(user, loc, 20f, predicate: predicate))
  171. return false;
  172. if (!CheckConstructionConditions(prototype, loc, dir, user, showPopup: true))
  173. return false;
  174. ghost = EntityManager.SpawnEntity("constructionghost", loc);
  175. var comp = EntityManager.GetComponent<ConstructionGhostComponent>(ghost.Value);
  176. comp.Prototype = prototype;
  177. comp.GhostId = ghost.GetHashCode();
  178. EntityManager.GetComponent<TransformComponent>(ghost.Value).LocalRotation = dir.ToAngle();
  179. _ghosts.Add(comp.GhostId, ghost.Value);
  180. var sprite = EntityManager.GetComponent<SpriteComponent>(ghost.Value);
  181. sprite.Color = new Color(48, 255, 48, 128);
  182. for (int i = 0; i < prototype.Layers.Count; i++)
  183. {
  184. sprite.AddBlankLayer(i); // There is no way to actually check if this already exists, so we blindly insert a new one
  185. sprite.LayerSetSprite(i, prototype.Layers[i]);
  186. sprite.LayerSetShader(i, "unshaded");
  187. sprite.LayerSetVisible(i, true);
  188. }
  189. if (prototype.CanBuildInImpassable)
  190. EnsureComp<WallMountComponent>(ghost.Value).Arc = new(Math.Tau);
  191. return true;
  192. }
  193. private bool CheckConstructionConditions(ConstructionPrototype prototype, EntityCoordinates loc, Direction dir,
  194. EntityUid user, bool showPopup = false)
  195. {
  196. foreach (var condition in prototype.Conditions)
  197. {
  198. if (!condition.Condition(user, loc, dir))
  199. {
  200. if (showPopup)
  201. {
  202. var message = condition.GenerateGuideEntry()?.Localization;
  203. if (message != null)
  204. {
  205. // Show the reason to the user:
  206. _popupSystem.PopupCoordinates(Loc.GetString(message), loc);
  207. }
  208. }
  209. return false;
  210. }
  211. }
  212. return true;
  213. }
  214. /// <summary>
  215. /// Checks if any construction ghosts are present at the given position
  216. /// </summary>
  217. private bool GhostPresent(EntityCoordinates loc)
  218. {
  219. foreach (var ghost in _ghosts)
  220. {
  221. if (EntityManager.GetComponent<TransformComponent>(ghost.Value).Coordinates.Equals(loc))
  222. return true;
  223. }
  224. return false;
  225. }
  226. public void TryStartConstruction(EntityUid ghostId, ConstructionGhostComponent? ghostComp = null)
  227. {
  228. if (!Resolve(ghostId, ref ghostComp))
  229. return;
  230. if (ghostComp.Prototype == null)
  231. {
  232. throw new ArgumentException($"Can't start construction for a ghost with no prototype. Ghost id: {ghostId}");
  233. }
  234. var transform = EntityManager.GetComponent<TransformComponent>(ghostId);
  235. var msg = new TryStartStructureConstructionMessage(GetNetCoordinates(transform.Coordinates), ghostComp.Prototype.ID, transform.LocalRotation, ghostId.GetHashCode());
  236. RaiseNetworkEvent(msg);
  237. }
  238. /// <summary>
  239. /// Starts constructing an item underneath the attached entity.
  240. /// </summary>
  241. public void TryStartItemConstruction(string prototypeName)
  242. {
  243. RaiseNetworkEvent(new TryStartItemConstructionMessage(prototypeName));
  244. }
  245. /// <summary>
  246. /// Removes a construction ghost entity with the given ID.
  247. /// </summary>
  248. public void ClearGhost(int ghostId)
  249. {
  250. if (!_ghosts.TryGetValue(ghostId, out var ghost))
  251. return;
  252. EntityManager.QueueDeleteEntity(ghost);
  253. _ghosts.Remove(ghostId);
  254. }
  255. /// <summary>
  256. /// Removes all construction ghosts.
  257. /// </summary>
  258. public void ClearAllGhosts()
  259. {
  260. foreach (var ghost in _ghosts.Values)
  261. {
  262. EntityManager.QueueDeleteEntity(ghost);
  263. }
  264. _ghosts.Clear();
  265. }
  266. }
  267. public sealed class CraftingAvailabilityChangedArgs : EventArgs
  268. {
  269. public bool Available { get; }
  270. public CraftingAvailabilityChangedArgs(bool available)
  271. {
  272. Available = available;
  273. }
  274. }
  275. }