54 #include "table/strings.h" 75 static inline int32
BigMulS(const int32 a, const int32 b, const uint8 shift)
77 return (int32)((int64)a * (int64)b >> shift);
101 Money _additional_cash_required;
102 static PriceMultipliers _price_base_multiplier;
120 FOR_ALL_STATIONS(st) {
124 Money value = num * _price[PR_STATION_VALUE] * 25;
128 if (v->
owner != owner)
continue;
134 value += v->
value * 3 >> 1;
158 memset(_score_part[owner], 0,
sizeof(_score_part[owner]));
163 Money min_profit = 0;
164 bool min_profit_first =
true;
168 if (v->
owner != owner)
continue;
175 min_profit_first =
false;
183 _score_part[owner][SCORE_VEHICLES] = num;
185 if (min_profit > 0) {
186 _score_part[owner][SCORE_MIN_PROFIT] =
ClampToI32(min_profit);
195 FOR_ALL_STATIONS(st) {
197 if (st->
owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num +=
CountBits((byte)st->
facilities);
199 _score_part[owner][SCORE_STATIONS] = num;
213 }
while (++cee, --numec);
215 if (min_income > 0) {
216 _score_part[owner][SCORE_MIN_INCOME] =
ClampToI32(min_income);
219 _score_part[owner][SCORE_MAX_INCOME] =
ClampToI32(max_income);
231 }
while (++cee, --numec);
233 _score_part[owner][SCORE_DELIVERED] =
ClampToI32(total_delivered);
263 s =
Clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].
score / _score_info[i].
needed;
265 total_score += _score_info[i].
score;
295 #ifdef ENABLE_NETWORK 305 FOR_ALL_COMPANIES(c) {
306 if (c->
index != old_owner) {
317 assert(old_owner != new_owner);
324 FOR_ALL_COMPANIES(c) {
325 for (i = 0; i < 4; i++) {
339 for (i = 0; i < 4; i++) {
360 FOR_ALL_SUBSIDIES(s) {
406 if (v->
Previous() == NULL)
delete v;
420 RemoveAllGroupsForCompany(old_owner);
424 if (g->
owner == old_owner) g->
owner = new_owner;
456 if (!v->ServiceIntervalIsCustom()) {
466 v->
owner = new_owner;
524 FOR_ALL_STATIONS(st) {
525 if (st->
owner == old_owner) {
535 if (wp->
owner == old_owner) {
548 if (g->
company == old_owner)
delete g;
555 FOR_ALL_STORY_PAGES(sp) {
556 if (sp->
company == old_owner)
delete sp;
600 SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
601 SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
603 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
614 c->bankrupt_value = val;
619 assert(c->bankrupt_value > 0);
659 FOR_ALL_COMPANIES(c) {
667 FOR_ALL_STATIONS(st) {
674 FOR_ALL_COMPANIES(c) {
698 FOR_ALL_COMPANIES(c) {
766 for (
Price i = PR_BEGIN; i < PR_END; i++) {
771 switch (_price_base_specs[i].category) {
783 case 0: price *= 6;
break;
784 case 1: price *= 8;
break;
785 case 2: price *= 9;
break;
786 default: NOT_REACHED();
793 int shift = _price_base_multiplier[i] - 16 - 3;
806 price =
Clamp(_price_base_specs[i].start_price, -1, 1);
816 FOR_ALL_CARGOSPECS(cs) {
817 cs->current_payment = ((int64)cs->initial_payment * _economy.
inflation_payment) >> 16;
833 FOR_ALL_COMPANIES(c) {
861 static void HandleEconomyFluctuations()
868 _economy.
fluct = -12;
874 if (_economy.
fluct == 0) {
875 _economy.
fluct = -(int)
GB(Random(), 0, 2);
877 }
else if (_economy.
fluct == -12) {
878 _economy.
fluct =
GB(Random(), 0, 8) + 312;
889 memset(_price_base_multiplier, 0,
sizeof(_price_base_multiplier));
901 assert(price < PR_END);
926 void StartupEconomy()
931 _economy.
fluct =
GB(Random(), 0, 8) + 168;
960 if (index >= PR_END)
return 0;
962 Money cost = _price[index] * cost_factor;
974 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days,
CargoID cargo_type)
984 uint32 var18 =
min(dist, 0xFFFF) | (
min(num_pieces, 0xFF) << 16) | (transit_days << 24);
987 int result =
GB(callback, 0, 14);
990 if (
HasBit(callback, 14)) result -= 0x4000;
995 return result * num_pieces * cs->current_payment / 8192;
999 static const int MIN_TIME_FACTOR = 31;
1000 static const int MAX_TIME_FACTOR = 255;
1002 const int days1 = cs->transit_days[0];
1003 const int days2 = cs->transit_days[1];
1004 const int days_over_days1 =
max( transit_days - days1, 0);
1005 const int days_over_days2 =
max(days_over_days1 - days2, 0);
1017 const int time_factor =
max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
1019 return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
1047 if (ind->
index == source)
continue;
1060 _cargo_delivery_destinations.
Include(ind);
1064 num_pieces -= amount;
1086 assert(num_pieces > 0);
1111 Money profit = GetTransportedGoodsIncome(accepted,
DistanceManhattan(source_tile, st->
xy), days_in_transit, cargo_type);
1119 case 0: profit += profit >> 1;
break;
1120 case 1: profit *= 2;
break;
1121 case 2: profit *= 3;
break;
1122 default: profit *= 4;
break;
1151 if (cargo_waiting == 0)
continue;
1170 current_station(front->last_station_visited)
1174 CargoPayment::~CargoPayment()
1188 SndPlayVehicleFx(SND_14_CASHTILL, this->
front);
1193 this->front->z_pos, this->visual_transfer, -this->visual_profit);
1196 this->front->z_pos, -this->visual_profit);
1209 if (this->
owner == NULL) {
1229 Money profit = GetTransportedGoodsIncome(
1250 curr_station->loading_vehicles.push_back(front_v);
1268 for (
Vehicle *v = front_v; v != NULL; v = v->
Next()) {
1270 if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1291 uint load_amount = e->info.load_amount;
1295 if (air_mail) load_amount =
CeilDiv(load_amount, 4);
1299 if (e->
GetGRF() != NULL && e->
GetGRF()->grf_version >= 8) {
1307 if (e->
GetGRF()->grf_version < 8) cb_load_amount =
GB(cb_load_amount, 0, 8);
1308 if (cb_load_amount >= 0x100) {
1310 }
else if (cb_load_amount != 0) {
1311 load_amount = cb_load_amount;
1320 return max(1u, load_amount);
1332 template<
class Taction>
1335 for (
Vehicle *w = v; w != NULL;
1337 if (!action(w))
return false;
1340 if (train->
IsMultiheaded() && !action(train->other_multiheaded_part))
return false;
1377 consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1388 this->refit_mask |= EngInfo(v->
engine_type)->refit_mask;
1438 consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve) {}
1448 if (this->do_reserve) {
1450 &v->
cargo, st->
xy, this->next_station);
1472 uint32 refit_mask = v->
GetEngine()->info.refit_mask;
1478 if (is_auto_refit) {
1482 FOR_EACH_SET_CARGO_ID(cid, refit_mask) {
1494 (consist_capleft[cid] == consist_capleft[new_cid] &&
1503 if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1525 st(st), next_station(next_station) {}
1531 &v->
cargo, st->
xy, *next_station);
1554 assert(v->cargo_cap >= v->cargo.RemainingCount());
1559 if (!v->IsArticulatedPart() &&
1565 if (consist_capleft == NULL || v->cargo_cap == 0)
continue;
1566 (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1584 ticks += (overhang * ticks) / 8;
1623 int new_load_unload_ticks = 0;
1624 bool dirty_vehicle =
false;
1625 bool dirty_station =
false;
1627 bool completely_emptied =
true;
1628 bool anything_unloaded =
false;
1629 bool anything_loaded =
false;
1630 uint32 full_load_amount = 0;
1631 uint32 cargo_not_full = 0;
1632 uint32 cargo_full = 0;
1633 uint32 reservation_left = 0;
1639 uint artic_part = 0;
1640 for (
Vehicle *v = front; v != NULL; v = v->
Next()) {
1642 if (v->cargo_cap == 0)
continue;
1648 uint cargo_count = v->
cargo.UnloadCount();
1650 bool remaining =
false;
1652 assert(payment != NULL);
1663 if (v->cargo_cap < new_remaining) {
1665 v->cargo.Return(new_remaining - v->cargo_cap, &ge->
cargo, INVALID_STATION);
1676 anything_unloaded =
true;
1682 dirty_station =
true;
1692 amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->
cargo, payment);
1693 remaining = v->cargo.UnloadCount() > 0;
1694 if (amount_unloaded > 0) {
1695 dirty_vehicle =
true;
1696 anything_unloaded =
true;
1697 new_load_unload_ticks += amount_unloaded;
1700 st->time_since_unload = 0;
1704 completely_emptied =
false;
1719 ge = &st->
goods[v->cargo_type];
1723 v->refit_cap = v->cargo_cap;
1727 switch (front->
type) {
1741 default: NOT_REACHED();
1749 assert(v->cargo_cap >= v->cargo.StoredCount());
1752 uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1754 if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1757 uint loaded = ge->
cargo.
Load(cap_left, &v->cargo, st->
xy, next_station);
1761 SetBit(reservation_left, v->cargo_type);
1765 if (loaded == cap_left) {
1766 SetBit(full_load_amount, v->cargo_type);
1768 ClrBit(full_load_amount, v->cargo_type);
1779 completely_emptied =
false;
1780 anything_loaded =
true;
1782 st->time_since_load = 0;
1783 st->last_vehicle_type = v->type;
1791 new_load_unload_ticks += loaded;
1793 dirty_vehicle = dirty_station =
true;
1797 if (v->cargo.StoredCount() >= v->cargo_cap) {
1798 SetBit(cargo_full, v->cargo_type);
1800 SetBit(cargo_not_full, v->cargo_type);
1804 if (anything_loaded || anything_unloaded) {
1812 completely_emptied &= anything_unloaded;
1814 if (!anything_unloaded)
delete payment;
1817 if (anything_loaded || anything_unloaded) {
1821 const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1823 new_load_unload_ticks = gradual_loading_wait_time[front->
type];
1835 bool finished_loading =
true;
1841 (cargo_not_full && (cargo_full & ~cargo_not_full) == 0)) {
1842 finished_loading =
false;
1844 }
else if (cargo_not_full != 0) {
1845 finished_loading =
false;
1866 StringID percent_up_down = STR_NULL;
1875 if (completely_emptied) {
1878 dirty_vehicle =
true;
1879 TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
1882 if (dirty_vehicle) {
1887 if (dirty_station) {
1902 if (st->loading_vehicles.empty())
return;
1905 std::list<Vehicle *>::iterator iter;
1908 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1924 if (last_loading == NULL)
return;
1926 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1929 if (v == last_loading)
break;
1933 const Industry *
const *isend = _cargo_delivery_destinations.
End();
1934 for (
Industry **iid = _cargo_delivery_destinations.
Begin(); iid != isend; iid++) {
1937 _cargo_delivery_destinations.
Clear();
1951 HandleEconomyFluctuations();
1954 static void DoAcquireCompany(
Company *c)
1961 SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
1962 SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
1966 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
1972 if (c->bankrupt_value == 0) {
2016 if (!c->
is_ai)
return cost;
2031 c->bankrupt_value = 0;
2032 DoAcquireCompany(c);
2068 cost = -(cost - (cost >> 7));
2114 DoAcquireCompany(c);
Functions related to OTTD's strings.
void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
byte infl_amount_pr
inflation rate for payment rates
static bool IsLocalCompany()
Is the current company the local company?
uint RemainingCount() const
Returns the sum of cargo to be kept in the vehicle at the current station.
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
Vehicle is stopped by the player.
Money Prices[PR_END]
Prices of everything.
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
Trigger station when cargo is completely taken.
VehicleCargoList cargo
The cargo this vehicle is carrying.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
used in multiplayer to create a new companies etc.
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
IndustryVector industries_near
Cached list of industries near the station that can accept cargo,.
const ScoreInfo _score_info[]
Score info, values used for computing the detailed performance rating.
Money value
Value of the vehicle.
bool _networking
are we in networking mode?
bool operator()(Vehicle *v)
Reserve cargo from the station and update the remaining consist capacities with the vehicle's remaini...
Functions for NewGRF engines.
static void CompaniesGenStatistics()
Update the finances of all companies.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
TransportedCargoStat< uint16 > received[NUM_TE]
Cargo statistics about received cargotypes.
byte infl_amount
inflation amount
Definition of link refreshing utility.
Station * st
Station to give the returned cargo to.
Automatically choose cargo type when doing auto refitting.
Minimal stack that uses a pool to avoid pointers.
Money start_price
Default value at game start, before adding multipliers.
static int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
Multiply two integer values and shift the results to right.
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
RailType
Enumeration for all possible railtypes.
Vehicle * GetFirstEnginePart()
Get the first part of an articulated engine.
static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source)
Transfer goods from station to industry.
byte GetCount() const
Get the amount of cargos that have an amount.
EconomySettings economy
settings to change the economy
Vehicle has finished loading.
static Titem * Get(size_t index)
Returns Titem with given index.
int32 performance_history
Company score (scale 0-1000)
Functions related to dates.
static const Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
CompanyByte exclusivity
which company has exclusivity
Cargo has been delivered.
Company * owner
The owner of the vehicle.
uint32 GetRailTotal() const
Get total sum of all owned track bits.
Base for the train class.
static uint MapLogX()
Logarithm of the map size along the X side.
Year inaugurated_year
Year of starting the company.
static bool HasSignalOnTrack(TileIndex tile, Track track)
Checks for the presence of signals (either way) on the given track on the given rail tile...
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
uint32 & refit_mask
Bitmask of possible refit cargoes.
change the server interval of a vehicle
Track
These are used to specify a single track.
uint16 cur_speed
current speed
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.
query cost only, don't build.
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Replace vehicle window; Window numbers:
uint64 inflation_prices
Cumulated inflation of prices since game start; 16 bit fractional part.
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval...
uint16 _returned_refit_capacity
Stores the capacity after a refit operation.
Specification of a cargo type.
Money FeederShare() const
Gets the amount of money already paid to earlier vehicles in the feeder chain.
OrderList * list
Pointer to the order list for this vehicle.
byte block_preview
Number of quarters that the company is not allowed to get new exclusive engine previews (see Companie...
byte interest_rate
Interest.
CompanyMask bankrupt_asked
which companies were asked about buying it?
Functions related to vehicles.
Set when cargo was delivered for final delivery this month.
uint16 callback_mask
Bitmask of industry callbacks that have to be called.
uint32 current_order_time
How many ticks have passed since this order started.
uint TotalCount() const
Returns total count of cargo at the station, including cargo which is already reserved for loading...
Struct about goals, current and completed.
Price
Enumeration of all base prices for use with Prices.
CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Acquire shares in an opposing company.
Build vehicle; Window numbers:
PrepareRefitAction(CargoArray &consist_capleft, uint32 &refit_mask)
Create a refit preparation action.
Called to calculate the income of delivered cargo.
void Clear()
Remove all items from the list.
Action for returning reserved cargo.
void Change(const U &new_value)
Change the value of the variable.
Defines the internal data of a functional industry.
const T * Begin() const
Get the pointer to the first item (const)
custom profit calculation
DifficultySettings difficulty
settings related to the difficulty
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Stores station stats for a single cargo.
Tindex index
Index of this pool item.
void IndustryProductionCallback(Industry *ind, int reason)
Get the industry production callback and apply it to the industry.
static Money SignalMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of signals.
byte months_of_bankruptcy
Number of months that the company is unable to pay its debts.
This must always be the last entry.
TileIndex SourceStationXY() const
Gets the coordinates of the cargo's source station.
Payment rates graph; Window numbers:
Company value graph; Window numbers:
byte subsidy_multiplier
amount of subsidy
static SigSegState UpdateSignalsInBuffer(Owner owner)
Updates blocks in _globset buffer.
Vehicle is unloading cargo.
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
Representation of a waypoint.
StationID last_station_visited
The last station we stopped at.
The client is spectating.
Simple vector template class.
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Money GetCost() const
The costs as made up to this moment.
byte was_cargo_delivered
flag that indicate this has been the closest industry chosen for cargo delivery by a station...
Refit preparation action.
static uint MapLogY()
Logarithm of the map size along the y side.
int32 lateness_counter
How many ticks late (or early if negative) this vehicle is.
FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve)
Create a finalizing action.
uint32 station
Count of company owned station tiles.
Common return value for all commands.
StationIDStack & next_station
Next hops to reserve cargo for.
RoadType
The different roadtypes we support.
StationCargoList cargo
The cargo packets of cargo waiting in this station.
static T max(const T a, const T b)
Returns the maximum of two values.
Town * town
The town this station is associated with.
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...
bool HasRating() const
Does this cargo have a rating at this station?
uint32 max_loan
the maximum initial loan
Types related to cargoes...
Year _cur_year
Current year, starting at 0.
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
uint16 incoming_cargo_waiting[3]
incoming cargo waiting to be processed
bool improved_load
improved loading algorithm
uint Return(uint max_move, StationCargoList *dest, StationID next_station)
Returns reserved cargo to the station and removes it from the cache.
bool infrastructure_maintenance
enable monthly maintenance fee for owner infrastructure
static Aircraft * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Tstorage new_act
Actually transported this month.
static const int MIN_PRICE_MODIFIER
Maximum NewGRF price modifiers.
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
CompanySettings settings
settings specific for each company
const T * End() const
Get the pointer behind the last valid item (const)
Trigger platform when train loads/unloads.
Generates sequence of free UnitID numbers.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
uint Load(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next)
Loads cargo onto a vehicle.
void DeleteCompanyWindows(CompanyID company)
Delete all windows of a company.
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow. ...
static const uint TILE_SIZE
Tile size in world coordinates.
GoodsEntry goods[NUM_CARGO]
Goods at this station.
uint32 industry_daily_increment
The value which will increment industry_daily_change_counter. Computed value. NOSAVE.
bool operator()(const Vehicle *v)
Checks if the vehicle has stored cargo.
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
CargoArray & consist_capleft
Capacities left in the consist.
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoID cargo_type)
Check whether an industry temporarily refuses to accept a certain cargo.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
uint16 servint_ships
service interval for ships
Money profit_last_year
Profit last year << 8, low 8 bits are fract.
CargoID ct
The currently handled cargo type.
void InitializeEconomy()
Resets economy to initial values.
Class to backup a specific variable and restore it later.
CompanyByte _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
company bankrupts, skip money check, skip vehicle on tile check in some cases
bool allow_shares
allow the buying/selling of shares
uint32 always_accepted
Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn't accept c...
void AddCargoDelivery(CargoID cargo_type, CompanyID company, uint32 amount, SourceType src_type, SourceID src, const Station *st)
Cargo was delivered to its final destination, update the pickup and delivery maps.
uint16 multiplier
Capacity multiplier for vehicles. (8 fractional bits)
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Income graph; Window numbers:
Money expenses
The amount of expenses.
static const size_t MAX_SIZE
Make template parameter accessible from outside.
SourceID SourceSubsidyID() const
Gets the ID of the cargo's source.
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
TrackBits
Bitfield corresponding to Track.
TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
Display vehicle loading indicators.
uint16 cargo_cap
total capacity
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Transfer the cargo to the station.
Struct about stories, current and completed.
Some methods of Pool are placed here in order to reduce compilation time and binary size...
uint32 signal
Count of company owned signals.
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a give tiletype.
Triggered when a cargo type is completely removed from the station (for all tiles at the same time)...
How many scores are there..
bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
May company cbig buy company csmall?
byte num_valid_stat_ent
Number of valid statistical entries in old_economy.
static void LoadUnloadVehicle(Vehicle *front)
Loads/unload the vehicle if possible.
UnitID unitnumber
unit number, for display purposes only
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
This indicates whether a cargo has a rating at the station.
uint Length() const
Get the number of items in the list.
byte DaysInTransit() const
Gets the number of days this cargo has been in transit.
Vehicle * front
The front vehicle to do the payment of.
uint16 produced_cargo_waiting[2]
amount of cargo produced per cargo
bool IsRefit() const
Is this order a refit order.
Price is affected by "construction cost" difficulty setting.
int16 ratings[MAX_COMPANIES]
ratings of each company for this town
VehicleDefaultSettings vehicle
default settings for vehicles
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Buy up another company.
Don't load anymore during the next load cycle.
bool IsType(OrderType type) const
Check whether this order is of the given type.
DoCommandFlag
List of flags for a command.
Money current_loan
Amount of money borrowed from the bank.
Money PayTransfer(const CargoPacket *cp, uint count)
Handle payment for transfer of the given cargo packet.
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
ClientSettings _settings_client
The current settings for this game.
bool operator()(const Vehicle *v)
Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and adding th...
byte status
Status of this cargo, see GoodsEntryStatus.
Money visual_profit
The visual profit to show.
void UpdateCompanyHQ(TileIndex tile, uint score)
Update the CompanyHQ to the state associated with the given score.
Money AirportMaintenanceCost(Owner owner)
Calculates the maintenance cost of all airports of a company.
bool Succeeded() const
Did this command succeed?
Container for cargo from the same location and time.
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
TileIndex location_of_HQ
Northern tile of HQ; INVALID_TILE when there is none.
Definition of base types and functions in a cross-platform compatible way.
virtual ExpensesType GetExpenseType(bool income) const
Sets the expense type associated to this vehicle type.
void NetworkClientsToSpectators(CompanyID cid)
Move the clients of a company to the spectators.
uint32 road[ROADTYPE_END]
Count of company owned track bits for each road type.
A number of safeguards to prevent using unsafe methods.
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
IndustryType type
type of industry.
void PayFinalDelivery(const CargoPacket *cp, uint count)
Handle payment for final delivery of the given cargo packet.
bool inflation
disable inflation
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
CargoID accepts_cargo[3]
3 input cargo slots
int score
How much score it will give.
uint8 callback_mask
Bitmask of cargo callbacks that have to be called.
Money route_profit
The amount of money to add/remove from the bank account.
Station * st
Station to reserve cargo from.
Operating profit graph; Window numbers:
Company league window; Window numbers:
CargoID cargo_type
type of cargo this vehicle is carrying
CargoPayment()
Constructor for pool saveload.
GUI Functions related to companies.
Trigger when cargo is received .
uint16 load_unload_ticks
Ticks to wait before starting next cycle.
Normal news item. (Newspaper with text only)
CompanyByte awarded
Subsidy is awarded to this company; INVALID_COMPANY if it's not awarded to anyone.
Money CalculateCompanyValue(const Company *c, bool including_loan)
Calculate the value of the company.
byte misc_flags
Miscellaneous flags.
byte vehicle_costs
amount of money spent on vehicle running cost
TileIndex tile
Current tile index.
Road vehicle list; Window numbers:
Defines the data structure for constructing industry.
void ClearCargoPickupMonitoring(CompanyID company)
Clear all pick-up cargo monitors.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
The tile has no ownership.
bool HasArticulatedPart() const
Check if an engine has an articulated part.
Money money
Money owned by the company.
Station view; Window numbers:
OrderLoadFlags GetLoadType() const
How must the consist be loaded?
Basic functions/variables used all over the place.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
StationFacilityByte facilities
The facilities that this station has.
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
Industry view; Window numbers:
#define lengthof(x)
Return the length of an fixed size array.
byte last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
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 autoref...
CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Sell shares in an opposing company.
SourceType SourceSubsidyType() const
Gets the type of the cargo's source.
uint Reserve(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next)
Reserves cargo for loading onto the vehicle.
static T min(const T a, const T b)
Returns the minimum of two values.
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
static bool EconomyIsInRecession()
Is the economy in recession?
Helper class to perform the cargo payment.
Deliver the cargo to some town or industry.
static bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
bool CheckSubsidised(CargoID cargo_type, CompanyID company, SourceType src_type, SourceID src, const Station *st)
Tests whether given delivery is subsidised and possibly awards the subsidy to delivering company...
Functions related to sound.
static void RemoveAllEngineReplacementForCompany(Company *c)
Remove all engine replacement settings for the given company.
void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
Change the ownership of all the items of a company.
static const Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Money max_loan
NOSAVE: Maximum possible loan.
void CompanyAdminUpdate(const Company *company)
Called whenever company related information changes in order to notify admins.
Vehicle * First() const
Get the first vehicle of this vehicle chain.
NewGRF handling of industry tiles.
The max score that can be in the performance history.
byte last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
CompanyByte company
StoryPage is for a specific company; INVALID_COMPANY if it is global.
Action for finalizing a refit.
void UpdateLevelCrossing(TileIndex tile, bool sound=true)
Sets correct crossing state.
static void Stop(CompanyID company)
Stop a company to be controlled by an AI.
Maximum number of companies.
void ClearCargoDeliveryMonitoring(CompanyID company)
Clear all delivery cargo monitors.
ReturnCargoAction(Station *st, StationID next_one)
Construct a cargo return action.
int16 bankrupt_timeout
If bigger than 0, amount of time to wait for an answer on an offer to buy this company.
bool IterateVehicleParts(Vehicle *v, Taction action)
Iterate the articulated parts of a vehicle, also considering the special cases of "normal" aircraft a...
Year build_year
Year the vehicle has been built.
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Transfer all cargo onto the platform.
NewGRF handling of airport tiles.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
StationID next_hop
Next hop the cargo should be assigned to.
Base class for all pools.
Station list; Window numbers:
static bool HasSignals(TileIndex t)
Checks if a rail tile has signals.
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
OrderUnloadFlags GetUnloadType() const
How must the consist be unloaded?
uint16 input_cargo_multiplier[3][2]
Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes) ...
Struct about subsidies, offered and awarded.
'Train' is either a loco or a wagon.
SourceType
Types of cargo source and destination.
Performance detail window; Window numbers:
bool IsEngineCountable() const
Check if a vehicle is counted in num_engines in each company struct.
void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
Update vehicle loading indicators.
Month _cur_month
Current month (0..11)
OwnerByte owner
The owner of this station.
static TrackBits GetTrackBits(TileIndex tile)
Gets the track bits of the given tile.
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
uint32 rail[RAILTYPE_END]
Count of company owned track bits for each rail type.
static void TriggerIndustryProduction(Industry *i)
Inform the industry about just delivered cargo DeliverGoodsToIndustry() silently incremented incoming...
execute the given command
Company infrastructure overview; Window numbers:
Keep the cargo in the vehicle.
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Set when a vehicle ever delivered cargo to the station for final delivery.
static uint GetLoadAmount(Vehicle *v)
Gets the amount of cargo the given vehicle can load in the current tick.
static int32 ClampToI32(const int64 a)
Reduce a signed 64-bit int to a signed 32-bit one.
Functions related to companies.
void TriggerIndustry(Industry *ind, IndustryTileTrigger trigger)
Trigger a random trigger for all industry tiles.
TileIndex LoadedAtXY() const
Gets the coordinates of the cargo's last loading station.
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
void SetCargo(CargoID ct)
Sets the currently handled cargo type.
uint16 GetTimetabledWait() const
Get the time in ticks a vehicle should wait at the destination or 0 if it's not timetabled.
static uint MapSize()
Get the size of the map.
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies...
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Class for storing amounts of cargo.
Determine the amount of cargo to load per unit of time when using gradual loading.
static const uint MAX_HISTORY_QUARTERS
The maximum number of quarters kept as performance's history.
Header file for NewGRF stations.
static void CompanyCheckBankrupt(Company *c)
Check for bankruptcy of a company.
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
void CompaniesMonthlyLoop()
Monthly update of the economic data (of the companies as well as economic fluctuations).
GUISettings gui
settings related to the GUI
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
CompanyByte company
Goal is for a specific company; INVALID_COMPANY if it is global.
static Track RemoveFirstTrack(TrackBits *tracks)
Removes first Track from TrackBits and returns it.
void RecomputePrices()
Computes all prices, payments and maximum loan.
Whenever cargo payment is made for a vehicle.
static Money StationMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of station tiles.
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Action to check if a vehicle has no stored cargo.
bool gradual_loading
load vehicles gradually
CompanyByte _current_company
Company currently doing an action.
static SmallIndustryList _cargo_delivery_destinations
The industries we've currently brought cargo to.
Ships list; Window numbers:
uint32 TileIndex
The index/ID of a Tile.
Functions related to objects.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Cargo support for NewGRFs.
OwnerByte share_owners[4]
Owners of the 4 shares of the company. INVALID_OWNER if nobody has bought them yet.
uint16 servint_trains
service interval for trains
static const uint64 MAX_INFLATION
Maximum inflation (including fractional part) without causing overflows in int64 price computations...
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32 ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32 ref2=UINT32_MAX, void *free_data=NULL)
Add a new newsitem to be shown.
Vehicle * Next() const
Get the next vehicle of this vehicle.
sell a share from a company
The company went belly-up.
CargoPayment * cargo_payment
The cargo payment we're currently in.
static bool IsLevelCrossingTile(TileIndex t)
Return whether a tile is a level crossing tile.
OrderSettings order
settings related to orders
CargoArray delivered_cargo
The amount of delivered cargo.
Source/destination is an industry.
int UpdateCompanyRatingAndValue(Company *c, bool update)
if update is set to true, the economy is updated with this score (also the house is updated...
uint16 SourceID
Contains either industry ID, town ID or company ID (or INVALID_SOURCE)
Cargo transport monitoring declarations.
bool servint_ispercent
service intervals are in percents
OwnerByte owner
Which company owns the vehicle?
StationIDStack GetNextStoppingStation() const
Get the next station the vehicle will stop at.
UnitID NextID()
Returns next free UnitID.
TileIndex xy
Base tile of the station.
Trigger platform when train loads/unloads.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
uint16 cached_total_length
Length of the whole vehicle (valid only for the first engine).
Trains list; Window numbers:
CompanyEconomyEntry old_economy[MAX_HISTORY_QUARTERS]
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
Full load all cargoes of the consist.
void SubtractMoneyFromCompany(CommandCost cost)
Subtract money from the _current_company, if the company is valid.
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
bool Include(const T &item)
Tests whether a item is present in the vector, and appends it to the end if not.
call production callback when cargo arrives at the industry
uint32 industry_daily_change_counter
Bits 31-16 are number of industry to be performed, 15-0 are fractional collected daily.
int16 fluct
Economy fluctuation status.
uint8 loading_indicators
show loading indicators
uint64 inflation_payment
Cumulated inflation of cargo paypent since game start; 16 bit fractional part.
uint16 servint_aircraft
service interval for aircraft
uint8 exclusive_counter
months till the exclusivity expires
Totally no unloading will be done.
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
static Money CanalMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of canal tiles.
Aircraft list; Window numbers:
Vehicle details; Window numbers:
static uint CountBits(T value)
Counts the number of set bits in a variable.
Base functions for all Games.
Functions related to commands.
Network functions used by other parts of OpenTTD.
bool _network_server
network-server is active
CargoPaymentPool _cargo_payment_pool("CargoPayment")
The actual pool to store cargo payments in.
uint8 CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
Calculates how full a vehicle is.
bool HasCargoFor(StationIDStack next) const
Check for cargo headed for a specific station.
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
Base classes related to the economy.
uint ReservedCount() const
Returns sum of reserved cargo.
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Load the cargo from the station.
void StartupIndustryDailyChanges(bool init_counter)
Initialize the variables that will maintain the daily industry change system.
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
Delivered cargo graph; Window numbers:
ScoreID
Score categories in the detailed performance rating.
void ChangeWindowOwner(Owner old_owner, Owner new_owner)
Change the owner of all the windows one company can take over from another company in the case of a c...
bool economy
how volatile is the economy
void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
Display animated feeder income.
Price is affected by "vehicle running cost" difficulty setting.
Statistics about the economy.
EngineID engine_type
The type of engine used for this vehicle.
OwnerByte owner
Group Owner.
byte initial_interest
amount of interest (to pay over the loan)
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
bool IsValid() const
Tests for validity of this cargospec.
Functions related to NewGRF provided sounds.
void Restore()
Restore the variable.
Base functions for all AIs.
#define FOR_ALL_VEHICLES(var)
Iterate over all vehicles.
Data structure for storing how the score is computed for a single score id.
bool AddInflation(bool check_year)
Add monthly inflation.
int needed
How much you need to get the perfect score.
Date last_cargo_accepted_at
Last day cargo was accepted by this industry.
GameCreationSettings game_creation
settings used during the creation of a game (map)
uint AvailableCount() const
Returns sum of cargo still available for loading at the sation.
uint16 servint_roadveh
service interval for road vehicles
byte CargoID
Cargo slots to indicate a cargo type within a game.
Money income
The amount of income.
Owner
Enum for all companies/owners.
static void CompaniesPayInterest()
Let all companies pay the monthly interest on their loan.
Money company_value
The value of the company.
byte time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
Functions related to water (management)
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Force unloading all cargo onto the platform, possibly not getting paid.
union Vehicle::@46 orders
The orders currently assigned to the vehicle.
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
CompanyEconomyEntry cur_economy
Economic data of the company of this quarter.
Use the new capacity algorithm. The default cargotype of the vehicle does not affect capacity multipl...
static Money RailMaintenanceCost(RailType railtype, uint32 num, uint32 total_num)
Calculates the maintenance cost of a number of track bits.
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Trigger station when cargo is completely taken.
Functions related to news.
Base classes/functions for stations.
call production callback every 256 ticks
CargoArray & consist_capleft
Capacities left in the consist.
VehicleCache vcache
Cache of often used vehicle values.
static Station * Get(size_t index)
Gets station with given index.
Date _date
Current date in days (day counter)
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const
Determines the REMAINING length of a platform, starting at (and including) the given tile...
Functions related to autoreplacing.
StationID current_station
The current station.
Company view; Window numbers:
static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
Refit a vehicle in a station.
byte construction_cost
how expensive is building
Full load a single cargo of the consist.
uint8 feeder_payment_share
percentage of leg payment to virtually pay in feeder systems
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
VehicleTypeByte type
Type of vehicle.
Year starting_year
starting date
Base class and functions for all vehicles that move through ground.
Class for backupping variables and making sure they are restored later.
Functions related to subsidies.
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
static Money RoadMaintenanceCost(RoadType roadtype, uint32 num)
Calculates the maintenance cost of a number of road bits.
Set when the station accepts the cargo currently for final deliveries.
Order current_order
The current order (+ status, like: loading)
bool do_reserve
If the vehicle should reserve.
const T GetSum() const
Get the sum of all cargo amounts.
Performance history graph; Window numbers:
#define FOR_ALL_WAYPOINTS(var)
Iterate over all waypoints.
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
CompanyMask have_ratings
which companies have a rating
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
CargoID GetRefitCargo() const
Get the cargo to to refit to.
bool operator()(Vehicle *v)
Return all reserved cargo from a vehicle.
SpriteID colourmap
NOSAVE: cached colour mapping.
Economic changes (recession, industry up/dowm)
Dynamic data of a loaded NewGRF.
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Interest payments over the loan.
uint32 water
Count of company owned track bits for canals.
Money visual_transfer
The transfer credits to be shown.