OpenTTD
Data Structures | Typedefs | Functions | Variables
economy.cpp File Reference

Handling of the economy. More...

#include "stdafx.h"
#include "company_func.h"
#include "command_func.h"
#include "industry.h"
#include "town.h"
#include "news_func.h"
#include "network/network.h"
#include "network/network_func.h"
#include "ai/ai.hpp"
#include "aircraft.h"
#include "train.h"
#include "newgrf_engine.h"
#include "engine_base.h"
#include "ground_vehicle.hpp"
#include "newgrf_cargo.h"
#include "newgrf_sound.h"
#include "newgrf_industrytiles.h"
#include "newgrf_station.h"
#include "newgrf_airporttiles.h"
#include "object.h"
#include "strings_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "autoreplace_func.h"
#include "company_gui.h"
#include "signs_base.h"
#include "subsidy_base.h"
#include "subsidy_func.h"
#include "station_base.h"
#include "waypoint_base.h"
#include "economy_base.h"
#include "core/pool_func.hpp"
#include "core/backup_type.hpp"
#include "cargo_type.h"
#include "water.h"
#include "game/game.hpp"
#include "cargomonitor.h"
#include "goal_base.h"
#include "story_base.h"
#include "linkgraph/refresh.h"
#include "table/strings.h"
#include "table/pricebase.h"
#include "safeguards.h"

Go to the source code of this file.

Data Structures

struct  IsEmptyAction
 Action to check if a vehicle has no stored cargo. More...
 
struct  PrepareRefitAction
 Refit preparation action. More...
 
struct  ReturnCargoAction
 Action for returning reserved cargo. More...
 
struct  FinalizeRefitAction
 Action for finalizing a refit. More...
 
struct  ReserveCargoAction
 

Typedefs

typedef SmallVector< Industry *, 16 > SmallIndustryList
 

Functions

static int32 BigMulS (const int32 a, const int32 b, const uint8 shift)
 Multiply two integer values and shift the results to right. More...
 
Money CalculateCompanyValue (const Company *c, bool including_loan)
 Calculate the value of the company. More...
 
int UpdateCompanyRatingAndValue (Company *c, bool update)
 if update is set to true, the economy is updated with this score (also the house is updated, should only be true in the on-tick event) More...
 
void ChangeOwnershipOfCompanyItems (Owner old_owner, Owner new_owner)
 Change the ownership of all the items of a company. More...
 
static void CompanyCheckBankrupt (Company *c)
 Check for bankruptcy of a company. More...
 
static void CompaniesGenStatistics ()
 Update the finances of all companies. More...
 
bool AddInflation (bool check_year)
 Add monthly inflation. More...
 
void RecomputePrices ()
 Computes all prices, payments and maximum loan.
 
static void CompaniesPayInterest ()
 Let all companies pay the monthly interest on their loan. More...
 
static void HandleEconomyFluctuations ()
 
void ResetPriceBaseMultipliers ()
 Reset changes to the price base multipliers.
 
void SetPriceBaseMultiplier (Price price, int factor)
 Change a price base by the given factor. More...
 
void StartupIndustryDailyChanges (bool init_counter)
 Initialize the variables that will maintain the daily industry change system. More...
 
void StartupEconomy ()
 
void InitializeEconomy ()
 Resets economy to initial values.
 
Money GetPrice (Price index, uint cost_factor, const GRFFile *grf_file, int shift)
 Determine a certain price. More...
 
