Skip to content

Game.ExtractorAISystem

Assembly: Assembly-CSharp
Namespace: Game.Simulation

Type: class

Base: GameSystemBase

Summary:
{{ ExtractorAISystem is a simulation system that controls the AI behaviour of extractor-type companies (processing/extractor companies) in the game. It periodically schedules a parallel IJobChunk (ExtractorAITickJob) that iterates over company entities, reads prefab/process/storage data and per-building buffers (employees, resources, upgrades, sub-areas, geometry, lots) and adjusts WorkProvider.m_MaxWorkers for extractors depending on area, available resources and configured limits. The system also enables PropertySeeker for companies that don't have a PropertyRenter and are not already seekers. It integrates with the simulation update-frame scheme, the EndFrameBarrier command buffer, and the ResourceSystem for reading prefab data. Key constants: kUpdatesPerDay (32) and kMinimumEmployee (5). }}


Fields

  • public static readonly int kUpdatesPerDay
    {{ kUpdatesPerDay = 32. Used to compute the update-frame index for scheduling job ticks. The system uses SimulationUtils.GetUpdateFrame with this value to run logic on a subset of frames per day. }}

  • public static readonly int kMinimumEmployee
    {{ kMinimumEmployee = 5. Lower threshold for WorkProvider.m_MaxWorkers; the system won't reduce max workers below this value. }}

  • private EntityQuery m_EconomyParameterQuery
    {{ Query used to ensure EconomyParameterData exists so the system only updates when economy parameters are present. }}

  • private EntityQuery m_ExtractorParameterQuery
    {{ Query used to ensure ExtractorParameterData exists so the system only updates when extractor parameters are present. }}

  • private EndFrameBarrier m_EndFrameBarrier
    {{ EndFrameBarrier system used to obtain an EntityCommandBuffer.ParallelWriter for deferring structural changes (e.g., enabling PropertySeeker) produced by the scheduled job. }}

  • private SimulationSystem m_SimulationSystem
    {{ Reference to the SimulationSystem used to get the global frame index for determining the update frame. }}

  • private ResourceSystem m_ResourceSystem
    {{ Reference to the ResourceSystem. The system informs ResourceSystem about jobs that read prefabs via AddPrefabsReader() so resources/prefab reading synchronization is handled. }}

  • private Random m_RandomSeed
    {{ Instance of Unity.Mathematics.Random initialized on OnCreate. Not heavily used in the current code, but seeded to a fixed value (346745637u). }}

  • private EntityQuery m_CompanyQuery
    {{ Primary query selecting processing/extractor companies: includes ProcessingCompany and ExtractorCompany tags and requires WorkProvider, UpdateFrame, PrefabRef, Resources, while excluding ServiceAvailable and Created. This is the query used to schedule the ExtractorAITickJob. }}

  • private TypeHandle __TypeHandle
    {{ Internal helper struct generated by compiler to cache component/lookup/buffer type handles used by jobs. Populated in OnCreateForCompiler. }}

Properties

  • None
    {{ This system does not expose public properties. Internal state is managed by fields and methods. }}

Constructors

  • public ExtractorAISystem()
    {{ Default parameterless constructor. The system initialization happens in OnCreate. Marked with [Preserve] to avoid stripping. }}

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    {{ Returns the system update interval in ticks. Implementation returns 262144 / (kUpdatesPerDay * 16) so the system runs at a frequency derived from the configured updates per day. This interacts with the game's system scheduling. }}

  • [Preserve] protected override void OnCreate()
    {{ Initializes the system: seeds m_RandomSeed, gets references to EndFrameBarrier, SimulationSystem and ResourceSystem, creates entity queries (economy/ extractor params and company query), and calls RequireForUpdate for required queries so the system runs only when relevant data exists. Also the company query requires WorkProvider and Resources, and excludes ServiceAvailable/Created. }}

  • public static float GetArea(Entity mainBuilding, ref BufferLookup<Game.Areas.SubArea> subAreas, ref BufferLookup<InstalledUpgrade> installedUpgrades, ref ComponentLookup<Game.Areas.Lot> lots, ref ComponentLookup<Geometry> geometries)
    {{ Computes the total usable area (in 64m^2 units) for a main building including installed upgrades that contribute sub-areas. Uses sub-area buffers and geometry surface area divided by 64. This value is used to determine suitable worker count (via CompanyUtils.GetExtractorFittingWorkers). }}

  • private static float GetArea(DynamicBuffer<Game.Areas.SubArea> subAreas, ref ComponentLookup<Game.Areas.Lot> lots, ref ComponentLookup<Geometry> geometries)
    {{ Helper that sums the surface area for a DynamicBuffer of SubArea entries, converting raw surface area to the normalized area (m_SurfaceArea / 64f) when the lot exists. }}

  • public static float GetResourcesInArea(Entity mainBuilding, ref BufferLookup<Game.Areas.SubArea> subAreas, ref BufferLookup<InstalledUpgrade> installedUpgrades, ref ComponentLookup<Extractor> extractors)
    {{ Calculates total extractable resource amount still available in all extractors within the building's sub-areas (including upgrades). This sums max(0, m_ResourceAmount - m_ExtractedAmount) from extractor components in each area. }}

  • private static float GetResourcesInArea(DynamicBuffer<Game.Areas.SubArea> subAreas, ref ComponentLookup<Extractor> extractors)
    {{ Helper overload that processes a DynamicBuffer of SubArea entries and sums remaining resource amounts from extractors present in those areas. }}

  • [Preserve] protected override void OnStopRunning()
    {{ Hook invoked when system stops running. In this implementation it just calls base.OnStopRunning() and contains no custom teardown logic. }}

  • [Preserve] protected override void OnUpdate()
    {{ Main update method: computes the updateFrame index using SimulationUtils.GetUpdateFrame with kUpdatesPerDay and a subdivision (16). Prepares and schedules the ExtractorAITickJob with all required type handles and component lookups/buffer lookups, providing an EntityCommandBuffer.ParallelWriter from EndFrameBarrier. The job is scheduled in parallel over m_CompanyQuery; returned dependency is recorded and added to EndFrameBarrier and ResourceSystem for synchronization. }}

  • [MethodImpl(MethodImplOptions.AggressiveInlining)] private void __AssignQueries(ref SystemState state)
    {{ Compiler helper stub used to initialize queries when generating code. In this build it only constructs and disposes an EntityQueryBuilder. Not intended for manual use. }}

  • protected override void OnCreateForCompiler()
    {{ Compiler-time initialization used by generated code: calls __AssignQueries and __TypeHandle.__AssignHandles to prepare type handles. }}

  • [Preserve] public override void Dispose() (inherited)
    {{ No explicit override in this file, but system lifecycle is managed via OnStopRunning/OnCreate. }}

  • Nested: ExtractorAITickJob (IJobChunk)
    {{ A Burst-compiled IJobChunk that performs the per-chunk logic for extractor companies. Key responsibilities:

  • Filters chunks by UpdateFrame shared component index to run on the correct frame index.
  • Reads entity, Resources buffer, Employee buffer, PrefabRef, IndustrialProcessData, StorageLimitData, Attached/InstalledUpgrade/SubArea/Lot/Geometry lookups.
  • For entities with PropertyRenter: computes combined storage limit (including upgrades), computes building area and extractor-fitting workers, compares current worker count (WorkProvider.m_MaxWorkers) and employee buffer length, and increments/decrements m_MaxWorkers accordingly (respecting kMinimumEmployee).
  • For entities without PropertyRenter and with PropertySeeker disabled: enables PropertySeeker via command buffer.
  • Uses a parallel command buffer writer (m_CommandBuffer) for structural/enable changes.
  • Scheduled in parallel via JobChunkExtensions.ScheduleParallel in OnUpdate. The job implements Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask). }}

  • Nested: TypeHandle struct
    {{ Compiler-generated struct that caches EntityTypeHandle, BufferTypeHandles, ComponentTypeHandles, SharedComponentTypeHandle and ComponentLookup/BufferLookup references. Provides __AssignHandles(ref SystemState) to initialize handles for use in jobs. }}

Usage Example

// Example: read total remaining resources in the area of a building (can be called from other systems or utility code)
Entity mainBuilding = /* some building entity */;
float resources = ExtractorAISystem.GetResourcesInArea(
    mainBuilding,
    ref someBufferLookup_SubArea,        // BufferLookup<Game.Areas.SubArea>
    ref someBufferLookup_InstalledUpgrades, // BufferLookup<InstalledUpgrade>
    ref someComponentLookup_Extractor    // ComponentLookup<Extractor>
);

{{ Notes: - The system is designed to run in a Burst-compiled job for performance and uses Unity.Entities low-level APIs (IJobChunk, BufferLookup, ComponentLookup, SharedComponentTypeHandle). - The logic balances workforce limits according to physical area (sub-areas & upgrades) and available resources inside extractor areas, and ensures companies that require properties become PropertySeekers. - When modding, be careful interacting with internal component types and job scheduling; changes to expected component layout or tags (e.g., WorkProvider, PropertyRenter, PropertySeeker) will affect behavior. }}