Game.ZoneSpawnSystem
Assembly:
Namespace: Game.Simulation
Type: class
Base: GameSystemBase
Summary:
ZoneSpawnSystem is the ECS system responsible for evaluating vacant lots and spawning buildings (residential, commercial, industrial/storage) during simulation updates. It runs two main Burst-compiled jobs: EvaluateSpawnAreas (collects best candidate lots per update) and SpawnBuildingJob (creates Building/Area/Net creation entities via an EndFrameBarrier command buffer). The system reads demand, resource availability, land value, pollution and lot geometry to pick and score appropriate prefabs. It schedules jobs safely with various system readers/writers and uses the zone search tree and prefab data to produce CreationDefinition/ObjectDefinition entries that are later resolved into in-game objects.
Fields
-
private ZoneSystem m_ZoneSystem
Handles zone prefabs and zone-related data access used to evaluate lots. -
private ResidentialDemandSystem m_ResidentialDemandSystem
Provides residential building demand values. -
private CommercialDemandSystem m_CommercialDemandSystem
Provides commercial building demand values. -
private IndustrialDemandSystem m_IndustrialDemandSystem
Provides industrial and storage building demand values. -
private GroundPollutionSystem m_PollutionSystem
Provides pollution map used when scoring lot suitability. -
private TerrainSystem m_TerrainSystem
Provides terrain height data used when placing objects. -
private Game.Zones.SearchSystem m_SearchSystem
Zone search tree used for spatial queries (e.g., checking heights in an area). -
private ResourceSystem m_ResourceSystem
Provides resource prefabs and resource-related data used for scoring. -
private CityConfigurationSystem m_CityConfigurationSystem
Provides city-wide configuration values (e.g., left-hand traffic flag). -
private EndFrameBarrier m_EndFrameBarrier
Barrier used to create command buffers for deferred entity creation at end of frame. -
private EntityQuery m_LotQuery
Query selecting blocks/owners/curve positions with VacantLot buffers (input to evaluation job). -
private EntityQuery m_BuildingQuery
Query selecting spawnable building prefabs and their group metadata. -
private EntityQuery m_ProcessQuery
Query selecting industrial process data used for manufacturing/storage evaluation. -
private EntityQuery m_BuildingConfigurationQuery
Query to get building configuration singleton used when spawning placeholder areas. -
private EntityArchetype m_DefinitionArchetype
Archetype used to create creation/definition entities (CreationDefinition/ObjectDefinition/Updated/Deleted). -
private TypeHandle __TypeHandle
Compiled container of Component/Buffer/SharedComponent handles for efficient job scheduling. -
private EntityQuery __query_1944910157_0
Internal query used to fetch ZonePreferenceData singleton. -
public bool debugFastSpawn { get; set; }
Public flag to force faster/always-on spawning behavior useful for debugging or tests.
Properties
public bool debugFastSpawn { get; set; }
When true the system relaxes demand checks to allow faster/forced spawning for debugging. Defaults to false.
Constructors
public ZoneSpawnSystem()
Default constructor. The system sets up queries and required resources in OnCreate.
Methods
-
public override int GetUpdateInterval(SystemUpdatePhase phase)
Returns 16 — determines the update interval of the system (runs every N ticks/frames as configured). -
public override int GetUpdateOffset(SystemUpdatePhase phase)
Returns 13 — determines the update offset used by the scheduler. -
protected override void OnCreate()
Initializes subsystem references (zone, demand systems, pollution, terrain, resource system, search system, city configuration, end frame barrier), sets up EntityQueries (lots, building prefabs, processes, configuration), and prepares the Definition archetype. Requires the lot and building queries so the system only updates when relevant data exist. -
protected override void OnUpdate()
Main update function. Steps: - Reads demand booleans (residential/commercial/industrial/storage) and debug flag.
- Allocates temporary NativeQueues for candidate SpawnLocations (residential/commercial/industrial).
- Constructs and schedules EvaluateSpawnAreas (IJobChunk, Burst) to scan lots and enqueue the best candidate lot for each area type based on scoring (demand, availability, land value, pollution, prefab properties, etc.).
- Constructs and schedules SpawnBuildingJob (IJobParallelFor, Burst) which dequeues chosen locations and emits CreationDefinition/ObjectDefinition/OwnerDefinition entities (and sub-areas/sub-nets) via the EndFrameBarrier command buffer.
- Adds job dependencies/readers to required systems (Resource, Pollution, Demand systems, Zone system, Terrain/Zone search trees).
-
Disposes temporary queues after producers are finished and attaches job handle to the EndFrameBarrier so creation commands are processed at the correct time.
-
protected override void OnCreateForCompiler()
Internal setup used by generated code to assign queries and type handles for compiled job use. -
private void __AssignQueries(ref SystemState state)
Internal helper used during system creation to build required queries (exposes ZonePreferenceData query etc.). -
(Nested)
struct SpawnLocation
Lightweight container used to represent a candidate lot + building prefab + scoring priority. Fields include entity, building prefab Entity, lot int4 area, priority score, ZoneType, AreaType and LotFlags. -
(Nested)
BurstCompile struct EvaluateSpawnAreas : IJobChunk
Chunk job that iterates lot entities (VacantLot buffers) and determines the best lot for residential/commercial/industrial spawns within that chunk. It: - Uses building prefab archetype chunks to choose matching prefabs for candidate lots.
- Scores candidates using ZoneEvaluationUtils and other heuristics (lot fit, land value, pollution, demand, resource availability, processes).
-
Enqueues top candidates into NativeQueue
.ParallelWriter for each area type. -
(Nested)
BurstCompile struct SpawnBuildingJob : IJobParallelFor
Parallel-for job that pops the highest-priority SpawnLocation from each queue and creates CreationDefinition/ObjectDefinition entities using an EntityCommandBuffer. It: - Calculates final placement, samples terrain height and clamps to max height.
- Creates CreationDefinition/ObjectDefinition and OwnerDefinition entities.
- Spawns sub-areas and sub-nets (creating CreationDefinition entries for sub-prefabs) and handles placeholder selection for spawnable objects.
-
Uses a NativeQuadTree iterator to determine max allowable height inside a bounding box.
-
private int EvaluateDemandAndAvailability(BuildingPropertyData buildingPropertyData, Game.Zones.AreaType areaType, ZoneDensity zoneDensity, bool storage = false)
(inside EvaluateSpawnAreas)
Helper that computes an integer demand score for a given building property depending on area type: - Residential: picks value from m_ResidentialDemands based on zone density.
- Commercial: sums building demand per resource allowed to be sold.
-
Industrial: sums industrial or storage demands per resource depending on the storage flag.
-
Other internal helpers (CalculateCurvePos, TryAddLot, SelectBuilding, GetMaxHeight, CreateSubNet, Spawn overloads)
Various helpers implementing scoring, prefab selection, area/net spawning and spatial checks.
Usage Example
// Enable fast spawning for debug/testing via the system instance:
var zoneSpawn = World.DefaultGameObjectInjectionWorld.GetOrCreateSystemManaged<Game.Simulation.ZoneSpawnSystem>();
zoneSpawn.debugFastSpawn = true;
// The system will run on its schedule and spawn buildings based on the configured world state.
// For unit tests you may call Update() on the World or advance the simulation until the system executes.
Notes and tips: - The system is multi-threaded and heavily relies on Burst-compiled jobs — do not attempt to access most of its internals from the main thread without respecting job dependencies/readers. - CreationDefinition/ObjectDefinition entities are produced via an EndFrameBarrier command buffer; consuming systems should read those entities after the barrier has played back. - To influence spawning behavior from a mod, adjust demand systems, resource availabilities, zone/zone-property prefabs, or provide custom building prefabs with appropriate SpawnableBuildingData/BuildingPropertyData and ObjectGeometryData.