Skip to content

Game.Simulation.ElectricityStatisticsSystem

Assembly: Game (Cities: Skylines 2)
Namespace: Game.Simulation

Type: class

Base: GameSystemBase, implements IElectricityStatisticsSystem, IDefaultSerializable, ISerializable

Summary:
ElectricityStatisticsSystem collects aggregated electricity statistics for the simulation using DOTS ECS jobs. It counts total production capacity, wanted and fulfilled consumption, and battery stored energy and capacity across all building entities that expose ElectricityProducer, ElectricityConsumer and Battery components. The system uses burst-compiled IJobChunk jobs and NativePerThreadSumInt accumulators for parallel counting, runs on a fixed update schedule (interval/offset), and supports save/load via ISerializable patterns.


Fields

  • private EntityQuery m_ProducerGroup
    Holds the query selecting entities that have ElectricityProducer (excluding Temp and Deleted). Used to schedule the production counting job.

  • private EntityQuery m_ConsumerGroup
    Holds the query selecting entities that have ElectricityConsumer (excluding Temp and Deleted). Used to schedule the consumption counting job.

  • private EntityQuery m_BatteryGroup
    Holds the query selecting entities that have Battery (excluding Temp and Deleted). Used to schedule the battery counting job.

  • private NativePerThreadSumInt m_Production
    Parallel accumulator for production capacity totals across threads/chunks. Allocated persistent and reset each update.

  • private NativePerThreadSumInt m_Consumption
    Parallel accumulator for wanted consumption totals.

  • private NativePerThreadSumInt m_FulfilledConsumption
    Parallel accumulator for fulfilled consumption totals.

  • private NativePerThreadSumInt m_BatteryCharge
    Parallel accumulator for stored energy in batteries (storedEnergyHours).

  • private NativePerThreadSumInt m_BatteryCapacity
    Parallel accumulator for battery capacity totals.

  • private int m_LastProduction
    Cached integer representing the last computed total production (read by public property).

  • private int m_LastConsumption
    Cached integer representing the last computed total consumption (read by public property).

  • private int m_LastFulfilledConsumption
    Cached integer representing the last computed total fulfilled consumption.

  • private int m_LastBatteryCharge
    Cached integer representing the last computed total battery stored energy.

  • private int m_LastBatteryCapacity
    Cached integer representing the last computed total battery capacity.

  • private TypeHandle __TypeHandle
    Internal struct bundling ComponentTypeHandle instances for ElectricityProducer, ElectricityConsumer and Battery. Used to get type handles for chunk jobs efficiently.

Properties

  • public int production { get; }
    Returns the last computed total electricity production capacity (m_LastProduction). This is updated once per system update in OnUpdate.

  • public int consumption { get; }
    Returns the last computed total wanted electricity consumption (m_LastConsumption).

  • public int fulfilledConsumption { get; }
    Returns the last computed total fulfilled electricity consumption (m_LastFulfilledConsumption).

  • public int batteryCharge { get; }
    Returns the last computed total battery stored energy (m_LastBatteryCharge).

  • public int batteryCapacity { get; }
    Returns the last computed total battery capacity (m_LastBatteryCapacity).

