1
0

ConstructionSystem.Initial.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. using System.IO;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using Content.Server.Construction.Components;
  5. using Content.Shared.ActionBlocker;
  6. using Content.Shared.Construction;
  7. using Content.Shared.Construction.Prototypes;
  8. using Content.Shared.Construction.Steps;
  9. using Content.Shared.Coordinates;
  10. using Content.Shared.Database;
  11. using Content.Shared.DoAfter;
  12. using Content.Shared.Hands.Components;
  13. using Content.Shared.Hands.EntitySystems;
  14. using Content.Shared.Interaction;
  15. using Content.Shared.Inventory;
  16. using Content.Shared.Storage;
  17. using Content.Shared.Whitelist;
  18. using Robust.Shared.Containers;
  19. using Robust.Shared.Map;
  20. using Robust.Shared.Player;
  21. using Robust.Shared.Timing;
  22. namespace Content.Server.Construction
  23. {
  24. public sealed partial class ConstructionSystem
  25. {
  26. [Dependency] private readonly IComponentFactory _factory = default!;
  27. [Dependency] private readonly InventorySystem _inventorySystem = default!;
  28. [Dependency] private readonly SharedInteractionSystem _interactionSystem = default!;
  29. [Dependency] private readonly ActionBlockerSystem _actionBlocker = default!;
  30. [Dependency] private readonly SharedHandsSystem _handsSystem = default!;
  31. [Dependency] private readonly EntityLookupSystem _lookupSystem = default!;
  32. [Dependency] private readonly SharedTransformSystem _transformSystem = default!;
  33. [Dependency] private readonly EntityWhitelistSystem _whitelistSystem = default!;
  34. // --- WARNING! LEGACY CODE AHEAD! ---
  35. // This entire file contains the legacy code for initial construction.
  36. // This is bound to be replaced by a better alternative (probably using dummy entities)
  37. // but for now I've isolated them in their own little file. This code is largely unchanged.
  38. // --- YOU HAVE BEEN WARNED! AAAH! ---
  39. private readonly Dictionary<ICommonSession, HashSet<int>> _beingBuilt = new();
  40. private void InitializeInitial()
  41. {
  42. SubscribeNetworkEvent<TryStartStructureConstructionMessage>(HandleStartStructureConstruction);
  43. SubscribeNetworkEvent<TryStartItemConstructionMessage>(HandleStartItemConstruction);
  44. }
  45. // LEGACY CODE. See warning at the top of the file!
  46. private IEnumerable<EntityUid> EnumerateNearby(EntityUid user)
  47. {
  48. foreach (var item in _handsSystem.EnumerateHeld(user))
  49. {
  50. if (TryComp(item, out StorageComponent? storage))
  51. {
  52. foreach (var storedEntity in storage.Container.ContainedEntities!)
  53. {
  54. yield return storedEntity;
  55. }
  56. }
  57. yield return item;
  58. }
  59. if (_inventorySystem.TryGetContainerSlotEnumerator(user, out var containerSlotEnumerator))
  60. {
  61. while (containerSlotEnumerator.MoveNext(out var containerSlot))
  62. {
  63. if(!containerSlot.ContainedEntity.HasValue)
  64. continue;
  65. if (EntityManager.TryGetComponent(containerSlot.ContainedEntity.Value, out StorageComponent? storage))
  66. {
  67. foreach (var storedEntity in storage.Container.ContainedEntities)
  68. {
  69. yield return storedEntity;
  70. }
  71. }
  72. yield return containerSlot.ContainedEntity.Value;
  73. }
  74. }
  75. var pos = _transformSystem.GetMapCoordinates(user);
  76. foreach (var near in _lookupSystem.GetEntitiesInRange(pos, 2f, LookupFlags.Contained | LookupFlags.Dynamic | LookupFlags.Sundries | LookupFlags.Approximate))
  77. {
  78. if (near == user)
  79. continue;
  80. if (_interactionSystem.InRangeUnobstructed(pos, near, 2f) && _container.IsInSameOrParentContainer(user, near))
  81. yield return near;
  82. }
  83. }
  84. // LEGACY CODE. See warning at the top of the file!
  85. private async Task<EntityUid?> Construct(
  86. EntityUid user,
  87. string materialContainer,
  88. ConstructionGraphPrototype graph,
  89. ConstructionGraphEdge edge,
  90. ConstructionGraphNode targetNode,
  91. EntityCoordinates coords,
  92. Angle angle = default)
  93. {
  94. // We need a place to hold our construction items!
  95. var container = _container.EnsureContainer<Container>(user, materialContainer, out var existed);
  96. var containers = new Dictionary<string, Container>();
  97. var doAfterTime = 0f;
  98. // HOLY SHIT THIS IS SOME HACKY CODE.
  99. // But I'd rather do this shit than risk having collisions with other containers.
  100. Container GetContainer(string name)
  101. {
  102. if (containers.TryGetValue(name, out var container1))
  103. return container1;
  104. while (true)
  105. {
  106. var random = _robustRandom.Next();
  107. var c = _container.EnsureContainer<Container>(user, random.ToString(), out var exists);
  108. if (exists)
  109. continue;
  110. containers[name] = c;
  111. return c;
  112. }
  113. }
  114. void FailCleanup()
  115. {
  116. foreach (var entity in container.ContainedEntities.ToArray())
  117. {
  118. _container.Remove(entity, container);
  119. }
  120. foreach (var cont in containers.Values)
  121. {
  122. foreach (var entity in cont.ContainedEntities.ToArray())
  123. {
  124. _container.Remove(entity, cont);
  125. }
  126. }
  127. // If we don't do this, items are invisible for some fucking reason. Nice.
  128. Timer.Spawn(1, ShutdownContainers);
  129. }
  130. void ShutdownContainers()
  131. {
  132. _container.ShutdownContainer(container);
  133. foreach (var c in containers.Values.ToArray())
  134. {
  135. _container.ShutdownContainer(c);
  136. }
  137. }
  138. var failed = false;
  139. var steps = new List<ConstructionGraphStep>();
  140. var used = new HashSet<EntityUid>();
  141. foreach (var step in edge.Steps)
  142. {
  143. doAfterTime += step.DoAfter;
  144. var handled = false;
  145. switch (step)
  146. {
  147. case MaterialConstructionGraphStep materialStep:
  148. foreach (var entity in EnumerateNearby(user))
  149. {
  150. if (!materialStep.EntityValid(entity, out var stack))
  151. continue;
  152. if (used.Contains(entity))
  153. continue;
  154. // TODO allow taking from several stacks.
  155. // Also update crafting steps to check if it works.
  156. var splitStack = _stackSystem.Split(entity, materialStep.Amount, user.ToCoordinates(0, 0), stack);
  157. if (splitStack == null)
  158. continue;
  159. if (string.IsNullOrEmpty(materialStep.Store))
  160. {
  161. if (!_container.Insert(splitStack.Value, container))
  162. continue;
  163. }
  164. else if (!_container.Insert(splitStack.Value, GetContainer(materialStep.Store)))
  165. continue;
  166. handled = true;
  167. break;
  168. }
  169. break;
  170. case ArbitraryInsertConstructionGraphStep arbitraryStep:
  171. foreach (var entity in new HashSet<EntityUid>(EnumerateNearby(user)))
  172. {
  173. if (!arbitraryStep.EntityValid(entity, EntityManager, _factory))
  174. continue;
  175. if (used.Contains(entity))
  176. continue;
  177. // Dump out any stored entities in used entity
  178. if (TryComp<StorageComponent>(entity, out var storage))
  179. {
  180. _container.EmptyContainer(storage.Container);
  181. }
  182. if (string.IsNullOrEmpty(arbitraryStep.Store))
  183. {
  184. if (!_container.Insert(entity, container))
  185. continue;
  186. }
  187. else if (!_container.Insert(entity, GetContainer(arbitraryStep.Store)))
  188. continue;
  189. handled = true;
  190. used.Add(entity);
  191. break;
  192. }
  193. break;
  194. }
  195. if (handled == false)
  196. {
  197. failed = true;
  198. break;
  199. }
  200. steps.Add(step);
  201. }
  202. if (failed)
  203. {
  204. _popup.PopupEntity(Loc.GetString("construction-system-construct-no-materials"), user, user);
  205. FailCleanup();
  206. return null;
  207. }
  208. var doAfterArgs = new DoAfterArgs(EntityManager, user, doAfterTime, new AwaitedDoAfterEvent(), null)
  209. {
  210. BreakOnDamage = true,
  211. BreakOnMove = true,
  212. NeedHand = false,
  213. // allow simultaneously starting several construction jobs using the same stack of materials.
  214. CancelDuplicate = false,
  215. BlockDuplicate = false,
  216. };
  217. if (await _doAfterSystem.WaitDoAfter(doAfterArgs) == DoAfterStatus.Cancelled)
  218. {
  219. FailCleanup();
  220. return null;
  221. }
  222. var newEntityProto = graph.Nodes[edge.Target].Entity.GetId(null, user, new(EntityManager));
  223. var newEntity = EntityManager.SpawnAttachedTo(newEntityProto, coords, rotation: angle);
  224. if (!TryComp(newEntity, out ConstructionComponent? construction))
  225. {
  226. Log.Error($"Initial construction does not have a valid target entity! It is missing a ConstructionComponent.\nGraph: {graph.ID}, Initial Target: {edge.Target}, Ent. Prototype: {newEntityProto}\nCreated Entity {ToPrettyString(newEntity)} will be deleted.");
  227. Del(newEntity); // Screw you, make proper construction graphs.
  228. return null;
  229. }
  230. // We attempt to set the pathfinding target.
  231. SetPathfindingTarget(newEntity, targetNode.Name, construction);
  232. // We preserve the containers...
  233. foreach (var (name, cont) in containers)
  234. {
  235. var newCont = _container.EnsureContainer<Container>(newEntity, name);
  236. foreach (var entity in cont.ContainedEntities.ToArray())
  237. {
  238. _container.Remove(entity, cont, reparent: false, force: true);
  239. _container.Insert(entity, newCont);
  240. }
  241. }
  242. // We now get rid of all them.
  243. ShutdownContainers();
  244. // We have step completed steps!
  245. foreach (var step in steps)
  246. {
  247. foreach (var completed in step.Completed)
  248. {
  249. completed.PerformAction(newEntity, user, EntityManager);
  250. }
  251. }
  252. // And we also have edge completed effects!
  253. foreach (var completed in edge.Completed)
  254. {
  255. completed.PerformAction(newEntity, user, EntityManager);
  256. }
  257. return newEntity;
  258. }
  259. private async void HandleStartItemConstruction(TryStartItemConstructionMessage ev, EntitySessionEventArgs args)
  260. {
  261. if (args.SenderSession.AttachedEntity is {Valid: true} user)
  262. await TryStartItemConstruction(ev.PrototypeName, user);
  263. }
  264. // LEGACY CODE. See warning at the top of the file!
  265. public async Task<bool> TryStartItemConstruction(string prototype, EntityUid user)
  266. {
  267. if (!PrototypeManager.TryIndex(prototype, out ConstructionPrototype? constructionPrototype))
  268. {
  269. Log.Error($"Tried to start construction of invalid recipe '{prototype}'!");
  270. return false;
  271. }
  272. if (!PrototypeManager.TryIndex(constructionPrototype.Graph,
  273. out ConstructionGraphPrototype? constructionGraph))
  274. {
  275. Log.Error(
  276. $"Invalid construction graph '{constructionPrototype.Graph}' in recipe '{prototype}'!");
  277. return false;
  278. }
  279. if (_whitelistSystem.IsWhitelistFail(constructionPrototype.EntityWhitelist, user))
  280. {
  281. _popup.PopupEntity(Loc.GetString("construction-system-cannot-start"), user, user);
  282. return false;
  283. }
  284. var startNode = constructionGraph.Nodes[constructionPrototype.StartNode];
  285. var targetNode = constructionGraph.Nodes[constructionPrototype.TargetNode];
  286. var pathFind = constructionGraph.Path(startNode.Name, targetNode.Name);
  287. if (!_actionBlocker.CanInteract(user, null))
  288. return false;
  289. if (!HasComp<HandsComponent>(user))
  290. return false;
  291. foreach (var condition in constructionPrototype.Conditions)
  292. {
  293. if (!condition.Condition(user, user.ToCoordinates(0, 0), Direction.South))
  294. return false;
  295. }
  296. if (pathFind == null)
  297. {
  298. throw new InvalidDataException(
  299. $"Can't find path from starting node to target node in construction! Recipe: {prototype}");
  300. }
  301. var edge = startNode.GetEdge(pathFind[0].Name);
  302. if (edge == null)
  303. {
  304. throw new InvalidDataException(
  305. $"Can't find edge from starting node to the next node in pathfinding! Recipe: {prototype}");
  306. }
  307. // No support for conditions here!
  308. foreach (var step in edge.Steps)
  309. {
  310. switch (step)
  311. {
  312. case ToolConstructionGraphStep _:
  313. throw new InvalidDataException("Invalid first step for construction recipe!");
  314. }
  315. }
  316. if (await Construct(
  317. user,
  318. "item_construction",
  319. constructionGraph,
  320. edge,
  321. targetNode,
  322. Transform(user).Coordinates) is not { Valid: true } item)
  323. return false;
  324. // Just in case this is a stack, attempt to merge it. If it isn't a stack, this will just normally pick up
  325. // or drop the item as normal.
  326. _stackSystem.TryMergeToHands(item, user);
  327. return true;
  328. }
  329. // LEGACY CODE. See warning at the top of the file!
  330. private async void HandleStartStructureConstruction(TryStartStructureConstructionMessage ev, EntitySessionEventArgs args)
  331. {
  332. if (!PrototypeManager.TryIndex(ev.PrototypeName, out ConstructionPrototype? constructionPrototype))
  333. {
  334. Log.Error($"Tried to start construction of invalid recipe '{ev.PrototypeName}'!");
  335. RaiseNetworkEvent(new AckStructureConstructionMessage(ev.Ack));
  336. return;
  337. }
  338. if (!PrototypeManager.TryIndex(constructionPrototype.Graph, out ConstructionGraphPrototype? constructionGraph))
  339. {
  340. Log.Error($"Invalid construction graph '{constructionPrototype.Graph}' in recipe '{ev.PrototypeName}'!");
  341. RaiseNetworkEvent(new AckStructureConstructionMessage(ev.Ack));
  342. return;
  343. }
  344. if (args.SenderSession.AttachedEntity is not {Valid: true} user)
  345. {
  346. Log.Error($"Client sent {nameof(TryStartStructureConstructionMessage)} with no attached entity!");
  347. return;
  348. }
  349. if (_whitelistSystem.IsWhitelistFail(constructionPrototype.EntityWhitelist, user))
  350. {
  351. _popup.PopupEntity(Loc.GetString("construction-system-cannot-start"), user, user);
  352. return;
  353. }
  354. if (_container.IsEntityInContainer(user))
  355. {
  356. _popup.PopupEntity(Loc.GetString("construction-system-inside-container"), user, user);
  357. return;
  358. }
  359. var startNode = constructionGraph.Nodes[constructionPrototype.StartNode];
  360. var targetNode = constructionGraph.Nodes[constructionPrototype.TargetNode];
  361. var pathFind = constructionGraph.Path(startNode.Name, targetNode.Name);
  362. if (_beingBuilt.TryGetValue(args.SenderSession, out var set))
  363. {
  364. if (!set.Add(ev.Ack))
  365. {
  366. _popup.PopupEntity(Loc.GetString("construction-system-already-building"), user, user);
  367. return;
  368. }
  369. }
  370. else
  371. {
  372. var newSet = new HashSet<int> {ev.Ack};
  373. _beingBuilt[args.SenderSession] = newSet;
  374. }
  375. var location = GetCoordinates(ev.Location);
  376. foreach (var condition in constructionPrototype.Conditions)
  377. {
  378. if (!condition.Condition(user, location, ev.Angle.GetCardinalDir()))
  379. {
  380. Cleanup();
  381. return;
  382. }
  383. }
  384. void Cleanup()
  385. {
  386. _beingBuilt[args.SenderSession].Remove(ev.Ack);
  387. }
  388. if (!_actionBlocker.CanInteract(user, null)
  389. || !EntityManager.TryGetComponent(user, out HandsComponent? hands) || hands.ActiveHandEntity == null)
  390. {
  391. Cleanup();
  392. return;
  393. }
  394. var mapPos = location.ToMap(EntityManager, _transformSystem);
  395. var predicate = GetPredicate(constructionPrototype.CanBuildInImpassable, mapPos);
  396. if (!_interactionSystem.InRangeUnobstructed(user, mapPos, predicate: predicate))
  397. {
  398. Cleanup();
  399. return;
  400. }
  401. if (pathFind == null)
  402. throw new InvalidDataException($"Can't find path from starting node to target node in construction! Recipe: {ev.PrototypeName}");
  403. var edge = startNode.GetEdge(pathFind[0].Name);
  404. if(edge == null)
  405. throw new InvalidDataException($"Can't find edge from starting node to the next node in pathfinding! Recipe: {ev.PrototypeName}");
  406. var valid = false;
  407. if (hands.ActiveHandEntity is not {Valid: true} holding)
  408. {
  409. Cleanup();
  410. return;
  411. }
  412. // No support for conditions here!
  413. foreach (var step in edge.Steps)
  414. {
  415. switch (step)
  416. {
  417. case EntityInsertConstructionGraphStep entityInsert:
  418. if (entityInsert.EntityValid(holding, EntityManager, _factory))
  419. valid = true;
  420. break;
  421. case ToolConstructionGraphStep _:
  422. throw new InvalidDataException("Invalid first step for item recipe!");
  423. }
  424. if (valid)
  425. break;
  426. }
  427. if (!valid)
  428. {
  429. Cleanup();
  430. return;
  431. }
  432. if (await Construct(user,
  433. (ev.Ack + constructionPrototype.GetHashCode()).ToString(),
  434. constructionGraph,
  435. edge,
  436. targetNode,
  437. GetCoordinates(ev.Location),
  438. constructionPrototype.CanRotate ? ev.Angle : Angle.Zero) is not {Valid: true} structure)
  439. {
  440. Cleanup();
  441. return;
  442. }
  443. RaiseNetworkEvent(new AckStructureConstructionMessage(ev.Ack, GetNetEntity(structure)));
  444. _adminLogger.Add(LogType.Construction, LogImpact.Low, $"{ToPrettyString(user):player} has turned a {ev.PrototypeName} construction ghost into {ToPrettyString(structure)} at {Transform(structure).Coordinates}");
  445. Cleanup();
  446. }
  447. }
  448. }