Skip to content

Game.CrimeCheckSystem

Assembly: Assembly-CSharp (game runtime)
Namespace: Game.Simulation

Type: class

Base: GameSystemBase

Summary:
CrimeCheckSystem is a simulation system that periodically evaluates citizens to potentially spawn crime events. It iterates over eligible Citizen entities (excluding children, elderly, students, workers, temporarily flagged, deleted or those with health problems) and, using configurable CrimeData prefab entries and city-level modifiers/coverage, determines whether to create a crime event prefab targeted at a citizen. The system updates on a coarse interval (kUpdatesPerDay) and schedules a parallel job (CrimeCheckJob) to perform the per-citizen checks and create events via an EndFrameBarrier command buffer. It also reports crime counts to the city statistics queue and emits trigger actions for other systems.


Fields

  • public readonly int kUpdatesPerDay
    Controls how often (relative to the simulation frame cadence) crime checks are distributed. The system uses this to compute the update frame index for scheduling; default value in this class is 1 (meaning a daily cadence factor used by GetUpdateInterval).

  • public bool debugFullCrimeMode
    Public flag that, when true, effectively bypasses probabilistic checks so crimes occur more deterministically for testing/debugging. Modders can toggle this to test crime spawning without random gating.

  • private EndFrameBarrier m_EndFrameBarrier
    Barrier system used to create entities and set components safely from a job (the job uses an EntityCommandBuffer.ParallelWriter produced by this barrier).

  • private SimulationSystem m_SimulationSystem
    Reference to the global SimulationSystem (used to obtain the current frameIndex and compute update frames).

  • private CitySystem m_CitySystem
    Reference to the CitySystem used to obtain the current city Entity and related city-level data.

  • private CityStatisticsSystem m_CityStatisticsSystem
    Reference to the statistics system; used to acquire a statistics event queue writer to enqueue crime count updates.

  • private EntityQuery m_CitizenQuery
    Query selecting citizens to process. Built to include Citizen and UpdateFrame, and to exclude HealthProblem, Worker, Student, Deleted, Temp.

  • private EntityQuery m_EventQuery
    Query that selects crime event prefabs (CrimeData) and excludes Locked components (so only active event prefabs are considered).

  • private EntityQuery m_PoliceConfigurationQuery
    Query that retrieves PoliceConfigurationData singleton used for scaling crime probabilities, welfare crime recurrence factor, etc.

  • private TriggerSystem m_TriggerSystem
    Reference to the TriggerSystem used to enqueue trigger actions (TriggerAction) when crimes are created.

  • private TypeHandle __TypeHandle
    Internal struct that caches various ComponentTypeHandle/Lookup objects used by the job and by the system's compiled update. Assigned in OnCreateForCompiler / __AssignHandles.

Properties

  • None declared on this type (no public C# properties; uses public fields and queries).

Constructors

  • public CrimeCheckSystem()
    Default constructor. The system relies on OnCreate to initialize references and queries. Marked with Preserve attribute in the compiled assembly for runtime usage.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the internal interval used by the scheduler for when this system should run. Uses kUpdatesPerDay and a fixed factor (262144/(kUpdatesPerDay*16)) to compute the update interval used by the simulation framework.

  • protected override void OnCreate()
    Initializes system references (EndFrameBarrier, SimulationSystem, CitySystem, TriggerSystem, CityStatisticsSystem), builds the EntityQueries (m_CitizenQuery, m_EventQuery, m_PoliceConfigurationQuery), and sets the system's update requirements (RequireForUpdate calls). Sets up which entities the job will process and which prefab events the system will consider.

  • protected override void OnUpdate()
    Main update entry: computes the current updateFrame index (SimulationUtils.GetUpdateFrame) and schedules the parallel CrimeCheckJob. The job gets:

  • a list of event prefab archetype chunks (m_EventPrefabChunks),
  • component type handles and lookups,
  • parallel writers for trigger actions and statistics events,
  • a RandomSeed and PoliceConfigurationData,
  • a command buffer writer from m_EndFrameBarrier. The method wires job dependencies with the world dependency, adds the producer job handle to the EndFrameBarrier, registers writers with the TriggerSystem and CityStatisticsSystem, and stores the resulting JobHandle in base.Dependency.

  • protected override void OnCreateForCompiler()
    Internal helper used by compiled workflow to assign query handles and component type handles; calls __AssignQueries and __TypeHandle.__AssignHandles.

  • [MethodImpl(MethodImplOptions.AggressiveInlining)] private void __AssignQueries(ref SystemState state)
    Compiler-generated placeholder that initializes any query-building logic required by the generated code path. In this decompiled form it only allocates and disposes an EntityQueryBuilder; real handle assignment happens in __TypeHandle.__AssignHandles.

  • private struct TypeHandle (nested)
    Holds cached ComponentTypeHandle, SharedComponentTypeHandle, ComponentLookup, BufferLookup, and an EntityTypeHandle used to build IJobChunk job inputs. It defines __AssignHandles to populate those handles from a SystemState.

  • private struct CrimeCheckJob : IJobChunk (nested)
    The Burst-compiled job that does the per-chunk / per-citizen crime evaluation. Important behavior and methods inside:

  • Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
    Filters by UpdateFrame shared component, iterates Citizens in the chunk, skips children and elderly, skips citizens that are already participating in an event (Criminal.m_Event != Entity.Null when applicable), obtains household/property for renter checks, then calls TryAddCrime for each eligible citizen.
  • TryAddCrime(int jobIndex, ref Random random, Entity entity, Citizen citizen, bool isCriminal, Entity household, Entity property, DynamicBuffer cityModifiers)
    Computes a crime probability "t" from citizen.m_WellBeing (low well-being increases probability; higher well-being reduces it non-linearly). For each CrimeData prefab (Event prefab archetype) that targets Citizen and isn't locked, calculates occurrence or recurrence probability (based on whether the citizen is flagged as a Criminal) and applies city modifiers (CityUtils.ApplyModifier) and population/police scaling. If probabilities pass randomized checks (unless debugFullCrimeMode is enabled), further checks building welfare service coverage for recurrence cases. If a crime is approved, enqueues a statistics event (CrimeCount +1) and calls CreateCrimeEvent.
  • CreateCrimeEvent(int jobIndex, Entity targetEntity, Entity eventPrefab, EventData eventData)
    Creates an event entity using the prefab's archetype, sets a PrefabRef to the prefab, fills the event's Target buffer with the target citizen, and enqueues a TriggerAction of type TriggerType.CitizenCommitedCrime so other systems can react.

Notes on concurrency and safety: - The job uses ToArchetypeChunkListAsync for event prefabs and schedules in parallel over the citizen query. - The job uses EntityCommandBuffer.ParallelWriter (m_CommandBuffer) and NativeQueue.ParallelWriter for trigger and statistics buffers, which are registered with the corresponding systems (EndFrameBarrier, TriggerSystem, CityStatisticsSystem) so dependencies are tracked correctly.

Usage Example

// Example: Toggle debug crime mode at runtime so all eligible crimes are evaluated without probabilistic gating.
var world = World.DefaultGameObjectInjectionWorld;
var crimeSystem = world.GetOrCreateSystemManaged<Game.Simulation.CrimeCheckSystem>();
crimeSystem.debugFullCrimeMode = true;

// Alternatively, the system will run automatically within the simulation; you can inspect or adjust
// PoliceConfigurationData or CrimeData prefabs to change behavior without modifying the system.