# 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 "vehicle_gui.h"`
`#include "ai/ai.hpp"`
`#include "aircraft.h"`
`#include "train.h"`
`#include "newgrf_cargo.h"`
`#include "newgrf_engine.h"`
`#include "newgrf_sound.h"`
`#include "newgrf_industries.h"`
`#include "newgrf_industrytiles.h"`
`#include "newgrf_station.h"`
`#include "unmovable.h"`
`#include "group.h"`
`#include "strings_func.h"`
`#include "functions.h"`
`#include "window_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 "newgrf.h"`
`#include "engine_base.h"`
`#include "table/strings.h"`
`#include "table/sprites.h"`
`#include "table/pricebase.h"`

Go to the source code of this file.

## 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.
static uint32 | BigMulSU (const uint32 a, const uint32 b, const uint8 shift)
| Multiply two unsigned integers and shift the results to right.
Money | CalculateCompanyValue (const Company *c, bool including_loan)
| Calculate the value of the company.
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)
void | ChangeOwnershipOfCompanyItems (Owner old_owner, Owner new_owner)
static void | ChangeNetworkOwner (Owner current_owner, Owner new_owner)
static void | CompanyCheckBankrupt (Company *c)
static void | CompaniesGenStatistics ()
void | AddInflation (bool check_year)
| Add monthly inflation.
void | RecomputePrices ()
| Computes all prices, payments and maximum loan.
static void | CompaniesPayInterest ()
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.
void | StartupIndustryDailyChanges (bool init_counter)
| Initialize the variables that will maintain the daily industry change system.
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.
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.
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.
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.
void | PrepareUnload (Vehicle *front_v)
| Prepare the vehicle to be unloaded.
static void | LoadUnloadVehicle (Vehicle *v, int *cargo_left)
| Loads/unload the vehicle if possible.
void | LoadUnloadStation (Station *st)
| Load/unload the vehicles in this station according to the order they entered.
void | CompaniesMonthlyLoop ()
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.
CommandCost | CmdSellShareInCompany (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
| Sell shares in an opposing company.
CommandCost | CmdBuyCompany (TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
| Buy up another company.

## Variables

CargoPaymentPool | _cargo_payment_pool ("CargoPayment")
| The actual pool to store cargo payments in.
const ScoreInfo | _score_info []
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.

## Detailed Description

Handling of the economy.

Definition in file economy.cpp.

## Function Documentation

void AddInflation | ( | bool | check_year | ) |

Add monthly inflation.

Parameters:

  | check_year | Shall the inflation get stopped after 170 years?

Definition at line 600 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, min(), ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR, and GameCreationSettings::starting_year.

static int32 BigMulS | ( | const int32 | a,
|  | const int32 | b,
|  | const uint8 | shift |
| ) |  |  | `[inline, static]`

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:

  | a | The first integer
  | b | The second integer
  | shift | The amount to shift the value to right.

Returns:
  The shifted result

Definition at line 70 of file economy.cpp.

static uint32 BigMulSU | ( | const uint32 | a,
|  | const uint32 | b,
|  | const uint8 | shift |
| ) |  |  | `[inline, static]`

Multiply two unsigned integers and shift the results to right.

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

Parameters:

  | a | The first unsigned integer
  | b | The second unsigned integer
  | shift | The amount to shift the value to right.

Returns:
  The shifted result

Definition at line 86 of file economy.cpp.

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:

  | c | the company to get the value of.
  | including_loan | include the loan in the company value.

Returns:
  the value of the company.

Definition at line 122 of file economy.cpp.

References CountBits(), BaseStation::facilities, SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, Aircraft::IsNormalAircraft(), max(), BaseStation::owner, BaseVehicle::type, Vehicle::value, VEH_AIRCRAFT, VEH_ROAD, VEH_SHIP, and VEH_TRAIN.

Referenced by CmdBuyShareInCompany(), CmdSellShareInCompany(), DestroyCompanyHQ(), AICompany::GetCompanyValue(), CompanyWindow::SetStringParameters(), and UpdateCompanyRatingAndValue().

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:

  | tile | unused
  | flags | type of operation
  | p1 | company to buy up
  | p2 | unused
  | text | unused

Returns:
  the cost of this operation or an error

Definition at line 1574 of file economy.cpp.

References _networking, Company::bankrupt_asked, CMD_ERROR, DC_EXEC, EXPENSES_OTHER, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_company_pool >::GetIfValid(), HasBit(), and Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index.

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

Acquire shares in an opposing company.

Parameters:

  | tile | unused
  | flags | type of operation
  | p1 | company to buy the shares from
  | p2 | unused
  | text | unused

Returns:
  the cost of this operation or an error

Definition at line 1492 of file economy.cpp.

References _cur_year, _settings_game, CommandCost::AddCost(), EconomySettings::allow_shares, CalculateCompanyValue(), CMD_ERROR, COMPANY_SPECTATOR, DC_EXEC, GameSettings::economy, EXPENSES_OTHER, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_company_pool >::GetIfValid(), return_cmd_error, and SetWindowDirty().

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

Sell shares in an opposing company.

Parameters:

  | tile | unused
  | flags | type of operation
  | p1 | company to sell the shares from
  | p2 | unused
  | text | unused

Returns:
  the cost of this operation or an error

Definition at line 1539 of file economy.cpp.

References _settings_game, EconomySettings::allow_shares, CalculateCompanyValue(), CMD_ERROR, COMPANY_SPECTATOR, DC_EXEC, GameSettings::economy, EXPENSES_OTHER, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_company_pool >::GetIfValid(), and SetWindowDirty().

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_pieces | amount of cargo delivered
  | cargo_type | the type of cargo that is delivered
  | dest | Station the cargo has been unloaded
  | source_tile | The origin of the cargo for distance calculation
  | days_in_transit | Travel time
  | company | The company delivering the cargo
  | src_type | Type of source of cargo (industry, town, headquarters)
  | src | Index 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 937 of file economy.cpp.

References _settings_game, Station::always_accepted, Company::cargo_types, CheckSubsidised(), DeliverGoodsToIndustry(), GameSettings::difficulty, DistanceManhattan(), CargoSpec::Get(), SpecializedStation< Station, false >::Get(), HasBit(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, SetBit(), ST_INDUSTRY, DifficultySettings::subsidy_multiplier, TE_FOOD, TE_WATER, BaseStation::town, CargoSpec::town_effect, and BaseStation::xy.

Referenced by CargoPayment::PayFinalDelivery().

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:

  | st | The station that accepted the cargo
  | cargo_type | Type of cargo delivered
  | num_pieces | Amount of cargo delivered
  | source | The source of the cargo

Returns:
  actually accepted pieces of cargo

Definition at line 882 of file economy.cpp.

References Industry::accepts_cargo, IndustrySpec::callback_mask, CBID_INDUSTRY_REFUSE_CARGO, CBM_IND_REFUSE_CARGO, GetIndustrySpec(), IndustrySpec::grf_prop, GRFFileProps::grffile, HasBit(), SmallVector< T, S >::Include(), Industry::incoming_cargo_waiting, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, Station::industries_near, SmallVector< T, S >::Length(), lengthof, Industry::location, min(), TileArea::tile, and Industry::type.

Referenced by DeliverGoods().

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

Determine a certain price.

Parameters:

  | index | Price base
  | cost_factor | Price factor
  | grf_file | NewGRF to use local price multipliers from.
  | shift | Extra bit shifting after the computation

Returns:
  Price

Definition at line 806 of file economy.cpp.

References GRFFile::price_base_multipliers.

Referenced by AITile::GetBuildCost(), AIRoad::GetBuildCost(), AIRail::GetBuildCost(), AIMarine::GetBuildCost(), GetRefitCost(), Train::GetRunningCost(), Ship::GetRunningCost(), RoadVehicle::GetRunningCost(), and Aircraft::GetRunningCost().

void LoadUnloadStation | ( | Station * | st | ) |

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

Parameters:

  | st | the station to do the loading/unloading for

Definition at line 1398 of file economy.cpp.

References SmallVector< T, S >::Begin(), GoodsEntry::cargo, SmallVector< T, S >::Clear(), CargoList< Tinst >::Count(), SmallVector< T, S >::End(), Station::goods, LoadUnloadVehicle(), NUM_CARGO, TriggerIndustryProduction(), and Vehicle::vehstatus.

static void LoadUnloadVehicle | ( | Vehicle * | v,
|  | int * | cargo_left |
| ) |  |  | `[static]`

Loads/unload the vehicle if possible.

Parameters:

  | v | the vehicle to be (un)loaded
  | cargo_left | the amount of each cargo type that is virtually left on the platform to be picked up by another vehicle when all previous vehicles have loaded.

Definition at line 1118 of file economy.cpp.

References _cur_year, _settings_client, _settings_game, TrainCache::cached_max_speed, TrainCache::cached_total_length, CalcPercentVehicleFilled(), CALLBACK_FAILED, EngineInfo::callback_mask, GoodsEntry::cargo, Vehicle::cargo, Vehicle::cargo_cap, Vehicle::cargo_payment, Vehicle::cargo_type, CBID_VEHICLE_LOAD_AMOUNT, CBM_VEHICLE_LOAD_AMOUNT, CC_PASSENGERS, ClrBit(), COMPANY_SPECTATOR, CargoList< Tinst >::Count(), Vehicle::cur_speed, Vehicle::current_order, CargoList< Tinst >::Empty(), SpecializedVehicle< Train, VEH_TRAIN >::From(), SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From(), GB(), Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem<&_engine_pool >::Get(), SpecializedStation< Station, false >::Get(), Order::GetLoadType(), Station::GetPlatformLength(), GetStationIndex(), Order::GetUnloadType(), GetVehicleCallback(), GetWindowClassForVehicleType(), Station::goods, OrderSettings::gradual_loading, ClientSettings::gui, HasBit(), OrderSettings::improved_load, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, IsCargoInClass(), Aircraft::IsNormalAircraft(), IsTileType(), Order::IsType(), Vehicle::load_unload_ticks, GUISettings::loading_indicators, Vehicle::MarkDirty(), Station::MarkTilesDirty(), max(), Vehicle::max_speed, min(), CargoList< Tinst >::MoveTo(), MP_STATION, CargoList< StationCargoList >::MTA_CARGO_LOAD, CargoList< VehicleCargoList >::MTA_FINAL_DELIVERY, CargoList< VehicleCargoList >::MTA_TRANSFER, CargoList< VehicleCargoList >::MTA_UNLOAD, Vehicle::Next(), OLF_FULL_LOAD_ANY, OLFB_FULL_LOAD, OLFB_NO_LOAD, GameSettings::order, OUFB_NO_UNLOAD, OUFB_TRANSFER, OUFB_UNLOAD, SB(), SetBit(), CargoPayment::SetCargo(), SetWindowDirty(), Vehicle::tile, TILE_SIZE, BaseVehicle::type, VEH_AIRCRAFT, VEH_ROAD, VEH_SHIP, VEH_TRAIN, Vehicle::vehicle_flags, and BaseStation::xy.

Referenced by LoadUnloadStation().

void PrepareUnload | ( | Vehicle * | front_v | ) |

Prepare the vehicle to be unloaded.

Parameters:

  | front_v | the vehicle to be unloaded

Definition at line 1090 of file economy.cpp.

References Vehicle::cargo, Vehicle::cargo_cap, Vehicle::cargo_payment, ClrBit(), Vehicle::current_order, CargoList< Tinst >::Empty(), Order::GetUnloadType(), Vehicle::load_unload_ticks, Vehicle::Next(), OUFB_NO_UNLOAD, SetBit(), and Vehicle::vehicle_flags.

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:

  | price | Index of price base to change.
  | factor | Amount to change by.

Definition at line 749 of file economy.cpp.

References Clamp().

Referenced by FinalisePriceBaseMultipliers().

void StartupIndustryDailyChanges | ( | bool | init_counter | ) |

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

Parameters:

  | init_counter | specifies if the counter is required to be initialized

Definition at line 759 of file economy.cpp.

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

Referenced by Load_ECMY().

static void TriggerIndustryProduction | ( | Industry * | i | ) | `[static]`

Inform the industry about just delivered cargo DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.

Parameters:

  | i | The industry to process

Definition at line 979 of file economy.cpp.

References _date, IndustrySpec::callback_mask, CBM_IND_PRODUCTION_256_TICKS, CBM_IND_PRODUCTION_CARGO_ARRIVAL, GetIndustrySpec(), HasBit(), Industry::incoming_cargo_waiting, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, IndustryProductionCallback(), IndustrySpec::input_cargo_multiplier, Industry::last_cargo_accepted_at, lengthof, min(), Industry::produced_cargo_waiting, SetWindowDirty(), Industry::type, and Industry::was_cargo_delivered.

Referenced by LoadUnloadStation().

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:

  | update | the economy with calculated score
  | c | company been evaluated

Returns:
  actual score of this company

Definition at line 161 of file economy.cpp.

References CalculateCompanyValue(), Company::cargo_types, Clamp(), ClampToI32(), CountBits(), BaseStation::facilities, Pool< Titem, Tindex, Tgrowth_step, Tmax_size, Tcache, Tzero >::PoolItem< Tpool >::index, Vehicle::IsPrimaryVehicle(), max(), min(), ScoreInfo::needed, BaseStation::owner, CompanyEconomyEntry::performance_history, Vehicle::profit_last_year, ScoreInfo::score, SCORE_END, SCORE_MAX, SCORE_TOTAL, SetWindowDirty(), and BaseVehicle::type.

Referenced by CmdBuildCompanyHQ().

## Variable Documentation

SmallIndustryList _cargo_delivery_destinations`[static]`

The industries we've currently brought cargo to.

Definition at line 871 of file economy.cpp.

CargoPaymentPool _cargo_payment_pool("CargoPayment")

The actual pool to store cargo payments in.

const ScoreInfo _score_info[]

Initial value:

     {
      { SCORE_VEHICLES,        120, 100 },
      { SCORE_STATIONS,         80, 100 },
      { SCORE_MIN_PROFIT,    10000, 100 },
      { SCORE_MIN_INCOME,    50000,  50 },
      { SCORE_MAX_INCOME,   100000, 100 },
      { SCORE_DELIVERED,     40000, 400 },
      { SCORE_CARGO,             8,  50 },
      { SCORE_MONEY,      10000000,  50 },
      { SCORE_LOAN,         250000,  50 },
      { SCORE_TOTAL,             0,   0 }
    }

Definition at line 94 of file economy.cpp.