Skip to content

Game.Simulation.CommuterSpawnSystem

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

Type: class

Base: GameSystemBase

Summary:
CommuterSpawnSystem is a simulation system responsible for spawning "commuter" household entities (households that originate from outside connections and travel into the city to work) when the internal workforce is insufficient relative to available workplaces and demand parameters. It runs on a coarse update interval (every 16 simulation frames) and schedules a Burst-compiled IJob (SpawnCommuterHouseholdJob) that selects outside connections and household prefabs, then creates household entities via an EndFrameBarrier EntityCommandBuffer. The system reads counts from other systems (workplaces and household data) and uses DemandParameterData to control spawn behavior (including ratios and spawn parameters).


Fields

  • private EntityQuery m_HouseholdPrefabQuery
    Used to query all household prefab entities (components: ArchetypeData, HouseholdData). The query is required for the system to run; prefab lists are read and passed to the job.

  • private EntityQuery m_OutsideConnectionQuery
    Queries outside connections that can be used as origins for commuter households. Excludes special outside connection types (electricity, water pipe) and excludes Building, Temp, Deleted.

  • private EntityQuery m_CommuterQuery
    Query for existing CommuterHousehold components (used to count current commuters).

  • private EntityQuery m_WorkerQuery
    Query for Worker components (used to count current workers).

  • private EntityQuery m_DemandParameterQuery
    Query to obtain DemandParameterData singleton that contains parameters controlling commuter spawn behavior.

  • private EndFrameBarrier m_EndFrameBarrier
    Reference to the EndFrameBarrier system used to create command buffers for entity creation that will be played back at the end of the frame.

  • private SimulationSystem m_SimulationSystem
    Reference to the central simulation system (used for frameIndex and other simulation timing data).

  • private CountWorkplacesSystem m_CountWorkplacesSystem
    Reference to the system that counts available workplaces; used to determine how many commuter households to spawn.

  • private CountHouseholdDataSystem m_CountHouseholdDataSystem
    Reference to the system that provides counts of employable household members and related data.

  • private TypeHandle __TypeHandle
    Internal struct that caches ComponentLookup handles for read-only access to components used by the job (OutsideConnectionData and PrefabRef). Populated during OnCreateForCompiler.

  • private struct SpawnCommuterHouseholdJob (nested)
    Burst-compiled job that performs the actual selection and creation of commuter household entities. It reads prefab lists, archetypes, household prefabs, and outside connection entities, and uses Random + DemandParameterData to decide how many and which outside connections to spawn from. Entities are created through an EntityCommandBuffer (m_CommandBuffer) and are assigned PrefabRef, Household (with HouseholdFlags.Commuter), CurrentBuilding, and CommuterHousehold components.

  • private struct TypeHandle (nested)
    Contains ComponentLookup fields and an __AssignHandles method that initializes those lookups from a SystemState. Used to safely pass lookups into the job or to retrieve them inside OnCreateForCompiler.

Properties

  • None (the system does not expose public properties).

