1
0

TriggerSystem.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using Content.Server.Administration.Logs;
  2. using Content.Server.Body.Systems;
  3. using Content.Server.Explosion.Components;
  4. using Content.Server.Flash;
  5. using Content.Server.Electrocution;
  6. using Content.Server.Pinpointer;
  7. using Content.Shared.Chemistry.EntitySystems;
  8. using Content.Shared.Flash.Components;
  9. using Content.Server.Radio.EntitySystems;
  10. using Content.Shared.Chemistry.Components;
  11. using Content.Shared.Chemistry.Components.SolutionManager;
  12. using Content.Shared.Database;
  13. using Content.Shared.Explosion.Components;
  14. using Content.Shared.Explosion.Components.OnTrigger;
  15. using Content.Shared.Implants.Components;
  16. using Content.Shared.Interaction;
  17. using Content.Shared.Interaction.Events;
  18. using Content.Shared.Inventory;
  19. using Content.Shared.Mobs;
  20. using Content.Shared.Mobs.Components;
  21. using Content.Shared.Payload.Components;
  22. using Content.Shared.Radio;
  23. using Content.Shared.Slippery;
  24. using Content.Shared.StepTrigger.Systems;
  25. using Content.Shared.Trigger;
  26. using Content.Shared.Weapons.Ranged.Events;
  27. using Content.Shared.Whitelist;
  28. using JetBrains.Annotations;
  29. using Robust.Shared.Audio;
  30. using Robust.Shared.Audio.Systems;
  31. using Robust.Shared.Containers;
  32. using Robust.Shared.Physics.Events;
  33. using Robust.Shared.Physics.Systems;
  34. using Robust.Shared.Prototypes;
  35. using Robust.Shared.Random;
  36. using Robust.Shared.Utility;
  37. namespace Content.Server.Explosion.EntitySystems
  38. {
  39. /// <summary>
  40. /// Raised whenever something is Triggered on the entity.
  41. /// </summary>
  42. public sealed class TriggerEvent : HandledEntityEventArgs
  43. {
  44. public EntityUid Triggered { get; }
  45. public EntityUid? User { get; }
  46. public TriggerEvent(EntityUid triggered, EntityUid? user = null)
  47. {
  48. Triggered = triggered;
  49. User = user;
  50. }
  51. }
  52. /// <summary>
  53. /// Raised before a trigger is activated.
  54. /// </summary>
  55. [ByRefEvent]
  56. public record struct BeforeTriggerEvent(EntityUid Triggered, EntityUid? User, bool Cancelled = false);
  57. /// <summary>
  58. /// Raised when timer trigger becomes active.
  59. /// </summary>
  60. [ByRefEvent]
  61. public readonly record struct ActiveTimerTriggerEvent(EntityUid Triggered, EntityUid? User);
  62. [UsedImplicitly]
  63. public sealed partial class TriggerSystem : EntitySystem
  64. {
  65. [Dependency] private readonly ExplosionSystem _explosions = default!;
  66. [Dependency] private readonly FixtureSystem _fixtures = default!;
  67. [Dependency] private readonly FlashSystem _flashSystem = default!;
  68. [Dependency] private readonly SharedBroadphaseSystem _broadphase = default!;
  69. [Dependency] private readonly IAdminLogManager _adminLogger = default!;
  70. [Dependency] private readonly SharedContainerSystem _container = default!;
  71. [Dependency] private readonly BodySystem _body = default!;
  72. [Dependency] private readonly SharedAudioSystem _audio = default!;
  73. [Dependency] private readonly SharedTransformSystem _transformSystem = default!;
  74. [Dependency] private readonly NavMapSystem _navMap = default!;
  75. [Dependency] private readonly RadioSystem _radioSystem = default!;
  76. [Dependency] private readonly IRobustRandom _random = default!;
  77. [Dependency] private readonly IPrototypeManager _prototypeManager = default!;
  78. [Dependency] private readonly SharedSolutionContainerSystem _solutionContainerSystem = default!;
  79. [Dependency] private readonly InventorySystem _inventory = default!;
  80. [Dependency] private readonly ElectrocutionSystem _electrocution = default!;
  81. [Dependency] private readonly EntityWhitelistSystem _whitelist = default!;
  82. public override void Initialize()
  83. {
  84. base.Initialize();
  85. InitializeProximity();
  86. InitializeOnUse();
  87. InitializeSignal();
  88. InitializeTimedCollide();
  89. InitializeVoice();
  90. InitializeMobstate();
  91. SubscribeLocalEvent<TriggerOnSpawnComponent, MapInitEvent>(OnSpawnTriggered);
  92. SubscribeLocalEvent<TriggerOnCollideComponent, StartCollideEvent>(OnTriggerCollide);
  93. SubscribeLocalEvent<TriggerOnActivateComponent, ActivateInWorldEvent>(OnActivate);
  94. SubscribeLocalEvent<TriggerOnUseComponent, UseInHandEvent>(OnUse);
  95. SubscribeLocalEvent<TriggerImplantActionComponent, ActivateImplantEvent>(OnImplantTrigger);
  96. SubscribeLocalEvent<TriggerOnStepTriggerComponent, StepTriggeredOffEvent>(OnStepTriggered);
  97. SubscribeLocalEvent<TriggerOnSlipComponent, SlipEvent>(OnSlipTriggered);
  98. SubscribeLocalEvent<TriggerWhenEmptyComponent, OnEmptyGunShotEvent>(OnEmptyTriggered);
  99. SubscribeLocalEvent<RepeatingTriggerComponent, MapInitEvent>(OnRepeatInit);
  100. SubscribeLocalEvent<SpawnOnTriggerComponent, TriggerEvent>(OnSpawnTrigger);
  101. SubscribeLocalEvent<DeleteOnTriggerComponent, TriggerEvent>(HandleDeleteTrigger);
  102. SubscribeLocalEvent<ExplodeOnTriggerComponent, TriggerEvent>(HandleExplodeTrigger);
  103. SubscribeLocalEvent<FlashOnTriggerComponent, TriggerEvent>(HandleFlashTrigger);
  104. SubscribeLocalEvent<GibOnTriggerComponent, TriggerEvent>(HandleGibTrigger);
  105. SubscribeLocalEvent<AnchorOnTriggerComponent, TriggerEvent>(OnAnchorTrigger);
  106. SubscribeLocalEvent<SoundOnTriggerComponent, TriggerEvent>(OnSoundTrigger);
  107. SubscribeLocalEvent<ShockOnTriggerComponent, TriggerEvent>(HandleShockTrigger);
  108. SubscribeLocalEvent<RattleComponent, TriggerEvent>(HandleRattleTrigger);
  109. SubscribeLocalEvent<TriggerWhitelistComponent, BeforeTriggerEvent>(HandleWhitelist);
  110. }
  111. private void HandleWhitelist(Entity<TriggerWhitelistComponent> ent, ref BeforeTriggerEvent args)
  112. {
  113. args.Cancelled = !_whitelist.CheckBoth(args.User, ent.Comp.Blacklist, ent.Comp.Whitelist);
  114. }
  115. private void OnSoundTrigger(EntityUid uid, SoundOnTriggerComponent component, TriggerEvent args)
  116. {
  117. if (component.RemoveOnTrigger) // if the component gets removed when it's triggered
  118. {
  119. var xform = Transform(uid);
  120. _audio.PlayPvs(component.Sound, xform.Coordinates); // play the sound at its last known coordinates
  121. }
  122. else // if the component doesn't get removed when triggered
  123. {
  124. _audio.PlayPvs(component.Sound, uid); // have the sound follow the entity itself
  125. }
  126. }
  127. private void HandleShockTrigger(Entity<ShockOnTriggerComponent> shockOnTrigger, ref TriggerEvent args)
  128. {
  129. if (!_container.TryGetContainingContainer(shockOnTrigger.Owner, out var container))
  130. return;
  131. var containerEnt = container.Owner;
  132. var curTime = _timing.CurTime;
  133. if (curTime < shockOnTrigger.Comp.NextTrigger)
  134. {
  135. // The trigger's on cooldown.
  136. return;
  137. }
  138. _electrocution.TryDoElectrocution(containerEnt, null, shockOnTrigger.Comp.Damage, shockOnTrigger.Comp.Duration, true);
  139. shockOnTrigger.Comp.NextTrigger = curTime + shockOnTrigger.Comp.Cooldown;
  140. }
  141. private void OnAnchorTrigger(EntityUid uid, AnchorOnTriggerComponent component, TriggerEvent args)
  142. {
  143. var xform = Transform(uid);
  144. if (xform.Anchored)
  145. return;
  146. _transformSystem.AnchorEntity(uid, xform);
  147. if (component.RemoveOnTrigger)
  148. RemCompDeferred<AnchorOnTriggerComponent>(uid);
  149. }
  150. private void OnSpawnTrigger(Entity<SpawnOnTriggerComponent> ent, ref TriggerEvent args)
  151. {
  152. var xform = Transform(ent);
  153. if (ent.Comp.mapCoords)
  154. {
  155. var mapCoords = _transformSystem.GetMapCoordinates(ent, xform);
  156. Spawn(ent.Comp.Proto, mapCoords);
  157. }
  158. else
  159. {
  160. var coords = xform.Coordinates;
  161. if (!coords.IsValid(EntityManager))
  162. return;
  163. Spawn(ent.Comp.Proto, coords);
  164. }
  165. }
  166. private void HandleExplodeTrigger(EntityUid uid, ExplodeOnTriggerComponent component, TriggerEvent args)
  167. {
  168. _explosions.TriggerExplosive(uid, user: args.User);
  169. args.Handled = true;
  170. }
  171. private void HandleFlashTrigger(EntityUid uid, FlashOnTriggerComponent component, TriggerEvent args)
  172. {
  173. // TODO Make flash durations sane ffs.
  174. _flashSystem.FlashArea(uid, args.User, component.Range, component.Duration * 1000f, probability: component.Probability);
  175. args.Handled = true;
  176. }
  177. private void HandleDeleteTrigger(EntityUid uid, DeleteOnTriggerComponent component, TriggerEvent args)
  178. {
  179. EntityManager.QueueDeleteEntity(uid);
  180. args.Handled = true;
  181. }
  182. private void HandleGibTrigger(EntityUid uid, GibOnTriggerComponent component, TriggerEvent args)
  183. {
  184. if (!TryComp(uid, out TransformComponent? xform))
  185. return;
  186. if (component.DeleteItems)
  187. {
  188. var items = _inventory.GetHandOrInventoryEntities(xform.ParentUid);
  189. foreach (var item in items)
  190. {
  191. Del(item);
  192. }
  193. }
  194. _body.GibBody(xform.ParentUid, true);
  195. args.Handled = true;
  196. }
  197. private void HandleRattleTrigger(EntityUid uid, RattleComponent component, TriggerEvent args)
  198. {
  199. if (!TryComp<SubdermalImplantComponent>(uid, out var implanted))
  200. return;
  201. if (implanted.ImplantedEntity == null)
  202. return;
  203. // Gets location of the implant
  204. var posText = FormattedMessage.RemoveMarkupOrThrow(_navMap.GetNearestBeaconString(uid));
  205. var critMessage = Loc.GetString(component.CritMessage, ("user", implanted.ImplantedEntity.Value), ("position", posText));
  206. var deathMessage = Loc.GetString(component.DeathMessage, ("user", implanted.ImplantedEntity.Value), ("position", posText));
  207. if (!TryComp<MobStateComponent>(implanted.ImplantedEntity, out var mobstate))
  208. return;
  209. // Sends a message to the radio channel specified by the implant
  210. if (mobstate.CurrentState == MobState.Critical)
  211. _radioSystem.SendRadioMessage(uid, critMessage, _prototypeManager.Index<RadioChannelPrototype>(component.RadioChannel), uid);
  212. if (mobstate.CurrentState == MobState.Dead)
  213. _radioSystem.SendRadioMessage(uid, deathMessage, _prototypeManager.Index<RadioChannelPrototype>(component.RadioChannel), uid);
  214. args.Handled = true;
  215. }
  216. private void OnTriggerCollide(EntityUid uid, TriggerOnCollideComponent component, ref StartCollideEvent args)
  217. {
  218. if (args.OurFixtureId == component.FixtureID && (!component.IgnoreOtherNonHard || args.OtherFixture.Hard))
  219. Trigger(uid, args.OtherEntity);
  220. }
  221. private void OnSpawnTriggered(EntityUid uid, TriggerOnSpawnComponent component, MapInitEvent args)
  222. {
  223. Trigger(uid);
  224. }
  225. private void OnActivate(EntityUid uid, TriggerOnActivateComponent component, ActivateInWorldEvent args)
  226. {
  227. if (args.Handled || !args.Complex)
  228. return;
  229. Trigger(uid, args.User);
  230. args.Handled = true;
  231. }
  232. private void OnUse(Entity<TriggerOnUseComponent> ent, ref UseInHandEvent args)
  233. {
  234. if (args.Handled)
  235. return;
  236. Trigger(ent.Owner, args.User);
  237. args.Handled = true;
  238. }
  239. private void OnImplantTrigger(EntityUid uid, TriggerImplantActionComponent component, ActivateImplantEvent args)
  240. {
  241. args.Handled = Trigger(uid);
  242. }
  243. private void OnStepTriggered(EntityUid uid, TriggerOnStepTriggerComponent component, ref StepTriggeredOffEvent args)
  244. {
  245. Trigger(uid, args.Tripper);
  246. }
  247. private void OnSlipTriggered(EntityUid uid, TriggerOnSlipComponent component, ref SlipEvent args)
  248. {
  249. Trigger(uid, args.Slipped);
  250. }
  251. private void OnEmptyTriggered(EntityUid uid, TriggerWhenEmptyComponent component, ref OnEmptyGunShotEvent args)
  252. {
  253. Trigger(uid, args.EmptyGun);
  254. }
  255. private void OnRepeatInit(Entity<RepeatingTriggerComponent> ent, ref MapInitEvent args)
  256. {
  257. ent.Comp.NextTrigger = _timing.CurTime + ent.Comp.Delay;
  258. }
  259. public bool Trigger(EntityUid trigger, EntityUid? user = null)
  260. {
  261. var beforeTriggerEvent = new BeforeTriggerEvent(trigger, user);
  262. RaiseLocalEvent(trigger, ref beforeTriggerEvent);
  263. if (beforeTriggerEvent.Cancelled)
  264. return false;
  265. var triggerEvent = new TriggerEvent(trigger, user);
  266. EntityManager.EventBus.RaiseLocalEvent(trigger, triggerEvent, true);
  267. return triggerEvent.Handled;
  268. }
  269. public void TryDelay(EntityUid uid, float amount, ActiveTimerTriggerComponent? comp = null)
  270. {
  271. if (!Resolve(uid, ref comp, false))
  272. return;
  273. comp.TimeRemaining += amount;
  274. }
  275. /// <summary>
  276. /// Start the timer for triggering the device.
  277. /// </summary>
  278. public void StartTimer(Entity<OnUseTimerTriggerComponent?> ent, EntityUid? user)
  279. {
  280. if (!Resolve(ent, ref ent.Comp, false))
  281. return;
  282. var comp = ent.Comp;
  283. HandleTimerTrigger(ent, user, comp.Delay, comp.BeepInterval, comp.InitialBeepDelay, comp.BeepSound);
  284. }
  285. public void HandleTimerTrigger(EntityUid uid, EntityUid? user, float delay, float beepInterval, float? initialBeepDelay, SoundSpecifier? beepSound)
  286. {
  287. if (delay <= 0)
  288. {
  289. RemComp<ActiveTimerTriggerComponent>(uid);
  290. Trigger(uid, user);
  291. return;
  292. }
  293. if (HasComp<ActiveTimerTriggerComponent>(uid))
  294. return;
  295. if (user != null)
  296. {
  297. // Check if entity is bomb/mod. grenade/etc
  298. if (_container.TryGetContainer(uid, "payload", out BaseContainer? container) &&
  299. container.ContainedEntities.Count > 0 &&
  300. TryComp(container.ContainedEntities[0], out ChemicalPayloadComponent? chemicalPayloadComponent))
  301. {
  302. // If a beaker is missing, the entity won't explode, so no reason to log it
  303. if (chemicalPayloadComponent?.BeakerSlotA.Item is not { } beakerA ||
  304. chemicalPayloadComponent?.BeakerSlotB.Item is not { } beakerB ||
  305. !TryComp(beakerA, out SolutionContainerManagerComponent? containerA) ||
  306. !TryComp(beakerB, out SolutionContainerManagerComponent? containerB) ||
  307. !TryComp(beakerA, out FitsInDispenserComponent? fitsA) ||
  308. !TryComp(beakerB, out FitsInDispenserComponent? fitsB) ||
  309. !_solutionContainerSystem.TryGetSolution((beakerA, containerA), fitsA.Solution, out _, out var solutionA) ||
  310. !_solutionContainerSystem.TryGetSolution((beakerB, containerB), fitsB.Solution, out _, out var solutionB))
  311. return;
  312. _adminLogger.Add(LogType.Trigger,
  313. $"{ToPrettyString(user.Value):user} started a {delay} second timer trigger on entity {ToPrettyString(uid):timer}, which contains {SharedSolutionContainerSystem.ToPrettyString(solutionA)} in one beaker and {SharedSolutionContainerSystem.ToPrettyString(solutionB)} in the other.");
  314. }
  315. else
  316. {
  317. _adminLogger.Add(LogType.Trigger,
  318. $"{ToPrettyString(user.Value):user} started a {delay} second timer trigger on entity {ToPrettyString(uid):timer}");
  319. }
  320. }
  321. else
  322. {
  323. _adminLogger.Add(LogType.Trigger,
  324. $"{delay} second timer trigger started on entity {ToPrettyString(uid):timer}");
  325. }
  326. var active = AddComp<ActiveTimerTriggerComponent>(uid);
  327. active.TimeRemaining = delay;
  328. active.User = user;
  329. active.BeepSound = beepSound;
  330. active.BeepInterval = beepInterval;
  331. active.TimeUntilBeep = initialBeepDelay == null ? active.BeepInterval : initialBeepDelay.Value;
  332. var ev = new ActiveTimerTriggerEvent(uid, user);
  333. RaiseLocalEvent(uid, ref ev);
  334. if (TryComp<AppearanceComponent>(uid, out var appearance))
  335. _appearance.SetData(uid, TriggerVisuals.VisualState, TriggerVisualState.Primed, appearance);
  336. }
  337. public override void Update(float frameTime)
  338. {
  339. base.Update(frameTime);
  340. UpdateProximity();
  341. UpdateTimer(frameTime);
  342. UpdateTimedCollide(frameTime);
  343. UpdateRepeat();
  344. }
  345. private void UpdateTimer(float frameTime)
  346. {
  347. HashSet<EntityUid> toRemove = new();
  348. var query = EntityQueryEnumerator<ActiveTimerTriggerComponent>();
  349. while (query.MoveNext(out var uid, out var timer))
  350. {
  351. timer.TimeRemaining -= frameTime;
  352. timer.TimeUntilBeep -= frameTime;
  353. if (timer.TimeRemaining <= 0)
  354. {
  355. Trigger(uid, timer.User);
  356. toRemove.Add(uid);
  357. continue;
  358. }
  359. if (timer.BeepSound == null || timer.TimeUntilBeep > 0)
  360. continue;
  361. timer.TimeUntilBeep += timer.BeepInterval;
  362. _audio.PlayPvs(timer.BeepSound, uid, timer.BeepSound.Params);
  363. }
  364. foreach (var uid in toRemove)
  365. {
  366. RemComp<ActiveTimerTriggerComponent>(uid);
  367. // In case this is a re-usable grenade, un-prime it.
  368. if (TryComp<AppearanceComponent>(uid, out var appearance))
  369. _appearance.SetData(uid, TriggerVisuals.VisualState, TriggerVisualState.Unprimed, appearance);
  370. }
  371. }
  372. private void UpdateRepeat()
  373. {
  374. var now = _timing.CurTime;
  375. var query = EntityQueryEnumerator<RepeatingTriggerComponent>();
  376. while (query.MoveNext(out var uid, out var comp))
  377. {
  378. if (comp.NextTrigger > now)
  379. continue;
  380. comp.NextTrigger = now + comp.Delay;
  381. Trigger(uid);
  382. }
  383. }
  384. }
  385. }