Skip to content

Game.FireHazardSystem

Assembly:
Assembly-CSharp (game assembly)

Namespace:
Game.Simulation

Type:
class

Base:
GameSystemBase

Summary:
FireHazardSystem is an ECS system that evaluates flammable entities (buildings and trees) and probabilistically starts fire events based on prefab FireData and computed fire hazard values. It integrates climate and city configuration (rain, temperature, natural disasters) and uses a parallel IJobChunk (FireHazardJob) to sample entity chunks, compute hazard using EventHelpers.FireHazardData, and spawn event entities (fire events) via an EndFrameBarrier command buffer. The system also tracks consecutive no-rain progress as a floating "noRainDays" value and is serializable so that noRainDays is persisted across saves.


Fields

  • private const int UPDATES_PER_DAY
    Tracks the number of hazard update ticks per in-game day (value: 64). Used to convert tick progress into days for climate/rain accumulation.

  • private LocalEffectSystem m_LocalEffectSystem
    Reference to the LocalEffectSystem used to read local effect data needed by the hazard calculation and to register readers for scheduled jobs.

  • private PrefabSystem m_PrefabSystem
    Reference to the PrefabSystem used to access FireConfigurationPrefab and other prefab data.

  • private ClimateSystem m_ClimateSystem
    Reference to ClimateSystem for temperature and rain status which influence fire hazard.

  • private CityConfigurationSystem m_CityConfigurationSystem
    Reference to CityConfigurationSystem to check whether natural disasters are enabled (affects tree fires).

  • private EndFrameBarrier m_EndFrameBarrier
    Barrier used to produce event entities at the end of frame via a parallel EntityCommandBuffer.

  • private EntityQuery m_FlammableQuery
    EntityQuery that matches flammable entities (buildings OR trees) while excluding placeholders, owners, on-fire entities, deleted/overridden/temp, and fire stations.

  • private EntityQuery m_FirePrefabQuery
    EntityQuery that matches event prefabs that contain EventData and FireData (and excludes Locked), used to sample available fire event prefabs.

  • private EntityQuery m_FireConfigQuery
    EntityQuery that holds the FireConfigurationData entity (singletons) used to fetch FireConfigurationPrefab.

  • private EventHelpers.FireHazardData m_FireHazardData
    Helper that computes per-entity fire hazard using prefab, building/tree state, district, damage and construction status, plus environmental modifiers.

  • private TypeHandle __TypeHandle
    Internal container of EntityTypeHandle and ComponentTypeHandle<> instances used for the job's access to components.

Properties

  • public float noRainDays { get; private set; }
    Accumulated number of in-game days without rain (incremented by 1/64 each update tick when not raining). Used by FireHazardData to influence start probabilities (drier conditions increase hazard). Serialized for save/load.

Constructors

  • public FireHazardSystem()
    Default constructor (preserved for serialization / runtime creation). Typical systems are created by the world; no special initialization is done in the ctor — initialization happens in OnCreate.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the update interval for the system (4096). This controls how frequently the system receives OnUpdate calls relative to other systems/phases.

{{ YOUR_INFO }}: This method makes the system run less frequently than every frame; the scheduling uses Unity ECS system update cadence to distribute workload.

  • protected override void OnCreate()
    Sets up dependencies: resolves LocalEffectSystem, PrefabSystem, ClimateSystem, CityConfigurationSystem and EndFrameBarrier; builds the EntityQueries (m_FlammableQuery, m_FirePrefabQuery, m_FireConfigQuery); initializes EventHelpers.FireHazardData; and calls RequireForUpdate on necessary queries.

{{ YOUR_INFO }}: The flammable query includes both Building and Tree as Any components, and excludes buildings that are fire stations or currently flagged as OnFire, Deleted, Overridden, etc. The fire prefab query looks for prefabs with EventData + FireData and excludes Locked prefabs so only usable fire event prefabs are considered.

  • protected override void OnUpdate()
    Main system tick. Updates noRainDays depending on m_ClimateSystem.isRaining. Obtains read data from LocalEffectSystem and FireConfigurationPrefab from PrefabSystem, then updates m_FireHazardData. Schedules the Burst-compiled FireHazardJob in parallel across matching flammable entities. The job receives a list of fire event prefab chunks, component type handles, the random seed, and the EndFrameBarrier command buffer (parallel writer). Adds the job as a local effect reader and registers the producer with the EndFrameBarrier.

