CatStation/Content.Shared/Alert/AlertsSystem.cs
Dmitry 25c5e59248
Upstream (#3172)
Signed-off-by: Prole <172158352+Prole0@users.noreply.github.com>
Co-authored-by: PJBot <pieterjan.briers+bot@gmail.com>
Co-authored-by: ScarKy0 <106310278+ScarKy0@users.noreply.github.com>
Co-authored-by: Samuka-C <47865393+Samuka-C@users.noreply.github.com>
Co-authored-by: ArtisticRoomba <145879011+ArtisticRoomba@users.noreply.github.com>
Co-authored-by: Partmedia <kevinz5000@gmail.com>
Co-authored-by: slarticodefast <161409025+slarticodefast@users.noreply.github.com>
Co-authored-by: themias <89101928+themias@users.noreply.github.com>
Co-authored-by: Victor Shen <71985089+Vexerot@users.noreply.github.com>
Co-authored-by: Ed <96445749+TheShuEd@users.noreply.github.com>
Co-authored-by: Milon <milonpl.git@proton.me>
Co-authored-by: Kirus59 <145689588+Kirus59@users.noreply.github.com>
Co-authored-by: Nemanja <98561806+EmoGarbage404@users.noreply.github.com>
Co-authored-by: Stomf <5dorkydorks@gmail.com>
Co-authored-by: drakewill-CRL <46307022+drakewill-CRL@users.noreply.github.com>
Co-authored-by: PraxisMapper <praxismapper@gmail.com>
Co-authored-by: EmoGarbage404 <retron404@gmail.com>
Co-authored-by: lzk <124214523+lzk228@users.noreply.github.com>
Co-authored-by: Princess Cheeseballs <66055347+Pronana@users.noreply.github.com>
Co-authored-by: IProduceWidgets <107586145+IProduceWidgets@users.noreply.github.com>
Co-authored-by: TytosB <54259736+TytosB@users.noreply.github.com>
Co-authored-by: abadaba695 <spacestation13thingy@gmail.com>
Co-authored-by: kosticia <kosticia46@gmail.com>
Co-authored-by: Thinbug <101073555+Thinbug0@users.noreply.github.com>
Co-authored-by: pathetic meowmeow <uhhadd@gmail.com>
Co-authored-by: SlamBamActionman <83650252+SlamBamActionman@users.noreply.github.com>
Co-authored-by: Boaz1111 <149967078+Boaz1111@users.noreply.github.com>
Co-authored-by: ActiveMammmoth <140334666+ActiveMammmoth@users.noreply.github.com>
Co-authored-by: Myra <vasilis@pikachu.systems>
Co-authored-by: Whatstone <166147148+whatston3@users.noreply.github.com>
Co-authored-by: Pieter-Jan Briers <pieterjan.briers+git@gmail.com>
Co-authored-by: K-Dynamic <20566341+K-Dynamic@users.noreply.github.com>
Co-authored-by: Gentleman-Bird <dcgreen406@gmail.com>
Co-authored-by: metalgearsloth <31366439+metalgearsloth@users.noreply.github.com>
Co-authored-by: BIGZi0348 <svalker0348@gmail.com>
Co-authored-by: LaCumbiaDelCoronavirus <90893484+LaCumbiaDelCoronavirus@users.noreply.github.com>
Co-authored-by: imatsoup <93290208+imatsoup@users.noreply.github.com>
Co-authored-by: Matthew Herber <32679887+happyrobot33@users.noreply.github.com>
Co-authored-by: Ertanic <36124833+Ertanic@users.noreply.github.com>
Co-authored-by: MissKay1994 <15877268+MissKay1994@users.noreply.github.com>
Co-authored-by: Errant <35878406+Errant-4@users.noreply.github.com>
Co-authored-by: eoineoineoin <helloworld@eoinrul.es>
Co-authored-by: Tiniest Shark <head.rebel@yahoo.com>
Co-authored-by: nikitosych <boriszyn@gmail.com>
Co-authored-by: Tayrtahn <tayrtahn@gmail.com>
Co-authored-by: Perry Fraser <perryprog@users.noreply.github.com>
Co-authored-by: YoungThug <ramialanbagy@gmail.com>
Co-authored-by: beck-thompson <107373427+beck-thompson@users.noreply.github.com>
Co-authored-by: metalgearsloth <comedian_vs_clown@hotmail.com>
Co-authored-by: Southbridge <7013162+southbridge-fur@users.noreply.github.com>
Co-authored-by: Vladislav Suchkov <20380250+murolem@users.noreply.github.com>
Co-authored-by: Prole <172158352+Prole0@users.noreply.github.com>
Co-authored-by: Unkn0wn_Gh0st <shadowstalkermll@gmail.com>
Co-authored-by: 3nderall <101940324+3nderall@users.noreply.github.com>
Co-authored-by: Radezolid <snappednexus@gmail.com>
Co-authored-by: J <billsmith116@gmail.com>
Co-authored-by: Ghagliiarghii <68826635+Ghagliiarghii@users.noreply.github.com>
Co-authored-by: chromiumboy <50505512+chromiumboy@users.noreply.github.com>
Co-authored-by: youtissoum <51883137+youtissoum@users.noreply.github.com>
Co-authored-by: Minemoder5000 <minemoder50000@gmail.com>
Co-authored-by: Spanky <scott@wearejacob.com>
Co-authored-by: Spessmann <156740760+Spessmann@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: brainfood1183 <113240905+brainfood1183@users.noreply.github.com>
Co-authored-by: Deerstop <edainturner@gmail.com>
Co-authored-by: B_Kirill <153602297+B-Kirill@users.noreply.github.com>
Co-authored-by: archee1 <archee3@hotmail.co.uk>
Co-authored-by: Cojoke <83733158+Cojoke-dot@users.noreply.github.com>
Co-authored-by: Quantum-cross <7065792+Quantum-cross@users.noreply.github.com>
Co-authored-by: poklj <compgeek223@gmail.com>
Co-authored-by: Krunklehorn <42424291+Krunklehorn@users.noreply.github.com>
Co-authored-by: OnyxTheBrave <131422822+OnyxTheBrave@users.noreply.github.com>
Co-authored-by: UpAndLeaves <92269094+Alpha-Two@users.noreply.github.com>
Co-authored-by: Flareguy <78941145+Flareguy@users.noreply.github.com>
Co-authored-by: Zalycon <84675130+Zalycon@users.noreply.github.com>
Co-authored-by: deltanedas <39013340+deltanedas@users.noreply.github.com>
Co-authored-by: Verm <32827189+Vermidia@users.noreply.github.com>
Co-authored-by: nikthechampiongr <32041239+nikthechampiongr@users.noreply.github.com>
Co-authored-by: ScarKy0 <scarky0@onet.eu>
Co-authored-by: Dmitry <57028746+dimm00n@users.noreply.github.com>
2025-05-24 11:00:17 +03:00

359 lines
12 KiB
C#

using System.Collections.Frozen;
using System.Diagnostics.CodeAnalysis;
using Robust.Shared.Player;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
namespace Content.Shared.Alert;
public abstract class AlertsSystem : EntitySystem
{
[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
private FrozenDictionary<ProtoId<AlertPrototype>, AlertPrototype> _typeToAlert = default!;
public IReadOnlyDictionary<AlertKey, AlertState>? GetActiveAlerts(EntityUid euid)
{
return EntityManager.TryGetComponent(euid, out AlertsComponent? comp)
? comp.Alerts
: null;
}
public short GetSeverityRange(ProtoId<AlertPrototype> alertType)
{
var minSeverity = _typeToAlert[alertType].MinSeverity;
return (short)MathF.Max(minSeverity,_typeToAlert[alertType].MaxSeverity - minSeverity);
}
public short GetMaxSeverity(ProtoId<AlertPrototype> alertType)
{
return _typeToAlert[alertType].MaxSeverity;
}
public short GetMinSeverity(ProtoId<AlertPrototype> alertType)
{
return _typeToAlert[alertType].MinSeverity;
}
public bool IsShowingAlert(EntityUid euid, ProtoId<AlertPrototype> alertType)
{
if (!EntityManager.TryGetComponent(euid, out AlertsComponent? alertsComponent))
return false;
if (TryGet(alertType, out var alert))
{
return alertsComponent.Alerts.ContainsKey(alert.AlertKey);
}
Log.Debug("Unknown alert type {0}", alertType);
return false;
}
/// <returns>true iff an alert of the indicated alert category is currently showing</returns>
public bool IsShowingAlertCategory(EntityUid euid, ProtoId<AlertCategoryPrototype> alertCategory)
{
return EntityManager.TryGetComponent(euid, out AlertsComponent? alertsComponent)
&& alertsComponent.Alerts.ContainsKey(AlertKey.ForCategory(alertCategory));
}
public bool TryGetAlertState(EntityUid euid, AlertKey key, out AlertState alertState)
{
if (EntityManager.TryGetComponent(euid, out AlertsComponent? alertsComponent))
return alertsComponent.Alerts.TryGetValue(key, out alertState);
alertState = default;
return false;
}
/// <summary>
/// Shows the alert. If the alert or another alert of the same category is already showing,
/// it will be updated / replaced with the specified values.
/// </summary>
/// <param name="euid"></param>
/// <param name="alertType">type of the alert to set</param>
/// <param name="severity">severity, if supported by the alert</param>
/// <param name="cooldown">cooldown start and end, if null there will be no cooldown (and it will
/// be erased if there is currently a cooldown for the alert)</param>
/// <param name="autoRemove">if true, the alert will be removed at the end of the cooldown</param>
/// <param name="showCooldown">if true, the cooldown will be visibly shown over the alert icon</param>
public void ShowAlert(EntityUid euid, ProtoId<AlertPrototype> alertType, short? severity = null, (TimeSpan, TimeSpan)? cooldown = null, bool autoRemove = false, bool showCooldown = true )
{
// This should be handled as part of networking.
if (_timing.ApplyingState)
return;
if (!TryComp(euid, out AlertsComponent? alertsComponent))
return;
if (TryGet(alertType, out var alert))
{
// Check whether the alert category we want to show is already being displayed, with the same type,
// severity, and cooldown.
if (alertsComponent.Alerts.TryGetValue(alert.AlertKey, out var alertStateCallback) &&
alertStateCallback.Type == alertType &&
alertStateCallback.Severity == severity &&
alertStateCallback.Cooldown == cooldown &&
alertStateCallback.AutoRemove == autoRemove &&
alertStateCallback.ShowCooldown == showCooldown)
{
return;
}
// In the case we're changing the alert type but not the category, we need to remove it first.
alertsComponent.Alerts.Remove(alert.AlertKey);
var state = new AlertState
{ Cooldown = cooldown, Severity = severity, Type = alertType, AutoRemove = autoRemove, ShowCooldown = showCooldown};
alertsComponent.Alerts[alert.AlertKey] = state;
// Keeping a list of AutoRemove alerts, so Update() doesn't need to check every alert
if (autoRemove)
{
var autoComp = EnsureComp<AlertAutoRemoveComponent>(euid);
if (!autoComp.AlertKeys.Contains(alert.AlertKey))
autoComp.AlertKeys.Add(alert.AlertKey);
}
AfterShowAlert((euid, alertsComponent));
Dirty(euid, alertsComponent);
}
else
{
Log.Error("Unable to show alert {0}, please ensure this alertType has" +
" a corresponding YML alert prototype",
alertType);
}
}
/// <summary>
/// Clear the alert with the given category, if one is currently showing.
/// </summary>
public void ClearAlertCategory(EntityUid euid, ProtoId<AlertCategoryPrototype> category)
{
if(!TryComp(euid, out AlertsComponent? alertsComponent))
return;
var key = AlertKey.ForCategory(category);
if (!alertsComponent.Alerts.Remove(key))
{
return;
}
AfterClearAlert((euid, alertsComponent));
Dirty(euid, alertsComponent);
}
/// <summary>
/// Clear the alert of the given type if it is currently showing.
/// </summary>
public void ClearAlert(EntityUid euid, ProtoId<AlertPrototype> alertType)
{
if (_timing.ApplyingState)
return;
if (!EntityManager.TryGetComponent(euid, out AlertsComponent? alertsComponent))
return;
if (TryGet(alertType, out var alert))
{
if (!alertsComponent.Alerts.Remove(alert.AlertKey))
{
return;
}
AfterClearAlert((euid, alertsComponent));
Dirty(euid, alertsComponent);
}
else
{
Log.Error("Unable to clear alert, unknown alertType {0}", alertType);
}
}
/// <summary>
/// Invoked after showing an alert prior to dirtying the component
/// </summary>
protected virtual void AfterShowAlert(Entity<AlertsComponent> alerts) { }
/// <summary>
/// Invoked after clearing an alert prior to dirtying the component
/// </summary>
protected virtual void AfterClearAlert(Entity<AlertsComponent> alerts) { }
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<AlertsComponent, ComponentStartup>(HandleComponentStartup);
SubscribeLocalEvent<AlertsComponent, ComponentShutdown>(HandleComponentShutdown);
SubscribeLocalEvent<AlertsComponent, PlayerAttachedEvent>(OnPlayerAttached);
SubscribeLocalEvent<AlertAutoRemoveComponent, EntityUnpausedEvent>(OnAutoRemoveUnPaused);
SubscribeAllEvent<ClickAlertEvent>(HandleClickAlert);
SubscribeLocalEvent<PrototypesReloadedEventArgs>(HandlePrototypesReloaded);
LoadPrototypes();
}
private void OnAutoRemoveUnPaused(EntityUid uid, AlertAutoRemoveComponent comp, EntityUnpausedEvent args)
{
if (!TryComp<AlertsComponent>(uid, out var alertComp))
{
return;
}
var dirty = false;
foreach (var alert in alertComp.Alerts)
{
if (alert.Value.Cooldown is null)
continue;
var cooldown = (alert.Value.Cooldown.Value.Item1, alert.Value.Cooldown.Value.Item2 + args.PausedTime);
var state = new AlertState
{
Severity = alert.Value.Severity,
Cooldown = cooldown,
ShowCooldown = alert.Value.ShowCooldown,
AutoRemove = alert.Value.AutoRemove,
Type = alert.Value.Type
};
alertComp.Alerts[alert.Key] = state;
dirty = true;
}
if (dirty)
Dirty(uid, comp);
}
public override void Update(float frameTime)
{
base.Update(frameTime);
var query = EntityQueryEnumerator<AlertAutoRemoveComponent>();
while (query.MoveNext(out var uid, out var autoComp))
{
var dirtyComp = false;
if (autoComp.AlertKeys.Count <= 0 || !TryComp<AlertsComponent>(uid, out var alertComp))
{
RemCompDeferred(uid, autoComp);
continue;
}
var removeList = new List<AlertKey>();
foreach (var alertKey in autoComp.AlertKeys)
{
alertComp.Alerts.TryGetValue(alertKey, out var alertState);
if (alertState.Cooldown is null || alertState.Cooldown.Value.Item2 >= _timing.CurTime)
continue;
removeList.Add(alertKey);
alertComp.Alerts.Remove(alertKey);
dirtyComp = true;
}
foreach (var alertKey in removeList)
{
autoComp.AlertKeys.Remove(alertKey);
}
if (dirtyComp)
Dirty(uid, alertComp);
}
}
protected virtual void HandleComponentShutdown(EntityUid uid, AlertsComponent component, ComponentShutdown args)
{
RaiseLocalEvent(uid, new AlertSyncEvent(uid), true);
}
private void HandleComponentStartup(EntityUid uid, AlertsComponent component, ComponentStartup args)
{
RaiseLocalEvent(uid, new AlertSyncEvent(uid), true);
}
private void HandlePrototypesReloaded(PrototypesReloadedEventArgs obj)
{
if (obj.WasModified<AlertPrototype>())
LoadPrototypes();
}
protected virtual void LoadPrototypes()
{
var dict = new Dictionary<ProtoId<AlertPrototype>, AlertPrototype>();
foreach (var alert in _prototypeManager.EnumeratePrototypes<AlertPrototype>())
{
if (!dict.TryAdd(alert.ID, alert))
{
Log.Error("Found alert with duplicate alertType {0} - all alerts must have" +
" a unique alertType, this one will be skipped", alert.ID);
}
}
_typeToAlert = dict.ToFrozenDictionary();
}
/// <summary>
/// Tries to get the alert of the indicated type
/// </summary>
/// <returns>true if found</returns>
public bool TryGet(ProtoId<AlertPrototype> alertType, [NotNullWhen(true)] out AlertPrototype? alert)
{
return _typeToAlert.TryGetValue(alertType, out alert);
}
private void HandleClickAlert(ClickAlertEvent msg, EntitySessionEventArgs args)
{
var player = args.SenderSession.AttachedEntity;
if (player is null || !EntityManager.HasComponent<AlertsComponent>(player))
return;
if (!IsShowingAlert(player.Value, msg.Type))
{
Log.Debug("User {0} attempted to" +
" click alert {1} which is not currently showing for them",
EntityManager.GetComponent<MetaDataComponent>(player.Value).EntityName, msg.Type);
return;
}
if (!TryGet(msg.Type, out var alert))
{
Log.Warning("Unrecognized encoded alert {0}", msg.Type);
return;
}
if (ActivateAlert(player.Value, alert) && _timing.IsFirstTimePredicted)
{
HandledAlert();
}
}
protected virtual void HandledAlert()
{
}
public bool ActivateAlert(EntityUid user, AlertPrototype alert)
{
if (alert.ClickEvent is not { } clickEvent)
return false;
clickEvent.Handled = false;
clickEvent.User = user;
clickEvent.AlertId = alert.ID;
RaiseLocalEvent(user, (object) clickEvent, true);
return clickEvent.Handled;
}
private void OnPlayerAttached(EntityUid uid, AlertsComponent component, PlayerAttachedEvent args)
{
Dirty(uid, component);
}
}