Game.Simulation.PostFacilityAISystem
Assembly:
Namespace: Game.Simulation
Type: class
Base: GameSystemBase
Summary:
PostFacilityAISystem is an ECS (DOTS) system that manages Post Facility (post office) behaviour: processing stored mail, sorting, creating/handling mail transfer requests, and spawning/managing post vans and delivery trucks. It runs as a scheduled system that uses Burst-compiled jobs (PostFacilityTickJob and PostFacilityActionJob) to perform per-chunk simulation work in parallel and then apply queued actions. The system interacts with vehicle selection helpers, city configuration and the simulation frame index, and uses an EndFrameBarrier command buffer to emit entity commands safely for the end of the frame.
Fields
-
public static readonly int kUpdatesPerDay
Constant (1024) used to scale or schedule update logic in relation to in-game time. -
private EntityQuery m_BuildingQuery
Query selecting PostFacility buildings to process each update. -
private EntityQuery m_PostVanPrefabQuery
Query used by PostVanSelectData to collect available post van prefabs. -
private EntityQuery m_PostConfigurationQuery
Query to fetch singleton PostConfigurationData (global post settings). -
private EntityArchetype m_MailTransferRequestArchetype
Archetype used when creating MailTransferRequest entities. -
private EntityArchetype m_PostVanRequestArchetype
Archetype used when creating PostVanRequest (service request) entities. -
private EntityArchetype m_HandleRequestArchetype
Archetype used to create HandleRequest entities (responses/handlers for requests). -
private ComponentTypeSet m_ParkedToMovingRemoveTypes
Component type set used to remove parked-only components when turning a parked vehicle to moving. -
private ComponentTypeSet m_ParkedToMovingCarAddTypes
Component type set used to add components to a vehicle when converting it from parked to moving (navigation, path, moving markers, etc). -
private VehicleCapacitySystem m_VehicleCapacitySystem
Reference to the VehicleCapacitySystem used for vehicle selection (delivery truck capacities, etc). -
private CityConfigurationSystem m_CityConfigurationSystem
Reference to the city configuration system (per-city settings). -
private SimulationSystem m_SimulationSystem
Reference to the simulation system (provides frame index and other simulation state). -
private EndFrameBarrier m_EndFrameBarrier
Command buffer barrier used to produce entity commands at end of frame. -
private PostVanSelectData m_PostVanSelectData
Helper that selects and creates post van prefabs; precomputes available vehicles. -
private TypeHandle __TypeHandle
Internal holder for all Entity/Component/Buffer type handles used by the Burst jobs (assigned in OnCreateForCompiler).
Properties
- None (this system exposes no public properties).
Constructors
public PostFacilityAISystem()
Default constructor (preserved). The real initialization happens in OnCreate.
Methods
-
public override int GetUpdateInterval(SystemUpdatePhase phase)
Returns the update interval in ticks for the system. This system returns 256, controlling how often it runs relative to the update scheduler. -
public override int GetUpdateOffset(SystemUpdatePhase phase)
Returns the update offset for scheduling; this system returns 176. Together with GetUpdateInterval this determines which simulation frames the system runs on. -
[Preserve] protected override void OnCreate()
Initializes queries, archetypes, component type sets and references to other systems. Registers the system to require the building and post configuration queries for updates. It also creates post-van selection helper data and asserts expected state. Key setup performed: - Acquire VehicleCapacitySystem, CityConfigurationSystem, SimulationSystem, EndFrameBarrier.
- Create entity queries (buildings, post van prefabs, post configuration).
- Create archetypes for mail/post-van requests and handle requests.
- Setup ComponentTypeSet arrays for parked->moving conversion.
-
Calls RequireForUpdate to ensure the system only runs when relevant data exists.
-
[Preserve] protected override void OnUpdate()
Main scheduling method. Prepares PostVanSelectData, creates a NativeQueueto collect actions for post vans (enable/disable). Builds and schedules: - PostFacilityTickJob (IJobChunk, Burst compiled) — iterates over PostFacility building chunks, computes mail processing, sorting, request generation, vehicle spawning decisions. Writes entity commands to EndFrameBarrier's command buffer (parallel writer) and enqueues PostFacilityAction entries to the action queue when toggling post van disabled state or when converting parked vehicles to moving.
- PostFacilityActionJob (IJob) — consumes the NativeQueue and applies PostVan state toggles (sets/clears Disabled flag on PostVan components) via ComponentLookup.
-
Ensures the action queue is disposed after job completion, posts PostVanSelectData updates, and adds job handle to EndFrameBarrier for producer tracking.
-
private void __AssignQueries(ref SystemState state)
Internal compiler helper used to assign queries in compiled builds (kept for compiler compatibility). -
protected override void OnCreateForCompiler()
Compiler helper: calls __AssignQueries and assigns __TypeHandle handles (Get*TypeHandle/GetBufferLookup/GetComponentLookup). -
Nested/Burst jobs (significant behavior implemented here):
-
private struct PostFacilityTickJob : IJobChunk
- Core per-chunk processing job. For each PostFacility entity it:
- Reads prefab data, upgrades and efficiencies, owned/guest vehicles, service dispatch buffers and resource buffers.
- Calculates capacities (post vans & trucks) as functions of building efficiency and prefab capacities.
- Tallies mail types (unsorted, local, outgoing) across owned vehicles, guest vehicles and parked vehicles, and calculates sorting throughput based on sorting rate and efficiency.
- Updates PostFacility flags and priorities (AcceptMailPriority, DeliverMailPriority, ProcessingFactor).
- Processes ServiceDispatch entries: handles PostVanRequest and MailTransferRequest by attempting to spawn vehicles via TrySpawnPostVan and TrySpawnDeliveryTruck.
- Calls RequestTargetIfNeeded to create periodic PostVan service requests when needed.
- Enqueues PostFacilityAction entries (via action queue) to toggle PostVan disabled states and writes entity commands to the command buffer when vehicles are created, moved or when requests are created/handled.
- Uses many ComponentLookups, BufferLookups, random seed and selection helpers to create vehicles and copy path data if path elements are present.
- Important helper methods inside the job:
- RequestTargetIfNeeded(...) — creates a PostVanRequest (ServiceRequest + PostVanRequest + RequestGroup) under certain frame timing conditions.
- TrySpawnPostVan(...) — attempts to spawn or unpark a PostVan to satisfy a PostVanRequest: handles parked vehicle conversion, prefab selection, owner assignment, setting PostVan component flags, target and path copying, and creating HandleRequest entity pointing to spawned vehicle.
- TrySpawnDeliveryTruck(...) — attempts to create a delivery truck for a MailTransferRequest: computes required loaded/unloaded amounts and capacities, selects an appropriate truck via DeliveryTruckSelectData, adjusts resources, sets owner & target, copies path info and creates HandleRequest.
- Burst compiled for parallel performance.
-
private struct PostFacilityActionJob : IJob
- Runs on the main thread (non-chunk) and consumes the PostFacilityAction queue. For each action it tries to read the Game.Vehicles.PostVan component and sets or clears the Disabled bit in m_State accordingly, writing the component back with ComponentLookup.
Usage Example
[Preserve]
protected override void OnCreate()
{
base.OnCreate();
// Acquire related systems used by this system
m_VehicleCapacitySystem = base.World.GetOrCreateSystemManaged<VehicleCapacitySystem>();
m_CityConfigurationSystem = base.World.GetOrCreateSystemManaged<CityConfigurationSystem>();
m_SimulationSystem = base.World.GetOrCreateSystemManaged<SimulationSystem>();
m_EndFrameBarrier = base.World.GetOrCreateSystemManaged<EndFrameBarrier>();
// Prepare the helper used to pick and create post vans
m_PostVanSelectData = new PostVanSelectData(this);
// Create queries and archetypes used at runtime
m_BuildingQuery = GetEntityQuery(
ComponentType.ReadOnly<Game.Buildings.PostFacility>(),
ComponentType.ReadOnly<Building>(),
ComponentType.ReadOnly<ServiceDispatch>(),
ComponentType.ReadOnly<PrefabRef>(),
ComponentType.Exclude<Temp>(),
ComponentType.Exclude<Deleted>());
m_PostVanPrefabQuery = GetEntityQuery(PostVanSelectData.GetEntityQueryDesc());
m_PostConfigurationQuery = GetEntityQuery(ComponentType.ReadOnly<PostConfigurationData>());
m_MailTransferRequestArchetype = base.EntityManager.CreateArchetype(
ComponentType.ReadWrite<ServiceRequest>(),
ComponentType.ReadWrite<MailTransferRequest>(),
ComponentType.ReadWrite<RequestGroup>());
m_PostVanRequestArchetype = base.EntityManager.CreateArchetype(
ComponentType.ReadWrite<ServiceRequest>(),
ComponentType.ReadWrite<PostVanRequest>(),
ComponentType.ReadWrite<RequestGroup>());
// Setup conversion type sets for parked vehicle -> moving vehicle transitions
m_ParkedToMovingRemoveTypes = new ComponentTypeSet(ComponentType.ReadWrite<ParkedCar>(), ComponentType.ReadWrite<Stopped>());
// ... and so on
RequireForUpdate(m_BuildingQuery);
RequireForUpdate(m_PostConfigurationQuery);
}
Notes / Implementation tips: - This system is heavily optimized for ECS and Burst: most heavy logic runs inside PostFacilityTickJob in parallel. When modding or debugging, prefer to instrument at higher-level systems or use safe main-thread helpers to avoid bypassing DOTS synchronization. - To change spawning rules or capacities, mod PostVanSelectData, DeliveryTruckSelectData, or alter prefab PostFacilityData/PostVanData/DeliveryTruckData values rather than editing the job without care (Burst/unsafe pointers and component lookups are used). - When creating additional behaviors that enqueue entity commands, use the system's EndFrameBarrier command buffer pattern (CreateCommandBuffer().AsParallelWriter()) to ensure correct scheduling and producer/consumer relationships.