Game.Economy.EconomyUtils
Assembly: Assembly-CSharp
Namespace: Game.Economy
Type: public class
Base: System.Object
Summary:
Utility class used by the game's economy systems. Provides helpers for working with Resource bitmasks, prices, transport costs, production/profit calculations, workforce & wages, and various conversions between game types (AvailableResource, ResourceInEditor, ResourcePrefabs, ResourceData, etc.). Most methods are static and are intended to be used from systems that operate on Unity Entities / DOTS (DynamicBuffer, ComponentLookup, EntityManager, NativeCollections). Many methods assume Resource is used as a bitmask enum and that ResourcePrefabs & ResourceData components exist for mapping resource metadata (weight, price, production needs).
Fields
-
public static readonly int kCompanyUpdatesPerDay
A constant representing how many company update ticks are considered "per day" (256). Used in production calculations. -
public static readonly int ResourceCount
The number of distinct resources supported. Initialized via GetResourceIndex(Resource.Last).
Properties
- None. (All functionality is exposed via static methods / readonly fields.)
Constructors
public EconomyUtils()
Default constructor (the class is used as a static-style utility; no instance-specific state required).
Methods
-
public static int GetResourceIndex(Resource r)
Returns an integer index for a single Resource enum value (maps enum values to indices used internally). Returns -1 for invalid or non-singleton resources. Important: expects a single Resource value (not a bitmask of multiple resources). -
public static float3 BuildPseudoTradeCost(float distance, IndustrialProcessData process, ref ComponentLookup<ResourceData> resourceDatas, ResourcePrefabs resourcePrefabs)
Builds a pseudo trade-cost vector (x = net output cost, y = input1 transport cost, z = input2 transport cost) for an industrial process given distance and resource weights. Useful when estimating trade/transport costs for processes. -
public static Resource GetAllResources()
Returns a Resource bitmask containing all resources (used as a convenience for masks). -
public static bool IsProducedFrom(Resource product, Resource material)
Checks whether a given product Resource can be produced (directly) from a given material Resource. Uses bitmask checks for known production relationships. -
public static Resource GetResources([CanBeNull] ResourceInEditor[] resources, Resource defaultResources = Resource.NoResource)
Converts an array of ResourceInEditor (editor indices) to a Resource bitmask. If array is null/empty returns defaultResources. -
public static Resource GetResource(ResourceInEditor resource)
Converts a ResourceInEditor into a Resource bitmask (using GetResource(int index)). -
public static Resource GetResource(int index)
Returns a Resource that is 1 << index. If index < 0 returns Resource.NoResource. -
public static int CountResources(Resource resource)
Counts how many individual resources are present in the provided Resource bitmask. -
public static TradeCost GetTradeCost(Resource resource, DynamicBuffer<TradeCost> costs)
Searches a DynamicBuffer of TradeCost for an entry matching resource. Returns an empty TradeCost with m_Resource set if none found. -
public static long GetLastTradeRequestTime(DynamicBuffer<TradeCost> costs)
Returns the latest m_LastTransferRequestTime value found in the costs buffer (or 0 if none). -
public static void SetTradeCost(Resource resource, TradeCost newcost, DynamicBuffer<TradeCost> costs, bool keepLastTime, float buyLerp = 1f, float sellLerp = 1f)
Adds or updates a TradeCost entry in the costs buffer. Optionally preserves last transfer time and interpolates (lerps) buy/sell costs with previous values. Asserts that costs are valid (not NaN). -
public static void SetResources(Resource resource, DynamicBuffer<Resources> resources, int amount)
Sets resource amount in a DynamicBuffer, adding an entry if missing. -
public static int GetResources(Resource resource, DynamicBuffer<Resources> resources)
Gets amount of a specific resource from a DynamicBuffer, returns 0 if not present. -
public static int AddResources(Resource resource, int amount, DynamicBuffer<Resources> resources)
Adds (or creates) a resource entry in the DynamicBuffer and clamps the stored value to int range. Returns the new amount. -
public static Resource GetResource(AvailableResource available)
Maps AvailableResource enum values to Resource enum values (supply mapping). Returns Resource.NoResource for unknown values. -
public static AvailableResource GetAvailableResourceSupply(Resource resource)
Inverse mapping: maps a Resource to the corresponding AvailableResource supply enum. Returns AvailableResource.Count if not mappable. -
public static int GetHouseholdTotalWealth(Household householdData, DynamicBuffer<Resources> resources)
Returns the total household wealth (householdData.m_Resources + money in resources), clamped to Int32.MaxValue. -
public static int GetHouseholdSpendableMoney(Household householdData, DynamicBuffer<Resources> resources, ref BufferLookup<Renter> m_RenterBufs, ref ComponentLookup<ConsumptionData> consumptionDatas, ref ComponentLookup<PrefabRef> prefabRefs, PropertyRenter propertyRenter)
Calculates spendable money for a household, taking into account rent and upkeep divided among renters. Uses ComponentLookup calls and renter buffers; must be called in a system context where these lookups/buffers are valid. -
public static int GetHouseholdIncome(DynamicBuffer<HouseholdCitizen> citizens, ref ComponentLookup<Worker> workers, ref ComponentLookup<Citizen> citizenDatas, ref ComponentLookup<HealthProblem> healthProblems, ref EconomyParameterData economyParameters, NativeArray<int> taxRates)
Calculates household income from citizens, including wages, pensions, unemployment & family allowances; subtracts tax on wages based on taxRates. -
public static int GetCompanyTotalWorth(DynamicBuffer<Resources> resources, DynamicBuffer<OwnedVehicle> vehicles, ref BufferLookup<LayoutElement> layouts, ref ComponentLookup<Game.Vehicles.DeliveryTruck> deliveryTrucks, ResourcePrefabs resourcePrefabs, ref ComponentLookup<ResourceData> resourceDatas)
Calculates total worth of a company including stored resources and loaded vehicles (checks delivery truck states and layout buffers). -
public static int GetCompanyTotalWorth(DynamicBuffer<Resources> resources, ResourcePrefabs resourcePrefabs, ref ComponentLookup<ResourceData> resourceDatas)
Calculates total worth from resources only using industrial price per resource. -
public static void AddResources(DynamicBuffer<Resources> from, DynamicBuffer<Resources> to)
Adds every resource/amount from one buffer into another using AddResources. -
public static int GetTotalStorageUsed(DynamicBuffer<Resources> resources)
Sums the amounts of all non-money resources (used storage space). -
public static float GetServicePriceMultiplier(float serviceAvailable, int maxServiceAvailable)
Returns a multiplier [0.7,1.3] based on saturation: prices go up when service is scarce. -
public static int GetTransportCost(float distance, Resource resource, int amount, float weight)
Computes transport cost (rounded) for a resource based on distance, weight and amount. Returns 0 for Resource.NoResource. -
public static float GetTransportCost(float distance, int amount, float weight, StorageTransferFlags flags)
Alternative transport cost using storage transfer flags (Car / Transport) to modify cost formula and scaling. -
public static string GetNames(Resource r)
Returns a pipe-separated string of all resource names present in the Resource bitmask. -
public static string GetName(Resource r)
Returns a short string name for a single Resource (e.g., "grain", "oil", "furniture"). Returns "none" for unknown/NoResource. -
public static FixedString32Bytes GetNameFixed(Resource r)
Same as GetName but returns a FixedString32Bytes (allocation-free) for DOTS/native-friendly usage. -
public static Color GetResourceColor(Resource r)
Returns a UnityEngine.Color used for UI/visualization for the given resource; defaults to Color.black for unknown. -
public static float GetIndustrialPrice(Resource r, ResourcePrefabs prefabs, ref ComponentLookup<ResourceData> resourceDatas)
Returns the industrial price component (m_Price.x) of a resource if ResourceData exists; otherwise 0. -
public static float GetServicePrice(Resource r, ResourcePrefabs prefabs, ref ComponentLookup<ResourceData> resourceDatas)
Returns the service price component (m_Price.y) if present; otherwise 0. -
public static float GetMarketPrice(Resource r, ResourcePrefabs prefabs, ref ComponentLookup<ResourceData> resourceDatas)
Returns m_Price.x + m_Price.y (industrial + service portion) if present; otherwise 0. -
public static float GetMarketPrice(Resource r, ResourcePrefabs prefabs, EntityManager entityManager)
EntityManager variant: tries to read ResourceData via TryGetComponent and returns combined market price. -
public static float GetMarketPrice(ResourceData data)
Returns the combined market price from a ResourceData instance. -
public static float GetWeight(EntityManager entityManager, Resource r, ResourcePrefabs prefabs)
Returns resource weight read from ResourceData via EntityManager. Returns 0 for NoResource/All/Last or 1 if ResourceData missing. -
public static float GetWeight(Resource r, ResourcePrefabs prefabs, ref ComponentLookup<ResourceData> datas)
ComponentLookup variant to get resource weight. Returns 0 for NoResource/All/Last or 1 if missing. -
public static bool IsMaterial(Resource r, ResourcePrefabs prefabs, ref ComponentLookup<ResourceData> datas)
Returns whether a resource is considered a physical material (weight > 0). -
public static bool IsOfficeResource(Resource resource)
Checks bitmask to see if resource is an "office" resource (predefined mask). -
public static bool IsCommercialResource(Resource resource)
Checks bitmask whether resource is commercial (predefined mask). -
public static bool IsExtractorResource(Resource resource)
Checks if resource is from extractors (predefined mask for extractable resources). -
public static bool IsIndustrialResource(ResourceData resourceData, bool includeMaterial, bool includeOffice)
Returns true if resourceData matches production & material/office criteria; used for filtering resources by type. -
public static bool GetProcessComplexity(NativeList<ArchetypeChunk> m_IndustrialProcessDataChunks, ref ComponentLookup<WorkplaceData> workplaceDatas, Resource r, EntityTypeHandle entityType, ComponentTypeHandle<IndustrialProcessData> processType, out WorkplaceComplexity complexity)
Searches through provided process data chunks to find an IndustrialProcessData that outputs Resource r, and if found returns the associated WorkplaceComplexity. Useful while iterating chunks in a job/system. -
public static int CalculateTotalWage(DynamicBuffer<Employee> employees, ref EconomyParameterData econParams)
Sum of wages for given employee buffer using economy parameters. -
public static int CalculateTotalWage(int totalWorkers, WorkplaceComplexity complexity, int buildingLevel, EconomyParameterData econParams)
Calculate expected total wage by splitting workers among workplace levels and summing wages. -
public static Workplaces CalculateNumberOfWorkplaces(int totalWorkers, WorkplaceComplexity complexity, int buildingLevel)
Distributes a total number of workers into the 5 workplace levels, using complexity & building level to bias distribution; returns a Workplaces struct/array with counts for each level. -
public static float GetWorkforce(DynamicBuffer<Employee> employees, ref ComponentLookup<Citizen> citizens)
Computes effective workforce contribution from employees by summing GetWorkerWorkforce(happiness, level) for each employee (requires citizens component lookup). -
public static float GetAverageWorkforce(int maxWorkers, WorkplaceComplexity complexity, int buildingLevel)
Computes expected average workforce for a building given max workers, complexity and level. -
public static float GetAverageWorkforce(Workplaces workplaces)
Computes average workforce given a workplaces distribution. -
public static float GetAverageWorkforce(DynamicBuffer<Employee> employees)
Estimates average workforce for employees assuming default happiness (50) for each. -
public static float GetWorkerWorkforce(int happiness, int level)
Returns per-worker workforce output based on happiness and workplace level. Formula used by other workforce estimators. -
public static int GetCompanyMaxProfitPerDay(WorkProvider workProvider, bool isIndustrial, int level, IndustrialProcessData processData, ResourcePrefabs resourcePrefabs, WorkplaceData workplaceData, ref ComponentLookup<ResourceData> resourceDatas, ref EconomyParameterData economyParameters)
Estimates the maximum possible profit per day for a company based on max workers and other parameters. Uses wage calculation and production-per-day estimate. -
public static float GetCompanyProfitPerUnit(bool isIndustrial, IndustrialProcessData processData, ResourcePrefabs resourcePrefabs, ref ComponentLookup<ResourceData> resourceDatas)
Returns expected profit per produced unit (output value minus input costs) for a process. Uses industrial price for inputs/outputs or market service price based on isIndustrial. -
public static int GetCompanyProfitPerDay(float buildingEfficiency, bool isIndustrial, DynamicBuffer<Employee> employees, IndustrialProcessData processData, ResourcePrefabs resourcePrefabs, ref ComponentLookup<ResourceData> resourceDatas, ref ComponentLookup<Citizen> citizens, ref EconomyParameterData economyParameters)
Profit per day for an actual company instance: calculates wages and production given employees, then computes profit. -
public static int GetCompanyProductionPerDay(float buildingEfficiency, bool isIndustrial, DynamicBuffer<Employee> employees, IndustrialProcessData processData, ResourcePrefabs resourcePrefabs, ref ComponentLookup<ResourceData> resourceDatas, ref ComponentLookup<Citizen> citizens, ref EconomyParameterData economyParameters)
Calculates production per day for a company instance using ResourceData fetched via resourcePrefabs. -
public static int GetCompanyProductionPerDay(float buildingEfficiency, bool isIndustrial, DynamicBuffer<Employee> employees, IndustrialProcessData processData, ResourceData resourceData, ref ComponentLookup<Citizen> citizens, ref EconomyParameterData economyParameters)
Production per day variant that accepts ResourceData directly. -
public static int GetCompanyProductionPerDay(float buildingEfficiency, int workerAmount, int level, bool isIndustrial, WorkplaceData workplaceData, IndustrialProcessData processData, ResourcePrefabs resourcePrefabs, ref ComponentLookup<ResourceData> resourceDatas, ref EconomyParameterData economyParameters)
Static estimation of production per day given worker count & building level (no per-employee buffer). -
public static int GetCompanyProductionPerDay(float buildingEfficiency, int workerAmount, int level, bool isIndustrial, WorkplaceData workplaceData, IndustrialProcessData processData, ResourceData resourceData, ref EconomyParameterData economyParameters)
Same as above but accepts ResourceData directly. -
public static IncomeSource GetIncomeSource(PlayerResource resource)
Maps certain PlayerResource enum values (electricity, healthcare, education groups, water/sewage, public transport, parking, garbage) to IncomeSource fee enums. Returns IncomeSource.Count if no mapping.
Usage Example
// Example: read a resource's market price (EntityManager version) and display name & color.
// This code must run in a context where you have access to the current EntityManager and ResourcePrefabs.
Resource r = Resource.Grain;
float marketPrice = EconomyUtils.GetMarketPrice(r, resourcePrefabs, entityManager);
string name = EconomyUtils.GetName(r);
Color color = EconomyUtils.GetResourceColor(r);
Debug.Log($"Resource {name} has market price {marketPrice} and color {color}");
// Example: compute company production estimate (static estimate)
int estimatedProduction = EconomyUtils.GetCompanyProductionPerDay(
buildingEfficiency: 0.9f,
workerAmount: 40,
level: 2,
isIndustrial: true,
workplaceData: workplaceData, // from the building/prefab
processData: processData, // the IndustrialProcessData for this building
resourceData: resourceData, // ResourceData for the output resource
economyParameters: economyParams
);
Notes:
- Many methods expect DOTS types (DynamicBuffer<>, ComponentLookup<>, BufferLookup<>, NativeList