Increase the number of road and tram subtypes to 32.
[openttd-joker.git] / src / economy.cpp
blob6c95607adfec563ffdee51ef9f762a0da38fdf7f
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file economy.cpp Handling of the economy. */
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "command_func.h"
15 #include "industry.h"
16 #include "town.h"
17 #include "news_func.h"
18 #include "network/network.h"
19 #include "network/network_func.h"
20 #include "ai/ai.hpp"
21 #include "aircraft.h"
22 #include "train.h"
23 #include "newgrf_engine.h"
24 #include "engine_base.h"
25 #include "ground_vehicle.hpp"
26 #include "newgrf_cargo.h"
27 #include "newgrf_sound.h"
28 #include "newgrf_industrytiles.h"
29 #include "newgrf_station.h"
30 #include "newgrf_airporttiles.h"
31 #include "object.h"
32 #include "strings_func.h"
33 #include "date_func.h"
34 #include "vehicle_func.h"
35 #include "sound_func.h"
36 #include "autoreplace_func.h"
37 #include "company_gui.h"
38 #include "signs_base.h"
39 #include "subsidy_base.h"
40 #include "subsidy_func.h"
41 #include "station_base.h"
42 #include "waypoint_base.h"
43 #include "triphistory.h"
44 #include "economy_base.h"
45 #include "core/pool_func.hpp"
46 #include "core/backup_type.hpp"
47 #include "cargo_type.h"
48 #include "water.h"
49 #include "game/game.hpp"
50 #include "cargomonitor.h"
51 #include "goal_base.h"
52 #include "story_base.h"
53 #include "linkgraph/refresh.h"
54 #include "tbtr_template_vehicle.h"
56 #include "table/strings.h"
57 #include "table/pricebase.h"
59 #include "safeguards.h"
62 /* Initialize the cargo payment-pool */
63 CargoPaymentPool _cargo_payment_pool("CargoPayment");
64 INSTANTIATE_POOL_METHODS(CargoPayment)
66 /**
67 * Multiply two integer values and shift the results to right.
69 * This function multiplies two integer values. The result is
70 * shifted by the amount of shift to right.
72 * @param a The first integer
73 * @param b The second integer
74 * @param shift The amount to shift the value to right.
75 * @return The shifted result
77 static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
79 return (int32)((int64)a * (int64)b >> shift);
82 typedef SmallVector<Industry *, 16> SmallIndustryList;
84 /**
85 * Score info, values used for computing the detailed performance rating.
87 const ScoreInfo _score_info[] = {
88 { 120, 100}, // SCORE_VEHICLES
89 { 80, 100}, // SCORE_STATIONS
90 { 10000, 100}, // SCORE_MIN_PROFIT
91 { 50000, 50}, // SCORE_MIN_INCOME
92 { 100000, 100}, // SCORE_MAX_INCOME
93 { 40000, 400}, // SCORE_DELIVERED
94 { 8, 50}, // SCORE_CARGO
95 {10000000, 50}, // SCORE_MONEY
96 { 250000, 50}, // SCORE_LOAN
97 { 0, 0} // SCORE_TOTAL
100 int _score_part[MAX_COMPANIES][SCORE_END];
101 Economy _economy;
102 Prices _price;
103 Money _additional_cash_required;
104 static PriceMultipliers _price_base_multiplier;
107 * Calculate the value of the company. That is the value of all
108 * assets (vehicles, stations, etc) and money minus the loan,
109 * except when including_loan is \c false which is useful when
110 * we want to calculate the value for bankruptcy.
111 * @param c the company to get the value of.
112 * @param including_loan include the loan in the company value.
113 * @return the value of the company.
115 Money CalculateCompanyValue(const Company *c, bool including_loan)
117 Owner owner = c->index;
119 Station *st;
120 uint num = 0;
122 FOR_ALL_STATIONS(st) {
123 if (st->owner == owner) num += CountBits((byte)st->facilities);
126 Money value = num * _price[PR_STATION_VALUE] * 25;
128 Vehicle *v;
129 FOR_ALL_VEHICLES(v) {
130 if (v->owner != owner) continue;
132 if (v->type == VEH_TRAIN ||
133 v->type == VEH_ROAD ||
134 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) ||
135 v->type == VEH_SHIP) {
136 value += v->value * 3 >> 1;
140 /* Add real money value */
141 if (including_loan) value -= c->current_loan;
142 value += c->money;
144 return max(value, (Money)1);
148 * if update is set to true, the economy is updated with this score
149 * (also the house is updated, should only be true in the on-tick event)
150 * @param update the economy with calculated score
151 * @param c company been evaluated
152 * @return actual score of this company
155 int UpdateCompanyRatingAndValue(Company *c, bool update)
157 Owner owner = c->index;
158 int score = 0;
160 memset(_score_part[owner], 0, sizeof(_score_part[owner]));
162 /* Count vehicles */
164 Vehicle *v;
165 Money min_profit = 0;
166 bool min_profit_first = true;
167 uint num = 0;
169 FOR_ALL_VEHICLES(v) {
170 if (v->owner != owner) continue;
171 if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
172 if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
173 if (v->age > 730) {
174 /* Find the vehicle with the lowest amount of profit */
175 if (min_profit_first || min_profit > v->profit_last_year) {
176 min_profit = v->profit_last_year;
177 min_profit_first = false;
183 min_profit >>= 8; // remove the fract part
185 _score_part[owner][SCORE_VEHICLES] = num;
186 /* Don't allow negative min_profit to show */
187 if (min_profit > 0) {
188 _score_part[owner][SCORE_MIN_PROFIT] = ClampToI32(min_profit);
192 /* Count stations */
194 uint num = 0;
195 const Station *st;
197 FOR_ALL_STATIONS(st) {
198 /* Only count stations that are actually serviced */
199 if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
201 _score_part[owner][SCORE_STATIONS] = num;
204 /* Generate statistics depending on recent income statistics */
206 int numec = min(c->num_valid_stat_ent, 12);
207 if (numec != 0) {
208 const CompanyEconomyEntry *cee = c->old_economy;
209 Money min_income = cee->income + cee->expenses;
210 Money max_income = cee->income + cee->expenses;
212 do {
213 min_income = min(min_income, cee->income + cee->expenses);
214 max_income = max(max_income, cee->income + cee->expenses);
215 } while (++cee, --numec);
217 if (min_income > 0) {
218 _score_part[owner][SCORE_MIN_INCOME] = ClampToI32(min_income);
221 _score_part[owner][SCORE_MAX_INCOME] = ClampToI32(max_income);
225 /* Generate score depending on amount of transported cargo */
227 int numec = min(c->num_valid_stat_ent, 4);
228 if (numec != 0) {
229 const CompanyEconomyEntry *cee = c->old_economy;
230 OverflowSafeInt64 total_delivered = 0;
231 do {
232 total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
233 } while (++cee, --numec);
235 _score_part[owner][SCORE_DELIVERED] = ClampToI32(total_delivered);
239 /* Generate score for variety of cargo */
241 _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
244 /* Generate score for company's money */
246 if (c->money > 0) {
247 _score_part[owner][SCORE_MONEY] = ClampToI32(c->money);
251 /* Generate score for loan */
253 _score_part[owner][SCORE_LOAN] = ClampToI32(_score_info[SCORE_LOAN].needed - c->current_loan);
256 /* Now we calculate the score for each item.. */
258 int total_score = 0;
259 int s;
260 score = 0;
261 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
262 /* Skip the total */
263 if (i == SCORE_TOTAL) continue;
264 /* Check the score */
265 s = Clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
266 score += s;
267 total_score += _score_info[i].score;
270 _score_part[owner][SCORE_TOTAL] = score;
272 /* We always want the score scaled to SCORE_MAX (1000) */
273 if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
276 if (update) {
277 c->old_economy[0].performance_history = score;
278 UpdateCompanyHQ(c->location_of_HQ, score);
279 c->old_economy[0].company_value = CalculateCompanyValue(c);
282 SetWindowDirty(WC_PERFORMANCE_DETAIL, 0);
283 return score;
287 * Change the ownership of all the items of a company.
288 * @param old_owner The company that gets removed.
289 * @param new_owner The company to merge to, or INVALID_OWNER to remove the company.
291 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
293 /* We need to set _current_company to old_owner before we try to move
294 * the client. This is needed as it needs to know whether "you" really
295 * are the current local company. */
296 Backup<CompanyByte> cur_company(_current_company, old_owner, FILE_LINE);
297 #ifdef ENABLE_NETWORK
298 /* In all cases, make spectators of clients connected to that company */
299 if (_networking) NetworkClientsToSpectators(old_owner);
300 #endif /* ENABLE_NETWORK */
301 if (old_owner == _local_company) {
302 /* Single player cheated to AI company.
303 * There are no spectators in single player, so we must pick some other company. */
304 assert(!_networking);
305 Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
306 Company *c;
307 FOR_ALL_COMPANIES(c) {
308 if (c->index != old_owner) {
309 SetLocalCompany(c->index);
310 break;
313 cur_company2.Restore();
314 assert(old_owner != _local_company);
317 Town *t;
319 assert(old_owner != new_owner);
322 Company *c;
323 uint i;
325 /* See if the old_owner had shares in other companies */
326 FOR_ALL_COMPANIES(c) {
327 for (i = 0; i < 4; i++) {
328 if (c->share_owners[i] == old_owner) {
329 /* Sell his shares */
330 CommandCost res = DoCommand(0, c->index, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
331 /* Because we are in a DoCommand, we can't just execute another one and
332 * expect the money to be removed. We need to do it ourself! */
333 SubtractMoneyFromCompany(res);
338 /* Sell all the shares that people have on this company */
339 Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
340 c = Company::Get(old_owner);
341 for (i = 0; i < 4; i++) {
342 cur_company2.Change(c->share_owners[i]);
343 if (_current_company != INVALID_OWNER) {
344 /* Sell the shares */
345 CommandCost res = DoCommand(0, old_owner, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
346 /* Because we are in a DoCommand, we can't just execute another one and
347 * expect the money to be removed. We need to do it ourself! */
348 SubtractMoneyFromCompany(res);
351 cur_company2.Restore();
354 /* Temporarily increase the company's money, to be sure that
355 * removing his/her property doesn't fail because of lack of money.
356 * Not too drastically though, because it could overflow */
357 if (new_owner == INVALID_OWNER) {
358 Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
361 Subsidy *s;
362 FOR_ALL_SUBSIDIES(s) {
363 if (s->awarded == old_owner) {
364 if (new_owner == INVALID_OWNER) {
365 delete s;
366 } else {
367 s->awarded = new_owner;
371 if (new_owner == INVALID_OWNER) RebuildSubsidisedSourceAndDestinationCache();
373 /* Take care of rating and transport rights in towns */
374 FOR_ALL_TOWNS(t) {
375 /* If a company takes over, give the ratings to that company. */
376 if (new_owner != INVALID_OWNER) {
377 if (HasBit(t->have_ratings, old_owner)) {
378 if (HasBit(t->have_ratings, new_owner)) {
379 /* use max of the two ratings. */
380 t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]);
381 } else {
382 SetBit(t->have_ratings, new_owner);
383 t->ratings[new_owner] = t->ratings[old_owner];
388 /* Reset the ratings for the old owner */
389 t->ratings[old_owner] = RATING_INITIAL;
390 ClrBit(t->have_ratings, old_owner);
392 /* Transfer exclusive rights */
393 if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
394 if (new_owner != INVALID_OWNER) {
395 t->exclusivity = new_owner;
396 } else {
397 t->exclusive_counter = 0;
398 t->exclusivity = INVALID_COMPANY;
404 Vehicle *v;
405 FOR_ALL_VEHICLES(v) {
406 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
407 if (new_owner == INVALID_OWNER) {
408 if (v->Previous() == nullptr) delete v;
409 } else {
410 if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
411 if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
417 /* In all cases clear replace engine rules.
418 * Even if it was copied, it could interfere with new owner's rules */
419 RemoveAllEngineReplacementForCompany(Company::Get(old_owner));
421 if (new_owner == INVALID_OWNER) {
422 RemoveAllGroupsForCompany(old_owner);
423 } else {
424 Group *g;
425 FOR_ALL_GROUPS(g) {
426 if (g->owner == old_owner) g->owner = new_owner;
431 FreeUnitIDGenerator unitidgen[] = {
432 FreeUnitIDGenerator(VEH_TRAIN, new_owner), FreeUnitIDGenerator(VEH_ROAD, new_owner),
433 FreeUnitIDGenerator(VEH_SHIP, new_owner), FreeUnitIDGenerator(VEH_AIRCRAFT, new_owner)
436 /* Override company settings to new company defaults in case we need to convert them.
437 * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
439 if (new_owner != INVALID_OWNER) {
440 Company *old_company = Company::Get(old_owner);
441 Company *new_company = Company::Get(new_owner);
443 old_company->settings.vehicle.servint_aircraft = new_company->settings.vehicle.servint_aircraft;
444 old_company->settings.vehicle.servint_trains = new_company->settings.vehicle.servint_trains;
445 old_company->settings.vehicle.servint_roadveh = new_company->settings.vehicle.servint_roadveh;
446 old_company->settings.vehicle.servint_ships = new_company->settings.vehicle.servint_ships;
447 old_company->settings.vehicle.servint_ispercent = new_company->settings.vehicle.servint_ispercent;
450 Vehicle *v;
451 FOR_ALL_VEHICLES(v) {
452 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
453 assert(new_owner != INVALID_OWNER);
455 /* Correct default values of interval settings while maintaining custom set ones.
456 * This prevents invalid values on mismatching company defaults being accepted.
458 if (!v->ServiceIntervalIsCustom()) {
459 Company *new_company = Company::Get(new_owner);
461 /* Technically, passing the interval is not needed as the command will query the default value itself.
462 * However, do not rely on that behaviour.
464 int interval = CompanyServiceInterval(new_company, v->type);
465 DoCommand(v->tile, v->index, interval | (new_company->settings.vehicle.servint_ispercent << 17), DC_EXEC | DC_BANKRUPT, CMD_CHANGE_SERVICE_INT);
468 v->owner = new_owner;
470 /* Owner changes, clear cache */
471 v->colourmap = PAL_NONE;
472 v->InvalidateNewGRFCache();
474 if (v->IsEngineCountable()) {
475 GroupStatistics::CountEngine(v, 1);
477 if (v->IsPrimaryVehicle()) {
478 GroupStatistics::CountVehicle(v, 1);
479 v->unitnumber = unitidgen[v->type].NextID();
482 /* Invalidate the vehicle's cargo payment "owner cache". */
483 if (v->cargo_payment != nullptr) v->cargo_payment->owner = nullptr;
487 if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
490 /* Change ownership of template vehicles */
491 if (new_owner == INVALID_OWNER) {
492 TemplateVehicle *tv;
493 FOR_ALL_TEMPLATES(tv) {
494 if (tv->owner == old_owner) {
495 TemplateReplacement *tr;
496 FOR_ALL_TEMPLATE_REPLACEMENTS(tr) {
497 if (tr->Template() == tv->index) {
498 delete tr;
501 delete tv;
504 } else {
505 TemplateVehicle *tv;
506 FOR_ALL_TEMPLATES(tv) {
507 if (tv->owner == old_owner) tv->owner = new_owner;
511 /* Change ownership of tiles */
513 TileIndex tile = 0;
514 do {
515 ChangeTileOwner(tile, old_owner, new_owner);
516 } while (++tile != MapSize());
518 if (new_owner != INVALID_OWNER) {
519 /* Update all signals because there can be new segment that was owned by two companies
520 * and signals were not propagated
521 * Similar with crossings - it is needed to bar crossings that weren't before
522 * because of different owner of crossing and approaching train */
523 tile = 0;
525 do {
526 if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
527 TrackBits tracks = GetTrackBits(tile);
528 do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
529 Track track = RemoveFirstTrack(&tracks);
530 if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
531 } while (tracks != TRACK_BIT_NONE);
532 } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
533 UpdateLevelCrossing(tile);
535 } while (++tile != MapSize());
538 /* update signals in buffer */
539 UpdateSignalsInBuffer();
542 /* Add airport infrastructure count of the old company to the new one. */
543 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
545 /* convert owner of stations (including deleted ones, but excluding buoys) */
546 Station *st;
547 FOR_ALL_STATIONS(st) {
548 if (st->owner == old_owner) {
549 /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
550 * also, drawing station window would cause reading invalid company's colour */
551 st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
555 /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
556 Waypoint *wp;
557 FOR_ALL_WAYPOINTS(wp) {
558 if (wp->owner == old_owner) {
559 wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
563 Sign *si;
564 FOR_ALL_SIGNS(si) {
565 if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
568 /* Remove Game Script created Goals, CargoMonitors and Story pages. */
569 Goal *g;
570 FOR_ALL_GOALS(g) {
571 if (g->company == old_owner) delete g;
574 ClearCargoPickupMonitoring(old_owner);
575 ClearCargoDeliveryMonitoring(old_owner);
577 StoryPage *sp;
578 FOR_ALL_STORY_PAGES(sp) {
579 if (sp->company == old_owner) delete sp;
582 /* Change colour of existing windows */
583 if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
585 cur_company.Restore();
587 MarkWholeScreenDirty();
591 * Check for bankruptcy of a company. Called every three months.
592 * @param c Company to check.
594 static void CompanyCheckBankrupt(Company *c)
596 /* If the company has money again, it does not go bankrupt */
597 if (c->money - c->current_loan >= -_economy.max_loan) {
598 c->months_of_bankruptcy = 0;
599 c->bankrupt_asked = 0;
600 return;
603 c->months_of_bankruptcy++;
605 switch (c->months_of_bankruptcy) {
606 /* All the boring cases (months) with a bad balance where no action is taken */
607 case 0:
608 case 1:
609 case 2:
610 case 3:
612 case 5:
613 case 6:
615 case 8:
616 case 9:
617 break;
619 /* Warn about bankruptcy after 3 months */
620 case 4: {
621 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
622 cni->FillData(c);
623 SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
624 SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
625 SetDParamStr(2, cni->company_name);
626 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
627 AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
628 Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
629 break;
632 /* Offer company for sale after 6 months */
633 case 7: {
634 /* Don't consider the loan */
635 Money val = CalculateCompanyValue(c, false);
637 c->bankrupt_value = val;
638 c->bankrupt_asked = 1 << c->index; // Don't ask the owner
639 c->bankrupt_timeout = 0;
641 /* The company assets should always have some value */
642 assert(c->bankrupt_value > 0);
643 break;
646 /* Bankrupt company after 6 months (if the company has no value) or latest
647 * after 9 months (if it still had value after 6 months) */
648 default:
649 case 10: {
650 if (!_networking && _local_company == c->index) {
651 /* If we are in offline mode, leave the company playing. Eg. there
652 * is no THE-END, otherwise mark the client as spectator to make sure
653 * he/she is no long in control of this company. However... when you
654 * join another company (cheat) the "unowned" company can bankrupt. */
655 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
656 break;
659 /* Actually remove the company, but not when we're a network client.
660 * In case of network clients we will be getting a command from the
661 * server. It is done in this way as we are called from the
662 * StateGameLoop which can't change the current company, and thus
663 * updating the local company triggers an assert later on. In the
664 * case of a network game the command will be processed at a time
665 * that changing the current company is okay. In case of single
666 * player we are sure (the above check) that we are not the local
667 * company and thus we won't be moved. */
668 if (!_networking || _network_server) DoCommandP(0, 2 | (c->index << 16), CRR_BANKRUPT, CMD_COMPANY_CTRL);
669 break;
675 * Update the finances of all companies.
676 * Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy.
678 static void CompaniesGenStatistics()
680 /* Check for bankruptcy each month */
681 Company *c;
682 FOR_ALL_COMPANIES(c) {
683 CompanyCheckBankrupt(c);
686 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
688 if (!_settings_game.economy.infrastructure_maintenance) {
689 Station *st;
690 FOR_ALL_STATIONS(st) {
691 cur_company.Change(st->owner);
692 CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1);
693 SubtractMoneyFromCompany(cost);
695 } else {
696 /* Improved monthly infrastructure costs. */
697 FOR_ALL_COMPANIES(c) {
698 cur_company.Change(c->index);
700 CommandCost cost(EXPENSES_PROPERTY);
701 uint32 rail_total = c->infrastructure.GetRailTotal();
702 for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
703 if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
705 cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
706 for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
707 uint32 road_total = c->infrastructure.GetRoadTotal(rt);
708 for (RoadSubType rst = ROADSUBTYPE_BEGIN; rst < ROADSUBTYPE_END; rst++) {
709 if (c->infrastructure.road[rt][rst] != 0) cost.AddCost(RoadMaintenanceCost(RoadTypeIdentifier(rt, rst), c->infrastructure.road[rt][rst], road_total));
712 cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
713 cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
714 cost.AddCost(AirportMaintenanceCost(c->index));
716 SubtractMoneyFromCompany(cost);
719 cur_company.Restore();
721 Backup<CompanyByte> cur_company_2(_current_company, FILE_LINE);
723 FOR_ALL_COMPANIES(c) {
724 cur_company_2.Change(c->index);
726 if (c->inaugurated_year + 2 > _cur_year) continue;
728 CommandCost cost(EXPENSES_OTHER, 0);
730 if (c->old_economy[0].company_value > 1500000) {
731 cost.AddCost(c->old_economy[0].company_value >> 6); //~20% company value tax per year
732 }else if (c->old_economy[0].company_value > 200000 ) {
733 cost.AddCost(c->old_economy[0].company_value >> 7); //~10% company value tax per year
736 if (cost.GetCost() > 0) {
737 _economy.industry_helper += cost.GetCost();
738 SubtractMoneyFromCompany(cost);
741 cur_company_2.Restore();
743 /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
744 if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return;
746 FOR_ALL_COMPANIES(c) {
747 memmove(&c->old_economy[1], &c->old_economy[0], sizeof(c->old_economy) - sizeof(c->old_economy[0]));
748 c->old_economy[0] = c->cur_economy;
749 memset(&c->cur_economy, 0, sizeof(c->cur_economy));
751 if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
753 UpdateCompanyRatingAndValue(c, true);
754 if (c->block_preview != 0) c->block_preview--;
757 SetWindowDirty(WC_INCOME_GRAPH, 0);
758 SetWindowDirty(WC_OPERATING_PROFIT, 0);
759 SetWindowDirty(WC_DELIVERED_CARGO, 0);
760 SetWindowDirty(WC_PERFORMANCE_HISTORY, 0);
761 SetWindowDirty(WC_COMPANY_VALUE, 0);
762 SetWindowDirty(WC_COMPANY_LEAGUE, 0);
766 * Add monthly inflation
767 * @param check_year Shall the inflation get stopped after 170 years?
768 * @return true if inflation is maxed and nothing was changed
770 bool AddInflation(bool check_year)
772 /* The cargo payment inflation differs from the normal inflation, so the
773 * relative amount of money you make with a transport decreases slowly over
774 * the 170 years. After a few hundred years we reach a level in which the
775 * games will become unplayable as the maximum income will be less than
776 * the minimum running cost.
778 * Furthermore there are a lot of inflation related overflows all over the
779 * place. Solving them is hardly possible because inflation will always
780 * reach the overflow threshold some day. So we'll just perform the
781 * inflation mechanism during the first 170 years (the amount of years that
782 * one had in the original TTD) and stop doing the inflation after that
783 * because it only causes problems that can't be solved nicely and the
784 * inflation doesn't add anything after that either; it even makes playing
785 * it impossible due to the diverging cost and income rates.
787 if (check_year && (_cur_year - _settings_game.game_creation.starting_year) >= (ORIGINAL_MAX_YEAR - ORIGINAL_BASE_YEAR)) return true;
789 if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
791 /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
792 * scaled by 65536
793 * 12 -> months per year
794 * This is only a good approximation for small values
796 _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16;
797 _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
799 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
800 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
802 return false;
806 * Computes all prices, payments and maximum loan.
808 void RecomputePrices()
810 /* Setup maximum loan */
811 _economy.max_loan = (_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000;
813 /* Setup price bases */
814 for (Price i = PR_BEGIN; i < PR_END; i++) {
815 Money price = _price_base_specs[i].start_price;
817 /* Apply difficulty settings */
818 uint mod = 1;
819 switch (_price_base_specs[i].category) {
820 case PCAT_RUNNING:
821 mod = _settings_game.difficulty.vehicle_costs;
822 break;
824 case PCAT_CONSTRUCTION:
825 mod = _settings_game.difficulty.construction_cost;
826 break;
828 default: break;
830 switch (mod) {
831 case 0: price *= 6; break;
832 case 1: price *= 8; break; // normalised to 1 below
833 case 2: price *= 9; break;
834 default: NOT_REACHED();
837 /* Apply inflation */
838 price = (int64)price * _economy.inflation_prices;
840 /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
841 int shift = _price_base_multiplier[i] - 16 - 3;
842 if (shift >= 0) {
843 price <<= shift;
844 } else {
845 price >>= -shift;
848 /* Make sure the price does not get reduced to zero.
849 * Zero breaks quite a few commands that use a zero
850 * cost to see whether something got changed or not
851 * and based on that cause an error. When the price
852 * is zero that fails even when things are done. */
853 if (price == 0) {
854 price = Clamp(_price_base_specs[i].start_price, -1, 1);
855 /* No base price should be zero, but be sure. */
856 assert(price != 0);
858 /* Store value */
859 _price[i] = price;
862 /* Setup cargo payment */
863 CargoSpec *cs;
864 FOR_ALL_CARGOSPECS(cs) {
865 cs->current_payment = ((int64)cs->initial_payment * _economy.inflation_payment) >> 16;
868 SetWindowClassesDirty(WC_BUILD_VEHICLE);
869 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
870 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
871 SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE);
872 InvalidateWindowData(WC_PAYMENT_RATES, 0);
875 /** Let all companies pay the monthly interest on their loan. */
876 static void CompaniesPayInterest()
878 const Company *c;
880 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
881 FOR_ALL_COMPANIES(c) {
882 cur_company.Change(c->index);
884 /* Over a year the paid interest should be "loan * interest percentage",
885 * but... as that number is likely not dividable by 12 (pay each month),
886 * one needs to account for that in the monthly fee calculations.
887 * To easily calculate what one should pay "this" month, you calculate
888 * what (total) should have been paid up to this month and you subtract
889 * whatever has been paid in the previous months. This will mean one month
890 * it'll be a bit more and the other it'll be a bit less than the average
891 * monthly fee, but on average it will be exact.
892 * In order to prevent cheating or abuse (just not paying interest by not
893 * taking a loan we make companies pay interest on negative cash as well
895 Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
896 if (c->money < 0) {
897 yearly_fee += -c->money *_economy.interest_rate / 100;
899 Money up_to_previous_month = yearly_fee * _cur_month / 12;
900 Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12;
902 SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month));
904 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
906 cur_company.Restore();
909 static void HandleEconomyFluctuations()
911 if (_settings_game.difficulty.economy != 0) {
912 /* When economy is Fluctuating, decrease counter */
913 _economy.fluct--;
914 } else if (EconomyIsInRecession()) {
915 /* When it's Steady and we are in recession, end it now */
916 _economy.fluct = -12;
917 } else {
918 /* No need to do anything else in other cases */
919 return;
922 if (_economy.fluct == 0) {
923 _economy.fluct = -(int)GB(Random(), 0, 2);
924 AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
925 } else if (_economy.fluct == -12) {
926 _economy.fluct = GB(Random(), 0, 8) + 312;
927 AddNewsItem(STR_NEWS_END_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
933 * Reset changes to the price base multipliers.
935 void ResetPriceBaseMultipliers()
937 memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
941 * Change a price base by the given factor.
942 * The price base is altered by factors of two.
943 * NewBaseCost = OldBaseCost * 2^n
944 * @param price Index of price base to change.
945 * @param factor Amount to change by.
947 void SetPriceBaseMultiplier(Price price, int factor)
949 assert(price < PR_END);
950 _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
954 * Initialize the variables that will maintain the daily industry change system.
955 * @param init_counter specifies if the counter is required to be initialized
957 void StartupIndustryDailyChanges(bool init_counter)
959 uint map_size = MapLogX() + MapLogY();
960 /* After getting map size, it needs to be scaled appropriately and divided by 31,
961 * which stands for the days in a month.
962 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
963 * would not be needed.
964 * Since it is based on "fractional parts", the leftover days will not make much of a difference
965 * on the overall total number of changes performed */
966 _economy.industry_daily_increment = (1 << map_size) / 31;
968 if (init_counter) {
969 /* A new game or a savegame from an older version will require the counter to be initialized */
970 _economy.industry_daily_change_counter = 0;
974 void StartupEconomy()
976 _economy.interest_rate = _settings_game.difficulty.initial_interest;
977 _economy.infl_amount = _settings_game.difficulty.initial_interest;
978 _economy.infl_amount_pr = max(0, _settings_game.difficulty.initial_interest - 1);
979 _economy.fluct = GB(Random(), 0, 8) + 168;
981 /* Set up prices */
982 RecomputePrices();
984 StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
989 * Resets economy to initial values
991 void InitializeEconomy()
993 _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
994 ClearCargoPickupMonitoring();
995 ClearCargoDeliveryMonitoring();
999 * Determine a certain price
1000 * @param index Price base
1001 * @param cost_factor Price factor
1002 * @param grf_file NewGRF to use local price multipliers from.
1003 * @param shift Extra bit shifting after the computation
1004 * @return Price
1006 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
1008 if (index >= PR_END) return 0;
1010 Money cost = _price[index] * cost_factor;
1011 if (grf_file != nullptr) shift += grf_file->price_base_multipliers[index];
1013 if (shift >= 0) {
1014 cost <<= shift;
1015 } else {
1016 cost >>= -shift;
1019 return cost;
1022 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
1024 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1025 if (!cs->IsValid()) {
1026 /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
1027 return 0;
1030 /* Use callback to calculate cargo profit, if available */
1031 if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
1032 uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
1033 uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
1034 if (callback != CALLBACK_FAILED) {
1035 int result = GB(callback, 0, 14);
1037 /* Simulate a 15 bit signed value */
1038 if (HasBit(callback, 14)) result -= 0x4000;
1040 /* "The result should be a signed multiplier that gets multiplied
1041 * by the amount of cargo moved and the price factor, then gets
1042 * divided by 8192." */
1043 return result * num_pieces * cs->current_payment / 8192;
1047 static const float DECAY1 = 40.0f;
1048 static const float DECAY2 = 5.0f;
1049 static const float TILE2KM = 28.66f;
1050 static const float INCOME_DIVISOR = 5000.0f;
1051 const float d = dist;
1052 float transitdays = transit_days;
1053 transitdays = 2.5f * max<float>(transitdays, 1.0f);
1054 const int cargo_payment = cs->current_payment;
1056 const int days1 = cs->transit_days[0];
1057 const int days2 = cs->transit_days[1];
1059 const float inv_vt1 =days1/(200*TILE2KM); // reciprocal of first threshold velocity
1060 const float inv_vt2 = (days1 + days2) / (200 * TILE2KM); // reciprocal of second threshold velocity
1061 const float vt1 = inv_vt1 > 0.0f ? (1.0f / inv_vt1) : 1.0f;
1062 const float vt2 = inv_vt2 > 0.0f ? (1.0f / inv_vt2) : 1.0f;
1063 const float v_avg = d*TILE2KM/(transitdays); //average transit velocity
1066 * The income factor is calculated based on the average velocity
1067 * compared to two cargo-depending threshold velocities.
1068 * Formula is divided into three parts:
1070 * - fast exponential growth limited by 1st threshold velocity
1071 * - slow exponential growth depending on 2nd threshold
1074 const float exp1 = (1.0f - exp((-v_avg) / (vt1 / DECAY1)));
1075 const float exp2 = (1.0f - exp((-v_avg) / (vt2 / DECAY2)));
1077 const Money income = static_cast<Money>(dist * cargo_payment * num_pieces * exp1 * exp2 / INCOME_DIVISOR);
1079 return income;
1082 /** The industries we've currently brought cargo to. */
1083 static SmallIndustryList _cargo_delivery_destinations;
1086 * Transfer goods from station to industry.
1087 * The cargo is delivered to all accepting industries in a round-robin way.
1088 * @param st The station that accepted the cargo
1089 * @param cargo_type Type of cargo delivered
1090 * @param num_pieces Amount of cargo delivered
1091 * @param source The source of the cargo
1092 * @return actually accepted pieces of cargo
1094 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source)
1096 /* Find any industry tile inside the catchment area, whose industry accepts the cargo.
1097 * This fails in three cases:
1098 * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1099 * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1100 * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behavior)
1103 uint accepted = 0;
1105 std::vector<std::tuple<Industry*, uint, bool> > accepting_industries;
1107 for (uint i = 0; i < st->industries_near.Length(); i++) {
1108 Industry *ind = st->industries_near[i];
1109 if (ind->index == source) continue;
1111 uint cargo_index;
1112 for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
1113 if (cargo_type == ind->accepts_cargo[cargo_index]) break;
1115 /* Check if matching cargo has been found */
1116 if (cargo_index >= lengthof(ind->accepts_cargo)) continue;
1118 /* Check if industry temporarily refuses acceptance */
1119 if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
1121 /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1122 _cargo_delivery_destinations.Include(ind);
1124 accepting_industries.push_back(std::tuple<Industry*, uint, bool>(ind, cargo_index, true));
1127 int num_accepting_industries = (int)accepting_industries.size();
1128 int ind_index = 0;
1130 // Do a round-robin for all industries and mark all industries that are no longer accepting because their maximum stockpile is full.
1131 while (num_accepting_industries > 0 && num_pieces > 0) {
1132 // Check if the current industry still accepts cargo
1133 if (std::get<2>(accepting_industries[ind_index])) {
1134 Industry* ind = std::get<0>(accepting_industries[ind_index]);
1135 uint cargo_index = std::get<1>(accepting_industries[ind_index]);
1137 if ((0xFFFFU - ind->incoming_cargo_waiting[cargo_index]) == 0) {
1138 // The maximum stockpile limit is reached. Mark the industry as no longer accepting.
1139 std::get<2>(accepting_industries[ind_index]) = false;
1140 --num_accepting_industries;
1142 else {
1143 // The industry still accepts cargo.
1144 ++ind->incoming_cargo_waiting[cargo_index];
1145 --num_pieces;
1146 ++accepted;
1150 ind_index = (++ind_index) % accepting_industries.size();
1153 return accepted;
1157 * Delivers goods to industries/towns and calculates the payment
1158 * @param num_pieces amount of cargo delivered
1159 * @param cargo_type the type of cargo that is delivered
1160 * @param dest Station the cargo has been unloaded
1161 * @param source_tile The origin of the cargo for distance calculation
1162 * @param days_in_transit Travel time
1163 * @param company The company delivering the cargo
1164 * @param src_type Type of source of cargo (industry, town, headquarters)
1165 * @param src Index of source of cargo
1166 * @return Revenue for delivering cargo
1167 * @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
1169 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)
1171 assert(num_pieces > 0);
1173 Station *st = Station::Get(dest);
1175 /* Give the goods to the industry. */
1176 uint accepted = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == ST_INDUSTRY ? src : INVALID_INDUSTRY);
1178 /* If this cargo type is always accepted, accept all */
1179 if (HasBit(st->always_accepted, cargo_type)) accepted = num_pieces;
1181 /* Update station statistics */
1182 if (accepted > 0) {
1183 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_EVER_ACCEPTED);
1184 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_CURRENT_MONTH);
1185 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
1188 /* Update company statistics */
1189 company->cur_economy.delivered_cargo[cargo_type] += accepted;
1191 /* Increase town's counter for town effects */
1192 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1193 st->town->received[cs->town_effect].new_act += accepted;
1195 /* Determine profit */
1196 Money profit = GetTransportedGoodsIncome(accepted, DistanceOpenTTD(source_tile, st->xy), days_in_transit, cargo_type);
1198 /* Update the cargo monitor. */
1199 AddCargoDelivery(cargo_type, company->index, accepted, src_type, src, st);
1201 /* Modify profit if a subsidy is in effect */
1202 if (CheckSubsidised(cargo_type, company->index, src_type, src, st)) {
1203 switch (_settings_game.difficulty.subsidy_multiplier) {
1204 case 0: profit += profit >> 1; break;
1205 case 1: profit *= 2; break;
1206 case 2: profit *= 3; break;
1207 default: profit *= 4; break;
1211 return profit;
1215 * Inform the industry about just delivered cargo
1216 * DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.
1217 * @param i The industry to process
1219 static void TriggerIndustryProduction(Industry *i)
1221 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1222 uint16 callback = indspec->callback_mask;
1224 i->was_cargo_delivered = true;
1225 i->last_cargo_accepted_at = _date;
1227 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
1228 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
1229 IndustryProductionCallback(i, 0);
1230 } else {
1231 SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
1233 } else {
1234 for (uint cargo_index = 0; cargo_index < lengthof(i->incoming_cargo_waiting); cargo_index++) {
1235 uint cargo_waiting = i->incoming_cargo_waiting[cargo_index];
1236 if (cargo_waiting == 0) continue;
1238 i->produced_cargo_waiting[0] = min(i->produced_cargo_waiting[0] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][0] / 256), 0xFFFF);
1239 i->produced_cargo_waiting[1] = min(i->produced_cargo_waiting[1] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][1] / 256), 0xFFFF);
1241 i->incoming_cargo_waiting[cargo_index] = 0;
1245 TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO);
1246 StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
1250 * Makes us a new cargo payment helper.
1251 * @param front The front of the train
1253 CargoPayment::CargoPayment(Vehicle *front) :
1254 front(front),
1255 current_station(front->last_station_visited)
1259 CargoPayment::~CargoPayment()
1261 if (this->CleaningPool()) return;
1263 this->front->cargo_payment = nullptr;
1265 if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1267 Backup<CompanyByte> cur_company(_current_company, this->front->owner, FILE_LINE);
1269 SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit));
1270 this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1272 if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
1273 SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1276 if (this->visual_transfer != 0) {
1277 ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos,
1278 this->front->z_pos, this->visual_transfer, -this->visual_profit);
1279 } else if (this->visual_profit != 0) {
1280 ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos,
1281 this->front->z_pos, -this->visual_profit);
1284 this->front->trip_history.AddValue((this->visual_profit + this->visual_transfer), GetCurrentTickCount());
1285 InvalidateWindowData(WC_VEHICLE_TRIP_HISTORY, this->front->index);
1286 cur_company.Restore();
1290 * Handle payment for final delivery of the given cargo packet.
1291 * @param cp The cargo packet to pay for.
1292 * @param count The number of packets to pay for.
1294 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
1296 if (this->owner == nullptr) {
1297 this->owner = Company::Get(this->front->owner);
1300 DeliverGoods(count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->SourceSubsidyType(), cp->SourceSubsidyID());
1302 // Pay vehicle for only the part of total route it has done: ie. cargo_loaded_at_xy to here
1303 uint distance;
1305 if ((this->front != nullptr) && (this->front->type == VEH_ROAD)) {
1306 distance = DistanceManhattan(cp->LoadedAtXY(), Station::Get(this->current_station)->xy);
1307 } else {
1308 distance = DistanceOpenTTD(cp->LoadedAtXY(), Station::Get(this->current_station)->xy);
1311 // Allows the actual profits for only the last part of the trip to be calculated and, consequently, paid.
1312 Money profit = GetTransportedGoodsIncome(count, distance, cp->DaysInTransit(), this->ct);
1314 this->route_profit += profit + cp->FeederShare();
1315 this->visual_profit += profit;
1319 * Handle payment for transfer of the given cargo packet.
1320 * @param cp The cargo packet to pay for; actual payment won't be made!.
1321 * @param count The number of packets to pay for.
1322 * @return The amount of money paid for the transfer.
1324 Money CargoPayment::PayTransfer(CargoPacket *cp, uint count)
1326 // Pay vehicle for only the part of total route it has done: ie. cargo_loaded_at_xy to here
1327 uint distance;
1329 if ((this->front != nullptr) && (this->front->type == VEH_ROAD)) {
1330 distance = DistanceManhattan(cp->LoadedAtXY(), Station::Get(this->current_station)->xy);
1331 } else {
1332 distance = DistanceOpenTTD(cp->LoadedAtXY(), Station::Get(this->current_station)->xy);
1335 Money profit = GetTransportedGoodsIncome(count, distance, cp->DaysInTransit(), this->ct);
1337 // Reset the amount of days this package has been in transit, important for the next leg
1338 cp->ResetTransitDays();
1340 this->visual_transfer += profit;
1342 return profit;
1346 * Returns the load type of a vehicle.
1347 * In case of cargo type order, the load type returned depends on the cargo carriable by the vehicle.
1348 * @pre v != nullptr
1349 * @param v A pointer to a vehicle.
1350 * @return the load type of this vehicle.
1352 static OrderLoadFlags GetLoadType(const Vehicle *v)
1354 return v->First()->current_order.GetCargoLoadType(v->cargo_type);
1358 * Returns the unload type of a vehicle.
1359 * In case of cargo type order, the unload type returned depends on the cargo carriable by the vehicle.
1360 * @pre v != nullptr
1361 * @param v A pointer to a vehicle.
1362 * @return The unload type of this vehicle.
1364 static OrderUnloadFlags GetUnloadType(const Vehicle *v)
1366 return v->First()->current_order.GetCargoUnloadType(v->cargo_type);
1370 * Prepare the vehicle to be unloaded.
1371 * @param curr_station the station where the consist is at the moment
1372 * @param front_v the vehicle to be unloaded
1374 void PrepareUnload(Vehicle *front_v)
1376 Station *curr_station = Station::Get(front_v->last_station_visited);
1377 curr_station->loading_vehicles.push_back(front_v);
1379 /* At this moment loading cannot be finished */
1380 ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED);
1382 /* Start unloading at the first possible moment */
1383 front_v->load_unload_ticks = 1;
1385 assert(front_v->cargo_payment == nullptr);
1386 /* One CargoPayment per vehicle and the vehicle limit equals the
1387 * limit in number of CargoPayments. Can't go wrong. */
1388 assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
1389 assert(CargoPayment::CanAllocateItem());
1390 front_v->cargo_payment = new CargoPayment(front_v);
1392 CargoStationIDStackSet next_station = front_v->GetNextStoppingStation();
1393 if (!front_v->HasOrdersList() || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1394 Station *st = Station::Get(front_v->last_station_visited);
1395 for (Vehicle *v = front_v; v != nullptr; v = v->Next()) {
1396 if (GetUnloadType(v) & OUFB_NO_UNLOAD) continue;
1397 const GoodsEntry *ge = &st->goods[v->cargo_type];
1398 if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1399 v->cargo.Stage(
1400 HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE),
1401 front_v->last_station_visited, next_station.Get(v->cargo_type),
1402 GetUnloadType(v), ge,
1403 front_v->cargo_payment);
1404 if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1411 * Gets the amount of cargo the given vehicle can load in the current tick.
1412 * This is only about loading speed. The free capacity is ignored.
1413 * @param v Vehicle to be queried.
1414 * @return Amount of cargo the vehicle can load at once.
1416 static uint GetLoadAmount(Vehicle *v)
1418 const Engine *e = v->GetEngine();
1419 uint load_amount = e->info.load_amount;
1421 /* The default loadamount for mail is 1/4 of the load amount for passengers */
1422 bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft();
1423 if (air_mail) load_amount = CeilDiv(load_amount, 4);
1425 if (_settings_game.order.gradual_loading) {
1426 uint16 cb_load_amount = CALLBACK_FAILED;
1427 if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
1428 /* Use callback 36 */
1429 cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1430 } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
1431 /* Use callback 12 */
1432 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1434 if (cb_load_amount != CALLBACK_FAILED) {
1435 if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1436 if (cb_load_amount >= 0x100) {
1437 ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT, cb_load_amount);
1438 } else if (cb_load_amount != 0) {
1439 load_amount = cb_load_amount;
1444 /* Scale load amount the same as capacity */
1445 if (HasBit(e->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER) && !air_mail) load_amount = CeilDiv(load_amount * CargoSpec::Get(v->cargo_type)->multiplier, 0x100);
1447 /* Zero load amount breaks a lot of things. */
1448 return max(1u, load_amount);
1452 * Iterate the articulated parts of a vehicle, also considering the special cases of "normal"
1453 * aircraft and double headed trains. Apply an action to each vehicle and immediately return false
1454 * if that action does so. Otherwise return true.
1455 * @tparam Taction Class of action to be applied. Must implement bool operator()([const] Vehicle *).
1456 * @param v First articulated part.
1457 * @param action Instance of Taction.
1458 * @return false if any of the action invocations returned false, true otherwise.
1460 template<class Taction>
1461 bool IterateVehicleParts(Vehicle *v, Taction action)
1463 for (Vehicle *w = v; w != nullptr;
1464 w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : nullptr) {
1465 if (!action(w)) return false;
1466 if (w->type == VEH_TRAIN) {
1467 Train *train = Train::From(w);
1468 if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false;
1471 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next());
1472 return true;
1476 * Action to check if a vehicle has no stored cargo.
1478 struct IsEmptyAction
1481 * Checks if the vehicle has stored cargo.
1482 * @param v Vehicle to be checked.
1483 * @return true if v is either empty or has only reserved cargo, false otherwise.
1485 bool operator()(const Vehicle *v)
1487 return v->cargo.StoredCount() == 0;
1492 * Refit preparation action.
1494 struct PrepareRefitAction
1496 CargoArray &consist_capleft; ///< Capacities left in the consist.
1497 uint32 &refit_mask; ///< Bitmask of possible refit cargoes.
1500 * Create a refit preparation action.
1501 * @param consist_capleft Capacities left in consist, to be updated here.
1502 * @param refit_mask Refit mask to be constructed from refit information of vehicles.
1504 PrepareRefitAction(CargoArray &consist_capleft, uint32 &refit_mask) :
1505 consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1508 * Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and
1509 * adding the cargoes it can refit to to the refit mask.
1510 * @param v The vehicle to be refitted.
1511 * @return true.
1513 bool operator()(const Vehicle *v)
1515 this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount();
1516 this->refit_mask |= EngInfo(v->engine_type)->refit_mask;
1517 return true;
1522 * Action for returning reserved cargo.
1524 struct ReturnCargoAction
1526 Station *st; ///< Station to give the returned cargo to.
1527 StationID next_hop; ///< Next hop the cargo should be assigned to.
1530 * Construct a cargo return action.
1531 * @param st Station to give the returned cargo to.
1532 * @param next_one Next hop the cargo should be assigned to.
1534 ReturnCargoAction(Station *st, StationID next_one) : st(st), next_hop(next_one) {}
1537 * Return all reserved cargo from a vehicle.
1538 * @param v Vehicle to return cargo from.
1539 * @return true.
1541 bool operator()(Vehicle *v)
1543 v->cargo.Return(UINT_MAX, &this->st->goods[v->cargo_type].cargo, this->next_hop);
1544 return true;
1549 * Action for finalizing a refit.
1551 struct FinalizeRefitAction
1553 CargoArray &consist_capleft; ///< Capacities left in the consist.
1554 Station *st; ///< Station to reserve cargo from.
1555 const CargoStationIDStackSet &next_station; ///< Next hops to reserve cargo for.
1556 bool do_reserve; ///< If the vehicle should reserve.
1557 Vehicle *cargo_type_loading; ///< Non-null if vehicle should reserve if the cargo type of the vehicle is a cargo-specific full-load order using this pointer
1560 * Create a finalizing action.
1561 * @param consist_capleft Capacities left in the consist.
1562 * @param st Station to reserve cargo from.
1563 * @param next_station Next hops to reserve cargo for.
1564 * @param do_reserve If we should reserve cargo or just add up the capacities.
1565 * @param cargo_type_loading Non-null if vehicle should reserve if the cargo type of the vehicle is a cargo-specific full-load order using this pointer
1567 FinalizeRefitAction(CargoArray &consist_capleft, Station *st, const CargoStationIDStackSet &next_station, bool do_reserve, Vehicle *cargo_type_loading) :
1568 consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve), cargo_type_loading(cargo_type_loading) {}
1572 * Reserve cargo from the station and update the remaining consist capacities with the
1573 * vehicle's remaining free capacity.
1574 * @param v Vehicle to be finalized.
1575 * @return true.
1577 bool operator()(Vehicle *v)
1579 if (this->do_reserve || (cargo_type_loading == nullptr || (cargo_type_loading->current_order.GetCargoLoadTypeRaw(v->cargo_type) & OLFB_FULL_LOAD))) {
1580 this->st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1581 &v->cargo, st->xy, this->next_station.Get(v->cargo_type));
1583 this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1584 return true;
1589 * Refit a vehicle in a station.
1590 * @param v Vehicle to be refitted.
1591 * @param consist_capleft Added cargo capacities in the consist.
1592 * @param st Station the vehicle is loading at.
1593 * @param next_station Possible next stations the vehicle can travel to.
1594 * @param new_cid Target cargo for refit.
1596 static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, CargoStationIDStackSet next_station, CargoID new_cid)
1598 Vehicle *v_start = v->GetFirstEnginePart();
1599 if (!IterateVehicleParts(v_start, IsEmptyAction())) return;
1601 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1603 uint32 refit_mask = v->GetEngine()->info.refit_mask;
1605 /* Remove old capacity from consist capacity and collect refit mask. */
1606 IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask));
1608 bool is_auto_refit = new_cid == CT_AUTO_REFIT;
1609 bool check_order = (v->First()->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD);
1610 if (is_auto_refit) {
1611 /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1612 CargoID cid;
1613 new_cid = v_start->cargo_type;
1614 FOR_EACH_SET_CARGO_ID(cid, refit_mask) {
1615 if (check_order && v->First()->current_order.GetCargoLoadType(cid) == OLFB_NO_LOAD) continue;
1616 if (st->goods[cid].cargo.HasCargoFor(next_station.Get(cid))) {
1617 /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1618 * the returned refit capacity will be greater than zero. */
1619 DoCommand(v_start->tile, v_start->index, cid | 1U << 6 | 0xFF << 8 | 1U << 16, DC_QUERY_COST, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
1620 /* Try to balance different loadable cargoes between parts of the consist, so that
1621 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1622 * to the first loadable cargo for which there is only one packet. If the capacities
1623 * are equal refit to the cargo of which most is available. This is important for
1624 * consists of only a single vehicle as those will generally have a consist_capleft
1625 * of 0 for all cargoes. */
1626 if (_returned_refit_capacity > 0 && (consist_capleft[cid] < consist_capleft[new_cid] ||
1627 (consist_capleft[cid] == consist_capleft[new_cid] &&
1628 st->goods[cid].cargo.AvailableCount() > st->goods[new_cid].cargo.AvailableCount()))) {
1629 new_cid = cid;
1635 /* Refit if given a valid cargo. */
1636 if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1637 /* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
1638 * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1639 * "via any station" before reserving. We rather produce some more "any station" cargo than
1640 * misrouting it. */
1641 IterateVehicleParts(v_start, ReturnCargoAction(st, INVALID_STATION));
1642 CommandCost cost = DoCommand(v_start->tile, v_start->index, new_cid | 1U << 6 | 0xFF << 8 | 1U << 16, DC_EXEC, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
1643 if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
1646 /* Add new capacity to consist capacity and reserve cargo */
1647 IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station,
1648 is_auto_refit || (v->First()->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0,
1649 (v->First()->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD) ? v->First() : nullptr));
1651 cur_company.Restore();
1654 struct ReserveCargoAction {
1655 Station *st;
1656 const CargoStationIDStackSet &next_station;
1657 Vehicle *cargo_type_loading;
1659 ReserveCargoAction(Station *st, const CargoStationIDStackSet &next_station, Vehicle *cargo_type_loading) :
1660 st(st), next_station(next_station), cargo_type_loading(cargo_type_loading) {}
1662 bool operator()(Vehicle *v)
1664 if (cargo_type_loading != nullptr && !(cargo_type_loading->current_order.GetCargoLoadTypeRaw(v->cargo_type) & OLFB_FULL_LOAD)) return true;
1665 if (v->cargo_cap > v->cargo.RemainingCount()) {
1666 st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1667 &v->cargo, st->xy, next_station.Get(v->cargo_type));
1670 return true;
1676 * Reserves cargo if the full load order and improved_load is set or if the
1677 * current order allows autorefit.
1678 * @param st Station where the consist is loading at the moment.
1679 * @param u Front of the loading vehicle consist.
1680 * @param consist_capleft If given, save free capacities after reserving there.
1681 * @param next_station Station(s) the vehicle will stop at next.
1682 * @param cargo_type_loading check cargo-specific loading type
1684 static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, const CargoStationIDStackSet &next_station, bool cargo_type_loading)
1686 /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1687 * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1688 * a vehicle belongs to already has the right cargo. */
1689 bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == nullptr;
1690 for (Vehicle *v = u; v != nullptr; v = v->Next()) {
1691 assert(v->cargo_cap >= v->cargo.RemainingCount());
1693 /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1694 * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1695 * to a different cargo and hasn't tried to do so, yet. */
1696 if (!v->IsArticulatedPart() &&
1697 (v->type != VEH_TRAIN || !Train::From(v)->IsRearDualheaded()) &&
1698 (v->type != VEH_AIRCRAFT || Aircraft::From(v)->IsNormalAircraft()) &&
1699 (must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) {
1700 IterateVehicleParts(v, ReserveCargoAction(st, next_station, cargo_type_loading ? u : nullptr));
1702 if (consist_capleft == nullptr || v->cargo_cap == 0) continue;
1703 if (cargo_type_loading && !(u->current_order.GetCargoLoadTypeRaw(v->cargo_type) & OLFB_FULL_LOAD)) continue;
1704 (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1709 * Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload
1710 * again. Adjust for overhang of trains and set it at least to 1.
1711 * @param front The vehicle to be updated.
1712 * @param st The station the vehicle is loading at.
1713 * @param ticks The time it would normally wait, based on cargo loaded and unloaded.
1715 static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
1717 if (front->type == VEH_TRAIN) {
1718 /* Each platform tile is worth 2 rail vehicles. */
1719 int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE;
1720 if (overhang > 0) {
1721 ticks <<= 1;
1722 ticks += (overhang * ticks) / 8;
1725 /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1726 front->load_unload_ticks = max(1, ticks);
1730 * Loads/unload the vehicle if possible.
1731 * @param front the vehicle to be (un)loaded
1733 static void LoadUnloadVehicle(Vehicle *front)
1735 assert(front->current_order.IsType(OT_LOADING));
1737 StationID last_visited = front->last_station_visited;
1738 Station *st = Station::Get(last_visited);
1740 CargoStationIDStackSet next_station = front->GetNextStoppingStation();
1741 bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CT_AUTO_REFIT;
1742 CargoArray consist_capleft;
1743 bool should_reserve_consist = false;
1744 bool reserve_consist_cargo_type_loading = false;
1745 if (_settings_game.order.improved_load && use_autorefit) {
1746 if (front->cargo_payment == nullptr) should_reserve_consist = true;
1747 } else {
1748 if ((front->current_order.GetLoadType() & OLFB_FULL_LOAD) || (front->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD)) {
1749 should_reserve_consist = true;
1750 reserve_consist_cargo_type_loading = (front->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD);
1754 if (should_reserve_consist) {
1755 ReserveConsist(st, front,
1756 (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : nullptr,
1757 next_station,
1758 reserve_consist_cargo_type_loading);
1761 /* We have not waited enough time till the next round of loading/unloading */
1762 if (front->load_unload_ticks != 0) return;
1764 if (front->type == VEH_TRAIN && (!IsTileType(front->tile, MP_STATION) || GetStationIndex(front->tile) != st->index)) {
1765 /* The train reversed in the station. Take the "easy" way
1766 * out and let the train just leave as it always did. */
1767 SetBit(front->vehicle_flags, VF_LOADING_FINISHED);
1768 front->load_unload_ticks = 1;
1769 return;
1772 int new_load_unload_ticks = 0;
1773 bool dirty_vehicle = false;
1774 bool dirty_station = false;
1776 bool completely_emptied = true;
1777 bool anything_unloaded = false;
1778 bool anything_loaded = false;
1779 uint32 full_load_amount = 0;
1780 uint32 cargo_not_full = 0;
1781 uint32 cargo_full = 0;
1782 uint32 reservation_left = 0;
1784 front->cur_speed = 0;
1786 CargoPayment *payment = front->cargo_payment;
1788 uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1789 for (Vehicle *v = front; v != nullptr; v = v->Next()) {
1790 if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
1791 if (v->cargo_cap == 0) continue;
1792 artic_part++;
1794 GoodsEntry *ge = &st->goods[v->cargo_type];
1796 if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (GetUnloadType(v) & OUFB_NO_UNLOAD) == 0) {
1797 uint cargo_count = v->cargo.UnloadCount();
1798 uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, GetLoadAmount(v)) : cargo_count;
1799 bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1801 assert(payment != nullptr);
1802 payment->SetCargo(v->cargo_type);
1804 if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
1805 /* The station does not accept our goods anymore. */
1806 if (GetUnloadType(v) & (OUFB_TRANSFER | OUFB_UNLOAD)) {
1807 /* Transfer instead of delivering. */
1808 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_TRANSFER>(
1809 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER), INVALID_STATION);
1810 } else {
1811 uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
1812 if (v->cargo_cap < new_remaining) {
1813 /* Return some of the reserved cargo to not overload the vehicle. */
1814 v->cargo.Return(new_remaining - v->cargo_cap, &ge->cargo, INVALID_STATION);
1817 /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1818 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_KEEP>(
1819 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER));
1821 /* ... say we unloaded something, otherwise we'll think we didn't unload
1822 * something and we didn't load something, so we must be finished
1823 * at this station. Setting the unloaded means that we will get a
1824 * retry for loading in the next cycle. *////
1825 anything_unloaded = true;
1829 if (v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0) {
1830 /* Mark the station dirty if we transfer, but not if we only deliver. */
1831 dirty_station = true;
1833 if (!ge->HasRating()) {
1834 /* Upon transfering cargo, make sure the station has a rating. Fake a pickup for the
1835 * first unload to prevent the cargo from quickly decaying after the initial drop. */
1836 ge->time_since_pickup = 0;
1837 SetBit(ge->status, GoodsEntry::GES_RATING);
1841 amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment);
1842 remaining = v->cargo.UnloadCount() > 0;
1843 if (amount_unloaded > 0) {
1844 dirty_vehicle = true;
1845 anything_unloaded = true;
1846 new_load_unload_ticks += amount_unloaded;
1848 /* Deliver goods to the station */
1849 st->time_since_unload = 0;
1852 if (_settings_game.order.gradual_loading && remaining) {
1853 completely_emptied = false;
1854 } else {
1855 /* We have finished unloading (cargo count == 0) */
1856 ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1859 continue;
1862 /* Do not pick up goods when we have no-load set or loading is stopped. */
1863 if (GetLoadType(v) & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
1865 /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1866 if (front->current_order.IsRefit() && artic_part == 1) {
1867 HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo());
1868 ge = &st->goods[v->cargo_type];
1871 /* As we're loading here the following link can carry the full capacity of the vehicle. */
1872 v->refit_cap = v->cargo_cap;
1874 /* update stats */
1875 int t;
1876 switch (front->type) {
1877 case VEH_TRAIN:
1878 t = front->GetDisplayMaxSpeed();
1879 break;
1881 case VEH_SHIP:
1882 t = front->GetDisplayMaxSpeed() * 4;
1883 break;
1885 case VEH_ROAD:
1886 t = front->GetDisplayMaxSpeed() * 2;
1887 break;
1889 case VEH_AIRCRAFT:
1890 t = Aircraft::From(front)->GetSpeedOldUnits() * 2; // Convert to old units.
1891 break;
1893 default: NOT_REACHED();
1896 /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1897 ge->last_speed = min(t, 255);
1898 ge->last_unprocessed_speed = front->GetDisplayMaxSpeed();
1899 ge->last_vehicle_type = front->type;
1900 ge->last_age = min(_cur_year - front->build_year, 255);
1901 ge->time_since_pickup = 0;
1903 assert(v->cargo_cap >= v->cargo.StoredCount());
1904 /* If there's goods waiting at the station, and the vehicle
1905 * has capacity for it, load it on the vehicle. */
1906 uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1907 if (cap_left > 0 && (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0)) {
1908 if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1909 if (_settings_game.order.gradual_loading) cap_left = min(cap_left, GetLoadAmount(v));
1911 uint loaded = ge->cargo.Load(cap_left, &v->cargo, st->xy, next_station.Get(v->cargo_type));
1912 if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
1913 /* Remember if there are reservations left so that we don't stop
1914 * loading before they're loaded. */
1915 SetBit(reservation_left, v->cargo_type);
1918 /* Store whether the maximum possible load amount was loaded or not.*/
1919 if (loaded == cap_left) {
1920 SetBit(full_load_amount, v->cargo_type);
1921 } else {
1922 ClrBit(full_load_amount, v->cargo_type);
1925 /* TODO: Regarding this, when we do gradual loading, we
1926 * should first unload all vehicles and then start
1927 * loading them. Since this will cause
1928 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1929 * the whole vehicle chain is really totally empty, the
1930 * completely_emptied assignment can then be safely
1931 * removed; that's how TTDPatch behaves too. --pasky */
1932 if (loaded > 0) {
1933 completely_emptied = false;
1934 anything_loaded = true;
1936 st->time_since_load = 0;
1937 st->last_vehicle_type = v->type;
1939 if (ge->cargo.TotalCount() == 0) {
1940 TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type);
1941 TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1942 AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
1945 new_load_unload_ticks += loaded;
1947 dirty_vehicle = dirty_station = true;
1951 if (v->cargo.StoredCount() >= v->cargo_cap) {
1952 SetBit(cargo_full, v->cargo_type);
1953 } else {
1954 SetBit(cargo_not_full, v->cargo_type);
1958 if (anything_loaded || anything_unloaded) {
1959 if (front->type == VEH_TRAIN) {
1960 TriggerStationRandomisation(st, front->tile, SRT_TRAIN_LOADS);
1961 TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS);
1965 /* Only set completely_emptied, if we just unloaded all remaining cargo */
1966 completely_emptied &= anything_unloaded;
1968 if (!anything_unloaded) delete payment;
1970 ClrBit(front->vehicle_flags, VF_STOP_LOADING);
1972 bool has_full_load_order = front->current_order.GetLoadType() & OLFB_FULL_LOAD;
1974 if (front->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD) {
1975 for (Vehicle *v = front; v != nullptr; v = v->Next()) {
1976 if (front->current_order.GetCargoLoadTypeRaw(v->cargo_type) & OLFB_FULL_LOAD) {
1977 has_full_load_order = true;
1978 break;
1983 if (anything_loaded || anything_unloaded) {
1984 if (_settings_game.order.gradual_loading) {
1985 /* The time it takes to load one 'slice' of cargo or passengers depends
1986 * on the vehicle type - the values here are those found in TTDPatch */
1987 const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1989 new_load_unload_ticks = gradual_loading_wait_time[front->type];
1991 /* We loaded less cargo than possible for all cargo types and it's not full
1992 * load and we're not supposed to wait any longer: stop loading. */
1993 if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !has_full_load_order &&
1994 front->current_order_time >= (uint)max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
1995 SetBit(front->vehicle_flags, VF_STOP_LOADING);
1998 UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
1999 } else {
2000 UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
2001 bool finished_loading = true;
2002 if (has_full_load_order) {
2003 if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
2004 /* if the aircraft carries passengers and is NOT full, then
2005 * continue loading, no matter how much mail is in */
2006 if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) ||
2007 (cargo_not_full && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
2008 finished_loading = false;
2010 } else if (front->current_order.GetLoadType() == OLFB_CARGO_TYPE_LOAD) {
2011 for (Vehicle *v = front; v != nullptr; v = v->Next()) {
2012 if ((front->current_order.GetCargoLoadTypeRaw(v->cargo_type) & OLFB_FULL_LOAD) && HasBit(cargo_not_full, v->cargo_type)) {
2013 finished_loading = false;
2014 break;
2017 } else if (cargo_not_full != 0) {
2018 finished_loading = false;
2021 /* Refresh next hop stats if we're full loading to make the links
2022 * known to the distribution algorithm and allow cargo to be sent
2023 * along them. Otherwise the vehicle could wait for cargo
2024 * indefinitely if it hasn't visited the other links yet, or if the
2025 * links die while it's loading. */
2026 if (!finished_loading) LinkRefresher::Run(front, true, true);
2029 SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
2032 /* Calculate the loading indicator fill percent and display
2033 * In the Game Menu do not display indicators
2034 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
2035 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
2036 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
2038 if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
2039 StringID percent_up_down = STR_NULL;
2040 int percent = CalcPercentVehicleFilled(front, &percent_up_down);
2041 if (front->fill_percent_te_id == INVALID_TE_ID) {
2042 front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
2043 } else {
2044 UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
2048 if (completely_emptied) {
2049 /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
2050 * properties such as weight, power and TE whenever the trigger runs. */
2051 dirty_vehicle = true;
2052 TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
2055 if (dirty_vehicle) {
2056 SetWindowDirty(GetWindowClassForVehicleType(front->type), front->owner);
2057 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
2058 front->MarkDirty();
2060 if (dirty_station) {
2061 st->MarkTilesDirty(true);
2062 SetWindowDirty(WC_STATION_VIEW, last_visited);
2063 InvalidateWindowData(WC_STATION_LIST, last_visited);
2068 * Load/unload the vehicles in this station according to the order
2069 * they entered.
2070 * @param st the station to do the loading/unloading for
2072 void LoadUnloadStation(Station *st)
2074 /* No vehicle is here... */
2075 if (st->loading_vehicles.empty()) return;
2077 Vehicle *last_loading = nullptr;
2079 /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
2080 for (Vehicle *v : st->loading_vehicles) {
2081 if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
2083 assert(v->load_unload_ticks != 0);
2084 if (--v->load_unload_ticks == 0) last_loading = v;
2087 /* We only need to reserve and load/unload up to the last loading vehicle.
2088 * Anything else will be forgotten anyway after returning from this function.
2090 * Especially this means we do _not_ need to reserve cargo for a single
2091 * consist in a station which is not allowed to load yet because its
2092 * load_unload_ticks is still not 0.
2094 if (last_loading == nullptr) return;
2096 for (Vehicle *v : st->loading_vehicles) {
2097 if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v);
2098 if (v == last_loading) break;
2101 /* Call the production machinery of industries */
2102 const Industry * const *isend = _cargo_delivery_destinations.End();
2103 for (Industry **iid = _cargo_delivery_destinations.Begin(); iid != isend; iid++) {
2104 TriggerIndustryProduction(*iid);
2106 _cargo_delivery_destinations.Clear();
2110 * Monthly update of the economic data (of the companies as well as economic fluctuations).
2112 void CompaniesMonthlyLoop()
2114 CompaniesGenStatistics();
2115 if (_settings_game.economy.inflation) {
2116 AddInflation();
2117 RecomputePrices();
2119 CompaniesPayInterest();
2120 HandleEconomyFluctuations();
2123 static void DoAcquireCompany(Company *c)
2125 CompanyID ci = c->index;
2127 CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
2128 cni->FillData(c, Company::Get(_current_company));
2130 SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
2131 SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
2132 SetDParamStr(2, cni->company_name);
2133 SetDParamStr(3, cni->other_company_name);
2134 SetDParam(4, c->bankrupt_value);
2135 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
2136 AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
2137 Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
2139 ChangeOwnershipOfCompanyItems(ci, _current_company);
2141 if (c->bankrupt_value == 0) {
2142 Company *owner = Company::Get(_current_company);
2143 owner->current_loan += c->current_loan;
2146 if (c->is_ai) AI::Stop(c->index);
2148 DeleteCompanyWindows(ci);
2149 InvalidateWindowClassesData(WC_TRAINS_LIST);
2150 InvalidateWindowClassesData(WC_TRACE_RESTRICT_SLOTS);
2151 InvalidateWindowClassesData(WC_SHIPS_LIST);
2152 InvalidateWindowClassesData(WC_ROADVEH_LIST);
2153 InvalidateWindowClassesData(WC_AIRCRAFT_LIST);
2155 delete c;
2158 extern int GetAmountOwnedBy(const Company *c, Owner owner);
2161 * Acquire shares in an opposing company.
2162 * @param tile unused
2163 * @param flags type of operation
2164 * @param p1 company to buy the shares from
2165 * @param p2 unused
2166 * @param text unused
2167 * @return the cost of this operation or an error
2169 CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2171 CommandCost cost(EXPENSES_OTHER);
2172 CompanyID target_company = (CompanyID)p1;
2173 Company *c = Company::GetIfValid(target_company);
2175 /* Check if buying shares is allowed (protection against modified clients)
2176 * Cannot buy own shares */
2177 if (c == nullptr || !_settings_game.economy.allow_shares || _current_company == target_company) return CommandError();
2179 /* Protect new companies from hostile takeovers */
2180 if (_cur_year - c->inaugurated_year < 6) return CommandError(STR_ERROR_PROTECTED);
2182 /* Those lines are here for network-protection (clients can be slow) */
2183 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost;
2185 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) {
2186 if (!c->is_ai) return cost; // We can not buy out a real company (temporarily). TODO: well, enable it obviously.
2188 if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return CommandError(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
2192 cost.AddCost(CalculateCompanyValue(c) >> 2);
2193 if (flags & DC_EXEC) {
2194 OwnerByte *b = c->share_owners;
2196 while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
2197 *b = _current_company;
2199 for (int i = 0; c->share_owners[i] == _current_company;) {
2200 if (++i == 4) {
2201 c->bankrupt_value = 0;
2202 DoAcquireCompany(c);
2203 break;
2206 InvalidateWindowData(WC_COMPANY, target_company);
2207 CompanyAdminUpdate(c);
2209 return cost;
2213 * Sell shares in an opposing company.
2214 * @param tile unused
2215 * @param flags type of operation
2216 * @param p1 company to sell the shares from
2217 * @param p2 unused
2218 * @param text unused
2219 * @return the cost of this operation or an error
2221 CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2223 CompanyID target_company = (CompanyID)p1;
2224 Company *c = Company::GetIfValid(target_company);
2226 /* Cannot sell own shares */
2227 if (c == nullptr || _current_company == target_company) return CommandError();
2229 /* Check if selling shares is allowed (protection against modified clients).
2230 * However, we must sell shares of companies being closed down. */
2231 if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CommandError();
2233 /* Those lines are here for network-protection (clients can be slow) */
2234 if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost();
2236 /* adjust it a little to make it less profitable to sell and buy */
2237 Money cost = CalculateCompanyValue(c) >> 2;
2238 cost = -(cost - (cost >> 7));
2240 if (flags & DC_EXEC) {
2241 OwnerByte *b = c->share_owners;
2242 while (*b != _current_company) b++; // share owners is guaranteed to contain company
2243 *b = COMPANY_SPECTATOR;
2244 InvalidateWindowData(WC_COMPANY, target_company);
2245 CompanyAdminUpdate(c);
2247 return CommandCost(EXPENSES_OTHER, cost);
2251 * Buy up another company.
2252 * When a competing company is gone bankrupt you get the chance to purchase
2253 * that company.
2254 * @todo currently this only works for AI companies
2255 * @param tile unused
2256 * @param flags type of operation
2257 * @param p1 company to buy up
2258 * @param p2 unused
2259 * @param text unused
2260 * @return the cost of this operation or an error
2262 CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2264 CompanyID target_company = (CompanyID)p1;
2265 Company *c = Company::GetIfValid(target_company);
2266 if (c == nullptr) return CommandError();
2268 /* Disable takeovers when not asked */
2269 if (!HasBit(c->bankrupt_asked, _current_company)) return CommandError();
2271 /* Disable taking over the local company in single player */
2272 if (!_networking && _local_company == c->index) return CommandError();
2274 /* Do not allow companies to take over themselves */
2275 if (target_company == _current_company) return CommandError();
2277 /* Disable taking over when not allowed. */
2278 if (!MayCompanyTakeOver(_current_company, target_company)) return CommandError();
2280 /* Get the cost here as the company is deleted in DoAcquireCompany. */
2281 CommandCost cost(EXPENSES_OTHER, c->bankrupt_value);
2283 if (flags & DC_EXEC) {
2284 DoAcquireCompany(c);
2286 return cost;