Game.ProcessingCompanySystem
Assembly: Assembly-CSharp (Cities: Skylines 2)
Namespace: Game.Simulation
Type: class
Base: GameSystemBase, IDefaultSerializable, ISerializable, IPostDeserialize
Summary:
ProcessingCompanySystem is the ECS simulation system that updates processing companies (factories / offices) each company-update tick. It schedules a Burst-compiled IJobChunk (UpdateProcessingJob) over the ProcessingCompany entity group to:
- compute production per update from IndustrialProcessData and employees,
- consume input resources and produce output resources into company storage buffers,
- apply city modifiers, specialization bonuses and building efficiencies,
- update taxation bookkeeping (TaxPayer),
- enqueue produced resources into the ProductionSpecializationSystem queue and accumulate totals into an internal NativeArray
The system also handles serialization of the per-resource produced totals, a versioning PostDeserialize fix for older saves, and provides APIs to read produced totals safely from jobs or main thread.
Fields
-
public const int kMaxCommercialOutputResource = 5000
Used to limit how many units a commercial (service) building will accumulate before skipping production (prevents excessive virtual stock for offices/services). -
public const float kMaximumTransportUnitCost = 0.03f
Threshold used to decide whether it's cheap enough to export manufactured goods by truck; compared against computed transport unit cost. -
private SimulationSystem m_SimulationSystem
Reference to the SimulationSystem used to derive update frame index. -
private EndFrameBarrier m_EndFrameBarrier
Barrier used to obtain an EntityCommandBuffer.ParallelWriter to add components (e.g., ResourceExporter) safely from jobs. -
private ResourceSystem m_ResourceSystem
Used to access resource prefabs and register as a reader of prefab data. -
private TaxSystem m_TaxSystem
Used to read tax rates and register readers for tax-related data. -
private VehicleCapacitySystem m_VehicleCapacitySystem
Provides DeliveryTruckSelectData used to decide export behaviour. -
private ProductionSpecializationSystem m_ProductionSpecializationSystem
Receives produced resource entries via a queue to be used for city specialization calculations. -
private CitySystem m_CitySystem
Used to obtain city-wide buffers (city modifiers, specialization bonuses) and the city entity reference. -
private EntityQuery m_CompanyGroup
EntityQuery selecting processing companies (ProcessingCompany + required components) that this system updates. -
private NativeArray<long> m_ProducedResources
Persistent NativeArray storing aggregated produced resource counts per resource type. Serialized and exposed via GetProducedResourcesArray. -
private JobHandle m_ProducedResourcesDeps
Tracks dependencies of readers that read m_ProducedResources to combine job dependencies. -
private TypeHandle __TypeHandle
Compiler-generated struct collecting ComponentLookup/TypeHandle references used when scheduling jobs. -
private EntityQuery __query_1038562630_0
Compiler-generated query used to fetch EconomyParameterData singleton. -
private struct UpdateProcessingJob
(nested)
The IJobChunk implementation that does the per-chunk company processing. See Methods for details on the job's behavior. -
private struct TypeHandle
(nested)
Compiler-generated helper that assigns all required handles from SystemState.
Properties
- None (the system exposes functionality via methods rather than public properties)
Constructors
public ProcessingCompanySystem()
Default constructor. System initialization is mostly performed in OnCreate / OnCreateForCompiler.
Methods
-
public override int GetUpdateInterval(SystemUpdatePhase phase)
Returns the update interval (in frames) for this system based on EconomyUtils.kCompanyUpdatesPerDay. This drives how often processing companies are processed. -
protected override void OnCreate()
Initializes references to other systems, builds the m_CompanyGroup EntityQuery, requires EconomyParameterData for updates, and allocates the persistent m_ProducedResources NativeArray. Also calls RequireForUpdate for the entity group so the system only runs when relevant entities exist. -
public void PostDeserialize(Context context)
Versioning migration executed after deserialization. For saves older than Version.officeFix it reduces or removes stored output resources for certain offices that should not have material weight, ensuring old saves remain consistent with newer logic. -
protected override void OnDestroy()
Disposes the persistent m_ProducedResources NativeArray and performs base cleanup. -
protected override void OnUpdate()
Main scheduling function. It: - computes the current updateFrame index using SimulationUtils.GetUpdateFrame,
- sets up an UpdateProcessingJob with many read/write handles, resource prefabs, tax rates, economy parameters, random seed, queues and buffers,
- schedules the job in parallel over m_CompanyGroup while combining dependencies with m_ProducedResourcesDeps and other readers,
- registers produced-resources and queue writers with the corresponding systems, and
-
resets m_ProducedResourcesDeps for the next frame.
-
public NativeArray<long> GetProducedResourcesArray(out JobHandle dependencies)
Returns the internal m_ProducedResources array and outputs current base.Dependency job handle. Use this to read aggregated produced counts; callers must respect the returned dependencies (complete them or add them to their job dependencies). -
public void AddProducedResourcesReader(JobHandle handle)
Allows external code to register a job handle that reads m_ProducedResources. The system combines it into m_ProducedResourcesDeps to ensure proper scheduling and completion. -
public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter
Writes the length (as byte) and each long value of m_ProducedResources for save serialization. -
public void Deserialize<TReader>(TReader reader) where TReader : IReader
Reads the previously serialized produced resources array values and populates m_ProducedResources, zeroing any remaining entries if the serialized length is smaller than current resource count. -
public void SetDefaults(Context context)
Resets m_ProducedResources entries to zero. Called when initializing defaults for serialization contexts. -
private void __AssignQueries(ref SystemState state)
Compiler-generated function that builds internal queries needed (e.g., for EconomyParameterData). -
protected override void OnCreateForCompiler()
Compiler-time helper that calls __AssignQueries and assigns type handles into __TypeHandle. -
private struct UpdateProcessingJob.Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
Job entry point for chunk processing. For each chunk whose shared UpdateFrame matches the job's target frame, it iterates entities and: - reads prefab, property, company data, employees, buffers and other lookups,
- computes building efficiency, companyProductionPerDay, and scaled production count for this update,
- checks inputs (input1, input2) and storage limits, consumes inputs and produces outputs,
- clamps production based on storage, virtual storage limits and weight rules,
- updates TaxPayer bookkeeping (average tax rate and untaxed income) per output,
- queues produced resources into ProductionSpecializationSystem via a parallel queue and atomically adds to m_ProducedResources,
-
possibly issues a ResourceExporter component via the EndFrameBarrier command buffer if exports are economically justified.
-
private void UpdateEfficiencyFactors(IndustrialProcessData process, bool isCommercial, DynamicBuffer<Efficiency> efficiencies, DynamicBuffer<CityModifier> cityModifiers, DynamicBuffer<SpecializationBonus> specializations)
Helper inside the job that applies city-wide modifiers and specialization bonuses to the building's efficiency buffer. It handles office vs industrial modifiers, fish input modifiers, software/electronics modifiers, and specialization bonus application. -
private bool IsOffice(IndustrialProcessData process)
Returns true when the process output is not a material (i.e., considered an office/service output). -
private Resource GetRandomUpkeepResource(CompanyData companyData, Resource outputResource)
Returns a pseudo-random upkeep resource chosen from a small set (Software, Telecom, Financial, Machinery/Furniture/Paper) — used by older logic or upkeep decisions inside the job. -
private unsafe void AddProducedResource(Resource resource, int amount)
Atomically adds produced amount to the correct index in the native m_ProducedResources array (using Interlocked.Add on the underlying pointer) and enqueues a ProducedResource entry into the production queue. -
Compiler-generated/private helpers and TypeHandle methods used to assign component handles (see TypeHandle struct in source).
Usage Example
// Obtain a reference to the ProcessingCompanySystem from the world (example context)
var processingSystem = World.DefaultGameObjectInjectionWorld.GetExistingSystemManaged<Game.Simulation.ProcessingCompanySystem>();
// If you want to read the produced resources safely from the main thread:
JobHandle dependencies;
NativeArray<long> produced = processingSystem.GetProducedResourcesArray(out dependencies);
// Ensure the system's dependent jobs are finished before reading on main thread:
dependencies.Complete();
// Now read totals per resource index:
long steelProduced = produced[EconomyUtils.GetResourceIndex(Resource.Steel)];
// If you schedule a job that reads the produced array, register its handle so the system knows about the reader:
JobHandle myReaderJob = /* schedule a job that reads `produced` */;
processingSystem.AddProducedResourcesReader(myReaderJob);
Notes: - When reading m_ProducedResources from a job, pass the job handle into AddProducedResourcesReader to be combined with the system's tracking so proper dependencies are enforced. - Most of the heavy work is done inside UpdateProcessingJob which is Burst-compiled and scheduled in parallel; modifying production logic is best done by adjusting IndustrialProcessData, building efficiencies, or by hooking into the ProductionSpecializationSystem / resource prefabs rather than directly changing system internals.