Constructors

  • public CommuterSpawnSystem()
    Default constructor. The system uses OnCreate to initialize queries and get required system references; no special construction logic beyond the base constructor.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the interval in simulation frames between updates for this system. This system returns 16, so it runs every 16 frames (coarse cadence to reduce overhead).

  • [Preserve] protected override void OnCreate()
    Initializes the system:

  • Retrieves EndFrameBarrier, SimulationSystem, CountWorkplacesSystem, CountHouseholdDataSystem from the world.
  • Creates the EntityQueries used by the system:
    • m_HouseholdPrefabQuery: reads ArchetypeData and HouseholdData.
    • m_OutsideConnectionQuery: reads Game.Objects.OutsideConnection and excludes certain types and tags.
    • m_CommuterQuery: reads CommuterHousehold (to count commuters).
    • m_WorkerQuery: reads Worker (to count workers).
    • m_DemandParameterQuery: reads DemandParameterData singleton.
  • Calls RequireForUpdate for the queries that must exist for this system to run.

  • [Preserve] protected override void OnUpdate()
    Main update logic executed every update interval:

  • Reads DemandParameterData singleton and counts of commuter and worker entities.
  • If the number of commuters is sufficiently low relative to workers (controlled by m_CommuterWorkerRatioLimit), the system schedules SpawnCommuterHouseholdJob:
    • Gathers asynchronous lists from queries: prefab entities, archetypes, household prefabs, outside connection entities (each produced as NativeList via To*ListAsync).
    • Retrieves employable counts and free workplaces from the corresponding counting systems.
    • Prepares ComponentLookup handles for OutsideConnectionData and PrefabRef using InternalCompilerInterface helper and the cached __TypeHandle.
    • Builds job data (including RandomSeed.Next() and frameIndex) and schedules the job with combined dependencies.
    • Adds the job handle to the m_EndFrameBarrier so the command buffer is played back only after the job completes.

SpawnCommuterHouseholdJob.Execute: - Computes the number of commuters to spawn based on free workplaces, employables and the demand parameter spawn factor. - For each spawn, picks a random allowed outside connection via BuildingUtils.GetRandomOutsideConnectionByParameters, picks a random household prefab, creates an entity with the prefab archetype via EntityCommandBuffer, and sets components: - PrefabRef (m_Prefab = chosen prefab) - Household (HouseholdFlags.Commuter) - CurrentBuilding (m_CurrentBuilding = chosen outside connection) - CommuterHousehold (m_OriginalFrom = chosen outside connection) - All entity creation uses the provided EntityCommandBuffer.

  • [MethodImpl(MethodImplOptions.AggressiveInlining)] private void __AssignQueries(ref SystemState state)
    Compiler helper used during generated OnCreateForCompiler; currently a no-op other than constructing and disposing an EntityQueryBuilder. Part of the compiler generated plumbing.

  • protected override void OnCreateForCompiler()
    Called by generated code path: assigns queries and component lookup handles via __AssignQueries and __TypeHandle.__AssignHandles to ensure lookups are ready for the job scheduling path.

Usage Example

// This demonstrates the essential behavior performed in CommuterSpawnSystem.OnUpdate:
// scheduling the SpawnCommuterHouseholdJob to create commuter households when needed.

[Preserve]
protected override void OnUpdate()
{
    // Get demand parameters and counts (as the system does)
    DemandParameterData demand = m_DemandParameterQuery.GetSingleton<DemandParameterData>();
    int commuterCount = m_CommuterQuery.CalculateEntityCount();
    int workerCount = m_WorkerQuery.CalculateEntityCount();

    // If too few commuters relative to workers, schedule the Burst job
    if (commuterCount * demand.m_CommuterWorkerRatioLimit < workerCount)
    {
        // Prepare async lists from queries and other inputs (prefabs, outside connections, counts)
        // Prepare component lookups via __TypeHandle and InternalCompilerInterface
        // Build SpawnCommuterHouseholdJob with RandomSeed.Next(), frame index and an EndFrameBarrier command buffer
        // Schedule the job and add the resulting JobHandle to the EndFrameBarrier so entity creations happen safely
    }
}

Notes / Tips for Modders: - The system expects household prefabs to have ArchetypeData and HouseholdData present. Adding or removing prefab entities will affect what can be spawned. - The SpawnCommuterHouseholdJob uses a Burst-compiled IJob and asynchronous query-to-list operations; ensure proper memory allocator usage and respect the job dependencies if integrating additional asynchronous reads. - To influence spawning behavior, modify the DemandParameterData singleton or the counted workplace/household systems — this system reacts to those inputs rather than exposing direct spawn configuration. - The system creates commuter households using the EndFrameBarrier EntityCommandBuffer: entity creation and component setting are deferred and will be applied at end of frame.