Factor out OnClick dispatching in Window::HandleEditBoxKey
[openttd/fttd.git] / src / economy.cpp
blobc933ecaa7ca37838ff497e35e2d4b783dcc97e05
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"
14 #include <algorithm>
15 #include <vector>
17 #include "company_func.h"
18 #include "command_func.h"
19 #include "industry.h"
20 #include "town.h"
21 #include "news_func.h"
22 #include "network/network.h"
23 #include "network/network_func.h"
24 #include "ai/ai.hpp"
25 #include "aircraft.h"
26 #include "train.h"
27 #include "newgrf_engine.h"
28 #include "engine_base.h"
29 #include "ground_vehicle.hpp"
30 #include "newgrf_cargo.h"
31 #include "newgrf_sound.h"
32 #include "newgrf_industrytiles.h"
33 #include "newgrf_station.h"
34 #include "newgrf_airporttiles.h"
35 #include "object.h"
36 #include "strings_func.h"
37 #include "date_func.h"
38 #include "vehicle_func.h"
39 #include "signalbuffer.h"
40 #include "sound_func.h"
41 #include "autoreplace_func.h"
42 #include "company_gui.h"
43 #include "signs_base.h"
44 #include "subsidy_base.h"
45 #include "subsidy_func.h"
46 #include "station_base.h"
47 #include "waypoint_base.h"
48 #include "economy_base.h"
49 #include "core/pool_func.hpp"
50 #include "core/backup_type.hpp"
51 #include "core/bitmath_func.hpp"
52 #include "cargo_type.h"
53 #include "water.h"
54 #include "game/game.hpp"
55 #include "cargomonitor.h"
56 #include "goal_base.h"
57 #include "story_base.h"
58 #include "linkgraph/refresh.h"
60 #include "table/strings.h"
61 #include "table/pricebase.h"
64 /* Initialize the cargo payment-pool */
65 template<> CargoPayment::Pool CargoPayment::PoolItem::pool ("CargoPayment");
66 INSTANTIATE_POOL_METHODS(CargoPayment)
68 /**
69 * Multiply two integer values and shift the results to right.
71 * This function multiplies two integer values. The result is
72 * shifted by the amount of shift to right.
74 * @param a The first integer
75 * @param b The second integer
76 * @param shift The amount to shift the value to right.
77 * @return The shifted result
79 static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
81 return (int32)((int64)a * (int64)b >> shift);
84 typedef SmallVector<Industry *, 16> SmallIndustryList;
86 /**
87 * Score info, values used for computing the detailed performance rating.
89 const ScoreInfo _score_info[] = {
90 { 120, 100}, // SCORE_VEHICLES
91 { 80, 100}, // SCORE_STATIONS
92 { 10000, 100}, // SCORE_MIN_PROFIT
93 { 50000, 50}, // SCORE_MIN_INCOME
94 { 100000, 100}, // SCORE_MAX_INCOME
95 { 40000, 400}, // SCORE_DELIVERED
96 { 8, 50}, // SCORE_CARGO
97 {10000000, 50}, // SCORE_MONEY
98 { 250000, 50}, // SCORE_LOAN
99 { 0, 0} // SCORE_TOTAL
102 int _score_part[MAX_COMPANIES][SCORE_END];
103 Economy _economy;
104 Prices _price;
105 Money _additional_cash_required;
106 static PriceMultipliers _price_base_multiplier;
109 * Calculate the value of the company. That is the value of all
110 * assets (vehicles, stations, etc) and money minus the loan,
111 * except when including_loan is \c false which is useful when
112 * we want to calculate the value for bankruptcy.
113 * @param c the company to get the value of.
114 * @param including_loan include the loan in the company value.
115 * @return the value of the company.
117 Money CalculateCompanyValue(const Company *c, bool including_loan)
119 Owner owner = c->index;
121 Station *st;
122 uint num = 0;
124 FOR_ALL_STATIONS(st) {
125 if (st->owner == owner) num += CountBits((byte)st->facilities);
128 Money value = num * _price[PR_STATION_VALUE] * 25;
130 Vehicle *v;
131 FOR_ALL_VEHICLES(v) {
132 if (v->owner != owner) continue;
134 if (v->type == VEH_TRAIN ||
135 v->type == VEH_ROAD ||
136 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) ||
137 v->type == VEH_SHIP) {
138 value += v->value * 3 >> 1;
142 /* Add real money value */
143 if (including_loan) value -= c->current_loan;
144 value += c->money;
146 return max(value, (Money)1);
150 * if update is set to true, the economy is updated with this score
151 * (also the house is updated, should only be true in the on-tick event)
152 * @param update the economy with calculated score
153 * @param c company been evaluated
154 * @return actual score of this company
157 int UpdateCompanyRatingAndValue(Company *c, bool update)
159 Owner owner = c->index;
160 int score = 0;
162 memset(_score_part[owner], 0, sizeof(_score_part[owner]));
164 /* Count vehicles */
166 Vehicle *v;
167 Money min_profit = 0;
168 bool min_profit_first = true;
169 uint num = 0;
171 FOR_ALL_VEHICLES(v) {
172 if (v->owner != owner) continue;
173 if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
174 if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
175 if (v->age > 730) {
176 /* Find the vehicle with the lowest amount of profit */
177 if (min_profit_first || min_profit > v->profit_last_year) {
178 min_profit = v->profit_last_year;
179 min_profit_first = false;
185 min_profit >>= 8; // remove the fract part
187 _score_part[owner][SCORE_VEHICLES] = num;
188 /* Don't allow negative min_profit to show */
189 if (min_profit > 0) {
190 _score_part[owner][SCORE_MIN_PROFIT] = ClampToI32(min_profit);
194 /* Count stations */
196 uint num = 0;
197 const Station *st;
199 FOR_ALL_STATIONS(st) {
200 /* Only count stations that are actually serviced */
201 if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
203 _score_part[owner][SCORE_STATIONS] = num;
206 /* Generate statistics depending on recent income statistics */
208 int numec = min(c->num_valid_stat_ent, 12);
209 if (numec != 0) {
210 const CompanyEconomyEntry *cee = c->old_economy;
211 Money min_income = cee->income + cee->expenses;
212 Money max_income = cee->income + cee->expenses;
214 do {
215 min_income = min(min_income, cee->income + cee->expenses);
216 max_income = max(max_income, cee->income + cee->expenses);
217 } while (++cee, --numec);
219 if (min_income > 0) {
220 _score_part[owner][SCORE_MIN_INCOME] = ClampToI32(min_income);
223 _score_part[owner][SCORE_MAX_INCOME] = ClampToI32(max_income);
227 /* Generate score depending on amount of transported cargo */
229 int numec = min(c->num_valid_stat_ent, 4);
230 if (numec != 0) {
231 const CompanyEconomyEntry *cee = c->old_economy;
232 OverflowSafeInt64 total_delivered = 0;
233 do {
234 total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
235 } while (++cee, --numec);
237 _score_part[owner][SCORE_DELIVERED] = ClampToI32(total_delivered);
241 /* Generate score for variety of cargo */
243 _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
246 /* Generate score for company's money */
248 if (c->money > 0) {
249 _score_part[owner][SCORE_MONEY] = ClampToI32(c->money);
253 /* Generate score for loan */
255 _score_part[owner][SCORE_LOAN] = ClampToI32(_score_info[SCORE_LOAN].needed - c->current_loan);
258 /* Now we calculate the score for each item.. */
260 int total_score = 0;
261 int s;
262 score = 0;
263 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
264 /* Skip the total */
265 if (i == SCORE_TOTAL) continue;
266 /* Check the score */
267 s = Clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
268 score += s;
269 total_score += _score_info[i].score;
272 _score_part[owner][SCORE_TOTAL] = score;
274 /* We always want the score scaled to SCORE_MAX (1000) */
275 if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
278 if (update) {
279 c->old_economy[0].performance_history = score;
280 UpdateCompanyHQ(c->location_of_HQ, score);
281 c->old_economy[0].company_value = CalculateCompanyValue(c);
284 SetWindowDirty(WC_PERFORMANCE_DETAIL, 0);
285 return score;
289 * Change the ownership of all the items of a company.
290 * @param old_owner The company that gets removed.
291 * @param new_owner The company to merge to, or INVALID_OWNER to remove the company.
293 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
295 /* We need to set _current_company to old_owner before we try to move
296 * the client. This is needed as it needs to know whether "you" really
297 * are the current local company. */
298 Backup<CompanyByte> cur_company(_current_company, old_owner, FILE_LINE);
299 #ifdef ENABLE_NETWORK
300 /* In all cases, make spectators of clients connected to that company */
301 if (_networking) NetworkClientsToSpectators(old_owner);
302 #endif /* ENABLE_NETWORK */
303 if (old_owner == _local_company) {
304 /* Single player cheated to AI company.
305 * There are no spectators in single player, so we must pick some other company. */
306 assert(!_networking);
307 Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
308 Company *c;
309 FOR_ALL_COMPANIES(c) {
310 if (c->index != old_owner) {
311 SetLocalCompany(c->index);
312 break;
315 cur_company2.Restore();
316 assert(old_owner != _local_company);
319 Town *t;
321 assert(old_owner != new_owner);
324 Company *c;
325 uint i;
327 /* See if the old_owner had shares in other companies */
328 FOR_ALL_COMPANIES(c) {
329 for (i = 0; i < 4; i++) {
330 if (c->share_owners[i] == old_owner) {
331 /* Sell his shares */
332 CommandCost res = DoCommand(0, c->index, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
333 /* Because we are in a DoCommand, we can't just execute another one and
334 * expect the money to be removed. We need to do it ourself! */
335 SubtractMoneyFromCompany(res);
340 /* Sell all the shares that people have on this company */
341 Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
342 c = Company::Get(old_owner);
343 for (i = 0; i < 4; i++) {
344 cur_company2.Change(c->share_owners[i]);
345 if (_current_company != INVALID_OWNER) {
346 /* Sell the shares */
347 CommandCost res = DoCommand(0, old_owner, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY);
348 /* Because we are in a DoCommand, we can't just execute another one and
349 * expect the money to be removed. We need to do it ourself! */
350 SubtractMoneyFromCompany(res);
353 cur_company2.Restore();
356 /* Temporarily increase the company's money, to be sure that
357 * removing his/her property doesn't fail because of lack of money.
358 * Not too drastically though, because it could overflow */
359 if (new_owner == INVALID_OWNER) {
360 Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
363 Subsidy *s;
364 FOR_ALL_SUBSIDIES(s) {
365 if (s->awarded == old_owner) {
366 if (new_owner == INVALID_OWNER) {
367 delete s;
368 } else {
369 s->awarded = new_owner;
373 if (new_owner == INVALID_OWNER) RebuildSubsidisedSourceAndDestinationCache();
375 /* Take care of rating and transport rights in towns */
376 FOR_ALL_TOWNS(t) {
377 /* If a company takes over, give the ratings to that company. */
378 if (new_owner != INVALID_OWNER) {
379 if (HasBit(t->have_ratings, old_owner)) {
380 if (HasBit(t->have_ratings, new_owner)) {
381 /* use max of the two ratings. */
382 t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]);
383 } else {
384 SetBit(t->have_ratings, new_owner);
385 t->ratings[new_owner] = t->ratings[old_owner];
390 /* Reset the ratings for the old owner */
391 t->ratings[old_owner] = RATING_INITIAL;
392 ClrBit(t->have_ratings, old_owner);
394 /* Transfer exclusive rights */
395 if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
396 if (new_owner != INVALID_OWNER) {
397 t->exclusivity = new_owner;
398 } else {
399 t->exclusive_counter = 0;
400 t->exclusivity = INVALID_COMPANY;
406 Vehicle *v;
407 FOR_ALL_VEHICLES(v) {
408 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
409 if (new_owner == INVALID_OWNER) {
410 if (v->Previous() == NULL) delete v;
411 } else {
412 if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
413 if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
419 /* In all cases clear replace engine rules.
420 * Even if it was copied, it could interfere with new owner's rules */
421 RemoveAllEngineReplacementForCompany(Company::Get(old_owner));
423 if (new_owner == INVALID_OWNER) {
424 RemoveAllGroupsForCompany(old_owner);
425 } else {
426 Group *g;
427 FOR_ALL_GROUPS(g) {
428 if (g->owner == old_owner) g->owner = new_owner;
433 FreeUnitIDGenerator unitidgen[] = {
434 FreeUnitIDGenerator(VEH_TRAIN, new_owner), FreeUnitIDGenerator(VEH_ROAD, new_owner),
435 FreeUnitIDGenerator(VEH_SHIP, new_owner), FreeUnitIDGenerator(VEH_AIRCRAFT, new_owner)
438 /* Override company settings to new company defaults in case we need to convert them.
439 * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
441 if (new_owner != INVALID_OWNER) {
442 Company *old_company = Company::Get(old_owner);
443 Company *new_company = Company::Get(new_owner);
445 old_company->settings.vehicle.servint_aircraft = new_company->settings.vehicle.servint_aircraft;
446 old_company->settings.vehicle.servint_trains = new_company->settings.vehicle.servint_trains;
447 old_company->settings.vehicle.servint_roadveh = new_company->settings.vehicle.servint_roadveh;
448 old_company->settings.vehicle.servint_ships = new_company->settings.vehicle.servint_ships;
449 old_company->settings.vehicle.servint_ispercent = new_company->settings.vehicle.servint_ispercent;
452 Vehicle *v;
453 FOR_ALL_VEHICLES(v) {
454 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
455 assert(new_owner != INVALID_OWNER);
457 /* Correct default values of interval settings while maintaining custom set ones.
458 * This prevents invalid values on mismatching company defaults being accepted.
460 if (!v->ServiceIntervalIsCustom()) {
461 Company *new_company = Company::Get(new_owner);
463 /* Technically, passing the interval is not needed as the command will query the default value itself.
464 * However, do not rely on that behaviour.
466 int interval = CompanyServiceInterval(new_company, v->type);
467 DoCommand(v->tile, v->index, interval | (new_company->settings.vehicle.servint_ispercent << 17), DC_EXEC | DC_BANKRUPT, CMD_CHANGE_SERVICE_INT);
470 v->owner = new_owner;
472 /* Owner changes, clear cache */
473 v->colourmap = PAL_NONE;
474 v->InvalidateNewGRFCache();
476 if (v->IsEngineCountable()) {
477 GroupStatistics::CountEngine(v, 1);
479 if (v->IsPrimaryVehicle()) {
480 GroupStatistics::CountVehicle(v, 1);
481 v->unitnumber = unitidgen[v->type].NextID();
484 /* Invalidate the vehicle's cargo payment "owner cache". */
485 if (v->cargo_payment != NULL) v->cargo_payment->owner = NULL;
489 if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
492 /* Change ownership of tiles */
494 TileIndex tile = 0;
495 do {
496 ChangeTileOwner(tile, old_owner, new_owner);
497 } while (++tile != MapSize());
499 if (new_owner != INVALID_OWNER) {
500 /* Update all signals because there can be new segment that was owned by two companies
501 * and signals were not propagated
502 * Similar with crossings - it is needed to bar crossings that weren't before
503 * because of different owner of crossing and approaching train */
504 tile = 0;
506 do {
507 if (IsRailwayTile(tile) && IsTileOwner(tile, new_owner)) {
508 TrackBits tracks = GetTrackBits(tile);
509 do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
510 Track track = RemoveFirstTrack(&tracks);
511 if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
512 } while (tracks != TRACK_BIT_NONE);
513 } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
514 UpdateLevelCrossing(tile);
516 } while (++tile != MapSize());
519 /* update signals in buffer */
520 UpdateSignalsInBuffer();
523 /* Add airport infrastructure count of the old company to the new one. */
524 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
526 /* convert owner of stations (including deleted ones, but excluding buoys) */
527 Station *st;
528 FOR_ALL_STATIONS(st) {
529 if (st->owner == old_owner) {
530 /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
531 * also, drawing station window would cause reading invalid company's colour */
532 st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
536 /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
537 Waypoint *wp;
538 FOR_ALL_WAYPOINTS(wp) {
539 if (wp->owner == old_owner) {
540 wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
544 Sign *si;
545 FOR_ALL_SIGNS(si) {
546 if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
549 /* Remove Game Script created Goals, CargoMonitors and Story pages. */
550 Goal *g;
551 FOR_ALL_GOALS(g) {
552 if (g->company == old_owner) delete g;
555 ClearCargoPickupMonitoring(old_owner);
556 ClearCargoDeliveryMonitoring(old_owner);
558 StoryPage *sp;
559 FOR_ALL_STORY_PAGES(sp) {
560 if (sp->company == old_owner) delete sp;
563 /* Change colour of existing windows */
564 if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
566 cur_company.Restore();
568 MarkWholeScreenDirty();
572 * Check for bankruptcy of a company. Called every three months.
573 * @param c Company to check.
575 static void CompanyCheckBankrupt(Company *c)
577 /* If the company has money again, it does not go bankrupt */
578 if (c->money - c->current_loan >= -_economy.max_loan) {
579 c->months_of_bankruptcy = 0;
580 c->bankrupt_asked = 0;
581 return;
584 c->months_of_bankruptcy++;
586 switch (c->months_of_bankruptcy) {
587 /* All the boring cases (months) with a bad balance where no action is taken */
588 case 0:
589 case 1:
590 case 2:
591 case 3:
593 case 5:
594 case 6:
596 case 8:
597 case 9:
598 break;
600 /* Warn about bankruptcy after 3 months */
601 case 4:
602 AddNewsItem<CompanyNewsItem> (STR_NEWS_COMPANY_IN_TROUBLE_TITLE,
603 STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION, c);
604 AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
605 Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
606 break;
608 /* Offer company for sale after 6 months */
609 case 7: {
610 /* Don't consider the loan */
611 Money val = CalculateCompanyValue(c, false);
613 c->bankrupt_value = val;
614 c->bankrupt_asked = 1 << c->index; // Don't ask the owner
615 c->bankrupt_timeout = 0;
617 /* The company assets should always have some value */
618 assert(c->bankrupt_value > 0);
619 break;
622 /* Bankrupt company after 6 months (if the company has no value) or latest
623 * after 9 months (if it still had value after 6 months) */
624 default:
625 case 10: {
626 if (!_networking && _local_company == c->index) {
627 /* If we are in offline mode, leave the company playing. Eg. there
628 * is no THE-END, otherwise mark the client as spectator to make sure
629 * he/she is no long in control of this company. However... when you
630 * join another company (cheat) the "unowned" company can bankrupt. */
631 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
632 break;
635 /* Actually remove the company, but not when we're a network client.
636 * In case of network clients we will be getting a command from the
637 * server. It is done in this way as we are called from the
638 * StateGameLoop which can't change the current company, and thus
639 * updating the local company triggers an assert later on. In the
640 * case of a network game the command will be processed at a time
641 * that changing the current company is okay. In case of single
642 * player we are sure (the above check) that we are not the local
643 * company and thus we won't be moved. */
644 if (!_networking || _network_server) DoCommandP(0, 2 | (c->index << 16), CRR_BANKRUPT, CMD_COMPANY_CTRL);
645 break;
651 * Update the finances of all companies.
652 * Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy.
654 static void CompaniesGenStatistics()
656 Station *st;
658 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
659 Company *c;
661 if (!_settings_game.economy.infrastructure_maintenance) {
662 FOR_ALL_STATIONS(st) {
663 cur_company.Change(st->owner);
664 CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1);
665 SubtractMoneyFromCompany(cost);
667 } else {
668 /* Improved monthly infrastructure costs. */
669 FOR_ALL_COMPANIES(c) {
670 cur_company.Change(c->index);
672 CommandCost cost(EXPENSES_PROPERTY);
673 uint32 rail_total = c->infrastructure.GetRailTotal();
674 for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
675 if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
677 cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
678 for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
679 if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt]));
681 cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
682 cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
683 cost.AddCost(AirportMaintenanceCost(c->index));
685 SubtractMoneyFromCompany(cost);
688 cur_company.Restore();
690 /* Check for bankruptcy each month */
691 FOR_ALL_COMPANIES(c) {
692 CompanyCheckBankrupt(c);
695 /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
696 if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return;
698 FOR_ALL_COMPANIES(c) {
699 memmove(&c->old_economy[1], &c->old_economy[0], sizeof(c->old_economy) - sizeof(c->old_economy[0]));
700 c->old_economy[0] = c->cur_economy;
701 memset(&c->cur_economy, 0, sizeof(c->cur_economy));
703 if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
705 UpdateCompanyRatingAndValue(c, true);
706 if (c->block_preview != 0) c->block_preview--;
709 SetWindowDirty(WC_INCOME_GRAPH, 0);
710 SetWindowDirty(WC_OPERATING_PROFIT, 0);
711 SetWindowDirty(WC_DELIVERED_CARGO, 0);
712 SetWindowDirty(WC_PERFORMANCE_HISTORY, 0);
713 SetWindowDirty(WC_COMPANY_VALUE, 0);
714 SetWindowDirty(WC_COMPANY_LEAGUE, 0);
718 * Add monthly inflation
719 * @param check_year Shall the inflation get stopped after 170 years?
720 * @return true if inflation is maxed and nothing was changed
722 bool AddInflation(bool check_year)
724 /* The cargo payment inflation differs from the normal inflation, so the
725 * relative amount of money you make with a transport decreases slowly over
726 * the 170 years. After a few hundred years we reach a level in which the
727 * games will become unplayable as the maximum income will be less than
728 * the minimum running cost.
730 * Furthermore there are a lot of inflation related overflows all over the
731 * place. Solving them is hardly possible because inflation will always
732 * reach the overflow threshold some day. So we'll just perform the
733 * inflation mechanism during the first 170 years (the amount of years that
734 * one had in the original TTD) and stop doing the inflation after that
735 * because it only causes problems that can't be solved nicely and the
736 * inflation doesn't add anything after that either; it even makes playing
737 * it impossible due to the diverging cost and income rates.
739 if (check_year && (_cur_year - _settings_game.game_creation.starting_year) >= (ORIGINAL_MAX_YEAR - ORIGINAL_BASE_YEAR)) return true;
741 if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
743 /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
744 * scaled by 65536
745 * 12 -> months per year
746 * This is only a good approximation for small values
748 _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16;
749 _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
751 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
752 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
754 return false;
758 * Computes all prices, payments and maximum loan.
760 void RecomputePrices()
762 /* Setup maximum loan */
763 _economy.max_loan = (_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000;
765 /* Setup price bases */
766 for (Price i = PR_BEGIN; i < PR_END; i++) {
767 Money price = _price_base_specs[i].start_price;
769 /* Apply difficulty settings */
770 uint mod = 1;
771 switch (_price_base_specs[i].category) {
772 case PCAT_RUNNING:
773 mod = _settings_game.difficulty.vehicle_costs;
774 break;
776 case PCAT_CONSTRUCTION:
777 mod = _settings_game.difficulty.construction_cost;
778 break;
780 default: break;
782 switch (mod) {
783 case 0: price *= 6; break;
784 case 1: price *= 8; break; // normalised to 1 below
785 case 2: price *= 9; break;
786 default: NOT_REACHED();
789 /* Apply inflation */
790 price = (int64)price * _economy.inflation_prices;
792 /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
793 int shift = _price_base_multiplier[i] - 16 - 3;
794 if (shift >= 0) {
795 price <<= shift;
796 } else {
797 price >>= -shift;
800 /* Make sure the price does not get reduced to zero.
801 * Zero breaks quite a few commands that use a zero
802 * cost to see whether something got changed or not
803 * and based on that cause an error. When the price
804 * is zero that fails even when things are done. */
805 if (price == 0) {
806 price = Clamp(_price_base_specs[i].start_price, -1, 1);
807 /* No base price should be zero, but be sure. */
808 assert(price != 0);
810 /* Store value */
811 _price[i] = price;
814 /* Setup cargo payment */
815 CargoSpec *cs;
816 FOR_ALL_CARGOSPECS(cs) {
817 cs->current_payment = ((int64)cs->initial_payment * _economy.inflation_payment) >> 16;
820 SetWindowClassesDirty(WC_BUILD_VEHICLE);
821 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
822 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
823 SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE);
824 InvalidateWindowData(WC_PAYMENT_RATES, 0);
827 /** Let all companies pay the monthly interest on their loan. */
828 static void CompaniesPayInterest()
830 const Company *c;
832 Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
833 FOR_ALL_COMPANIES(c) {
834 cur_company.Change(c->index);
836 /* Over a year the paid interest should be "loan * interest percentage",
837 * but... as that number is likely not dividable by 12 (pay each month),
838 * one needs to account for that in the monthly fee calculations.
839 * To easily calculate what one should pay "this" month, you calculate
840 * what (total) should have been paid up to this month and you subtract
841 * whatever has been paid in the previous months. This will mean one month
842 * it'll be a bit more and the other it'll be a bit less than the average
843 * monthly fee, but on average it will be exact.
844 * In order to prevent cheating or abuse (just not paying interest by not
845 * taking a loan we make companies pay interest on negative cash as well
847 Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
848 if (c->money < 0) {
849 yearly_fee += -c->money *_economy.interest_rate / 100;
851 Money up_to_previous_month = yearly_fee * _cur_month / 12;
852 Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12;
854 SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month));
856 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
858 cur_company.Restore();
861 static void HandleEconomyFluctuations()
863 if (_settings_game.difficulty.economy != 0) {
864 /* When economy is Fluctuating, decrease counter */
865 _economy.fluct--;
866 } else if (EconomyIsInRecession()) {
867 /* When it's Steady and we are in recession, end it now */
868 _economy.fluct = -12;
869 } else {
870 /* No need to do anything else in other cases */
871 return;
874 StringID str;
875 if (_economy.fluct == 0) {
876 _economy.fluct = -(int)GB(Random(), 0, 2);
877 str = STR_NEWS_BEGIN_OF_RECESSION;
878 } else if (_economy.fluct == -12) {
879 _economy.fluct = GB(Random(), 0, 8) + 312;
880 str = STR_NEWS_END_OF_RECESSION;
881 } else {
882 return;
884 AddNewsItem<NewsItem> (str, NT_ECONOMY, NF_NORMAL);
889 * Reset changes to the price base multipliers.
891 void ResetPriceBaseMultipliers()
893 memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
897 * Change a price base by the given factor.
898 * The price base is altered by factors of two.
899 * NewBaseCost = OldBaseCost * 2^n
900 * @param price Index of price base to change.
901 * @param factor Amount to change by.
903 void SetPriceBaseMultiplier(Price price, int factor)
905 assert(price < PR_END);
906 _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
910 * Initialize the variables that will maintain the daily industry change system.
911 * @param init_counter specifies if the counter is required to be initialized
913 void StartupIndustryDailyChanges(bool init_counter)
915 uint map_size = MapLogX() + MapLogY();
916 /* After getting map size, it needs to be scaled appropriately and divided by 31,
917 * which stands for the days in a month.
918 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
919 * would not be needed.
920 * Since it is based on "fractional parts", the leftover days will not make much of a difference
921 * on the overall total number of changes performed */
922 _economy.industry_daily_increment = (1 << map_size) / 31;
924 if (init_counter) {
925 /* A new game or a savegame from an older version will require the counter to be initialized */
926 _economy.industry_daily_change_counter = 0;
930 void StartupEconomy()
932 _economy.interest_rate = _settings_game.difficulty.initial_interest;
933 _economy.infl_amount = _settings_game.difficulty.initial_interest;
934 _economy.infl_amount_pr = max(0, _settings_game.difficulty.initial_interest - 1);
935 _economy.fluct = GB(Random(), 0, 8) + 168;
937 /* Set up prices */
938 RecomputePrices();
940 StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
945 * Resets economy to initial values
947 void InitializeEconomy()
949 _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
950 ClearCargoPickupMonitoring();
951 ClearCargoDeliveryMonitoring();
955 * Determine a certain price
956 * @param index Price base
957 * @param cost_factor Price factor
958 * @param grf_file NewGRF to use local price multipliers from.
959 * @param shift Extra bit shifting after the computation
960 * @return Price
962 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
964 if (index >= PR_END) return 0;
966 Money cost = _price[index] * cost_factor;
967 if (grf_file != NULL) shift += grf_file->price_base_multipliers[index];
969 if (shift >= 0) {
970 cost <<= shift;
971 } else {
972 cost >>= -shift;
975 return cost;
978 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
980 const CargoSpec *cs = CargoSpec::Get(cargo_type);
981 if (!cs->IsValid()) {
982 /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
983 return 0;
986 /* Use callback to calculate cargo profit, if available */
987 if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
988 uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
989 uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
990 if (callback != CALLBACK_FAILED) {
991 int result = GB(callback, 0, 14);
993 /* Simulate a 15 bit signed value */
994 if (HasBit(callback, 14)) result -= 0x4000;
996 /* "The result should be a signed multiplier that gets multiplied
997 * by the amount of cargo moved and the price factor, then gets
998 * divided by 8192." */
999 return result * num_pieces * cs->current_payment / 8192;
1003 static const int MIN_TIME_FACTOR = 31;
1004 static const int MAX_TIME_FACTOR = 255;
1006 const int days1 = cs->transit_days[0];
1007 const int days2 = cs->transit_days[1];
1008 const int days_over_days1 = max( transit_days - days1, 0);
1009 const int days_over_days2 = max(days_over_days1 - days2, 0);
1012 * The time factor is calculated based on the time it took
1013 * (transit_days) compared two cargo-depending values. The
1014 * range is divided into three parts:
1016 * - constant for fast transits
1017 * - linear decreasing with time with a slope of -1 for medium transports
1018 * - linear decreasing with time with a slope of -2 for slow transports
1021 const int time_factor = max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
1023 return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
1026 /** The industries we've currently brought cargo to. */
1027 static SmallIndustryList _cargo_delivery_destinations;
1030 * Transfer goods from station to industry.
1031 * All cargo is delivered to the nearest (Manhattan) industry to the station sign, which is inside the acceptance rectangle and actually accepts the cargo.
1032 * @param st The station that accepted the cargo
1033 * @param cargo_type Type of cargo delivered
1034 * @param num_pieces Amount of cargo delivered
1035 * @param source The source of the cargo
1036 * @return actually accepted pieces of cargo
1038 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source)
1040 /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1041 * This fails in three cases:
1042 * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1043 * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1044 * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1047 uint accepted = 0;
1049 for (uint i = 0; i < st->industries_near.Length() && num_pieces != 0; i++) {
1050 Industry *ind = st->industries_near[i];
1051 if (ind->index == source) continue;
1053 uint cargo_index;
1054 for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
1055 if (cargo_type == ind->accepts_cargo[cargo_index]) break;
1057 /* Check if matching cargo has been found */
1058 if (cargo_index >= lengthof(ind->accepts_cargo)) continue;
1060 /* Check if industry temporarily refuses acceptance */
1061 if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
1063 /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1064 _cargo_delivery_destinations.Include(ind);
1066 uint amount = min(num_pieces, 0xFFFFU - ind->incoming_cargo_waiting[cargo_index]);
1067 ind->incoming_cargo_waiting[cargo_index] += amount;
1068 num_pieces -= amount;
1069 accepted += amount;
1072 return accepted;
1076 * Delivers goods to industries/towns and calculates the payment
1077 * @param num_pieces amount of cargo delivered
1078 * @param cargo_type the type of cargo that is delivered
1079 * @param dest Station the cargo has been unloaded
1080 * @param source_tile The origin of the cargo for distance calculation
1081 * @param days_in_transit Travel time
1082 * @param company The company delivering the cargo
1083 * @param src Source of cargo
1084 * @return Revenue for delivering cargo
1085 * @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
1087 static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID dest, TileIndex source_tile, byte days_in_transit, Company *company, const CargoSource &src)
1089 assert(num_pieces > 0);
1091 Station *st = Station::Get(dest);
1093 /* Give the goods to the industry. */
1094 uint accepted = DeliverGoodsToIndustry (st, cargo_type, num_pieces, src.type == ST_INDUSTRY ? src.id : INVALID_INDUSTRY);
1096 /* If this cargo type is always accepted, accept all */
1097 if (HasBit(st->always_accepted, cargo_type)) accepted = num_pieces;
1099 /* Update station statistics */
1100 if (accepted > 0) {
1101 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_EVER_ACCEPTED);
1102 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_CURRENT_MONTH);
1103 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
1106 /* Update company statistics */
1107 company->cur_economy.delivered_cargo[cargo_type] += accepted;
1109 /* Increase town's counter for town effects */
1110 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1111 st->town->received[cs->town_effect].new_act += accepted;
1113 /* Determine profit */
1114 Money profit = GetTransportedGoodsIncome(accepted, DistanceManhattan(source_tile, st->xy), days_in_transit, cargo_type);
1116 /* Update the cargo monitor. */
1117 AddCargoDelivery (cargo_type, company->index, accepted, src, st);
1119 /* Modify profit if a subsidy is in effect */
1120 if (CheckSubsidised (cargo_type, company->index, src, st)) {
1121 switch (_settings_game.difficulty.subsidy_multiplier) {
1122 case 0: profit += profit >> 1; break;
1123 case 1: profit *= 2; break;
1124 case 2: profit *= 3; break;
1125 default: profit *= 4; break;
1129 return profit;
1133 * Inform the industry about just delivered cargo
1134 * DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.
1135 * @param i The industry to process
1137 static void TriggerIndustryProduction(Industry *i)
1139 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1140 uint16 callback = indspec->callback_mask;
1142 i->was_cargo_delivered = true;
1143 i->last_cargo_accepted_at = _date;
1145 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
1146 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
1147 IndustryProductionCallback(i, 0);
1148 } else {
1149 SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
1151 } else {
1152 for (uint cargo_index = 0; cargo_index < lengthof(i->incoming_cargo_waiting); cargo_index++) {
1153 uint cargo_waiting = i->incoming_cargo_waiting[cargo_index];
1154 if (cargo_waiting == 0) continue;
1156 i->produced_cargo_waiting[0] = min(i->produced_cargo_waiting[0] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][0] / 256), 0xFFFF);
1157 i->produced_cargo_waiting[1] = min(i->produced_cargo_waiting[1] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][1] / 256), 0xFFFF);
1159 i->incoming_cargo_waiting[cargo_index] = 0;
1163 TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO);
1164 StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
1168 * Makes us a new cargo payment helper.
1169 * @param front The front of the train
1171 CargoPayment::CargoPayment(Vehicle *front) :
1172 front(front),
1173 current_station(front->last_station_visited)
1177 CargoPayment::~CargoPayment()
1179 if (this->CleaningPool()) return;
1181 this->front->cargo_payment = NULL;
1183 if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1185 Backup<CompanyByte> cur_company(_current_company, this->front->owner, FILE_LINE);
1187 SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit));
1188 this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1190 if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
1191 SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1194 if (this->visual_transfer != 0) {
1195 ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos,
1196 this->front->z_pos, this->visual_transfer, -this->visual_profit);
1197 } else if (this->visual_profit != 0) {
1198 ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos,
1199 this->front->z_pos, -this->visual_profit);
1202 cur_company.Restore();
1206 * Handle payment for final delivery of the given cargo packet.
1207 * @param cp The cargo packet to pay for.
1208 * @param count The number of packets to pay for.
1210 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
1212 if (this->owner == NULL) {
1213 this->owner = Company::Get(this->front->owner);
1216 /* Handle end of route payment */
1217 Money profit = DeliverGoods (count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->Source());
1218 this->route_profit += profit;
1220 /* The vehicle's profit is whatever route profit there is minus feeder shares. */
1221 this->visual_profit += profit - cp->FeederShare(count);
1225 * Handle payment for transfer of the given cargo packet.
1226 * @param cp The cargo packet to pay for; actual payment won't be made!.
1227 * @param count The number of packets to pay for.
1228 * @return The amount of money paid for the transfer.
1230 Money CargoPayment::PayTransfer(const CargoPacket *cp, uint count)
1232 Money profit = GetTransportedGoodsIncome(
1233 count,
1234 /* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */
1235 DistanceManhattan(cp->LoadedAtXY(), Station::Get(this->current_station)->xy),
1236 cp->DaysInTransit(),
1237 this->ct);
1239 profit = profit * _settings_game.economy.feeder_payment_share / 100;
1241 this->visual_transfer += profit; // accumulate transfer profits for whole vehicle
1242 return profit; // account for the (virtual) profit already made for the cargo packet
1246 * Prepare the vehicle to be unloaded.
1247 * @param curr_station the station where the consist is at the moment
1248 * @param front_v the vehicle to be unloaded
1250 void PrepareUnload(Vehicle *front_v)
1252 Station *curr_station = Station::Get(front_v->last_station_visited);
1253 curr_station->loading_vehicles.push_back(front_v);
1255 /* At this moment loading cannot be finished */
1256 ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED);
1258 /* Start unloading at the first possible moment */
1259 front_v->load_unload_ticks = 1;
1261 assert(front_v->cargo_payment == NULL);
1262 /* One CargoPayment per vehicle and the vehicle limit equals the
1263 * limit in number of CargoPayments. Can't go wrong. */
1264 assert_compile(CargoPayment::Pool::MAX_SIZE == Vehicle::Pool::MAX_SIZE);
1265 assert(CargoPayment::CanAllocateItem());
1266 front_v->cargo_payment = new CargoPayment(front_v);
1268 StationIDStack next_station;
1269 front_v->AppendNextStoppingStations (&next_station);
1270 if (front_v->orders.list == NULL || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1271 Station *st = Station::Get(front_v->last_station_visited);
1272 for (Vehicle *v = front_v; v != NULL; v = v->Next()) {
1273 const GoodsEntry *ge = &st->goods[v->cargo_type];
1274 if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1275 v->cargo.Stage(
1276 HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE),
1277 front_v->last_station_visited, next_station,
1278 front_v->current_order.GetUnloadType(), ge,
1279 front_v->cargo_payment);
1280 if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1287 * Gets the amount of cargo the given vehicle can load in the current tick.
1288 * This is only about loading speed. The free capacity is ignored.
1289 * @param v Vehicle to be queried.
1290 * @return Amount of cargo the vehicle can load at once.
1292 static uint GetLoadAmount(Vehicle *v)
1294 const Engine *e = v->GetEngine();
1295 uint load_amount = e->info.load_amount;
1297 /* The default loadamount for mail is 1/4 of the load amount for passengers */
1298 bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft();
1299 if (air_mail) load_amount = CeilDiv(load_amount, 4);
1301 if (_settings_game.order.gradual_loading) {
1302 uint16 cb_load_amount = CALLBACK_FAILED;
1303 if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
1304 /* Use callback 36 */
1305 cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1306 } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
1307 /* Use callback 12 */
1308 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1310 if (cb_load_amount != CALLBACK_FAILED) {
1311 if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1312 if (cb_load_amount >= 0x100) {
1313 ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT, cb_load_amount);
1314 } else if (cb_load_amount != 0) {
1315 load_amount = cb_load_amount;
1320 /* Scale load amount the same as capacity */
1321 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);
1323 /* Zero load amount breaks a lot of things. */
1324 return max(1u, load_amount);
1328 * Iterate the articulated parts of a vehicle, also considering the special cases of "normal"
1329 * aircraft and double headed trains. Apply an action to each vehicle and immediately return false
1330 * if that action does so. Otherwise return true.
1331 * @tparam Taction Class of action to be applied. Must implement bool operator()([const] Vehicle *).
1332 * @param v First articulated part.
1333 * @param action Instance of Taction.
1334 * @return false if any of the action invocations returned false, true otherwise.
1336 template<class Taction>
1337 bool IterateVehicleParts(Vehicle *v, Taction action)
1339 for (Vehicle *w = v; w != NULL;
1340 w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : NULL) {
1341 if (!action(w)) return false;
1342 if (w->type == VEH_TRAIN) {
1343 Train *train = Train::From(w);
1344 if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false;
1347 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next());
1348 return true;
1352 * Action to check if a vehicle has no stored cargo.
1354 struct IsEmptyAction
1357 * Checks if the vehicle has stored cargo.
1358 * @param v Vehicle to be checked.
1359 * @return true if v is either empty or has only reserved cargo, false otherwise.
1361 bool operator()(const Vehicle *v)
1363 return v->cargo.StoredCount() == 0;
1368 * Refit preparation action.
1370 struct PrepareRefitAction
1372 CargoArray &consist_capleft; ///< Capacities left in the consist.
1373 uint32 &refit_mask; ///< Bitmask of possible refit cargoes.
1376 * Create a refit preparation action.
1377 * @param consist_capleft Capacities left in consist, to be updated here.
1378 * @param refit_mask Refit mask to be constructed from refit information of vehicles.
1380 PrepareRefitAction(CargoArray &consist_capleft, uint32 &refit_mask) :
1381 consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1384 * Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and
1385 * adding the cargoes it can refit to to the refit mask.
1386 * @param v The vehicle to be refitted.
1387 * @return true.
1389 bool operator()(const Vehicle *v)
1391 this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount();
1392 this->refit_mask |= EngInfo(v->engine_type)->refit_mask;
1393 return true;
1398 * Action for returning reserved cargo.
1400 struct ReturnCargoAction
1402 Station *st; ///< Station to give the returned cargo to.
1405 * Construct a cargo return action.
1406 * @param st Station to give the returned cargo to.
1407 * @param next_one Next hop the cargo should be assigned to.
1409 ReturnCargoAction (Station *st) : st(st) {}
1412 * Return all reserved cargo from a vehicle.
1413 * @param v Vehicle to return cargo from.
1414 * @return true.
1416 bool operator()(Vehicle *v)
1418 v->cargo.Return (&this->st->goods[v->cargo_type].cargo);
1419 return true;
1424 * Action for finalizing a refit.
1426 struct FinalizeRefitAction
1428 CargoArray &consist_capleft; ///< Capacities left in the consist.
1429 Station *st; ///< Station to reserve cargo from.
1430 const StationIDStack &next_station; ///< Next hops to reserve cargo for.
1431 bool do_reserve; ///< If the vehicle should reserve.
1434 * Create a finalizing action.
1435 * @param consist_capleft Capacities left in the consist.
1436 * @param st Station to reserve cargo from.
1437 * @param next_station Next hops to reserve cargo for.
1438 * @param do_reserve If we should reserve cargo or just add up the capacities.
1440 FinalizeRefitAction (CargoArray &consist_capleft, Station *st, const StationIDStack &next_station, bool do_reserve) :
1441 consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve) {}
1444 * Reserve cargo from the station and update the remaining consist capacities with the
1445 * vehicle's remaining free capacity.
1446 * @param v Vehicle to be finalized.
1447 * @return true.
1449 bool operator()(Vehicle *v)
1451 if (this->do_reserve) {
1452 this->st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1453 &v->cargo, st->xy, this->next_station);
1455 this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1456 return true;
1461 * Refit a vehicle in a station.
1462 * @param v Vehicle to be refitted.
1463 * @param consist_capleft Added cargo capacities in the consist.
1464 * @param st Station the vehicle is loading at.
1465 * @param next_station Possible next stations the vehicle can travel to.
1466 * @param new_cid Target cargo mask for refit.
1467 * @return Whether vehicle is locked to a cargo.
1469 static bool HandleStationRefit (Vehicle *v, CargoArray &consist_capleft,
1470 Station *st, const StationIDStack &next_station, CargoMask new_mask)
1472 Vehicle *v_start = v->GetFirstEnginePart();
1473 if (!IterateVehicleParts(v_start, IsEmptyAction())) return true;
1475 Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1477 uint32 refit_mask = v->GetEngine()->info.refit_mask;
1479 /* Remove old capacity from consist capacity and collect refit mask. */
1480 IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask));
1482 bool is_auto_refit = !HasAtMostOneBit (new_mask);
1483 new_mask &= refit_mask;
1485 for (;;) {
1486 CargoID new_cid;
1487 if (new_mask == 0) {
1488 /* no refit possible */
1489 break;
1490 } else if (HasAtMostOneBit (new_mask)) {
1491 new_cid = FindFirstBit (new_mask);
1492 } else {
1493 /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1494 new_cid = v_start->cargo_type;
1495 if (!HasBit(new_mask, new_cid)) {
1496 /* Old cargo is not present in the allowed refits. */
1497 new_cid = FindFirstBit (new_mask);
1499 CargoID cid;
1500 FOR_EACH_SET_CARGO_ID(cid, new_mask) {
1501 if (st->goods[cid].cargo.HasCargoFor (next_station)) {
1502 /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1503 * the returned refit capacity will be greater than zero. */
1504 DoCommand (v_start->tile, v_start->index, cid | 1U << 6 | 0xFF << 8 | 1U << 16, DC_QUERY_COST, CMD_REFIT_VEHICLE); // Auto-refit and only this vehicle including artic parts.
1505 /* Try to balance different loadable cargoes between parts of the consist, so that
1506 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1507 * to the first loadable cargo for which there is only one packet. If the capacities
1508 * are equal refit to the cargo of which most is available. This is important for
1509 * consists of only a single vehicle as those will generally have a consist_capleft
1510 * of 0 for all cargoes. */
1511 if (_returned_refit_capacity > 0 && (consist_capleft[cid] < consist_capleft[new_cid] ||
1512 (consist_capleft[cid] == consist_capleft[new_cid] &&
1513 st->goods[cid].cargo.AvailableCount() > st->goods[new_cid].cargo.AvailableCount()))) {
1514 new_cid = cid;
1520 assert (new_cid < NUM_CARGO);
1521 assert (HasBit(new_mask, new_cid));
1523 /* Refit if given a different cargo. */
1524 if (new_cid == v_start->cargo_type) break;
1526 IterateVehicleParts (v_start, ReturnCargoAction (st));
1527 CommandCost cost = DoCommand(v_start->tile, v_start->index, new_cid | 1U << 6 | 0xFF << 8 | 1U << 16, DC_EXEC, CMD_REFIT_VEHICLE); // Auto-refit and only this vehicle including artic parts.
1528 /* The command may return a success status even if it
1529 * actually fails to refit the vehicle, so we also have
1530 * to check _returned_refit_capacity. */
1531 if (cost.Succeeded() && (_returned_refit_capacity > 0)) {
1532 v->First()->profit_this_year -= cost.GetCost() << 8;
1533 break;
1536 ClrBit(new_mask, new_cid);
1539 /* Add new capacity to consist capacity and reserve cargo */
1540 IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station,
1541 is_auto_refit || (v->First()->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0));
1543 cur_company.Restore();
1545 return HasAtMostOneBit (new_mask);
1548 struct ReserveCargoAction {
1549 Station *st;
1550 const StationIDStack &next_station;
1552 ReserveCargoAction (Station *st, const StationIDStack &next_station) :
1553 st(st), next_station(next_station) {}
1555 bool operator()(Vehicle *v)
1557 if (v->cargo_cap > v->cargo.RemainingCount()) {
1558 st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1559 &v->cargo, st->xy, next_station);
1562 return true;
1568 * Reserves cargo if the full load order and improved_load is set or if the
1569 * current order allows autorefit.
1570 * @param st Station where the consist is loading at the moment.
1571 * @param u Front of the loading vehicle consist.
1572 * @param consist_capleft If given, save free capacities after reserving there.
1573 * @param next_station Station(s) the vehicle will stop at next.
1575 static void ReserveConsist (Station *st, Vehicle *u,
1576 CargoArray *consist_capleft, const StationIDStack &next_station)
1578 /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1579 * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1580 * a vehicle belongs to already has the right cargo. */
1581 bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == NULL;
1582 for (Vehicle *v = u; v != NULL; v = v->Next()) {
1583 assert(v->cargo_cap >= v->cargo.RemainingCount());
1585 /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1586 * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1587 * to a different cargo and hasn't tried to do so, yet. */
1588 if (!v->IsArticulatedPart() &&
1589 (v->type != VEH_TRAIN || !Train::From(v)->IsRearDualheaded()) &&
1590 (v->type != VEH_AIRCRAFT || Aircraft::From(v)->IsNormalAircraft()) &&
1591 (must_reserve || u->current_order.GetRefitCargoMask() == (1u << v->cargo_type))) {
1592 IterateVehicleParts(v, ReserveCargoAction(st, next_station));
1594 if (consist_capleft == NULL || v->cargo_cap == 0) continue;
1595 (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1600 * Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload
1601 * again. Adjust for overhang of trains and set it at least to 1.
1602 * @param front The vehicle to be updated.
1603 * @param st The station the vehicle is loading at.
1604 * @param ticks The time it would normally wait, based on cargo loaded and unloaded.
1606 static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
1608 if (front->type == VEH_TRAIN) {
1609 /* Each platform tile is worth 2 rail vehicles. */
1610 TileIndex tile = front->tile;
1611 assert (st->TileBelongsToRailStation (tile));
1612 DiagDirection dir = (GetRailStationAxis (tile) == AXIS_X ?
1613 DIAGDIR_NE : DIAGDIR_SE);
1614 uint length = Station::GetPlatformLength (tile, dir)
1615 + Station::GetPlatformLength (tile,
1616 ReverseDiagDir (dir))
1617 - 1;
1618 int overhang = Train::From(front)->gcache.cached_total_length
1619 - length * TILE_SIZE;
1620 if (overhang > 0) {
1621 ticks <<= 1;
1622 ticks += (overhang * ticks) / 8;
1625 /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1626 front->load_unload_ticks = max(1, ticks);
1629 struct LoadingVehicle {
1630 Vehicle *v; ///< Loading vehicle.
1631 uint left; ///< Remaining capacity.
1632 uint load; ///< Loading step.
1633 uint steps; ///< Number of steps required for a full load.
1635 LoadingVehicle (Vehicle *v, uint left, uint load) : v (v), left (left)
1637 assert (left > 0);
1638 if (!_settings_game.order.gradual_loading) {
1639 this->load = left;
1640 this->steps = 0; // ignored
1641 } else if (load < left) {
1642 this->load = load;
1643 this->steps = CeilDiv (left, load);
1644 } else {
1645 this->load = left;
1646 this->steps = 1;
1650 bool operator < (const LoadingVehicle &other) const
1652 /* Sort by cargo first... */
1653 CargoID c = this->v->cargo_type;
1654 CargoID cc = other.v->cargo_type;
1655 if (c != cc) return c < cc;
1657 /* ...then by number of steps remaining for full load...*/
1658 if (this->steps != other.steps) return this->steps > other.steps;
1660 /* ...then by remaining capacity. */
1661 return this->left > other.left;
1666 * Loads/unload the vehicle if possible.
1667 * @param front the vehicle to be (un)loaded
1669 static void LoadUnloadVehicle(Vehicle *front)
1671 assert(front->current_order.IsType(OT_LOADING));
1673 StationID last_visited = front->last_station_visited;
1674 Station *st = Station::Get(last_visited);
1676 StationIDStack next_station;
1677 front->AppendNextStoppingStations (&next_station);
1678 bool use_autorefit = front->current_order.IsAutoRefit();
1679 CargoArray consist_capleft;
1680 if (_settings_game.order.improved_load && use_autorefit ?
1681 front->cargo_payment == NULL : (front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0) {
1682 ReserveConsist(st, front,
1683 (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : NULL,
1684 next_station);
1687 /* We have not waited enough time till the next round of loading/unloading */
1688 if (front->load_unload_ticks != 0) return;
1690 if (front->type == VEH_TRAIN && !st->TileBelongsToStation(front->tile)) {
1691 /* The train reversed in the station. Take the "easy" way
1692 * out and let the train just leave as it always did. */
1693 SetBit(front->vehicle_flags, VF_LOADING_FINISHED);
1694 front->load_unload_ticks = 1;
1695 return;
1698 int new_load_unload_ticks = 0;
1699 bool dirty_vehicle = false;
1700 bool dirty_station = false;
1702 bool completely_emptied = true;
1703 bool anything_unloaded = false;
1704 bool anything_loaded = false;
1705 uint32 full_load_amount = 0;
1706 uint32 cargo_not_full = 0;
1707 uint32 cargo_full = 0;
1708 uint32 reservation_left = 0;
1710 std::vector <LoadingVehicle> to_load;
1712 front->cur_speed = 0;
1714 CargoPayment *payment = front->cargo_payment;
1716 bool cargo_locked = !front->current_order.IsRefit();
1717 uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1718 for (Vehicle *v = front; v != NULL; v = v->Next()) {
1719 if (!v->IsArticulatedPart()) artic_part = 0;
1720 if (v->cargo_cap == 0) continue;
1721 artic_part++;
1723 uint load_amount = GetLoadAmount(v);
1725 GoodsEntry *ge = &st->goods[v->cargo_type];
1727 if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1728 uint cargo_count = v->cargo.UnloadCount();
1729 uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, load_amount) : cargo_count;
1730 bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1732 assert(payment != NULL);
1733 payment->SetCargo(v->cargo_type);
1735 if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
1736 /* The station does not accept our goods anymore. */
1737 if (front->current_order.GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) {
1738 /* Transfer instead of delivering. */
1739 v->cargo.Transfer();
1740 } else {
1741 uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
1742 if (v->cargo_cap < new_remaining) {
1743 /* Return some of the reserved cargo to not overload the vehicle. */
1744 v->cargo.Return (&ge->cargo, new_remaining - v->cargo_cap);
1747 /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1748 v->cargo.Keep (VehicleCargoList::MTA_DELIVER);
1750 /* ... say we unloaded something, otherwise we'll think we didn't unload
1751 * something and we didn't load something, so we must be finished
1752 * at this station. Setting the unloaded means that we will get a
1753 * retry for loading in the next cycle. */
1754 anything_unloaded = true;
1758 if (v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0) {
1759 /* Mark the station dirty if we transfer, but not if we only deliver. */
1760 dirty_station = true;
1762 if (!ge->HasRating()) {
1763 /* Upon transfering cargo, make sure the station has a rating. Fake a pickup for the
1764 * first unload to prevent the cargo from quickly decaying after the initial drop. */
1765 ge->time_since_pickup = 0;
1766 SetBit(ge->status, GoodsEntry::GES_RATING);
1770 amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment);
1771 remaining = v->cargo.UnloadCount() > 0;
1772 if (amount_unloaded > 0) {
1773 dirty_vehicle = true;
1774 anything_unloaded = true;
1775 new_load_unload_ticks += amount_unloaded;
1777 /* Deliver goods to the station */
1778 st->time_since_unload = 0;
1781 if (_settings_game.order.gradual_loading && remaining) {
1782 completely_emptied = false;
1783 } else {
1784 /* We have finished unloading (cargo count == 0) */
1785 ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1788 continue;
1791 /* Do not pick up goods when we have no-load set or loading is stopped. */
1792 if (front->current_order.GetLoadType() & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
1794 /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1795 if (front->current_order.IsRefit() && artic_part == 1) {
1796 cargo_locked = HandleStationRefit (v, consist_capleft, st, next_station, front->current_order.GetRefitCargoMask());
1797 ge = &st->goods[v->cargo_type];
1800 /* As we're loading here the following link can carry the full capacity of the vehicle. */
1801 v->refit_cap = v->cargo_cap;
1803 /* update stats */
1804 int t;
1805 switch (front->type) {
1806 case VEH_TRAIN:
1807 case VEH_SHIP:
1808 t = front->vcache.cached_max_speed;
1809 break;
1811 case VEH_ROAD:
1812 t = front->vcache.cached_max_speed / 2;
1813 break;
1815 case VEH_AIRCRAFT:
1816 t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units.
1817 break;
1819 default: NOT_REACHED();
1822 /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1823 ge->last_speed = min(t, 255);
1824 ge->last_age = min(_cur_year - front->build_year, 255);
1825 ge->time_since_pickup = 0;
1827 assert(v->cargo_cap >= v->cargo.StoredCount());
1828 /* If there's goods waiting at the station, and the vehicle
1829 * has capacity for it, load it on the vehicle. */
1830 uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1831 if (cap_left == 0) {
1832 SetBit(cargo_full, v->cargo_type);
1833 } else if ((v->cargo.TotalCount() > 0) || cargo_locked) {
1834 to_load.push_back (LoadingVehicle (v, cap_left, load_amount));
1835 } else {
1836 SetBit(cargo_not_full, v->cargo_type);
1840 stable_sort (to_load.begin(), to_load.end());
1842 std::vector<LoadingVehicle>::iterator lv (to_load.end());
1843 while (lv != to_load.begin()) {
1844 std::vector<LoadingVehicle>::iterator last (lv--);
1845 CargoID c = lv->v->cargo_type;
1847 while (lv != to_load.begin()) {
1848 std::vector<LoadingVehicle>::iterator prev (lv - 1);
1849 if (prev->v->cargo_type != c) break;
1850 lv = prev;
1853 /* Pool the reservations, if any, and redistribute them. */
1854 VehicleCargoList pool;
1856 for (std::vector<LoadingVehicle>::iterator p (lv); p != last; p++) {
1857 Vehicle *v = p->v;
1858 v->cargo.Reattach (&pool);
1859 assert (v->cargo.ReservedCount() == 0);
1862 /* First pass, assign a loading step to each vehicle. */
1863 for (std::vector<LoadingVehicle>::iterator p (lv); p != last && pool.TotalCount() > 0; p++) {
1864 Vehicle *v = p->v;
1865 assert (v->cargo.ReservedCount() == 0);
1866 if (v->cargo.StoredCount() == 0) {
1867 TriggerVehicle (v, VEHICLE_TRIGGER_NEW_CARGO);
1868 p->load = min (p->left, GetLoadAmount(v));
1870 pool.Reattach (&v->cargo, p->load);
1871 assert (v->cargo.ReservedCount() > 0);
1874 /* Second pass, dump remaining reservations. */
1875 for (std::vector<LoadingVehicle>::iterator p (lv); pool.TotalCount() > 0; p++) {
1876 assert (p != last);
1877 Vehicle *v = p->v;
1878 assert (v->cargo.ReservedCount() > 0);
1879 pool.Reattach (&v->cargo, v->cargo_cap - v->cargo.TotalCount());
1882 /* Reservations redistributed, proceed with loading. */
1883 GoodsEntry *ge = &st->goods[c];
1884 for (std::vector<LoadingVehicle>::iterator p (lv); p != last; p++) {
1885 Vehicle *v = p->v;
1886 assert (v->cargo.StoredCount() < v->cargo_cap);
1888 if ((v->cargo.ReservedCount() > 0) || (ge->cargo.AvailableCount() > 0)) {
1889 if (v->cargo.TotalCount() == 0) {
1890 TriggerVehicle (v, VEHICLE_TRIGGER_NEW_CARGO);
1891 p->load = min (p->left, GetLoadAmount(v));
1894 uint loaded = ge->cargo.Load (p->load, &v->cargo, st->xy, next_station);
1895 if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
1896 /* Remember if there are reservations left so that we don't stop
1897 * loading before they're loaded. */
1898 SetBit(reservation_left, v->cargo_type);
1901 /* Store whether the maximum possible load amount was loaded or not.*/
1902 if (loaded == p->load) {
1903 SetBit(full_load_amount, v->cargo_type);
1904 } else {
1905 ClrBit(full_load_amount, v->cargo_type);
1908 /* TODO: Regarding this, when we do gradual loading, we
1909 * should first unload all vehicles and then start
1910 * loading them. Since this will cause
1911 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1912 * the whole vehicle chain is really totally empty, the
1913 * completely_emptied assignment can then be safely
1914 * removed; that's how TTDPatch behaves too. --pasky */
1915 if (loaded > 0) {
1916 completely_emptied = false;
1917 anything_loaded = true;
1919 st->time_since_load = 0;
1920 st->last_vehicle_type = v->type;
1922 if (ge->cargo.TotalCount() == 0) {
1923 TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type);
1924 TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1925 AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
1928 new_load_unload_ticks += loaded;
1930 dirty_vehicle = dirty_station = true;
1934 if (v->cargo.StoredCount() >= v->cargo_cap) {
1935 SetBit(cargo_full, v->cargo_type);
1936 } else {
1937 SetBit(cargo_not_full, v->cargo_type);
1942 if (anything_loaded || anything_unloaded) {
1943 if (front->type == VEH_TRAIN) {
1944 TriggerStationRandomisation(st, front->tile, SRT_TRAIN_LOADS);
1945 TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS);
1949 /* Only set completely_emptied, if we just unloaded all remaining cargo */
1950 completely_emptied &= anything_unloaded;
1952 if (!anything_unloaded) delete payment;
1954 ClrBit(front->vehicle_flags, VF_STOP_LOADING);
1955 if (anything_loaded || anything_unloaded) {
1956 if (_settings_game.order.gradual_loading) {
1957 /* The time it takes to load one 'slice' of cargo or passengers depends
1958 * on the vehicle type - the values here are those found in TTDPatch */
1959 const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1961 new_load_unload_ticks = gradual_loading_wait_time[front->type];
1963 /* We loaded less cargo than possible for all cargo types and it's not full
1964 * load and we're not supposed to wait any longer: stop loading. */
1965 if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) &&
1966 front->current_order_time >= (uint)max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
1967 SetBit(front->vehicle_flags, VF_STOP_LOADING);
1970 UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
1971 } else {
1972 UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
1973 bool finished_loading = true;
1974 if (front->current_order.GetLoadType() & OLFB_FULL_LOAD) {
1975 if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
1976 /* if the aircraft carries passengers and is NOT full, then
1977 * continue loading, no matter how much mail is in */
1978 if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) ||
1979 (cargo_not_full && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
1980 finished_loading = false;
1982 } else if (cargo_not_full != 0) {
1983 finished_loading = false;
1986 /* Refresh next hop stats if we're full loading to make the links
1987 * known to the distribution algorithm and allow cargo to be sent
1988 * along them. Otherwise the vehicle could wait for cargo
1989 * indefinitely if it hasn't visited the other links yet, or if the
1990 * links die while it's loading. */
1991 if (!finished_loading) LinkRefresher::Run(front, true, true);
1994 SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
1997 /* Calculate the loading indicator fill percent and display
1998 * In the Game Menu do not display indicators
1999 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
2000 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
2001 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
2003 if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
2004 StringID percent_up_down = STR_NULL;
2005 int percent = CalcPercentVehicleFilled(front, &percent_up_down);
2006 if (front->fill_percent_te_id == INVALID_TE_ID) {
2007 front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
2008 } else {
2009 UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
2013 if (completely_emptied) {
2014 /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
2015 * properties such as weight, power and TE whenever the trigger runs. */
2016 dirty_vehicle = true;
2017 TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
2020 if (dirty_vehicle) {
2021 SetWindowDirty(GetWindowClassForVehicleType(front->type), front->owner);
2022 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
2023 front->MarkDirty();
2025 if (dirty_station) {
2026 st->MarkTilesDirty(true);
2027 SetWindowDirty(WC_STATION_VIEW, last_visited);
2028 InvalidateWindowData(WC_STATION_LIST, last_visited);
2033 * Load/unload the vehicles in this station according to the order
2034 * they entered.
2035 * @param st the station to do the loading/unloading for
2037 void LoadUnloadStation(Station *st)
2039 /* No vehicle is here... */
2040 if (st->loading_vehicles.empty()) return;
2042 Vehicle *last_loading = NULL;
2043 std::list<Vehicle *>::iterator iter;
2045 /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
2046 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
2047 Vehicle *v = *iter;
2049 if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
2051 assert(v->load_unload_ticks != 0);
2052 if (--v->load_unload_ticks == 0) last_loading = v;
2055 /* We only need to reserve and load/unload up to the last loading vehicle.
2056 * Anything else will be forgotten anyway after returning from this function.
2058 * Especially this means we do _not_ need to reserve cargo for a single
2059 * consist in a station which is not allowed to load yet because its
2060 * load_unload_ticks is still not 0.
2062 if (last_loading == NULL) return;
2064 for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
2065 Vehicle *v = *iter;
2066 if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v);
2067 if (v == last_loading) break;
2070 /* Call the production machinery of industries */
2071 const Industry * const *isend = _cargo_delivery_destinations.End();
2072 for (Industry **iid = _cargo_delivery_destinations.Begin(); iid != isend; iid++) {
2073 TriggerIndustryProduction(*iid);
2075 _cargo_delivery_destinations.Clear();
2079 * Monthly update of the economic data (of the companies as well as economic fluctuations).
2081 void CompaniesMonthlyLoop()
2083 CompaniesGenStatistics();
2084 if (_settings_game.economy.inflation) {
2085 AddInflation();
2086 RecomputePrices();
2088 CompaniesPayInterest();
2089 HandleEconomyFluctuations();
2092 static void DoAcquireCompany(Company *c)
2094 CompanyID ci = c->index;
2096 AddNewsItem<MergerNewsItem> (c, Company::Get(_current_company));
2097 AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
2098 Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
2100 ChangeOwnershipOfCompanyItems(ci, _current_company);
2102 if (c->bankrupt_value == 0) {
2103 Company *owner = Company::Get(_current_company);
2104 owner->current_loan += c->current_loan;
2107 if (c->is_ai) AI::Stop(c->index);
2109 DeleteCompanyWindows(ci);
2110 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
2111 InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
2112 InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
2113 InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
2115 delete c;
2118 extern int GetAmountOwnedBy(const Company *c, Owner owner);
2121 * Acquire shares in an opposing company.
2122 * @param tile unused
2123 * @param flags type of operation
2124 * @param p1 company to buy the shares from
2125 * @param p2 unused
2126 * @param text unused
2127 * @return the cost of this operation or an error
2129 CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2131 CommandCost cost(EXPENSES_OTHER);
2132 CompanyID target_company = (CompanyID)p1;
2133 Company *c = Company::GetIfValid(target_company);
2135 /* Check if buying shares is allowed (protection against modified clients)
2136 * Cannot buy own shares */
2137 if (c == NULL || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
2139 /* Protect new companies from hostile takeovers */
2140 if (_cur_year - c->inaugurated_year < 6) return_cmd_error(STR_ERROR_PROTECTED);
2142 /* Those lines are here for network-protection (clients can be slow) */
2143 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost;
2145 if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) {
2146 if (!c->is_ai) return cost; // We can not buy out a real company (temporarily). TODO: well, enable it obviously.
2148 if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
2152 cost.AddCost(CalculateCompanyValue(c) >> 2);
2153 if (flags & DC_EXEC) {
2154 OwnerByte *b = c->share_owners;
2156 while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
2157 *b = _current_company;
2159 for (int i = 0; c->share_owners[i] == _current_company;) {
2160 if (++i == 4) {
2161 c->bankrupt_value = 0;
2162 DoAcquireCompany(c);
2163 break;
2166 InvalidateWindowData(WC_COMPANY, target_company);
2167 CompanyAdminUpdate(c);
2169 return cost;
2173 * Sell shares in an opposing company.
2174 * @param tile unused
2175 * @param flags type of operation
2176 * @param p1 company to sell the shares from
2177 * @param p2 unused
2178 * @param text unused
2179 * @return the cost of this operation or an error
2181 CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2183 CompanyID target_company = (CompanyID)p1;
2184 Company *c = Company::GetIfValid(target_company);
2186 /* Cannot sell own shares */
2187 if (c == NULL || _current_company == target_company) return CMD_ERROR;
2189 /* Check if selling shares is allowed (protection against modified clients).
2190 * However, we must sell shares of companies being closed down. */
2191 if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CMD_ERROR;
2193 /* Those lines are here for network-protection (clients can be slow) */
2194 if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost();
2196 /* adjust it a little to make it less profitable to sell and buy */
2197 Money cost = CalculateCompanyValue(c) >> 2;
2198 cost = -(cost - (cost >> 7));
2200 if (flags & DC_EXEC) {
2201 OwnerByte *b = c->share_owners;
2202 while (*b != _current_company) b++; // share owners is guaranteed to contain company
2203 *b = COMPANY_SPECTATOR;
2204 InvalidateWindowData(WC_COMPANY, target_company);
2205 CompanyAdminUpdate(c);
2207 return CommandCost(EXPENSES_OTHER, cost);
2211 * Buy up another company.
2212 * When a competing company is gone bankrupt you get the chance to purchase
2213 * that company.
2214 * @todo currently this only works for AI companies
2215 * @param tile unused
2216 * @param flags type of operation
2217 * @param p1 company to buy up
2218 * @param p2 unused
2219 * @param text unused
2220 * @return the cost of this operation or an error
2222 CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2224 CompanyID target_company = (CompanyID)p1;
2225 Company *c = Company::GetIfValid(target_company);
2226 if (c == NULL) return CMD_ERROR;
2228 /* Disable takeovers when not asked */
2229 if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
2231 /* Disable taking over the local company in single player */
2232 if (!_networking && _local_company == c->index) return CMD_ERROR;
2234 /* Do not allow companies to take over themselves */
2235 if (target_company == _current_company) return CMD_ERROR;
2237 /* Disable taking over when not allowed. */
2238 if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR;
2240 /* Get the cost here as the company is deleted in DoAcquireCompany. */
2241 CommandCost cost(EXPENSES_OTHER, c->bankrupt_value);
2243 if (flags & DC_EXEC) {
2244 DoAcquireCompany(c);
2246 return cost;