1
0

NukeopsRuleSystem.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. using Content.Server.Antag;
  2. using Content.Server.Communications;
  3. using Content.Server.GameTicking.Rules.Components;
  4. using Content.Server.Nuke;
  5. using Content.Server.NukeOps;
  6. using Content.Server.Popups;
  7. using Content.Server.Roles;
  8. using Content.Server.RoundEnd;
  9. using Content.Server.Shuttles.Events;
  10. using Content.Server.Shuttles.Systems;
  11. using Content.Server.Station.Components;
  12. using Content.Server.Store.Systems;
  13. using Content.Shared.GameTicking.Components;
  14. using Content.Shared.Mobs;
  15. using Content.Shared.Mobs.Components;
  16. using Content.Shared.NPC.Components;
  17. using Content.Shared.NPC.Systems;
  18. using Content.Shared.Nuke;
  19. using Content.Shared.NukeOps;
  20. using Content.Shared.Store;
  21. using Content.Shared.Tag;
  22. using Content.Shared.Zombies;
  23. using Robust.Shared.Map;
  24. using Robust.Shared.Random;
  25. using Robust.Shared.Utility;
  26. using System.Linq;
  27. using Content.Shared.Store.Components;
  28. namespace Content.Server.GameTicking.Rules;
  29. public sealed class NukeopsRuleSystem : GameRuleSystem<NukeopsRuleComponent>
  30. {
  31. [Dependency] private readonly AntagSelectionSystem _antag = default!;
  32. [Dependency] private readonly EmergencyShuttleSystem _emergency = default!;
  33. [Dependency] private readonly NpcFactionSystem _npcFaction = default!;
  34. [Dependency] private readonly PopupSystem _popupSystem = default!;
  35. [Dependency] private readonly RoundEndSystem _roundEndSystem = default!;
  36. [Dependency] private readonly StoreSystem _store = default!;
  37. [Dependency] private readonly TagSystem _tag = default!;
  38. [ValidatePrototypeId<CurrencyPrototype>]
  39. private const string TelecrystalCurrencyPrototype = "Telecrystal";
  40. [ValidatePrototypeId<TagPrototype>]
  41. private const string NukeOpsUplinkTagPrototype = "NukeOpsUplink";
  42. public override void Initialize()
  43. {
  44. base.Initialize();
  45. SubscribeLocalEvent<NukeExplodedEvent>(OnNukeExploded);
  46. SubscribeLocalEvent<GameRunLevelChangedEvent>(OnRunLevelChanged);
  47. SubscribeLocalEvent<NukeDisarmSuccessEvent>(OnNukeDisarm);
  48. SubscribeLocalEvent<NukeOperativeComponent, ComponentRemove>(OnComponentRemove);
  49. SubscribeLocalEvent<NukeOperativeComponent, MobStateChangedEvent>(OnMobStateChanged);
  50. SubscribeLocalEvent<NukeOperativeComponent, EntityZombifiedEvent>(OnOperativeZombified);
  51. SubscribeLocalEvent<NukeopsRoleComponent, GetBriefingEvent>(OnGetBriefing);
  52. SubscribeLocalEvent<ConsoleFTLAttemptEvent>(OnShuttleFTLAttempt);
  53. SubscribeLocalEvent<WarDeclaredEvent>(OnWarDeclared);
  54. SubscribeLocalEvent<CommunicationConsoleCallShuttleAttemptEvent>(OnShuttleCallAttempt);
  55. SubscribeLocalEvent<NukeopsRuleComponent, AfterAntagEntitySelectedEvent>(OnAfterAntagEntSelected);
  56. SubscribeLocalEvent<NukeopsRuleComponent, RuleLoadedGridsEvent>(OnRuleLoadedGrids);
  57. }
  58. protected override void Started(EntityUid uid,
  59. NukeopsRuleComponent component,
  60. GameRuleComponent gameRule,
  61. GameRuleStartedEvent args)
  62. {
  63. var eligible = new List<Entity<StationEventEligibleComponent, NpcFactionMemberComponent>>();
  64. var eligibleQuery = EntityQueryEnumerator<StationEventEligibleComponent, NpcFactionMemberComponent>();
  65. while (eligibleQuery.MoveNext(out var eligibleUid, out var eligibleComp, out var member))
  66. {
  67. if (!_npcFaction.IsFactionHostile(component.Faction, (eligibleUid, member)))
  68. continue;
  69. eligible.Add((eligibleUid, eligibleComp, member));
  70. }
  71. if (eligible.Count == 0)
  72. return;
  73. component.TargetStation = RobustRandom.Pick(eligible);
  74. }
  75. #region Event Handlers
  76. protected override void AppendRoundEndText(EntityUid uid,
  77. NukeopsRuleComponent component,
  78. GameRuleComponent gameRule,
  79. ref RoundEndTextAppendEvent args)
  80. {
  81. var winText = Loc.GetString($"nukeops-{component.WinType.ToString().ToLower()}");
  82. args.AddLine(winText);
  83. foreach (var cond in component.WinConditions)
  84. {
  85. var text = Loc.GetString($"nukeops-cond-{cond.ToString().ToLower()}");
  86. args.AddLine(text);
  87. }
  88. args.AddLine(Loc.GetString("nukeops-list-start"));
  89. var antags = _antag.GetAntagIdentifiers(uid);
  90. foreach (var (_, sessionData, name) in antags)
  91. {
  92. args.AddLine(Loc.GetString("nukeops-list-name-user", ("name", name), ("user", sessionData.UserName)));
  93. }
  94. }
  95. private void OnNukeExploded(NukeExplodedEvent ev)
  96. {
  97. var query = QueryActiveRules();
  98. while (query.MoveNext(out var uid, out _, out var nukeops, out _))
  99. {
  100. if (ev.OwningStation != null)
  101. {
  102. if (ev.OwningStation == GetOutpost(uid))
  103. {
  104. nukeops.WinConditions.Add(WinCondition.NukeExplodedOnNukieOutpost);
  105. SetWinType((uid, nukeops), WinType.CrewMajor);
  106. continue;
  107. }
  108. if (TryComp(nukeops.TargetStation, out StationDataComponent? data))
  109. {
  110. var correctStation = false;
  111. foreach (var grid in data.Grids)
  112. {
  113. if (grid != ev.OwningStation)
  114. {
  115. continue;
  116. }
  117. nukeops.WinConditions.Add(WinCondition.NukeExplodedOnCorrectStation);
  118. SetWinType((uid, nukeops), WinType.OpsMajor);
  119. correctStation = true;
  120. }
  121. if (correctStation)
  122. continue;
  123. }
  124. nukeops.WinConditions.Add(WinCondition.NukeExplodedOnIncorrectLocation);
  125. }
  126. else
  127. {
  128. nukeops.WinConditions.Add(WinCondition.NukeExplodedOnIncorrectLocation);
  129. }
  130. _roundEndSystem.EndRound();
  131. }
  132. }
  133. private void OnRunLevelChanged(GameRunLevelChangedEvent ev)
  134. {
  135. if (ev.New is not GameRunLevel.PostRound)
  136. return;
  137. var query = QueryActiveRules();
  138. while (query.MoveNext(out var uid, out _, out var nukeops, out _))
  139. {
  140. OnRoundEnd((uid, nukeops));
  141. }
  142. }
  143. private void OnRoundEnd(Entity<NukeopsRuleComponent> ent)
  144. {
  145. // If the win condition was set to operative/crew major win, ignore.
  146. if (ent.Comp.WinType == WinType.OpsMajor || ent.Comp.WinType == WinType.CrewMajor)
  147. return;
  148. var nukeQuery = AllEntityQuery<NukeComponent, TransformComponent>();
  149. var centcomms = _emergency.GetCentcommMaps();
  150. while (nukeQuery.MoveNext(out var nuke, out var nukeTransform))
  151. {
  152. if (nuke.Status != NukeStatus.ARMED)
  153. continue;
  154. // UH OH
  155. if (nukeTransform.MapUid != null && centcomms.Contains(nukeTransform.MapUid.Value))
  156. {
  157. ent.Comp.WinConditions.Add(WinCondition.NukeActiveAtCentCom);
  158. SetWinType((ent, ent), WinType.OpsMajor);
  159. return;
  160. }
  161. if (nukeTransform.GridUid == null || ent.Comp.TargetStation == null)
  162. continue;
  163. if (!TryComp(ent.Comp.TargetStation.Value, out StationDataComponent? data))
  164. continue;
  165. foreach (var grid in data.Grids)
  166. {
  167. if (grid != nukeTransform.GridUid)
  168. continue;
  169. ent.Comp.WinConditions.Add(WinCondition.NukeActiveInStation);
  170. SetWinType(ent, WinType.OpsMajor);
  171. return;
  172. }
  173. }
  174. if (_antag.AllAntagsAlive(ent.Owner))
  175. {
  176. SetWinType(ent, WinType.OpsMinor);
  177. ent.Comp.WinConditions.Add(WinCondition.AllNukiesAlive);
  178. return;
  179. }
  180. ent.Comp.WinConditions.Add(_antag.AnyAliveAntags(ent.Owner)
  181. ? WinCondition.SomeNukiesAlive
  182. : WinCondition.AllNukiesDead);
  183. var diskAtCentCom = false;
  184. var diskQuery = AllEntityQuery<NukeDiskComponent, TransformComponent>();
  185. while (diskQuery.MoveNext(out var diskUid, out _, out var transform))
  186. {
  187. diskAtCentCom = transform.MapUid != null && centcomms.Contains(transform.MapUid.Value);
  188. diskAtCentCom |= _emergency.IsTargetEscaping(diskUid);
  189. // TODO: The target station should be stored, and the nuke disk should store its original station.
  190. // This is fine for now, because we can assume a single station in base SS14.
  191. break;
  192. }
  193. // If the disk is currently at Central Command, the crew wins - just slightly.
  194. // This also implies that some nuclear operatives have died.
  195. SetWinType(ent,
  196. diskAtCentCom
  197. ? WinType.CrewMinor
  198. : WinType.OpsMinor);
  199. ent.Comp.WinConditions.Add(diskAtCentCom
  200. ? WinCondition.NukeDiskOnCentCom
  201. : WinCondition.NukeDiskNotOnCentCom);
  202. }
  203. private void OnNukeDisarm(NukeDisarmSuccessEvent ev)
  204. {
  205. CheckRoundShouldEnd();
  206. }
  207. private void OnComponentRemove(EntityUid uid, NukeOperativeComponent component, ComponentRemove args)
  208. {
  209. CheckRoundShouldEnd();
  210. }
  211. private void OnMobStateChanged(EntityUid uid, NukeOperativeComponent component, MobStateChangedEvent ev)
  212. {
  213. if (ev.NewMobState == MobState.Dead)
  214. CheckRoundShouldEnd();
  215. }
  216. private void OnOperativeZombified(EntityUid uid, NukeOperativeComponent component, ref EntityZombifiedEvent args)
  217. {
  218. RemCompDeferred(uid, component);
  219. }
  220. private void OnRuleLoadedGrids(Entity<NukeopsRuleComponent> ent, ref RuleLoadedGridsEvent args)
  221. {
  222. // Check each nukie shuttle
  223. var query = EntityQueryEnumerator<NukeOpsShuttleComponent>();
  224. while (query.MoveNext(out var uid, out var shuttle))
  225. {
  226. // Check if the shuttle's mapID is the one that just got loaded for this rule
  227. if (Transform(uid).MapID == args.Map)
  228. {
  229. shuttle.AssociatedRule = ent;
  230. break;
  231. }
  232. }
  233. }
  234. private void OnShuttleFTLAttempt(ref ConsoleFTLAttemptEvent ev)
  235. {
  236. var query = QueryActiveRules();
  237. while (query.MoveNext(out var uid, out _, out var nukeops, out _))
  238. {
  239. if (ev.Uid != GetShuttle((uid, nukeops)))
  240. continue;
  241. if (nukeops.WarDeclaredTime != null)
  242. {
  243. var timeAfterDeclaration = Timing.CurTime.Subtract(nukeops.WarDeclaredTime.Value);
  244. var timeRemain = nukeops.WarNukieArriveDelay.Subtract(timeAfterDeclaration);
  245. if (timeRemain > TimeSpan.Zero)
  246. {
  247. ev.Cancelled = true;
  248. ev.Reason = Loc.GetString("war-ops-infiltrator-unavailable",
  249. ("time", timeRemain.ToString("mm\\:ss")));
  250. continue;
  251. }
  252. }
  253. nukeops.LeftOutpost = true;
  254. }
  255. }
  256. private void OnShuttleCallAttempt(ref CommunicationConsoleCallShuttleAttemptEvent ev)
  257. {
  258. var query = QueryActiveRules();
  259. while (query.MoveNext(out _, out _, out var nukeops, out _))
  260. {
  261. // Can't call while war nukies are preparing to arrive
  262. if (nukeops is { WarDeclaredTime: not null })
  263. {
  264. // Nukies must wait some time after declaration of war to get on the station
  265. var warTime = Timing.CurTime.Subtract(nukeops.WarDeclaredTime.Value);
  266. if (warTime < nukeops.WarEvacShuttleDisabled)
  267. {
  268. ev.Cancelled = true;
  269. ev.Reason = Loc.GetString("war-ops-shuttle-call-unavailable");
  270. return;
  271. }
  272. }
  273. }
  274. }
  275. private void OnWarDeclared(ref WarDeclaredEvent ev)
  276. {
  277. // TODO: this is VERY awful for multi-nukies
  278. var query = QueryActiveRules();
  279. while (query.MoveNext(out var uid, out _, out var nukeops, out _))
  280. {
  281. if (nukeops.WarDeclaredTime != null)
  282. continue;
  283. if (TryComp<RuleGridsComponent>(uid, out var grids) && Transform(ev.DeclaratorEntity).MapID != grids.Map)
  284. continue;
  285. var newStatus = GetWarCondition(nukeops, ev.Status);
  286. ev.Status = newStatus;
  287. if (newStatus == WarConditionStatus.WarReady)
  288. {
  289. nukeops.WarDeclaredTime = Timing.CurTime;
  290. var timeRemain = nukeops.WarNukieArriveDelay + Timing.CurTime;
  291. ev.DeclaratorEntity.Comp.ShuttleDisabledTime = timeRemain;
  292. DistributeExtraTc((uid, nukeops));
  293. }
  294. }
  295. }
  296. #endregion Event Handlers
  297. /// <summary>
  298. /// Returns conditions for war declaration
  299. /// </summary>
  300. public WarConditionStatus GetWarCondition(NukeopsRuleComponent nukieRule, WarConditionStatus? oldStatus)
  301. {
  302. if (!nukieRule.CanEnableWarOps)
  303. return WarConditionStatus.NoWarUnknown;
  304. if (EntityQuery<NukeopsRoleComponent>().Count() < nukieRule.WarDeclarationMinOps)
  305. return WarConditionStatus.NoWarSmallCrew;
  306. if (nukieRule.LeftOutpost)
  307. return WarConditionStatus.NoWarShuttleDeparted;
  308. if (oldStatus == WarConditionStatus.YesWar)
  309. return WarConditionStatus.WarReady;
  310. return WarConditionStatus.YesWar;
  311. }
  312. private void DistributeExtraTc(Entity<NukeopsRuleComponent> nukieRule)
  313. {
  314. var enumerator = EntityQueryEnumerator<StoreComponent>();
  315. while (enumerator.MoveNext(out var uid, out var component))
  316. {
  317. if (!_tag.HasTag(uid, NukeOpsUplinkTagPrototype))
  318. continue;
  319. if (GetOutpost(nukieRule.Owner) is not { } outpost)
  320. continue;
  321. if (Transform(uid).MapID != Transform(outpost).MapID) // Will receive bonus TC only on their start outpost
  322. continue;
  323. _store.TryAddCurrency(new() { { TelecrystalCurrencyPrototype, nukieRule.Comp.WarTcAmountPerNukie } }, uid, component);
  324. var msg = Loc.GetString("store-currency-war-boost-given", ("target", uid));
  325. _popupSystem.PopupEntity(msg, uid);
  326. }
  327. }
  328. private void SetWinType(Entity<NukeopsRuleComponent> ent, WinType type, bool endRound = true)
  329. {
  330. ent.Comp.WinType = type;
  331. if (endRound && (type == WinType.CrewMajor || type == WinType.OpsMajor))
  332. _roundEndSystem.EndRound();
  333. }
  334. private void CheckRoundShouldEnd()
  335. {
  336. var query = QueryActiveRules();
  337. while (query.MoveNext(out var uid, out _, out var nukeops, out _))
  338. {
  339. CheckRoundShouldEnd((uid, nukeops));
  340. }
  341. }
  342. private void CheckRoundShouldEnd(Entity<NukeopsRuleComponent> ent)
  343. {
  344. var nukeops = ent.Comp;
  345. if (nukeops.RoundEndBehavior == RoundEndBehavior.Nothing || nukeops.WinType == WinType.CrewMajor || nukeops.WinType == WinType.OpsMajor)
  346. return;
  347. // If there are any nuclear bombs that are active, immediately return. We're not over yet.
  348. foreach (var nuke in EntityQuery<NukeComponent>())
  349. {
  350. if (nuke.Status == NukeStatus.ARMED)
  351. return;
  352. }
  353. var shuttle = GetShuttle((ent, ent));
  354. MapId? shuttleMapId = Exists(shuttle)
  355. ? Transform(shuttle.Value).MapID
  356. : null;
  357. MapId? targetStationMap = null;
  358. if (nukeops.TargetStation != null && TryComp(nukeops.TargetStation, out StationDataComponent? data))
  359. {
  360. var grid = data.Grids.FirstOrNull();
  361. targetStationMap = grid != null
  362. ? Transform(grid.Value).MapID
  363. : null;
  364. }
  365. // Check if there are nuke operatives still alive on the same map as the shuttle,
  366. // or on the same map as the station.
  367. // If there are, the round can continue.
  368. var operatives = EntityQuery<NukeOperativeComponent, MobStateComponent, TransformComponent>(true);
  369. var operativesAlive = operatives
  370. .Where(op =>
  371. op.Item3.MapID == shuttleMapId
  372. || op.Item3.MapID == targetStationMap)
  373. .Any(op => op.Item2.CurrentState == MobState.Alive && op.Item1.Running);
  374. if (operativesAlive)
  375. return; // There are living operatives than can access the shuttle, or are still on the station's map.
  376. // Check that there are spawns available and that they can access the shuttle.
  377. var spawnsAvailable = EntityQuery<NukeOperativeSpawnerComponent>(true).Any();
  378. if (spawnsAvailable && CompOrNull<RuleGridsComponent>(ent)?.Map == shuttleMapId)
  379. return; // Ghost spawns can still access the shuttle. Continue the round.
  380. // The shuttle is inaccessible to both living nuke operatives and yet to spawn nuke operatives,
  381. // and there are no nuclear operatives on the target station's map.
  382. nukeops.WinConditions.Add(spawnsAvailable
  383. ? WinCondition.NukiesAbandoned
  384. : WinCondition.AllNukiesDead);
  385. SetWinType(ent, WinType.CrewMajor, false);
  386. _roundEndSystem.DoRoundEndBehavior(nukeops.RoundEndBehavior,
  387. nukeops.EvacShuttleTime,
  388. nukeops.RoundEndTextSender,
  389. nukeops.RoundEndTextShuttleCall,
  390. nukeops.RoundEndTextAnnouncement);
  391. // prevent it called multiple times
  392. nukeops.RoundEndBehavior = RoundEndBehavior.Nothing;
  393. }
  394. private void OnAfterAntagEntSelected(Entity<NukeopsRuleComponent> ent, ref AfterAntagEntitySelectedEvent args)
  395. {
  396. var target = (ent.Comp.TargetStation is not null) ? Name(ent.Comp.TargetStation.Value) : "the target";
  397. _antag.SendBriefing(args.Session,
  398. Loc.GetString("nukeops-welcome",
  399. ("station", target),
  400. ("name", Name(ent))),
  401. Color.Red,
  402. null);
  403. }
  404. private void OnGetBriefing(Entity<NukeopsRoleComponent> role, ref GetBriefingEvent args)
  405. {
  406. // TODO Different character screen briefing for the 3 nukie types
  407. args.Append(Loc.GetString("nukeops-briefing"));
  408. }
  409. /// <remarks>
  410. /// Is this method the shitty glue holding together the last of my sanity? yes.
  411. /// Do i have a better solution? not presently.
  412. /// </remarks>
  413. private EntityUid? GetOutpost(Entity<RuleGridsComponent?> ent)
  414. {
  415. if (!Resolve(ent, ref ent.Comp, false))
  416. return null;
  417. return ent.Comp.MapGrids.Where(e => !HasComp<NukeOpsShuttleComponent>(e)).FirstOrNull();
  418. }
  419. /// <remarks>
  420. /// Is this method the shitty glue holding together the last of my sanity? yes.
  421. /// Do i have a better solution? not presently.
  422. /// </remarks>
  423. private EntityUid? GetShuttle(Entity<NukeopsRuleComponent?> ent)
  424. {
  425. if (!Resolve(ent, ref ent.Comp, false))
  426. return null;
  427. var query = EntityQueryEnumerator<NukeOpsShuttleComponent>();
  428. while (query.MoveNext(out var uid, out var comp))
  429. {
  430. if (comp.AssociatedRule == ent.Owner)
  431. return uid;
  432. }
  433. return null;
  434. }
  435. }