{{ YOUR_INFO }}: OnUpdate composes three JobHandles (system dependency, prefab chunk listing async job, and local effect read dependencies) and combines them before scheduling the FireHazardJob. The CommandBuffer used to spawn events is produced in parallel and consumed at the end frame barrier.

  • public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter
    Writes noRainDays to the save writer so the drought progress persists across saves.

{{ YOUR_INFO }}: Only noRainDays is serialized by the system. Other runtime state is reconstructed from world entities/prefabs on load.

  • public void Deserialize<TReader>(TReader reader) where TReader : IReader
    Reads noRainDays from the save reader and restores the field.

{{ YOUR_INFO }}: This method expects the same ordering/format as Serialize; it reads a single float.

  • public void SetDefaults(Context context)
    Resets system state to defaults (sets noRainDays = 0f).

{{ YOUR_INFO }}: Called during initialization for default game state creation.

  • private void __AssignQueries(ref SystemState state)
    Internal helper used by compiler-generated OnCreateForCompiler to assign or initialize any queries required by the system. In this compiled code it creates and disposes a temporary EntityQueryBuilder — present to ensure query initialization is compatible with codegen.

{{ YOUR_INFO }}: This is part of compiled/system scaffolding and normally not used directly by modders.

  • protected override void OnCreateForCompiler()
    Compiler helper: calls __AssignQueries and assigns component type handles via __TypeHandle.__AssignHandles.

{{ YOUR_INFO }}: Present for runtime/IL2CPP codegen compatibility; modders rarely need to interact with it.

Nested types (summary of important nested job/structs):

  • FireHazardJob (private, BurstCompile, implements IJobChunk)
  • Scans chunks of flammable entities in parallel, uses RandomSeed sampling (1/64 chance per call) to early-out most entities to limit spawn rate.
  • For buildings: reads Building, CurrentDistrict, PrefabRef, Damaged, UnderConstruction and computes hazard via m_FireHazardData.GetFireHazard(prefabRef,...). If hazard triggers, it calls TryStartFire.
  • For trees (only when natural disasters enabled): reads Transform and Damaged and computes hazard similarly.
  • TryStartFire iterates m_FirePrefabChunks (the available event prefabs) and their FireData to find a matching FireData.m_RandomTargetType (Building or WildTree) and not Locked. It computes final probability as fireHazard * FireData.m_StartProbability and samples Random.NextFloat(10000f) < num. On success, CreateFireEvent creates an event entity via the command buffer and sets its PrefabRef and target buffer TargetElement (with the target entity).
  • FireHazardJob uses EntityCommandBuffer.ParallelWriter so event creation is safe in parallel.

{{ YOUR_INFO }}: The job uses a chunk-level Random derived from RandomSeed.Next() using unfilteredChunkIndex, meaning the randomness is deterministic per job chunk provided the seed is reproducible.

Usage Example

// Example: accessing the FireHazardSystem from another system to read noRainDays.
[Preserve]
protected override void OnCreate()
{
    base.OnCreate();
    var fireSystem = World.GetOrCreateSystemManaged<Game.Simulation.FireHazardSystem>();
    UnityEngine.Debug.Log($"Current no-rain-days: {fireSystem.noRainDays}");
}

// Example: resetting the tracked drought progress (callable at world init)
[Preserve]
public void ResetFireSystemProgress()
{
    var fireSystem = World.GetOrCreateSystemManaged<Game.Simulation.FireHazardSystem>();
    fireSystem.SetDefaults(default); // sets noRainDays = 0
}

{{ YOUR_INFO }}: To influence fire behavior, modders can: - Add/modify FireData on event prefabs (m_StartProbability, m_RandomTargetType) to change which prefabs can start fires and their base start rates. - Extend or replace EventHelpers.FireHazardData logic (if accessible) to change how building/tree attributes, district, damage, or climate affect fireHazard. - Toggle naturalDisasters in CityConfigurationSystem to allow/disallow tree fires triggered by this system. - Be mindful that FireHazardJob runs in parallel and creates events via the EndFrameBarrier — spawned event entities will be processed later by event-handling systems.