Game.Simulation.GarbageAccumulationSystem
Assembly: Assembly-CSharp
Namespace: Game.Simulation
Type: class
Base: GameSystemBase, IDefaultSerializable, ISerializable, IPreDeserialize
Summary:
Manages per-building garbage accumulation and triggers garbage collection requests and warning icons. Runs on a staggered update schedule (kUpdatesPerDay slices) to spread workload across frames. Calculates daily garbage production for buildings based on ConsumptionData, building level, occupant/worker education, homeless population, district and city modifiers, and applies efficiency penalties to building performance based on piled-up garbage. Handles serialization of internal accumulation buffers used for bookkeeping across save/load.
Fields
-
public static readonly int kUpdatesPerDay
Constant number of update slices per day (16). Used to partition updates across frames. -
private SimulationSystem m_SimulationSystem
Reference to the SimulationSystem used to obtain frame timing and other simulation-wide data. -
private IconCommandSystem m_IconCommandSystem
Reference to the IconCommandSystem used to spawn or remove UI icons (e.g., garbage warning icons). -
private CitySystem m_CitySystem
Reference to the CitySystem; used to access the city entity and city-level modifiers. -
private EndFrameBarrier m_EndFrameBarrier
Barrier used to create an EntityCommandBuffer for deferred entity commands produced by jobs. -
private EntityQuery m_GarbageProducerQuery
Query selecting buildings that produce garbage (components: GarbageProducer, PrefabRef, UpdateFrame) and excluding Deleted/Destroyed/Temp. -
private EntityArchetype m_CollectionRequestArchetype
Archetype for creating garbage collection request entities (ServiceRequest + GarbageCollectionRequest + RequestGroup). -
private NativeArray<long> m_GarbageAccumulation
Ring buffer (length 16) used to accumulate garbage totals produced per update slice. Serialized and persisted across saves. -
private JobHandle m_AccumulationDeps
JobHandle tracking the currently running garbage accumulation job dependencies. -
private long m_Accumulation
Sum of the values in m_GarbageAccumulation (total accumulated garbage for the tracked period). -
private TypeHandle __TypeHandle
Generated type handle wrapper holding the various Entity/Component type handles used by the job system. -
private EntityQuery __query_2138252455_0
Generated query for GarbageParameterData (used to fetch garbage parameters singleton). -
private EntityQuery __query_2138252455_1
Generated query for BuildingEfficiencyParameterData (used to fetch garbage penalty parameter).
Properties
public long garbageAccumulation { get; }
Returns m_Accumulation multiplied by kUpdatesPerDay. This maps the stored accumulation to a per-day scale. Useful for UI or debug purposes to get an estimated daily garbage production value.
Constructors
public GarbageAccumulationSystem()
Default constructor (generated). The real initialization happens in the protected override OnCreate() where systems and resources are fetched and the NativeArray m_GarbageAccumulation is allocated.
Methods
-
public override int GetUpdateInterval(SystemUpdatePhase phase)
Returns the system update interval (determined by kUpdatesPerDay). Used to control how often the system is ticked relative to other systems. -
public static void GetGarbage(ref ConsumptionData consumption, Entity building, Entity prefab, BufferLookup<Renter> renters, BufferLookup<Game.Buildings.Student> students, BufferLookup<Occupant> occupants, ComponentLookup<HomelessHousehold> homelessHouseholds, BufferLookup<HouseholdCitizen> householdCitizens, ComponentLookup<Citizen> citizens, BufferLookup<Employee> employees, BufferLookup<Patient> patients, ComponentLookup<SpawnableBuildingData> spawnableDatas, ComponentLookup<CurrentDistrict> currentDistricts, BufferLookup<DistrictModifier> districtModifiers, ComponentLookup<ZoneData> zoneDatas, DynamicBuffer<CityModifier> cityModifiers, ref GarbageParameterData garbageParameter)
Convenience wrapper that computes and updates consumption.m_GarbageAccumulation for the given building by calling GetGarbageAccumulation with data fetched from various component lookups and buffers. -
public static void GetGarbageAccumulation(Entity building, Entity prefab, ref ConsumptionData consumption, CurrentDistrict currentDistrict, DynamicBuffer<CityModifier> cityModifiers, ComponentLookup<Citizen> citizens, ComponentLookup<SpawnableBuildingData> spawnableDatas, ComponentLookup<ZoneData> zoneDatas, ComponentLookup<HomelessHousehold> homelessHousehold, BufferLookup<HouseholdCitizen> householdCitizens, BufferLookup<Renter> renters, BufferLookup<Employee> employees, BufferLookup<Game.Buildings.Student> students, BufferLookup<Occupant> occupants, BufferLookup<Patient> patients, BufferLookup<DistrictModifier> districtModifiers, ref GarbageParameterData garbageParameter)
Core deterministic calculation of per-update garbage accumulation for a single building. Factors considered: - Base consumption.m_GarbageAccumulation from prefab/consumption data.
- Building spawn level (spawnable building level).
- Average education level of occupants/workers/students (education reduces garbage production).
- Homeless household count (adds fixed garbage per homeless).
-
District and city modifiers (e.g., district garbage production modifiers, industrial garbage multiplier). Result is stored back in consumption.m_GarbageAccumulation.
-
public static float GetGarbageEfficiencyFactor(int garbage, GarbageParameterData garbageParameters, float maxPenalty)
Computes and returns an efficiency factor (0..1) applied to building efficiency buffers based on current garbage piled up. Scales linearly from warning limit to max garbage accumulation and applies maxPenalty. -
protected override void OnCreate()
Initializes references to other systems (SimulationSystem, IconCommandSystem, CitySystem, EndFrameBarrier), allocates m_GarbageAccumulation (length 16), creates the m_GarbageProducerQuery and m_CollectionRequestArchetype, and registers update requirements. Also asserts minimum scheduling constraints. -
protected override void OnDestroy()
Disposes of the NativeArray m_GarbageAccumulation. -
public void PreDeserialize(Context context)
Resets m_Accumulation and zeroes the m_GarbageAccumulation buffer before loading to ensure a clean state. -
protected override void OnUpdate()
Main update entry. Steps performed: - Determine current updateFrame (stagger slice).
- Complete previous accumulation job dependencies.
- Sum the m_GarbageAccumulation buffer into m_Accumulation and zero the current slice entry.
- Read GarbageParameterData and BuildingEfficiencyParameterData singletons.
- If garbage service isn't locked, schedule the Burst-compiled GarbageAccumulationJob in parallel for buildings that match the current UpdateFrame slice. The job:
- Computes per-building garbage increase (randomized rounding).
- Caps garbage at the configured maximum.
- Requests collection by creating a GarbageCollectionRequest entity when limits are exceeded.
- Adds warning icons and sets flags when warning thresholds are crossed.
- Updates building efficiency factors in building efficiency buffers.
- Accumulates produced garbage into the m_GarbageAccumulation NativeArray (per-slice) using thread-safe Interlocked.Add via an unsafe pointer.
-
Connects job handles to EndFrameBarrier and IconCommandSystem for proper synchronization.
-
public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter
Writes the length of the accumulation buffer and each long value to persistent storage for saves. -
public void Deserialize<TReader>(TReader reader) where TReader : IReader
Reads buffer length and values back into m_GarbageAccumulation, recomputing m_Accumulation as values are read. Any remaining buffer slots are zeroed. -
public void SetDefaults(Context context)
Resets accumulation state (m_Accumulation = 0 and zeroes m_GarbageAccumulation) — used to initialize default save data. -
private void __AssignQueries(ref SystemState state)
Generated helper to build internal queries for retrieving garbage and building-efficiency parameter singletons. (Compiler-generated, internal use.) -
Inner types of note:
GarbageAccumulationJob
(IJobChunk, BurstCompile): the parallel chunk job that performs per-building accumulation, creates collection requests via EntityCommandBuffer.ParallelWriter, and writes to the NativeArraym_GarbageAccumulation using an unsafe pointer + Interlocked.Add for thread-safety. TypeHandle
(private struct): generated wrapper for all component/ buffer lookups and type handles used by the job.
Usage Example
// Example: reading today's (estimated) garbage accumulation reported by the system
var garbageSystem = World.DefaultGameObjectInjectionWorld.GetExistingSystemManaged<Game.Simulation.GarbageAccumulationSystem>();
if (garbageSystem != null)
{
long estimatedDailyGarbage = garbageSystem.garbageAccumulation;
Debug.Log($"Estimated daily garbage accumulation: {estimatedDailyGarbage}");
}
// Example: computing a building's garbage accumulation value (static helper).
// Requires valid component lookups/buffers from a System or Job context.
ConsumptionData consumption = default;
Game.Simulation.GarbageParameterData garbageParams = /* get singleton */;
CurrentDistrict district = /* get CurrentDistrict for building */;
DynamicBuffer<CityModifier> cityModifiers = /* get city modifiers buffer */;
Game.Simulation.GarbageAccumulationSystem.GetGarbageAccumulation(
buildingEntity,
prefabEntity,
ref consumption,
district,
cityModifiers,
citizensLookup,
spawnableDatasLookup,
zoneDatasLookup,
homelessLookup,
householdCitizensBufferLookup,
rentersBufferLookup,
employeesBufferLookup,
studentsBufferLookup,
occupantsBufferLookup,
patientsBufferLookup,
districtModifiersBufferLookup,
ref garbageParams
);
// consumption.m_GarbageAccumulation now contains the per-update garbage value for this building.