Skip to content

Game.Simulation.ResourceBuyerSystem

Assembly: Game
Namespace: Game.Simulation

Type: class

Base: GameSystemBase

Summary:
ResourceBuyerSystem manages buying behavior for citizens and companies. It detects ResourceBuyer and ResourceBought components, sets up pathfinding for buyers looking for sellers (shops, storage companies, outside connections), enqueues sales into an internal sales queue, and executes purchases in a separate job. The system coordinates with PathfindSetupSystem, ResourceSystem, TaxSystem, TimeSystem, CityConfigurationSystem and CitySystem. It runs on a 16-frame interval and uses Unity DOTS jobs (HandleBuyersJob and BuyJob) to perform most work in parallel and off the main thread.


Fields

  • private enum SaleFlags : byte
    Used to tag sales with metadata: CommercialSeller, ImportFromOC (outside connection), and Virtual (weightless/virtual goods).

  • private struct SalesEvent
    A plain struct representing a pending sale: m_Flags, m_Buyer, m_Seller, m_Resource, m_Amount, m_Distance. Instances are enqueued into m_SalesQueue by HandleBuyersJob and consumed by BuyJob.

  • private struct BuyJob : IJob
    Burst-compiled job that consumes SalesEvent entries from m_SalesQueue and applies the economic effects of a sale: price calculation (market/industrial), trade/transport costs, resource transfers, money transfers, updates to ServiceAvailable, trade cost learning, and special handling (e.g., vehicle creation when households buy vehicles). Interacts with many component/lookups and uses an EntityCommandBuffer for entity creation/changes.

  • private struct HandleBuyersJob : IJobChunk
    Burst-compiled job that iterates buyer archetype chunks. It:

  • Converts ResourceBought components into SalesEvent entries.
  • For ResourceBuyer entities, decides whether to enqueue a sale directly (e.g., seller is a property/OC/storage) or to start a pathfind to locate a seller (citizen/company shoppers).
  • Adds PathInformation and schedules pathfind requests through PathfindSetupSystem.
  • Potentially enqueues TripNeeded entries for agents to physically travel to buy goods (unless virtual). This job prepares the m_SalesQueue entries consumed by BuyJob.

  • private struct TypeHandle
    Container of ComponentTypeHandle / ComponentLookup / BufferLookup handles used by the jobs. Assigned in OnCreateForCompiler.

  • private const int UPDATE_INTERVAL = 16
    System update interval in frames.

  • private EntityQuery m_BuyerQuery
    Query for buyer entities that drive system updates.

  • private EntityQuery m_CarPrefabQuery
    Query used by PersonalCarSelectData to find car prefabs.

  • private EntityQuery m_EconomyParameterQuery
    Query to read economy parameters.

  • private EntityQuery m_ResidentPrefabQuery
    Query to collect resident prefabs for pedestrian pathfinding.

  • private EntityQuery m_PopulationQuery
    Query for population singleton entity.

  • private ComponentTypeSet m_PathfindTypes
    A set of components (PathInformation, PathElement) added/removed to entities when scheduling pathfinds.

  • private EndFrameBarrier m_EndFrameBarrier
    System barrier used to create command buffers for deferred entity changes.

  • private PathfindSetupSystem m_PathfindSetupSystem
    Reference to the pathfind setup system used to queue pathfinding targets.

  • private ResourceSystem m_ResourceSystem
    Reference to resource prefabs/data provider.

  • private TaxSystem m_TaxSystem
    Tax system reference (reader added as dependency during update).

  • private TimeSystem m_TimeSystem
    Time system reference used for time-of-day-based path options.

  • private CityConfigurationSystem m_CityConfigurationSystem
    City configuration used by PersonalCarSelectData.

  • private PersonalCarSelectData m_PersonalCarSelectData
    Helper to spawn personal cars when households buy vehicles.

  • private CitySystem m_CitySystem
    Reference to CitySystem, used to find the city entity.

  • private NativeQueue<SalesEvent> m_SalesQueue
    Persistent native queue used to pass SalesEvent items from HandleBuyersJob (producer) to BuyJob (consumer).

  • private TypeHandle __TypeHandle
    Instance of the TypeHandle container (internal).

Properties

  • This system exposes no public properties.

Constructors

  • public ResourceBuyerSystem()
    Default constructor. Systems in DOTS are typically created by the world/system manager; initialization occurs in OnCreate.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the update interval (16 frames). Used by the engine to schedule the system less frequently.

  • protected override void OnCreate()
    Initializes queries, system references, m_SalesQueue, Pathfind types, and other helpers. Creates PersonalCarSelectData and registers required queries so the system only updates when needed. Also sets up EndFrameBarrier, PathfindSetupSystem, ResourceSystem, etc.

  • protected override void OnDestroy()
    Disposes the persistent m_SalesQueue and calls base.OnDestroy.

  • protected override void OnStopRunning()
    Hook for when the system stops running; currently calls base implementation (reserved for cleanup logic).

  • protected override void OnUpdate()
    Main update method. If any buyers exist (m_BuyerQuery non-empty), it:

  • Prepares PersonalCarSelectData.
  • Schedules HandleBuyersJob (IJobChunk) as a parallel job to find sellers, enqueue SalesEvent entries, and schedule pathfinds/trips.
  • Adds required readers and dependencies for ResourceSystem, PathfindSetupSystem, TaxSystem, EndFrameBarrier.
  • Schedules BuyJob (IJob) to consume m_SalesQueue and carry out purchases, payments, create vehicles for households that bought cars, and update resources/money/trade costs.
  • Hooks job handles into EndFrameBarrier and relevant systems.

  • private void __AssignQueries(ref SystemState state)
    Internal helper used in OnCreateForCompiler; assigns entity queries. (Generated pattern for DOTS type safety.)

  • protected override void OnCreateForCompiler()
    DOTS/IL generation helper — assigns type handles for safety and compiler expectations.

  • Nested Job Methods:

  • BuyJob.Execute() — processes queued SalesEvent entries and applies economic/resource effects. Creates vehicles when households buy cars. Updates ServiceAvailable for commercial sellers and adjusts trade costs.
  • HandleBuyersJob.Execute(...) — processes chunks of buyers to convert ResourceBought components to direct SalesEvents, schedule pathfinds for ResourceBuyer entries, decide virtual buys, imports from outside connections, or trips for agents. Uses helper methods FindShopForCitizen and FindShopForCompany to build pathfind requests and enqueue them.

Usage Example

// Example: programmatically trigger a one-off sale by adding a ResourceBought component.
// Note: types like ResourceBought, Resource, and EntityManager are from the game's DOTS codebase.
var bought = new ResourceBought
{
    m_Payer = buyerEntity,      // entity that will pay / receive resources money change
    m_Seller = sellerEntity,    // entity that sells the resource
    m_Resource = Resource.Food, // resource enum
    m_Amount = 5,
    m_Distance = 12f
};
EntityManager.AddComponentData(targetEntity, bought);

// The ResourceBuyerSystem (on its next scheduled update) will pick up the ResourceBought
// component, convert it into a SalesEvent, and the BuyJob will execute the transaction.

Notes and Modding Tips: - The system uses DOTS jobs and low-level lookups; modifying its internals requires understanding of component lookups, buffer semantics, and command buffers. - To influence prices or transport costs, consider providing custom ResourceData / TradeCost buffers or intercepting ResourceSystem prefabs. - Creating ResourceBuyer or ResourceBought components on entities is the primary way to make entities request or perform purchases.