The current station event modifier system is quite specific, relying on hardcoded context retrieval methods (like GetLiquidSnapshot) within StationEventModifierContext and system interaction within StationEventModifierSystem.
To make it more generic and flexible while maintaining (or even reducing) complexity, we should focus on:
- Decoupling Context Retrieval: Instead of baking specific lookups into the context struct, allow modifiers to request services or data accessors they need.
- Leveraging the Component System: If modifiers need station state, they should probably query for components present on the station entity (or the implicitly referenced station entity).
- Simplifying
StationEventModifierPrototype: Making the core contract (GetModifier) simpler by hiding the context resolution complexity.
Here are a few refactoring ideas based on these principles:
Refactoring Idea 1: Context as an Interface/Delegate Bag
Instead of having StationEventModifierContext tightly coupled to StationEventModifierSystem and exposing internal helper methods like GetLiquidSnapshot, we can redefine what the context provides using interfaces or bags of functions.
Changes Required
1. Define Data Access Interfaces
Create interfaces that represent the data access required by various modifiers.
// In Modifiers/IDataAccess.cs
public interface IStationTimeAccess
{
TimeSpan EvaluationTime { get; }
}
public interface IStationLiquidAccess
{
StationEventModifierSystem.StationLiquidSnapshot GetLiquidSnapshot(ProtoId<ReagentPrototype> reagentId, TimeSpan cacheDuration);
}
// Potentially combine common ones into a base context interface
public interface IStationEventContext : IStationTimeAccess, IStationLiquidAccess
{
// ... other common accessors like PlayerCount, ChaosModifier
T GetOrAddCachedValue<T>(object key, TimeSpan cacheDuration, Func<T> factory);
}
2. Update StationEventModifierContext (Implementation Detail)
The internal StationEventModifierContext struct would implement IStationEventContext, hiding the system interaction details.
// StationEventModifierContext.cs (Implementation)
// This structure now directly implements the public interface, hiding the System dependency from the abstract modifier prototype.
public readonly struct StationEventModifierContext : IStationEventContext
{
private readonly StationEventModifierSystem _system;
// ... other private fields
internal StationEventModifierContext(/* ... */)
{
// ... initialization
}
// Implement IStationTimeAccess, IStationLiquidAccess, etc., by calling _system methods.
public TimeSpan EvaluationTime => _system.ResolveEvaluationTime(_timeOverride);
public StationLiquidSnapshot GetLiquidSnapshot(ProtoId<ReagentPrototype> reagentId, TimeSpan cacheDuration)
{
return _system.GetLiquidSnapshot(reagentId, cacheDuration);
}
// ...
}
3. Update Abstract Prototype and Usage
The abstract prototype now expects the context to implement the required interface.
// In StationEventModifierPrototype.cs
public abstract partial class StationEventModifierPrototype : IPrototype
{
// Changed signature to use the interface for better decoupling
public abstract float GetModifier(ref IStationEventContext context, StationEventComponent stationEvent);
}
// In LiquidPresenceModifierPrototype.cs
public sealed partial class LiquidPresenceModifierPrototype : StationEventModifierPrototype
{
// ... fields
public override float GetModifier(ref IStationEventContext context, StationEventComponent stationEvent)
{
if (Thresholds.Count == 0)
return 1f;
// We can safely cast/assume context implements IStationLiquidAccess if we want to keep caching internal,
// OR we just rely on IStationEventContext exposing the methods directly.
// Using the concrete method signature from the old context for now:
if (context is not StationEventModifierContext concreteContext)
return 1f; // Or throw, depending on strictness.
var snapshot = concreteContext.GetLiquidSnapshot(ReagentId, TimeSpan.FromSeconds(Math.Max(1f, CacheSeconds)));
// ... rest of logic remains the same
}
}
// In StationEventModifierSystem.EvaluateModifiers
// When calling the modifier:
// var multiplier = prototype.GetModifier(ref context, stationEvent); // context is still the concrete struct here, but modifiers only rely on IStationEventContext if we refactor the signature.
Benefit: This isolates what a modifier can do from how the system does it. If the underlying implementation of caching changes, only StationEventModifierSystem needs updating.
Refactoring Idea 2: Modifier as a Component/System Dependency (The "System Hook" Approach)
If a modifier needs complex, non-cachable, real-time information (like "Are any players currently venting?") that isn't easily represented by simple time/player count data, the modifier itself should potentially be a System or have access to a specific subsystem.
This requires moving away from the pure prototype model for stateful modifiers, but allows for maximum flexibility.
Changes Required
1. Introduce SystemDependency Attribute for Modifiers
Allow prototypes to declare what other systems they depend on.
// In StationEventModifierPrototype.cs
[Prototype("stationEventModifier")]
public abstract partial class StationEventModifierPrototype : IPrototype
{
// Define dependencies at the prototype level
[DataField("requiredSystems")]
public List<Type> RequiredSystemDependencies { get; private set; } = new();
// ...
}
2. Modify Context to Inject Dependencies
The StationEventModifierContext is updated to find and inject these dependencies during evaluation setup.
// StationEventModifierContext.cs (Update)
public struct StationEventModifierContext
{
private readonly StationEventModifierSystem _system;
private readonly Dictionary<Type, object> _injectedServices; // Store resolved dependencies
internal StationEventModifierContext(
StationEventModifierSystem system,
TimeSpan? timeOverride,
int? playerCountOverride,
Dictionary<Type, object>? initialServices = null)
{
_system = system;
// ...
_injectedServices = initialServices ?? new Dictionary<Type, object>();
}
// New method for modifiers to request services
public T GetService<T>() where T : ISystem
{
if (_injectedServices.TryGetValue(typeof(T), out var service))
{
return (T) service;
}
// Fallback: Resolve via IoC if not pre-injected (less ideal for hot path, but flexible)
// Or, better: Ensure the system pre-populates context with necessary system dependencies.
throw new InvalidOperationException($"System dependency {typeof(T)} was not provided in context.");
}
}
3. Update Modifier Evaluation Logic in StationEventModifierSystem
The system now resolves the requested services before calling the modifier.
// In StationEventModifierSystem.EvaluateModifiers
public float EvaluateModifiers(StationEventComponent stationEvent, ref StationEventModifierContext context)
{
// ...
var requiredDependencies = new Dictionary<Type, object>();
foreach (var modifierId in stationEvent.Modifiers)
{
// ... prototype resolution
// Aggregate all dependencies across all modifiers for this event weighting pass
foreach (var depType in prototype.RequiredSystemDependencies)
{
if (!requiredDependencies.ContainsKey(depType))
{
// Resolve the required system (e.g., using IoC or asking the system manager)
requiredDependencies[depType] = IoCManager.Resolve(depType);
}
}
}
// Create a *new* context instance potentially containing the dependency map,
// or update the existing one if context was mutable enough.
// For simplicity, let's assume we update the context structure to hold the dependency map.
foreach (var (prototype, stationEvent) in availableEvents)
{
// ...
var multiplier = prototype.GetModifier(ref context, stationEvent); // Context now has access to required systems
product *= multiplier;
}
return product;
}
4. Updating LiquidPresenceModifierPrototype
The liquid access logic is replaced by a generic system request.
// In LiquidPresenceModifierPrototype.cs (Refactored)
public override float GetModifier(ref StationEventModifierContext context, StationEventComponent stationEvent)
{
if (Thresholds.Count == 0)
return 1f;
// Request the system responsible for liquid data
var liquidSystem = context.GetService<StationEventModifierSystem>(); // Assuming it's registered or accessible
// NOTE: If we want to avoid exposing the internal system type, we use an interface defined in Idea 1.
var snapshot = context.GetLiquidSnapshot(ReagentId, TimeSpan.FromSeconds(Math.Max(1f, CacheSeconds)));
// ... rest of logic
}
Benefit: This is vastly more flexible. A new modifier needing complex fluid dynamics, physics simulation results, or specific atmospheric data can simply declare a dependency on the relevant system interface/type, rather than having StationEventModifierContext become a massive dump of every possible station stat.
Conclusion and Recommendation
The first idea (Context as an Interface/Delegate Bag) provides the best balance between increased flexibility and minimal refactoring complexity for your existing code, especially since the LiquidPresenceModifierPrototype is already accessing a specific, cached value.
If you only need to abstract how caching works, stick to Refactoring Idea 1.
If you anticipate needing access to many different, potentially non-cached subsystem results (like AtmosphereSystem or TraitorRoleSystem), Refactoring Idea 2 (System Hook Approach), likely implemented by having the context expose requested interfaces, is the path toward true flexibility.
Minimal Refactor Suggestion (Implementing Idea 1's Core Principle)
To quickly improve the decoupling for LiquidPresenceModifierPrototype, ensure StationEventModifierContext only exposes the accessors needed, keeping the internal structure of the context implementation hidden.
You already have:
public StationEventModifierContext GetLiquidSnapshot(ProtoId<ReagentPrototype> reagentId, TimeSpan cacheDuration)
And the prototype consumes it:
var snapshot = context.GetLiquidSnapshot(ReagentId, ...);
To make this more generic: Stop using the concrete StationEventModifierContext type in the public contract if you want true abstraction.
// In StationEventModifierPrototype.cs
// Change signature to use an interface that only defines what data is available.
public abstract partial class StationEventModifierPrototype : IPrototype
{
// ... existing PopulateContext
// Use a minimal interface for data access required for weighting.
public abstract float GetModifier(ref IStationDataAccessor context, StationEventComponent stationEvent);
}
// In Modifiers/IStationDataAccessor.cs
public interface IStationDataAccessor
{
TimeSpan EvaluationTime { get; }
int PlayerCount { get; }
float ChaosModifier { get; }
T GetOrAddCachedValue<T>(object key, TimeSpan cacheDuration, Func<T> factory);
StationEventModifierSystem.StationLiquidSnapshot GetLiquidSnapshot(ProtoId<ReagentPrototype> reagentId, TimeSpan cacheDuration);
}
// In LiquidPresenceModifierPrototype.cs
public sealed partial class LiquidPresenceModifierPrototype : StationEventModifierPrototype
{
// ...
public override float GetModifier(ref IStationDataAccessor context, StationEventComponent stationEvent)
{
if (Thresholds.Count == 0)
return 1f;
// Now we are fully decoupled from the internal structure name
var snapshot = context.GetLiquidSnapshot(ReagentId, TimeSpan.FromSeconds(Math.Max(1f, CacheSeconds)));
var totalUnits = snapshot.TotalQuantity.Float();
var puddleCount = snapshot.PuddleCount;
var multiplier = 1f;
// ... rest of logic
}
}
// In StationEventModifierSystem.EvaluateModifiers & Context creation
// System creates the concrete context, which implements IStationDataAccessor.
public StationEventModifierContext CreateContext(...) // This struct must implement IStationDataAccessor
{
return new StationEventModifierContext(this, ...);
}
This final suggested approach (making the contract use an interface) achieves maximum generic flexibility by clearly defining the contract of required data access for any modifier prototype.