Constructors

  • public ElectricityStatisticsSystem()
    Default constructor. The system is created by the ECS/serialization framework; initialization of queries and accumulators occurs in OnCreate.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the system's update interval. Implementation returns 128 — the system updates once every 128 ticks.

  • public override int GetUpdateOffset(SystemUpdatePhase phase)
    Returns the system's update offset. Implementation returns 127 to offset the update schedule.

  • [Preserve] protected override void OnCreate()
    Initializes the system: creates entity queries for producers, consumers and batteries and allocates the NativePerThreadSumInt accumulators (with Allocator.Persistent). This method is annotated [Preserve] to survive code stripping.

  • [Preserve] protected override void OnDestroy()
    Disposes the NativePerThreadSumInt accumulators and calls base.OnDestroy to clean up resources.

  • public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter
    Writes the last cached integer statistics (production, consumption, fulfilled consumption, battery charge, battery capacity) to the provided writer for save games.

  • public void Deserialize<TReader>(TReader reader) where TReader : IReader
    Reads saved statistics back from a reader. Handles multiple save-version cases: newer versions include battery stats; older version branches are also handled to preserve compatibility.

  • public void SetDefaults(Context context)
    Resets cached statistics to zero. Called to initialize defaults for a new save/context.

  • [Preserve] protected override void OnUpdate()
    Main work: transfers current accumulators into the cached m_Last* fields, resets accumulators to zero, and schedules three Burst-compiled IJobChunk jobs (CountElectricityProductionJob, CountElectricityConsumptionJob, CountBatteryCapacityJob) to populate accumulators in parallel. Jobs are scheduled only if their corresponding entity queries are non-empty, and dependencies are combined into base.Dependency.

  • protected override void OnCreateForCompiler()
    Internal helper used by generated/compiled code to assign component type handles via __TypeHandle.__AssignHandles and to assign queries.

  • private void __AssignQueries(ref SystemState state)
    Compiler-generated helper (no-op in this class except creating/disposing a temporary EntityQueryBuilder). Kept for compatibility with generated initialization flow.

Other internal types/methods: - CountElectricityProductionJob (Burst-compiled, IJobChunk) — counts ElectricityProducer.m_Capacity into m_Production concurrent accumulator. - CountElectricityConsumptionJob (Burst-compiled, IJobChunk) — sums ElectricityConsumer.m_WantedConsumption into m_Consumption and m_FulfilledConsumption into m_FulfilledConsumption accumulator. - CountBatteryCapacityJob (Burst-compiled, IJobChunk) — sums Battery.storedEnergyHours into m_BatteryCharge and Battery.m_Capacity into m_BatteryCapacity. - TypeHandle.__AssignHandles — obtains ComponentTypeHandle instances from SystemState for each component type (read-only).

Usage Example

// Typical system initialization (as implemented in the system)
[Preserve]
protected override void OnCreate()
{
    base.OnCreate();
    m_ProducerGroup = GetEntityQuery(ComponentType.ReadOnly<ElectricityProducer>(), ComponentType.Exclude<Temp>(), ComponentType.Exclude<Deleted>());
    m_ConsumerGroup = GetEntityQuery(ComponentType.ReadOnly<ElectricityConsumer>(), ComponentType.Exclude<Temp>(), ComponentType.Exclude<Deleted>());
    m_BatteryGroup = GetEntityQuery(ComponentType.ReadOnly<Battery>(), ComponentType.Exclude<Temp>(), ComponentType.Exclude<Deleted>());
    m_Production = new NativePerThreadSumInt(Allocator.Persistent);
    m_Consumption = new NativePerThreadSumInt(Allocator.Persistent);
    m_FulfilledConsumption = new NativePerThreadSumInt(Allocator.Persistent);
    m_BatteryCharge = new NativePerThreadSumInt(Allocator.Persistent);
    m_BatteryCapacity = new NativePerThreadSumInt(Allocator.Persistent);
}

// Reading the statistics from another part of the simulation:
// (actual retrieval method depends on your modding/runtime setup)
var stats = World.DefaultGameObjectInjectionWorld.GetExistingSystemManaged<ElectricityStatisticsSystem>();
if (stats != null)
{
    int prod = stats.production;
    int want = stats.consumption;
    int fulfilled = stats.fulfilledConsumption;
    int batteryStored = stats.batteryCharge;
    int batteryCap = stats.batteryCapacity;
    // use values for UI, logging, decisions, etc.
}

Notes: - The system uses NativePerThreadSumInt for lock-free parallel accumulation; values are folded to m_Last* once per system update. - Jobs are Burst-compiled for performance and operate via ComponentTypeHandle extracted from the SystemState. - Serialization supports older save versions for backward compatibility; battery stats are only deserialized if the save version includes them.