Money GetTransportedGoodsIncome (uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
 
static uint DeliverGoodsToIndustry (const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source)
 Transfer goods from station to industry. More...
 
static Money DeliverGoods (int num_pieces, CargoID cargo_type, StationID dest, TileIndex source_tile, byte days_in_transit, Company *company, SourceType src_type, SourceID src)
 Delivers goods to industries/towns and calculates the payment. More...
 
static void TriggerIndustryProduction (Industry *i)
 Inform the industry about just delivered cargo DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo. More...
 
void PrepareUnload (Vehicle *front_v)
 Prepare the vehicle to be unloaded. More...
 
static uint GetLoadAmount (Vehicle *v)
 Gets the amount of cargo the given vehicle can load in the current tick. More...
 
template<class Taction >
bool IterateVehicleParts (Vehicle *v, Taction action)
 Iterate the articulated parts of a vehicle, also considering the special cases of "normal" aircraft and double headed trains. More...
 
static void HandleStationRefit (Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
 Refit a vehicle in a station. More...
 
static void ReserveConsist (Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station)
 Reserves cargo if the full load order and improved_load is set or if the current order allows autorefit. More...
 
static void UpdateLoadUnloadTicks (Vehicle *front, const Station *st, int ticks)
 Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload again. More...
 
static void LoadUnloadVehicle (Vehicle *front)
 Loads/unload the vehicle if possible. More...
 
void LoadUnloadStation (Station *st)
 Load/unload the vehicles in this station according to the order they entered. More...
 
void CompaniesMonthlyLoop ()
 Monthly update of the economic data (of the companies as well as economic fluctuations).
 
static void DoAcquireCompany (Company *c)
 
int GetAmountOwnedBy (const Company *c, Owner owner)
 
CommandCost CmdBuyShareInCompany (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 Acquire shares in an opposing company. More...
 
CommandCost CmdSellShareInCompany (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 Sell shares in an opposing company. More...
 
CommandCost CmdBuyCompany (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 Buy up another company. More...
 

Variables

CargoPaymentPool _cargo_payment_pool ("CargoPayment")
 The actual pool to store cargo payments in. More...
 
const ScoreInfo _score_info []
 Score info, values used for computing the detailed performance rating. More...
 
int _score_part [MAX_COMPANIES][SCORE_END]
 
Economy _economy
 
Prices _price
 
Money _additional_cash_required
 
static PriceMultipliers _price_base_multiplier
 
static SmallIndustryList _cargo_delivery_destinations
 The industries we've currently brought cargo to. More...
 

Detailed Description

Handling of the economy.

Definition in file economy.cpp.

Function Documentation

◆ AddInflation()

bool AddInflation ( bool  check_year)

Add monthly inflation.

Parameters
check_yearShall the inflation get stopped after 170 years?
Returns
true if inflation is maxed and nothing was changed

Definition at line 722 of file economy.cpp.

References _cur_year, _settings_game, GameSettings::game_creation, Economy::infl_amount, Economy::infl_amount_pr, Economy::inflation_payment, Economy::inflation_prices, MAX_INFLATION, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR, and GameCreationSettings::starting_year.

Referenced by CompaniesMonthlyLoop().

◆ BigMulS()

static int32 BigMulS ( const int32  a,
const int32  b,
const uint8  shift 
)
inlinestatic

Multiply two integer values and shift the results to right.

This function multiplies two integer values. The result is shifted by the amount of shift to right.

Parameters
aThe first integer
bThe second integer
shiftThe amount to shift the value to right.
Returns
The shifted result

Definition at line 75 of file economy.cpp.

◆ CalculateCompanyValue()

Money CalculateCompanyValue ( const Company c,
bool  including_loan 
)

Calculate the value of the company.

That is the value of all assets (vehicles, stations, etc) and money minus the loan, except when including_loan is false which is useful when we want to calculate the value for bankruptcy.

Parameters
cthe company to get the value of.
including_loaninclude the loan in the company value.
Returns
the value of the company.

Definition at line 113 of file economy.cpp.

References Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index.

Referenced by Company::IsHumanID(), and CompanyWindow::SetStringParameters().

◆ ChangeOwnershipOfCompanyItems()

void ChangeOwnershipOfCompanyItems ( Owner  old_owner,
Owner  new_owner 
)

Change the ownership of all the items of a company.

Parameters
old_ownerThe company that gets removed.
new_ownerThe company to merge to, or INVALID_OWNER to remove the company.

Definition at line 289 of file economy.cpp.

References _current_company.

◆ CmdBuyCompany()

CommandCost CmdBuyCompany ( TileIndex  tile,
DoCommandFlag  flags,
uint32  p1,
uint32  p2,
const char *  text 
)

Buy up another company.

When a competing company is gone bankrupt you get the chance to purchase that company.

Todo:
currently this only works for AI companies
Parameters
tileunused
flagstype of operation
p1company to buy up
p2unused
textunused
Returns
the cost of this operation or an error

Definition at line 2092 of file economy.cpp.

◆ CmdBuyShareInCompany()

CommandCost CmdBuyShareInCompany ( TileIndex  tile,
DoCommandFlag  flags,
uint32  p1,
uint32  p2,
const char *  text 
)

Acquire shares in an opposing company.

Parameters
tileunused
flagstype of operation
p1company to buy the shares from
p2unused
textunused
Returns
the cost of this operation or an error

Definition at line 1999 of file economy.cpp.

References EXPENSES_OTHER.

◆ CmdSellShareInCompany()

CommandCost CmdSellShareInCompany ( TileIndex  tile,
DoCommandFlag  flags,
uint32  p1,
uint32  p2,
const char *  text 
)

Sell shares in an opposing company.

Parameters
tileunused
flagstype of operation
p1company to sell the shares from
p2unused
textunused
Returns
the cost of this operation or an error

Definition at line 2051 of file economy.cpp.

◆ CompaniesGenStatistics()

static void CompaniesGenStatistics ( )
static

Update the finances of all companies.

Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy.

Definition at line 655 of file economy.cpp.

Referenced by CompaniesMonthlyLoop().

◆ CompaniesPayInterest()

static void CompaniesPayInterest ( )
static

Let all companies pay the monthly interest on their loan.

Definition at line 828 of file economy.cpp.

References _current_company.

Referenced by CompaniesMonthlyLoop().

◆ CompanyCheckBankrupt()

static void CompanyCheckBankrupt ( Company c)
static

◆ DeliverGoods()

static Money DeliverGoods ( int  num_pieces,
CargoID  cargo_type,
StationID  dest,
TileIndex  source_tile,
byte  days_in_transit,
Company company,
SourceType  src_type,
SourceID  src 
)
static

Delivers goods to industries/towns and calculates the payment.

Parameters
num_piecesamount of cargo delivered
cargo_typethe type of cargo that is delivered
destStation the cargo has been unloaded
source_tileThe origin of the cargo for distance calculation
days_in_transitTravel time
companyThe company delivering the cargo
src_typeType of source of cargo (industry, town, headquarters)
srcIndex of source of cargo
Returns
Revenue for delivering cargo
Note
The cargo is just added to the stockpile of the industry. It is due to the caller to trigger the industry's production machinery

Definition at line 1084 of file economy.cpp.

Referenced by CargoPayment::PayFinalDelivery().

◆ DeliverGoodsToIndustry()

static uint DeliverGoodsToIndustry ( const Station st,
CargoID  cargo_type,
uint  num_pieces,
IndustryID  source 
)
static

Transfer goods from station to industry.

All cargo is delivered to the nearest (Manhattan) industry to the station sign, which is inside the acceptance rectangle and actually accepts the cargo.

Parameters
stThe station that accepted the cargo
cargo_typeType of cargo delivered
num_piecesAmount of cargo delivered
sourceThe source of the cargo
Returns
actually accepted pieces of cargo

Definition at line 1034 of file economy.cpp.

References Industry::accepts_cargo, SmallVector< T, S >::Include(), Industry::incoming_cargo_waiting, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index, Station::industries_near, IndustryTemporarilyRefusesCargo(), SmallVector< T, S >::Length(), lengthof, and min().

◆ GetLoadAmount()

static uint GetLoadAmount ( Vehicle v)
static

Gets the amount of cargo the given vehicle can load in the current tick.

This is only about loading speed. The free capacity is ignored.

Parameters
vVehicle to be queried.
Returns
Amount of cargo the vehicle can load at once.

Definition at line 1288 of file economy.cpp.

References _settings_game, CALLBACK_FAILED, CeilDiv(), SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), Vehicle::GetEngine(), Engine::GetGRF(), OrderSettings::gradual_loading, Aircraft::IsNormalAircraft(), GameSettings::order, BaseVehicle::type, and VEH_AIRCRAFT.

◆ GetPrice()

Money GetPrice ( Price  index,
uint  cost_factor,
const GRFFile grf_file,
int  shift 
)

Determine a certain price.

Parameters
indexPrice base
cost_factorPrice factor
grf_fileNewGRF to use local price multipliers from.
shiftExtra bit shifting after the computation
Returns
Price

Definition at line 958 of file economy.cpp.

Referenced by ObjectSpec::GetBuildCost(), and ObjectSpec::GetClearCost().

◆ HandleStationRefit()

static void HandleStationRefit ( Vehicle v,
CargoArray consist_capleft,
Station st,
StationIDStack  next_station,
CargoID  new_cid 
)
static

Refit a vehicle in a station.

Parameters
vVehicle to be refitted.
consist_capleftAdded cargo capacities in the consist.
stStation the vehicle is loading at.
next_stationPossible next stations the vehicle can travel to.
new_cidTarget cargo for refit.

Definition at line 1465 of file economy.cpp.

References _current_company, Vehicle::GetFirstEnginePart(), IterateVehicleParts(), and Vehicle::owner.

◆ IterateVehicleParts()

template<class Taction >
bool IterateVehicleParts ( Vehicle v,
Taction  action 
)

Iterate the articulated parts of a vehicle, also considering the special cases of "normal" aircraft and double headed trains.

Apply an action to each vehicle and immediately return false if that action does so. Otherwise return true.

Template Parameters
TactionClass of action to be applied. Must implement bool operator()([const] Vehicle *).
Parameters
vFirst articulated part.
actionInstance of Taction.
Returns
false if any of the action invocations returned false, true otherwise.

Definition at line 1333 of file economy.cpp.

References SpecializedVehicle< Train, Type >::From(), SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), Vehicle::HasArticulatedPart(), GroundVehicle< T, Type >::IsMultiheaded(), Aircraft::IsNormalAircraft(), Vehicle::Next(), BaseVehicle::type, VEH_AIRCRAFT, and VEH_TRAIN.

Referenced by HandleStationRefit().

◆ LoadUnloadStation()

void LoadUnloadStation ( Station st)

Load/unload the vehicles in this station according to the order they entered.

Parameters
stthe station to do the loading/unloading for

Definition at line 1899 of file economy.cpp.

References Vehicle::vehstatus, VS_CRASHED, and VS_STOPPED.

◆ LoadUnloadVehicle()

static void LoadUnloadVehicle ( Vehicle front)
static

Loads/unload the vehicle if possible.

Parameters
frontthe vehicle to be (un)loaded

Definition at line 1595 of file economy.cpp.

◆ PrepareUnload()

void PrepareUnload ( Vehicle front_v)

Prepare the vehicle to be unloaded.

Parameters
curr_stationthe station where the consist is at the moment
front_vthe vehicle to be unloaded

Definition at line 1247 of file economy.cpp.

References ClrBit(), SpecializedStation< Station, false >::Get(), Vehicle::last_station_visited, Vehicle::load_unload_ticks, BaseConsist::vehicle_flags, and VF_LOADING_FINISHED.

◆ ReserveConsist()

static void ReserveConsist ( Station st,
Vehicle u,
CargoArray consist_capleft,
StationIDStack next_station 
)
static

Reserves cargo if the full load order and improved_load is set or if the current order allows autorefit.

Parameters
stStation where the consist is loading at the moment.
uFront of the loading vehicle consist.
consist_capleftIf given, save free capacities after reserving there.
next_stationStation(s) the vehicle will stop at next.

Definition at line 1547 of file economy.cpp.

References Vehicle::cargo_payment, Vehicle::current_order, Order::IsRefit(), and Vehicle::Next().

◆ SetPriceBaseMultiplier()

void SetPriceBaseMultiplier ( Price  price,
int  factor 
)

Change a price base by the given factor.

The price base is altered by factors of two. NewBaseCost = OldBaseCost * 2^n

Parameters
priceIndex of price base to change.
factorAmount to change by.

Definition at line 899 of file economy.cpp.

◆ StartupIndustryDailyChanges()

void StartupIndustryDailyChanges ( bool  init_counter)

Initialize the variables that will maintain the daily industry change system.

Parameters
init_counterspecifies if the counter is required to be initialized

Definition at line 909 of file economy.cpp.

References Economy::industry_daily_change_counter, Economy::industry_daily_increment, MapLogX(), and MapLogY().

◆ TriggerIndustryProduction()

static void TriggerIndustryProduction ( Industry i)
static

◆ UpdateCompanyRatingAndValue()

int UpdateCompanyRatingAndValue ( Company c,
bool  update 
)

if update is set to true, the economy is updated with this score (also the house is updated, should only be true in the on-tick event)

Parameters
updatethe economy with calculated score
ccompany been evaluated
Returns
actual score of this company

Definition at line 153 of file economy.cpp.

References Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tpool_type, Tcache, Tzero >::PoolItem< Tpool >::index.

◆ UpdateLoadUnloadTicks()

static void UpdateLoadUnloadTicks ( Vehicle front,
const Station st,
int  ticks 
)
static

Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload again.

Adjust for overhang of trains and set it at least to 1.

Parameters
frontThe vehicle to be updated.
stThe station the vehicle is loading at.
ticksThe time it would normally wait, based on cargo loaded and unloaded.

Definition at line 1577 of file economy.cpp.

References GroundVehicleCache::cached_total_length, Vehicle::GetGroundVehicleCache(), Station::GetPlatformLength(), Vehicle::load_unload_ticks, max(), Vehicle::tile, TILE_SIZE, BaseVehicle::type, and VEH_TRAIN.

Variable Documentation

◆ _cargo_delivery_destinations

SmallIndustryList _cargo_delivery_destinations
static

The industries we've currently brought cargo to.

Definition at line 1023 of file economy.cpp.

◆ _cargo_payment_pool

CargoPaymentPool _cargo_payment_pool("CargoPayment")

The actual pool to store cargo payments in.

◆ _score_info

const ScoreInfo _score_info[]
Initial value:
= {
{ 120, 100},
{ 80, 100},
{ 10000, 100},
{ 50000, 50},
{ 100000, 100},
{ 40000, 400},
{ 8, 50},
{10000000, 50},
{ 250000, 50},
{ 0, 0}
}

Score info, values used for computing the detailed performance rating.

Definition at line 85 of file economy.cpp.