using System;
using System.Collections.Generic;
using Content.Server.StationEvents.Components;
using Content.Shared.Chemistry.Reagent;
using Robust.Shared.Prototypes;
namespace Content.Server.StationEvents.Modifiers;
///
/// Generic liquid-density modifier that scales event weight based on the presence of a specific reagent in puddles.
///
public sealed partial class LiquidPresenceModifierPrototype : StationEventModifierPrototype
{
private const float DefaultCacheSeconds = 60f;
[DataField("reagent", required: true)]
public ProtoId<ReagentPrototype> ReagentId { get; private set; } = default!;
[DataField("cacheSeconds")]
public float CacheSeconds { get; private set; } = DefaultCacheSeconds;
[DataField("thresholds", required: true)]
public List<LiquidThreshold> Thresholds { get; private set; } = new();
public override float GetModifier(ref StationEventModifierContext context, StationEventComponent stationEvent)
{
if (Thresholds.Count == 0)
return 1f;
var snapshot = context.GetLiquidSnapshot(ReagentId, TimeSpan.FromSeconds(Math.Max(1f, CacheSeconds)));
var totalUnits = snapshot.TotalQuantity.Float();
var puddleCount = snapshot.PuddleCount;
var multiplier = 1f;
foreach (var threshold in Thresholds)
{
if (puddleCount < threshold.MinPuddles)
continue;
if (totalUnits < threshold.MinUnits)
continue;
multiplier = MathF.Max(multiplier, threshold.Multiplier);
}
return multiplier;
}
[DataDefinition]
public sealed partial class LiquidThreshold
{
[DataField("minPuddles")]
public int MinPuddles = 0;
[DataField("minUnits")]
public float MinUnits = 0f;
[DataField("multiplier", required: true)]
public float Multiplier = 1f;
}
}
using System;
using Content.Shared.Chemistry.Reagent;
using Robust.Shared.Prototypes;
namespace Content.Server.StationEvents.Modifiers;
///
/// Shared modifier evaluation state passed to each modifier during a single weighting pass. The context exposes helper
/// accessors for common station data and delegates any longer-lived caching to .
///
public struct StationEventModifierContext
{
private readonly StationEventModifierSystem _system;
private readonly TimeSpan? _timeOverride;
private readonly int? _playerCountOverride;
private bool _roundTimeCached;
private TimeSpan _roundTime;
private bool _playerCountCached;
private int _playerCount;
private bool _chaosCached;
private float _chaosModifier;
internal StationEventModifierContext(
StationEventModifierSystem system,
TimeSpan? timeOverride,
int? playerCountOverride)
{
_system = system;
_timeOverride = timeOverride;
_playerCountOverride = playerCountOverride;
_roundTimeCached = false;
_roundTime = default;
_playerCountCached = false;
_playerCount = default;
_chaosCached = false;
_chaosModifier = 1f;
}
/// <summary>
/// Timestamp used for evaluation (matches current time or an override). Cached on first access.
/// </summary>
public TimeSpan EvaluationTime
{
get
{
if (!_roundTimeCached)
{
_roundTime = _system.ResolveEvaluationTime(_timeOverride);
_roundTimeCached = true;
}
return _roundTime;
}
}
/// <summary>
/// Player count seen by modifiers, cached on first access. Supports overrides used by admin simulations.
/// </summary>
public int PlayerCount
{
get
{
if (!_playerCountCached)
{
_playerCount = _system.ResolvePlayerCount(_playerCountOverride);
_playerCountCached = true;
}
return _playerCount;
}
}
/// <summary>
/// Chaos multiplier derived from the ramping scheduler (or other systems). Defaults to 1 until populated.
/// </summary>
public float ChaosModifier
{
get
{
if (!_chaosCached)
{
_chaosModifier = _system.ResolveChaosModifier();
_chaosCached = true;
}
return _chaosModifier;
}
}
/// <summary>
/// Accessor for modifier-specific cached values. Allows modifiers to share expensive lookups.
/// Values are cached in the modifier system for the provided duration.
/// </summary>
public T GetOrAddCachedValue<T>(object key, TimeSpan cacheDuration, Func<T> factory)
{
return _system.GetOrAddCachedValue(key, cacheDuration, factory);
}
public StationEventModifierSystem.StationLiquidSnapshot GetLiquidSnapshot(ProtoId<ReagentPrototype> reagentId, TimeSpan cacheDuration)
{
return _system.GetLiquidSnapshot(reagentId, cacheDuration);
}
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
using Content.Server.StationEvents.Components;
using Robust.Shared.Prototypes;
namespace Content.Server.StationEvents.Modifiers;
///
/// Prototype definition for station event modifiers. Each concrete modifier prototype
/// produces a multiplier that is applied to an event's weight based on current station state.
///
[Prototype("stationEventModifier")]
public abstract partial class StationEventModifierPrototype : IPrototype
{
///
[IdDataField]
public string ID { get; private set; } = default!;
/// <summary>
/// Allow a modifier to pre-populate any shared context entries it needs before contributing a multiplier.
/// </summary>
/// <remarks>
/// Implementations can leave this as the no-op default if no preparation is required.
/// </remarks>
public virtual void PopulateContext(ref StationEventModifierContext context)
{
}
/// <summary>
/// Return a scalar multiplier applied to the current event's weight.
/// </summary>
public abstract float GetModifier(ref StationEventModifierContext context, StationEventComponent stationEvent);
}
using System.Linq;
using Content.Server.Administration;
using Content.Server.GameTicking;
using Content.Server.GameTicking.Rules;
using Content.Server.StationEvents.Components;
using Content.Shared.Administration;
using Content.Shared.EntityTable;
using Content.Shared.GameTicking.Components;
using JetBrains.Annotations;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Toolshed;
using Robust.Shared.Toolshed.TypeParsers;
using Robust.Shared.Utility;
namespace Content.Server.StationEvents
{
///
/// The basic event scheduler rule, loosely based off of /tg/ events, which most
/// game presets use.
///
[UsedImplicitly]
public sealed class BasicStationEventSchedulerSystem : GameRuleSystem
{
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly EventManagerSystem _event = default!;
protected override void Started(EntityUid uid, BasicStationEventSchedulerComponent component, GameRuleComponent gameRule,
GameRuleStartedEvent args)
{
// A little starting variance so schedulers dont all proc at once.
component.TimeUntilNextEvent = RobustRandom.NextFloat(component.MinimumTimeUntilFirstEvent, component.MinimumTimeUntilFirstEvent + 120);
}
protected override void Ended(EntityUid uid, BasicStationEventSchedulerComponent component, GameRuleComponent gameRule,
GameRuleEndedEvent args)
{
component.TimeUntilNextEvent = component.MinimumTimeUntilFirstEvent;
}
public override void Update(float frameTime)
{
base.Update(frameTime);
if (!_event.EventsEnabled)
return;
var query = EntityQueryEnumerator<BasicStationEventSchedulerComponent, GameRuleComponent>();
while (query.MoveNext(out var uid, out var eventScheduler, out var gameRule))
{
if (!GameTicker.IsGameRuleActive(uid, gameRule))
continue;
if (eventScheduler.TimeUntilNextEvent > 0)
{
eventScheduler.TimeUntilNextEvent -= frameTime;
continue;
}
_event.RunRandomEvent(eventScheduler.ScheduledGameRules);
ResetTimer(eventScheduler);
}
}
/// <summary>
/// Reset the event timer once the event is done.
/// </summary>
private void ResetTimer(BasicStationEventSchedulerComponent component)
{
component.TimeUntilNextEvent = component.MinMaxEventTiming.Next(_random);
}
}
[ToolshedCommand, AdminCommand(AdminFlags.Debug)]
public sealed class StationEventCommand : ToolshedCommand
{
private EventManagerSystem? _stationEvent;
private EntityTableSystem? _entityTable;
private IComponentFactory? _compFac;
private IRobustRandom? _random;
private IPrototypeManager? _protoMan;
/// <summary>
/// Estimates the expected number of times an event will run over the course of X rounds, taking into account weights and
/// how many events are expected to run over a given timeframe for a given playercount by repeatedly simulating rounds.
/// Effectively /100 (if you put 100 rounds) = probability an event will run per round.
/// </summary>
/// <remarks>
/// This isn't perfect. Code path eventually goes into <see cref="EventManagerSystem.CanRun"/>, which requires
/// state from <see cref="GameTicker"/>. As a result, you should probably just run this locally and not doing
/// a real round (it won't pollute the state, but it will get contaminated by previously ran events in the actual round)
/// and things like `MaxOccurrences` and `ReoccurrenceDelay` won't be respected.
///
/// I consider these to not be that relevant to the analysis here though (and I don't want most uses of them
/// to even exist) so I think it's fine.
/// </remarks>
[CommandImplementation("simulate")]
public IEnumerable<(string, float)> Simulate([CommandArgument] EntProtoId eventSchedulerProto, [CommandArgument] int rounds, [CommandArgument] int playerCount, [CommandArgument] float roundEndMean, [CommandArgument] float roundEndStdDev)
{
_stationEvent ??= GetSys<EventManagerSystem>();
_entityTable ??= GetSys<EntityTableSystem>();
_compFac ??= IoCManager.Resolve<IComponentFactory>();
_random ??= IoCManager.Resolve<IRobustRandom>();
_protoMan ??= IoCManager.Resolve<IPrototypeManager>();
var occurrences = new Dictionary<string, int>();
foreach (var ev in _stationEvent.AllEvents())
{
occurrences.Add(ev.Key.ID, 0);
}
var eventScheduler = _protoMan.Index(eventSchedulerProto);
if (!eventScheduler.TryGetComponent<BasicStationEventSchedulerComponent>(out var basicScheduler, _compFac))
{
return occurrences.Select(p => (p.Key, (float)p.Value)).OrderByDescending(p => p.Item2);
}
var compMinMax = basicScheduler.MinMaxEventTiming; // we gotta do this since we cant execute on comp w/o an ent.
for (var i = 0; i < rounds; i++)
{
var curTime = TimeSpan.Zero;
var randomEndTime = _random.NextGaussian(roundEndMean, roundEndStdDev) * 60; // Its in minutes, should probably be a better time format once we get that in toolshed like [hh:mm:ss]
if (randomEndTime <= 0)
continue;
while (curTime.TotalSeconds < randomEndTime)
{
// sim an event
curTime += TimeSpan.FromSeconds(compMinMax.Next(_random));
var available = _stationEvent.AvailableEvents(false, playerCount, curTime);
if (!_stationEvent.TryBuildLimitedEvents(basicScheduler.ScheduledGameRules, available, out var selectedEvents))
{
continue; // doesnt break because maybe the time is preventing events being available.
}
var ev = _stationEvent.FindEvent(selectedEvents, curTime, playerCount);
if (ev == null)
continue;
occurrences[ev] += 1;
}
}
return occurrences.Select(p => (p.Key, (float)p.Value)).OrderByDescending(p => p.Item2);
}
[CommandImplementation("lsprob")]
public IEnumerable<(string, float)> LsProb([CommandArgument] EntProtoId eventSchedulerProto)
{
_compFac ??= IoCManager.Resolve<IComponentFactory>();
_stationEvent ??= GetSys<EventManagerSystem>();
_protoMan ??= IoCManager.Resolve<IPrototypeManager>();
var eventScheduler = _protoMan.Index(eventSchedulerProto);
if (!eventScheduler.TryGetComponent<BasicStationEventSchedulerComponent>(out var basicScheduler, _compFac))
yield break;
var available = _stationEvent.AvailableEvents();
if (!_stationEvent.TryBuildLimitedEvents(basicScheduler.ScheduledGameRules, available, out var events))
yield break;
var totalWeight = events.Values.Sum(x => _stationEvent.GetEventWeight(x));
if (totalWeight == 0)
yield break;
foreach (var (proto, comp) in events)
{
yield return (proto.ID, _stationEvent.GetEventWeight(comp) / totalWeight);
}
}
[CommandImplementation("lsprobtheoretical")]
public IEnumerable<(string, float)> LsProbTime([CommandArgument] EntProtoId eventSchedulerProto, [CommandArgument] int playerCount, [CommandArgument] float time)
{
_compFac ??= IoCManager.Resolve<IComponentFactory>();
_stationEvent ??= GetSys<EventManagerSystem>();
_protoMan ??= IoCManager.Resolve<IPrototypeManager>();
var eventScheduler = _protoMan.Index(eventSchedulerProto);
if (!eventScheduler.TryGetComponent<BasicStationEventSchedulerComponent>(out var basicScheduler, _compFac))
yield break;
var theoryTime = TimeSpan.FromMinutes(time);
var available = _stationEvent.AvailableEvents(false, playerCount, theoryTime);
if (!_stationEvent.TryBuildLimitedEvents(basicScheduler.ScheduledGameRules, available, out var untimedEvents))
yield break;
var events = untimedEvents.Where(pair => pair.Value.EarliestStart <= time).ToList();
var totalWeight = events.Sum(x => _stationEvent.GetEventWeight(x.Value, theoryTime, playerCount));
if (totalWeight == 0)
yield break;
foreach (var (proto, comp) in events)
{
yield return (proto.ID, _stationEvent.GetEventWeight(comp, theoryTime, playerCount) / totalWeight);
}
}
[CommandImplementation("prob")]
public float Prob([CommandArgument] EntProtoId eventSchedulerProto, [CommandArgument] string eventId)
{
_compFac ??= IoCManager.Resolve<IComponentFactory>();
_stationEvent ??= GetSys<EventManagerSystem>();
_protoMan ??= IoCManager.Resolve<IPrototypeManager>();
var eventScheduler = _protoMan.Index(eventSchedulerProto);
if (!eventScheduler.TryGetComponent<BasicStationEventSchedulerComponent>(out var basicScheduler, _compFac))
return 0f;
var available = _stationEvent.AvailableEvents();
if (!_stationEvent.TryBuildLimitedEvents(basicScheduler.ScheduledGameRules, available, out var events))
return 0f;
var totalWeight = events.Values.Sum(x => _stationEvent.GetEventWeight(x));
if (totalWeight == 0)
return 0f;
var weight = 0f;
if (events.TryFirstOrNull(p => p.Key.ID == eventId, out var pair))
{
weight = _stationEvent.GetEventWeight(pair.Value.Value);
}
return weight / totalWeight;
}
}}
using System.Linq;
using Content.Server.GameTicking;
using Content.Server.RoundEnd;
using Content.Server.StationEvents.Components;
using Content.Server.StationEvents.Modifiers;
using Content.Shared.CCVar;
using Robust.Server.Player;
using Robust.Shared.Configuration;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Content.Shared.EntityTable.EntitySelectors;
using Content.Shared.EntityTable;
using Robust.Shared.Timing;
public bool EventsEnabled { get; private set; }
private void SetEnabled(bool value) => EventsEnabled = value;
public override void Initialize()
{
base.Initialize();
Subs.CVar(_configurationManager, CCVars.EventsEnabled, SetEnabled, true);
}
/// <summary>
/// Randomly runs an event from provided EntityTableSelector.
/// </summary>
public void RunRandomEvent(EntityTableSelector limitedEventsTable)
{
var availableEvents = AvailableEvents(); // handles the player counts and individual event restrictions.
// Putting this here only makes any sense in the context of the toolshed commands in BasicStationEventScheduler. Kill me.
if (!TryBuildLimitedEvents(limitedEventsTable, availableEvents, out var limitedEvents))
{
Log.Warning("Provided event table could not build dict!");
return;
}
var randomLimitedEvent = FindEvent(limitedEvents); // this picks the event, It might be better to use the GetSpawns to do it, but that will be a major rebalancing fuck.
if (randomLimitedEvent == null)
{
Log.Warning("The selected random event is null!");
return;
}
if (!_prototype.Resolve(randomLimitedEvent, out _))
{
Log.Warning("A requested event is not available!");
return;
}
GameTicker.AddGameRule(randomLimitedEvent);
}
/// <summary>
/// Returns true if the provided EntityTableSelector gives at least one prototype with a StationEvent comp.
/// </summary>
public bool TryBuildLimitedEvents(
EntityTableSelector limitedEventsTable,
Dictionary<EntityPrototype, StationEventComponent> availableEvents,
out Dictionary<EntityPrototype, StationEventComponent> limitedEvents
)
{
limitedEvents = new Dictionary<EntityPrototype, StationEventComponent>();
if (availableEvents.Count == 0)
{
Log.Warning("No events were available to run!");
return false;
}
var selectedEvents = _entityTable.GetSpawns(limitedEventsTable);
if (selectedEvents.Any() != true) // This is here so if you fuck up the table it wont die.
return false;
foreach (var eventid in selectedEvents)
{
if (!_prototype.Resolve(eventid, out var eventproto))
{
Log.Warning("An event ID has no prototype index!");
continue;
}
if (limitedEvents.ContainsKey(eventproto)) // This stops it from dying if you add duplicate entries in a fucked table
continue;
if (eventproto.Abstract)
continue;
if (!eventproto.TryGetComponent<StationEventComponent>(out var stationEvent, EntityManager.ComponentFactory))
continue;
if (!availableEvents.ContainsKey(eventproto))
continue;
limitedEvents.Add(eventproto, stationEvent);
}
if (!limitedEvents.Any())
return false;
return true;
}
/// <summary>
/// Randomly picks a valid event.
/// </summary>
public string? PickRandomEvent()
{
var availableEvents = AvailableEvents();
Log.Info($"Picking from {availableEvents.Count} total available events");
return FindEvent(availableEvents);
}
/// <summary>
/// Pick a random event from the available events at this time, also considering their weightings.
/// </summary>
/// <returns></returns>
public string? FindEvent(Dictionary<EntityPrototype, StationEventComponent> availableEvents, TimeSpan? currentTimeOverride = null, int? playerCountOverride = null)
{
if (availableEvents.Count == 0)
{
Log.Warning("No events were available to run!");
return null;
}
var weightedEvents = new List<(EntityPrototype proto, float weight)>();
var sumOfWeights = 0.0f;
var modifierContext = _stationEventModifiers.CreateContext(currentTimeOverride, playerCountOverride);
foreach (var (proto, stationEvent) in availableEvents)
{
var weight = GetEventWeight(stationEvent, ref modifierContext);
if (weight <= 0)
continue;
weightedEvents.Add((proto, weight));
sumOfWeights += weight;
}
if (weightedEvents.Count == 0)
{
// This can happen if all available events have a weight of 0.
return null;
}
var randomPick = _random.NextFloat(sumOfWeights);
foreach (var (proto, weight) in weightedEvents)
{
randomPick -= weight;
if (randomPick <= 0.0f)
{
return proto.ID;
}
}
Log.Error("Event was not found after weighted pick process! This should not happen.");
// Fallback to the last event just in case of floating point shenanigans.
return weightedEvents[^1].proto.ID;
}
public float GetEventWeight(StationEventComponent stationEvent, TimeSpan? currentTimeOverride = null, int? playerCountOverride = null)
{
var context = _stationEventModifiers.CreateContext(currentTimeOverride, playerCountOverride);
return GetEventWeight(stationEvent, ref context);
}
private float GetEventWeight(StationEventComponent stationEvent, ref StationEventModifierContext context)
{
var finalWeight = stationEvent.Weight;
var curveMultiplier = 1.0f;
var dynamicWeight = stationEvent.DynamicWeight;
if (dynamicWeight != null)
{
var curve = dynamicWeight.Curve;
if (curve.Count > 0)
{
var currentTime = context.EvaluationTime.TotalMinutes;
if (currentTime < curve[0].X)
{
curveMultiplier = curve[0].Y;
}
else if (currentTime >= curve[^1].X)
{
curveMultiplier = curve[^1].Y;
}
else
{
var i = 0;
while (i < curve.Count - 1 && currentTime >= curve[i + 1].X)
{
i++;
}
switch (dynamicWeight.Interpolation)
{
case DynamicWeightInterpolation.Stepped:
curveMultiplier = curve[i].Y;
break;
case DynamicWeightInterpolation.Linear:
default:
var (x1, y1) = curve[i];
var (x2, y2) = curve[i + 1];
var t = (float) ((currentTime - x1) / (x2 - x1));
curveMultiplier = y1 + t * (y2 - y1);
break;
}
}
}
}
finalWeight *= curveMultiplier;
var modifierMultiplier = _stationEventModifiers.EvaluateModifiers(stationEvent, ref context);
finalWeight *= modifierMultiplier;
return finalWeight;
}
/// <summary>
/// Gets the events that have met their player count, time-until start, etc.
/// </summary>
/// <param name="playerCountOverride">Override for player count, if using this to simulate events rather than in an actual round.</param>
/// <param name="currentTimeOverride">Override for round time, if using this to simulate events rather than in an actual round.</param>
/// <returns></returns>
public Dictionary<EntityPrototype, StationEventComponent> AvailableEvents(
bool ignoreEarliestStart = false,
int? playerCountOverride = null,
TimeSpan? currentTimeOverride = null)
{
var playerCount = playerCountOverride ?? _playerManager.PlayerCount;
// playerCount does a lock so we'll just keep the variable here
var currentTime = currentTimeOverride ?? (!ignoreEarliestStart
? GameTicker.RoundDuration()
: TimeSpan.Zero);
var result = new Dictionary<EntityPrototype, StationEventComponent>();
foreach (var (proto, stationEvent) in AllEvents())
{
if (CanRun(proto, stationEvent, playerCount, currentTime))
{
result.Add(proto, stationEvent);
}
}
return result;
}
public Dictionary<EntityPrototype, StationEventComponent> AllEvents()
{
var allEvents = new Dictionary<EntityPrototype, StationEventComponent>();
foreach (var prototype in _prototype.EnumeratePrototypes<EntityPrototype>())
{
if (prototype.Abstract)
continue;
if (!prototype.TryGetComponent<StationEventComponent>(out var stationEvent, EntityManager.ComponentFactory))
continue;
allEvents.Add(prototype, stationEvent);
}
return allEvents;
}
private int GetOccurrences(EntityPrototype stationEvent)
{
return GetOccurrences(stationEvent.ID);
}
private int GetOccurrences(string stationEvent)
{
return GameTicker.AllPreviousGameRules.Count(p => p.Item2 == stationEvent);
}
public TimeSpan TimeSinceLastEvent(EntityPrototype stationEvent)
{
foreach (var (time, rule) in GameTicker.AllPreviousGameRules.Reverse())
{
if (rule == stationEvent.ID)
return time;
}
return TimeSpan.Zero;
}
private bool CanRun(EntityPrototype prototype, StationEventComponent stationEvent, int playerCount, TimeSpan currentTime)
{
if (GameTicker.IsGameRuleActive(prototype.ID))
return false;
if (stationEvent.MaxOccurrences.HasValue && GetOccurrences(prototype) >= stationEvent.MaxOccurrences.Value)
{
return false;
}
if (playerCount < stationEvent.MinimumPlayers)
{
return false;
}
if (currentTime != TimeSpan.Zero && currentTime.TotalMinutes < stationEvent.EarliestStart)
{
return false;
}
var lastRun = TimeSinceLastEvent(prototype);
if (lastRun != TimeSpan.Zero && currentTime.TotalMinutes <
stationEvent.ReoccurrenceDelay + lastRun.TotalMinutes)
{
return false;
}
if (_roundEnd.IsRoundEndRequested() && !stationEvent.OccursDuringRoundEnd)
{
return false;
}
return true;
}
}
using System;
using System.Collections.Generic;
using Content.Server.Fluids.Components;
using Content.Shared.Chemistry.Components;
using Content.Shared.Chemistry.Components.SolutionManager;
using Content.Shared.Chemistry.Reagent;
using Content.Shared.FixedPoint;
using Content.Shared.GameTicking;
using Content.Server.StationEvents.Components;
using Content.Server.StationEvents.Modifiers;
using Robust.Server.Player;
using Robust.Shared.Log;
using Robust.Shared.Prototypes;
using Robust.Shared.Timing;
namespace Content.Server.StationEvents;
///
/// Central point for evaluating station event modifiers. Provides the shared context used by every modifier and caches
/// expensive lookups (round time, population, chaos metrics) to keep the event selection hot path lightweight.
///
public sealed class StationEventModifierSystem : EntitySystem
{
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly SharedSolutionContainerSystem _solutionContainerSystem = default!;
private readonly Dictionary<object, (object Value, TimeSpan Expiry)> _cachedValues = new();
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<RoundRestartCleanupEvent>(OnRoundRestart);
}
private void OnRoundRestart(RoundRestartCleanupEvent ev)
{
_cachedValues.Clear();
}
/// <summary>
/// Creates a modifier context for a weighting pass, optionally overriding round time or player count for simulations.
/// </summary>
public StationEventModifierContext CreateContext(TimeSpan? timeOverride = null, int? playerCountOverride = null)
=> new(this, timeOverride, playerCountOverride);
/// <summary>
/// Evaluate all modifier prototypes attached to the event and return their combined weight multiplier.
/// </summary>
public float EvaluateModifiers(StationEventComponent stationEvent, ref StationEventModifierContext context)
{
if (stationEvent.Modifiers.Count == 0)
return 1f;
var product = 1f;
foreach (var modifierId in stationEvent.Modifiers)
{
if (!_prototypeManager.TryIndex(modifierId, out StationEventModifierPrototype? prototype))
{
Log.Warning($"Station event modifier prototype '{modifierId}' could not be resolved.");
continue;
}
prototype.PopulateContext(ref context);
var multiplier = prototype.GetModifier(ref context, stationEvent);
if (multiplier <= 0f)
return 0f;
product *= multiplier;
}
return product;
}
internal TimeSpan ResolveEvaluationTime(TimeSpan? overrideValue)
=> overrideValue ?? _gameTiming.CurTime;
internal int ResolvePlayerCount(int? overrideValue)
=> overrideValue ?? _playerManager.PlayerCount;
internal float ResolveChaosModifier()
{
// Placeholder until the chaos modifier is implemented inside this system.
return 1f;
}
internal T GetOrAddCachedValue<T>(object key, TimeSpan cacheDuration, Func<T> factory)
{
var now = _gameTiming.CurTime;
if (_cachedValues.TryGetValue(key, out var cached) && now < cached.Expiry)
{
return (T) cached.Value;
}
var value = factory();
_cachedValues[key] = (value!, now + cacheDuration);
return value;
}
internal StationLiquidSnapshot GetLiquidSnapshot(ProtoId<ReagentPrototype> reagentId, TimeSpan cacheDuration)
{
var cacheKey = ("station-liquid", reagentId.ID);
return GetOrAddCachedValue(cacheKey, cacheDuration, () => ComputeLiquidSnapshot(reagentId));
}
private StationLiquidSnapshot ComputeLiquidSnapshot(ProtoId<ReagentPrototype> reagentId)
{
var snapshot = new StationLiquidSnapshot();
var query = EntityQueryEnumerator<PuddleComponent, SolutionContainerManagerComponent>();
while (query.MoveNext(out var uid, out var puddle, out var manager))
{
var container = (uid, manager);
if (!_solutionContainerSystem.TryGetSolution(container, puddle.SolutionName, out _, out var solution))
continue;
var sol = solution.Value;
if (!sol.TryGetReagentQuantity(reagentId, out var quantity) || quantity <= FixedPoint2.Zero)
continue;
snapshot.PuddleCount++;
snapshot.TotalQuantity += quantity;
}
return snapshot;
}
public struct StationLiquidSnapshot
{
public int PuddleCount;
public FixedPoint2 TotalQuantity;
}
}
Come up with ideas how to make the station event modifier system more generic and flexible without making it more complicated. How to refactor it
Love this question. Your current setup is already pretty sane: modifiers are prototypes, there’s a shared context, and you batch their product into a final weight. The biggest wins now are about making it easier to add new “kinds” of modifiers and letting different modifiers reuse the same station metrics without any new plumbing each time.
Here’s how I’d refactor to make it more generic and flexible without making it more complicated.
Goals
Make it trivial to add a new modifier that uses any station metric.
Avoid adding new context methods every time you invent a new metric.
Reduce repeated lookups and boilerplate.
Keep the mental model: “weight = base × curve × product(modifiers)”.
Key ideas
Replace ad-hoc context helpers (like GetLiquidSnapshot) with a single typed “metric key” API.
Remove PopulateContext (it doesn’t buy much) and rely on per-pass caching with typed keys.
Pre-resolve modifier prototypes once so you’re not indexing them on every pass.
Offer simple, reusable base classes for common modifier patterns (thresholds, ranges).
Add optional tag-based targeting and modifier bundles to reduce duplication in event prototypes.
Add a small debugging hook so you can see the weight breakdown per event.
The small-but-powerful abstractions
Typed metric keys, one generic getter
Introduce IMetricKey with:
a unique cache identity (the key itself),
a Compute(StationEventModifierSystem sys) method that knows how to produce T.
Add to StationEventModifierContext:
T Get(IMetricKey key, TimeSpan? ttl = null)
This replaces special-purpose helpers like GetLiquidSnapshot with a generic mechanism and keeps all caching inside StationEventModifierSystem. New metrics become tiny key types instead of new methods.
var snap = context.Get(new LiquidMetricKey(ReagentId), TimeSpan.FromSeconds(CacheSeconds));
Because the key carries the compute logic, you don’t need to expand StationEventModifierContext/System for each new metric anymore.
Kill PopulateContext
It’s an extra concept without much practical use; modifiers can just ask for metrics via context.Get(key).
Less API surface, fewer passes.
Pre-resolve modifier prototypes per event
Change StationEventComponent.Modifiers from List to List<ProtoId> for type safety.
On first access (or during rule load), resolve and cache the actual StationEventModifierPrototype references so EvaluateModifiers doesn’t call TryIndex per pass.
Optionally store a ResolvedModifiers list on the component via a lightweight cache in StationEventModifierSystem.
Common base classes for 80% of modifiers
ThresholdModifier: feed it a metric key and a list of rules; it handles selecting the max multiplier that matches.
Your LiquidPresenceModifier becomes a 1-file subclass that only supplies the metric key and how to extract two numbers (units, puddles) from TMetric.
GateModifier: returns 0 or 1 based on a boolean predicate (useful to hard-disable big families of events cleanly).
This trims copy-paste and encourages consistency while staying dead simple to use.
Tag-based targeting and bundles (optional but helpful)
Add EventTags to StationEventComponent (lightweight string set).
Add AppliesToTags/ExceptTags to StationEventModifierPrototype. If set, a modifier only runs for matching events. This lets you attach global modifiers once (e.g., “Atmos events get a bonus when O2 alarms firing”) without stuffing every event’s Modifiers list.
Add ModifierBundle prototypes (just a list of modifier IDs). Then in events you can reference bundles, not 10 individual modifiers. Keep evaluation order deterministic by having Priority on modifiers.
Keep the aggregator simple, but make it debuggable
Stay with multiplication as the only combine mode; it’s consistent and easy to reason about. If you really need more, add a second mode (Add) behind a field on the modifier, default Multiply. Don’t overuse it.
Add a debug API: GetEventWeightBreakdown(stationEvent, context) -> list of (source, multiplier, note). Expose via toolshed so you can print per-modifier contributions for a given time/player count. This makes tuning painless.
Concrete changes (minimal surface)
StationEventModifierContext
Remove PopulateContext usage and the method from StationEventModifierPrototype.
Add: T Get(IMetricKey key, TimeSpan? ttl = null).
StationEventModifierSystem
Keep one cache dictionary keyed by object (the metric key). The key’s Equals/GetHashCode define uniqueness.
Implement GetOrAddCachedValue using the key instance directly. The key carries Compute(sys).
Provide a default TTL (e.g., 1–2 seconds), with per-call overrides.
StationEventModifierPrototype
Fields: int Priority = 0; string[] AppliesToTags?; string[] ExceptTags?;
Method: public abstract float GetModifier(ref StationEventModifierContext ctx, StationEventComponent evt).
EventManagerSystem
Resolve modifier prototypes once per event (or keep a small LRU cache keyed by event proto ID).
Optionally move dynamic weight curve into a built-in modifier (TimeCurveModifier) so all weighting flows through one pipeline. If you don’t want the migration noise, leave it as-is.
Example: refactoring LiquidPresenceModifier
Change it to derive from a generic threshold base, but still accept the same Thresholds and CacheSeconds.
public override float Evaluate(StationLiquidSnapshot m) => run thresholds over m.PuddleCount and m.TotalQuantity.Float();
LiquidMetricKey looks like:
record struct LiquidMetricKey(ProtoId Reagent)
StationLiquidSnapshot Compute(StationEventModifierSystem sys) => sys.ComputeLiquidSnapshot(Reagent); // reuse your existing impl
Migration plan
Step 1: Add metric-key API alongside existing helpers. Port Liquid to the new API.
Step 2: Remove PopulateContext from the base class and usages.
Step 3: Flip Modifiers to use ProtoId and pre-resolve them.
Step 4: Introduce ThresholdModifier base and convert copy-paste-y modifiers.
Step 5: (Optional) Add tags, bundles, and the breakdown tool.
This keeps the system simple to think about—“ask for metrics; return a multiplier”—but it removes the friction of adding new metrics and avoids constantly expanding the context surface area. You get better reuse, safer caching, and less boilerplate without turning it into a framework or a DSL.