OpenTTD Source: src/economy.cpp Source File

OpenTTD Source 14.0-RC3

economy.cpp
Go to the documentation of this file.
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
7
10 #include "stdafx.h"
11 #include "company_func.h"
12 #include "command_func.h"
13 #include "industry.h"
14 #include "town.h"
15 #include "news_func.h"
16 #include "network/network.h"
17 #include "network/network_func.h"
18 #include "ai/ai.hpp"
19 #include "aircraft.h"
20 #include "train.h"
21 #include "newgrf_engine.h"
22 #include "engine_base.h"
23 #include "ground_vehicle.hpp"
24 #include "newgrf_cargo.h"
25 #include "newgrf_sound.h"
26 #include "newgrf_industrytiles.h"
27 #include "newgrf_station.h"
28 #include "newgrf_airporttiles.h"
29 #include "newgrf_roadstop.h"
30 #include "object.h"
31 #include "strings_func.h"
32 #include "vehicle_func.h"
33 #include "sound_func.h"
34 #include "autoreplace_func.h"
35 #include "company_gui.h"
36 #include "signs_base.h"
37 #include "subsidy_base.h"
38 #include "subsidy_func.h"
39 #include "station_base.h"
40 #include "waypoint_base.h"
41 #include "economy_base.h"
42 #include "core/pool_func.hpp"
43 #include "core/backup_type.hpp"
44 #include "core/container_func.hpp"
45 #include "cargo_type.h"
46 #include "water.h"
47 #include "game/game.hpp"
48 #include "cargomonitor.h"
49 #include "goal_base.h"
50 #include "story_base.h"
51 #include "linkgraph/refresh.h"
52 #include "company_cmd.h"
53 #include "economy_cmd.h"
54 #include "vehicle_cmd.h"
55 #include "timer/timer.h"
56 #include "timer/timer_game_calendar.h"
57 #include "timer/timer_game_economy.h"
58
59 #include "table/strings.h"
60 #include "table/pricebase.h"
61
62 #include "safeguards.h"
63
64
65 /* Initialize the cargo payment-pool */
66 CargoPaymentPool _cargo_payment_pool("CargoPayment");
67 INSTANTIATE_POOL_METHODS(CargoPayment)
68
69
80 static inline int32_t BigMulS(const int32_t a, const int32_t b, const uint8_t shift)
81 {
82 return (int32_t)((int64_t)a * (int64_t)b >> shift);
83 }
84
85 typedef std::vector<Industry *> SmallIndustryList;
86
90 const ScoreInfo _score_info[] = {
91 { 120, 100}, // SCORE_VEHICLES
92 { 80, 100}, // SCORE_STATIONS
93 { 10000, 100}, // SCORE_MIN_PROFIT
94 { 50000, 50}, // SCORE_MIN_INCOME
95 { 100000, 100}, // SCORE_MAX_INCOME
96 { 40000, 400}, // SCORE_DELIVERED
97 { 8, 50}, // SCORE_CARGO
98 {10000000, 50}, // SCORE_MONEY
99 { 250000, 50}, // SCORE_LOAN
100 { 0, 0} // SCORE_TOTAL
101 };
102
103 int64_t _score_part[MAX_COMPANIES][SCORE_END];
104 Economy _economy;
105 Prices _price;
106 static PriceMultipliers _price_base_multiplier;
107
114 static Money CalculateCompanyAssetValue(const Company *c)
115 {
116 Owner owner = c->index;
117
118 uint num = 0;
119
120 for (const Station *st : Station::Iterate()) {
121 if (st->owner == owner) num += CountBits((byte)st->facilities);
122 }
123
124 Money value = num * _price[PR_STATION_VALUE] * 25;
125
126 for (const Vehicle *v : Vehicle::Iterate()) {
127 if (v->owner != owner) continue;
128
129 if (v->type == VEH_TRAIN ||
130 v->type == VEH_ROAD ||
131 (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) ||
132 v->type == VEH_SHIP) {
133 value += v->value * 3 >> 1;
134 }
135 }
136
137 return value;
138 }
139
149 Money CalculateCompanyValue(const Company *c, bool including_loan)
150 {
151 Money value = CalculateCompanyAssetValue(c);
152
153 /* Add real money value */
154 if (including_loan) value -= c->current_loan;
155 value += c->money;
156
157 return std::max<Money>(value, 1);
158 }
159
176 Money CalculateHostileTakeoverValue(const Company *c)
177 {
178 Money value = CalculateCompanyAssetValue(c);
179
180 value += c->current_loan;
181 /* Negative balance is basically a loan. */
182 if (c->money < 0) {
183 value += -c->money;
184 }
185
186 for (int quarter = 0; quarter < 4; quarter++) {
187 value += std::max<Money>(c->old_economy[quarter].income - c->old_economy[quarter].expenses, 0) * 2;
188 }
189
190 return std::max<Money>(value, 1);
191 }
192
201 int UpdateCompanyRatingAndValue(Company *c, bool update)
202 {
203 Owner owner = c->index;
204 int score = 0;
205
206 memset(_score_part[owner], 0, sizeof(_score_part[owner]));
207
208 /* Count vehicles */
209 {
210 Money min_profit = 0;
211 bool min_profit_first = true;
212 uint num = 0;
213
214 for (const Vehicle *v : Vehicle::Iterate()) {
215 if (v->owner != owner) continue;
216 if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
217 if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
218 if (v->economy_age > VEHICLE_PROFIT_MIN_AGE) {
219 /* Find the vehicle with the lowest amount of profit */
220 if (min_profit_first || min_profit > v->profit_last_year) {
221 min_profit = v->profit_last_year;
222 min_profit_first = false;
223 }
224 }
225 }
226 }
227
228 min_profit >>= 8; // remove the fract part
229
230 _score_part[owner][SCORE_VEHICLES] = num;
231 /* Don't allow negative min_profit to show */
232 if (min_profit > 0) {
233 _score_part[owner][SCORE_MIN_PROFIT] = min_profit;
234 }
235 }
236
237 /* Count stations */
238 {
239 uint num = 0;
240 for (const Station *st : Station::Iterate()) {
241 /* Only count stations that are actually serviced */
242 if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
243 }
244 _score_part[owner][SCORE_STATIONS] = num;
245 }
246
247 /* Generate statistics depending on recent income statistics */
248 {
249 int numec = std::min<uint>(c->num_valid_stat_ent, 12u);
250 if (numec != 0) {
251 const CompanyEconomyEntry *cee = c->old_economy;
252 Money min_income = cee->income + cee->expenses;
253 Money max_income = cee->income + cee->expenses;
254
255 do {
256 min_income = std::min(min_income, cee->income + cee->expenses);
257 max_income = std::max(max_income, cee->income + cee->expenses);
258 } while (++cee, --numec);
259
260 if (min_income > 0) {
261 _score_part[owner][SCORE_MIN_INCOME] = min_income;
262 }
263
264 _score_part[owner][SCORE_MAX_INCOME] = max_income;
265 }
266 }
267
268 /* Generate score depending on amount of transported cargo */
269 {
270 int numec = std::min<uint>(c->num_valid_stat_ent, 4u);
271 if (numec != 0) {
272 const CompanyEconomyEntry *cee = c->old_economy;
273 OverflowSafeInt64 total_delivered = 0;
274 do {
275 total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
276 } while (++cee, --numec);
277
278 _score_part[owner][SCORE_DELIVERED] = total_delivered;
279 }
280 }
281
282 /* Generate score for variety of cargo */
283 {
284 _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
285 }
286
287 /* Generate score for company's money */
288 {
289 if (c->money > 0) {
290 _score_part[owner][SCORE_MONEY] = c->money;
291 }
292 }
293
294 /* Generate score for loan */
295 {
296 _score_part[owner][SCORE_LOAN] = _score_info[SCORE_LOAN].needed - c->current_loan;
297 }
298
299 /* Now we calculate the score for each item.. */
300 {
301 int total_score = 0;
302 int s;
303 score = 0;
304 for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
305 /* Skip the total */
306 if (i == SCORE_TOTAL) continue;
307 /* Check the score */
308 s = Clamp<int64_t>(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
309 score += s;
310 total_score += _score_info[i].score;
311 }
312
313 _score_part[owner][SCORE_TOTAL] = score;
314
315 /* We always want the score scaled to SCORE_MAX (1000) */
316 if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
317 }
318
319 if (update) {
320 c->old_economy[0].performance_history = score;
321 UpdateCompanyHQ(c->location_of_HQ, score);
322 c->old_economy[0].company_value = CalculateCompanyValue(c);
323 }
324
325 SetWindowDirty(WC_PERFORMANCE_DETAIL, 0);
326 return score;
327 }
328
334 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
335 {
336 /* We need to set _current_company to old_owner before we try to move
337 * the client. This is needed as it needs to know whether "you" really
338 * are the current local company. */
339 Backup<CompanyID> cur_company(_current_company, old_owner, FILE_LINE);
340 /* In all cases, make spectators of clients connected to that company */
341 if (_networking) NetworkClientsToSpectators(old_owner);
342 if (old_owner == _local_company) {
343 /* Single player cheated to AI company.
344 * There are no spectators in singleplayer mode, so we must pick some other company. */
345 assert(!_networking);
346 Backup<CompanyID> cur_company2(_current_company, FILE_LINE);
347 for (const Company *c : Company::Iterate()) {
348 if (c->index != old_owner) {
349 SetLocalCompany(c->index);
350 break;
351 }
352 }
353 cur_company2.Restore();
354 assert(old_owner != _local_company);
355 }
356
357 assert(old_owner != new_owner);
358
359 /* Temporarily increase the company's money, to be sure that
360 * removing their property doesn't fail because of lack of money.
361 * Not too drastically though, because it could overflow */
362 if (new_owner == INVALID_OWNER) {
363 Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
364 }
365
366 for (Subsidy *s : Subsidy::Iterate()) {
367 if (s->awarded == old_owner) {
368 if (new_owner == INVALID_OWNER) {
369 delete s;
370 } else {
371 s->awarded = new_owner;
372 }
373 }
374 }
375 if (new_owner == INVALID_OWNER) RebuildSubsidisedSourceAndDestinationCache();
376
377 /* Take care of rating and transport rights in towns */
378 for (Town *t : Town::Iterate()) {
379 /* If a company takes over, give the ratings to that company. */
380 if (new_owner != INVALID_OWNER) {
381 if (HasBit(t->have_ratings, old_owner)) {
382 if (HasBit(t->have_ratings, new_owner)) {
383 /* use max of the two ratings. */
384 t->ratings[new_owner] = std::max(t->ratings[new_owner], t->ratings[old_owner]);
385 } else {
386 SetBit(t->have_ratings, new_owner);
387 t->ratings[new_owner] = t->ratings[old_owner];
388 }
389 }
390 }
391
392 /* Reset the ratings for the old owner */
393 t->ratings[old_owner] = RATING_INITIAL;
394 ClrBit(t->have_ratings, old_owner);
395
396 /* Transfer exclusive rights */
397 if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
398 if (new_owner != INVALID_OWNER) {
399 t->exclusivity = new_owner;
400 } else {
401 t->exclusive_counter = 0;
402 t->exclusivity = INVALID_COMPANY;
403 }
404 }
405 }
406
407 {
408 for (Vehicle *v : Vehicle::Iterate()) {
409 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
410 if (new_owner == INVALID_OWNER) {
411 if (v->Previous() == nullptr) delete v;
412 } else {
413 if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1);
414 if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1);
415 }
416 }
417 }
418 }
419
420 /* In all cases clear replace engine rules.
421 * Even if it was copied, it could interfere with new owner's rules */
422 RemoveAllEngineReplacementForCompany(Company::Get(old_owner));
423
424 if (new_owner == INVALID_OWNER) {
425 RemoveAllGroupsForCompany(old_owner);
426 } else {
427 for (Group *g : Group::Iterate()) {
428 if (g->owner == old_owner) g->owner = new_owner;
429 }
430 }
431
432 {
433 Company *new_company = new_owner == INVALID_OWNER ? nullptr : Company::Get(new_owner);
434
435 /* Override company settings to new company defaults in case we need to convert them.
436 * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
437 */
438 if (new_owner != INVALID_OWNER) {
439 Company *old_company = Company::Get(old_owner);
440
441 old_company->settings.vehicle.servint_aircraft = new_company->settings.vehicle.servint_aircraft;
442 old_company->settings.vehicle.servint_trains = new_company->settings.vehicle.servint_trains;
443 old_company->settings.vehicle.servint_roadveh = new_company->settings.vehicle.servint_roadveh;
444 old_company->settings.vehicle.servint_ships = new_company->settings.vehicle.servint_ships;
445 old_company->settings.vehicle.servint_ispercent = new_company->settings.vehicle.servint_ispercent;
446 }
447
448 for (Vehicle *v : Vehicle::Iterate()) {
449 if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
450 assert(new_owner != INVALID_OWNER);
451
452 /* Correct default values of interval settings while maintaining custom set ones.
453 * This prevents invalid values on mismatching company defaults being accepted.
454 */
455 if (!v->ServiceIntervalIsCustom()) {
456 /* Technically, passing the interval is not needed as the command will query the default value itself.
457 * However, do not rely on that behaviour.
458 */
459 int interval = CompanyServiceInterval(new_company, v->type);
460 Command<CMD_CHANGE_SERVICE_INT>::Do(DC_EXEC | DC_BANKRUPT, v->index, interval, false, new_company->settings.vehicle.servint_ispercent);
461 }
462
463 v->owner = new_owner;
464
465 /* Owner changes, clear cache */
466 v->colourmap = PAL_NONE;
467 v->InvalidateNewGRFCache();
468
469 if (v->IsEngineCountable()) {
470 GroupStatistics::CountEngine(v, 1);
471 }
472 if (v->IsPrimaryVehicle()) {
473 GroupStatistics::CountVehicle(v, 1);
474 auto &unitidgen = new_company->freeunits[v->type];
475 v->unitnumber = unitidgen.UseID(unitidgen.NextID());
476 }
477
478 /* Invalidate the vehicle's cargo payment "owner cache". */
479 if (v->cargo_payment != nullptr) v->cargo_payment->owner = nullptr;
480 }
481 }
482
483 if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
484 }
485
486 /* Change ownership of tiles */
487 {
488 TileIndex tile = 0;
489 do {
490 ChangeTileOwner(tile, old_owner, new_owner);
491 } while (++tile != Map::Size());
492
493 if (new_owner != INVALID_OWNER) {
494 /* Update all signals because there can be new segment that was owned by two companies
495 * and signals were not propagated
496 * Similar with crossings - it is needed to bar crossings that weren't before
497 * because of different owner of crossing and approaching train */
498 tile = 0;
499
500 do {
501 if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
502 TrackBits tracks = GetTrackBits(tile);
503 do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
504 Track track = RemoveFirstTrack(&tracks);
505 if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
506 } while (tracks != TRACK_BIT_NONE);
507 } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
508 UpdateLevelCrossing(tile);
509 }
510 } while (++tile != Map::Size());
511 }
512
513 /* update signals in buffer */
514 UpdateSignalsInBuffer();
515 }
516
517 /* Add airport infrastructure count of the old company to the new one. */
518 if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
519
520 /* convert owner of stations (including deleted ones, but excluding buoys) */
521 for (Station *st : Station::Iterate()) {
522 if (st->owner == old_owner) {
523 /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
524 * also, drawing station window would cause reading invalid company's colour */
525 st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
526 }
527 }
528
529 /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
530 for (Waypoint *wp : Waypoint::Iterate()) {
531 if (wp->owner == old_owner) {
532 wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
533 }
534 }
535
536 for (Sign *si : Sign::Iterate()) {
537 if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
538 }
539
540 /* Remove Game Script created Goals, CargoMonitors and Story pages. */
541 for (Goal *g : Goal::Iterate()) {
542 if (g->company == old_owner) delete g;
543 }
544
545 ClearCargoPickupMonitoring(old_owner);
546 ClearCargoDeliveryMonitoring(old_owner);
547
548 for (StoryPage *sp : StoryPage::Iterate()) {
549 if (sp->company == old_owner) delete sp;
550 }
551
552 /* Change colour of existing windows */
553 if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
554
555 cur_company.Restore();
556
557 MarkWholeScreenDirty();
558 }
559
564 static void CompanyCheckBankrupt(Company *c)
565 {
566 /* If "Infinite money" setting is on, companies should not go bankrupt. */
567 if (_settings_game.difficulty.infinite_money) return;
568
569 /* If the company has money again, it does not go bankrupt */
570 if (c->money - c->current_loan >= -c->GetMaxLoan()) {
571 int previous_months_of_bankruptcy = CeilDiv(c->months_of_bankruptcy, 3);
572 c->months_of_bankruptcy = 0;
573 c->bankrupt_asked = 0;
574 if (previous_months_of_bankruptcy != 0) CompanyAdminUpdate(c);
575 return;
576 }
577
578 c->months_of_bankruptcy++;
579
580 switch (c->months_of_bankruptcy) {
581 /* All the boring cases (months) with a bad balance where no action is taken */
582 case 0:
583 case 1:
584 case 2:
585 case 3:
586
587 case 5:
588 case 6:
589
590 case 8:
591 case 9:
592 break;
593
594 /* Warn about bankruptcy after 3 months */
595 case 4: {
596 CompanyNewsInformation *cni = new CompanyNewsInformation(c);
597 SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
598 SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
599 SetDParamStr(2, cni->company_name);
600 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
601 AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
602 Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
603 break;
604 }
605
606 /* Offer company for sale after 6 months */
607 case 7: {
608 /* Don't consider the loan */
609 Money val = CalculateCompanyValue(c, false);
610
611 c->bankrupt_value = val;
612 c->bankrupt_asked = 1 << c->index; // Don't ask the owner
613 c->bankrupt_timeout = 0;
614
615 /* The company assets should always have some value */
616 assert(c->bankrupt_value > 0);
617 break;
618 }
619
620 /* Bankrupt company after 6 months (if the company has no value) or latest
621 * after 9 months (if it still had value after 6 months) */
622 default:
623 case 10: {
624 if (!_networking && _local_company == c->index) {
625 /* If we are in singleplayer mode, leave the company playing. Eg. there
626 * is no THE-END, otherwise mark the client as spectator to make sure
627 * they are no longer in control of this company. However... when you
628 * join another company (cheat) the "unowned" company can bankrupt. */
629 c->bankrupt_asked = MAX_UVALUE(CompanyMask);
630 break;
631 }
632
633 /* Actually remove the company, but not when we're a network client.
634 * In case of network clients we will be getting a command from the
635 * server. It is done in this way as we are called from the
636 * StateGameLoop which can't change the current company, and thus
637 * updating the local company triggers an assert later on. In the
638 * case of a network game the command will be processed at a time
639 * that changing the current company is okay. In case of single
640 * player we are sure (the above check) that we are not the local
641 * company and thus we won't be moved. */
642 if (!_networking || _network_server) {
643 Command<CMD_COMPANY_CTRL>::Post(CCA_DELETE, c->index, CRR_BANKRUPT, INVALID_CLIENT_ID);
644 return;
645 }
646 break;
647 }
648 }
649
650 if (CeilDiv(c->months_of_bankruptcy, 3) != CeilDiv(c->months_of_bankruptcy - 1, 3)) CompanyAdminUpdate(c);
651 }
652
657 static void CompaniesGenStatistics()
658 {
659 /* Check for bankruptcy each month */
660 for (Company *c : Company::Iterate()) {
661 CompanyCheckBankrupt(c);
662 }
663
664 Backup<CompanyID> cur_company(_current_company, FILE_LINE);
665
666 /* Pay Infrastructure Maintenance, if enabled */
667 if (_settings_game.economy.infrastructure_maintenance) {
668 /* Improved monthly infrastructure costs. */
669 for (const Company *c : Company::Iterate()) {
670 cur_company.Change(c->index);
671
672 CommandCost cost(EXPENSES_PROPERTY);
673 uint32_t 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));
676 }
677 cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal));
678 uint32_t road_total = c->infrastructure.GetRoadTotal();
679 uint32_t tram_total = c->infrastructure.GetTramTotal();
680 for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
681 if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt], RoadTypeIsRoad(rt) ? road_total : tram_total));
682 }
683 cost.AddCost(CanalMaintenanceCost(c->infrastructure.water));
684 cost.AddCost(StationMaintenanceCost(c->infrastructure.station));
685 cost.AddCost(AirportMaintenanceCost(c->index));
686
687 SubtractMoneyFromCompany(cost);
688 }
689 }
690 cur_company.Restore();
691
692 /* Only run the economic statics and update company stats every 3rd economy month (1st of quarter). */
693 if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, TimerGameEconomy::month)) return;
694
695 for (Company *c : Company::Iterate()) {
696 /* Drop the oldest history off the end */
697 std::copy_backward(c->old_economy, c->old_economy + MAX_HISTORY_QUARTERS - 1, c->old_economy + MAX_HISTORY_QUARTERS);
698 c->old_economy[0] = c->cur_economy;
699 c->cur_economy = {};
700
701 if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++;
702
703 UpdateCompanyRatingAndValue(c, true);
704 if (c->block_preview != 0) c->block_preview--;
705 }
706
707 SetWindowDirty(WC_INCOME_GRAPH, 0);
708 SetWindowDirty(WC_OPERATING_PROFIT, 0);
709 SetWindowDirty(WC_DELIVERED_CARGO, 0);
710 SetWindowDirty(WC_PERFORMANCE_HISTORY, 0);
711 SetWindowDirty(WC_COMPANY_VALUE, 0);
712 SetWindowDirty(WC_COMPANY_LEAGUE, 0);
713 }
714
720 bool AddInflation(bool check_year)
721 {
722 /* The cargo payment inflation differs from the normal inflation, so the
723 * relative amount of money you make with a transport decreases slowly over
724 * the 170 years. After a few hundred years we reach a level in which the
725 * games will become unplayable as the maximum income will be less than
726 * the minimum running cost.
727 *
728 * Furthermore there are a lot of inflation related overflows all over the
729 * place. Solving them is hardly possible because inflation will always
730 * reach the overflow threshold some day. So we'll just perform the
731 * inflation mechanism during the first 170 years (the amount of years that
732 * one had in the original TTD) and stop doing the inflation after that
733 * because it only causes problems that can't be solved nicely and the
734 * inflation doesn't add anything after that either; it even makes playing
735 * it impossible due to the diverging cost and income rates.
736 */
737 if (check_year && (TimerGameCalendar::year < CalendarTime::ORIGINAL_BASE_YEAR || TimerGameCalendar::year >= CalendarTime::ORIGINAL_MAX_YEAR)) return true;
738
739 if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
740
741 /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
742 * scaled by 65536
743 * 12 -> months per year
744 * This is only a good approximation for small values
745 */
746 _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16;
747 _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
748
749 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
750 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
751
752 return false;
753 }
754
758 void RecomputePrices()
759 {
760 /* Setup maximum loan as a rounded down multiple of LOAN_INTERVAL. */
761 _economy.max_loan = ((uint64_t)_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / LOAN_INTERVAL * LOAN_INTERVAL;
762
763 /* Setup price bases */
764 for (Price i = PR_BEGIN; i < PR_END; i++) {
765 Money price = _price_base_specs[i].start_price;
766
767 /* Apply difficulty settings */
768 uint mod = 1;
769 switch (_price_base_specs[i].category) {
770 case PCAT_RUNNING:
771 mod = _settings_game.difficulty.vehicle_costs;
772 break;
773
774 case PCAT_CONSTRUCTION:
775 mod = _settings_game.difficulty.construction_cost;
776 break;
777
778 default: break;
779 }
780 switch (mod) {
781 case 0: price *= 6; break;
782 case 1: price *= 8; break; // normalised to 1 below
783 case 2: price *= 9; break;
784 default: NOT_REACHED();
785 }
786
787 /* Apply inflation */
788 price = (int64_t)price * _economy.inflation_prices;
789
790 /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
791 int shift = _price_base_multiplier[i] - 16 - 3;
792 if (shift >= 0) {
793 price <<= shift;
794 } else {
795 price >>= -shift;
796 }
797
798 /* Make sure the price does not get reduced to zero.
799 * Zero breaks quite a few commands that use a zero
800 * cost to see whether something got changed or not
801 * and based on that cause an error. When the price
802 * is zero that fails even when things are done. */
803 if (price == 0) {
804 price = Clamp(_price_base_specs[i].start_price, -1, 1);
805 /* No base price should be zero, but be sure. */
806 assert(price != 0);
807 }
808 /* Store value */
809 _price[i] = price;
810 }
811
812 /* Setup cargo payment */
813 for (CargoSpec *cs : CargoSpec::Iterate()) {
814 cs->current_payment = (cs->initial_payment * (int64_t)_economy.inflation_payment) >> 16;
815 }
816
817 SetWindowClassesDirty(WC_BUILD_VEHICLE);
818 SetWindowClassesDirty(WC_REPLACE_VEHICLE);
819 SetWindowClassesDirty(WC_VEHICLE_DETAILS);
820 SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE);
821 InvalidateWindowData(WC_PAYMENT_RATES, 0);
822 }
823
825 static void CompaniesPayInterest()
826 {
827 Backup<CompanyID> cur_company(_current_company, FILE_LINE);
828 for (const Company *c : Company::Iterate()) {
829 cur_company.Change(c->index);
830
831 /* Over a year the paid interest should be "loan * interest percentage",
832 * but... as that number is likely not dividable by 12 (pay each month),
833 * one needs to account for that in the monthly fee calculations.
834 *
835 * To easily calculate what one should pay "this" month, you calculate
836 * what (total) should have been paid up to this month and you subtract
837 * whatever has been paid in the previous months. This will mean one month
838 * it'll be a bit more and the other it'll be a bit less than the average
839 * monthly fee, but on average it will be exact.
840 *
841 * In order to prevent cheating or abuse (just not paying interest by not
842 * taking a loan) we make companies pay interest on negative cash as well,
843 * except if infinite money is enabled.
844 */
845 Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
846 Money available_money = GetAvailableMoney(c->index);
847 if (available_money < 0) {
848 yearly_fee += -available_money * _economy.interest_rate / 100;
849 }
850 Money up_to_previous_month = yearly_fee * TimerGameEconomy::month / 12;
851 Money up_to_this_month = yearly_fee * (TimerGameEconomy::month + 1) / 12;
852
853 SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INTEREST, up_to_this_month - up_to_previous_month));
854
855 SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
856 }
857 cur_company.Restore();
858 }
859
860 static void HandleEconomyFluctuations()
861 {
862 if (_settings_game.difficulty.economy != 0) {
863 /* When economy is Fluctuating, decrease counter */
864 _economy.fluct--;
865 } else if (EconomyIsInRecession()) {
866 /* When it's Steady and we are in recession, end it now */
867 _economy.fluct = -12;
868 } else {
869 /* No need to do anything else in other cases */
870 return;
871 }
872
873 if (_economy.fluct == 0) {
874 _economy.fluct = -(int)GB(Random(), 0, 2);
875 AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
876 } else if (_economy.fluct == -12) {
877 _economy.fluct = GB(Random(), 0, 8) + 312;
878 AddNewsItem(STR_NEWS_END_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
879 }
880 }
881
882
886 void ResetPriceBaseMultipliers()
887 {
888 memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
889 }
890
898 void SetPriceBaseMultiplier(Price price, int factor)
899 {
900 assert(price < PR_END);
901 _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
902 }
903
908 void StartupIndustryDailyChanges(bool init_counter)
909 {
910 uint map_size = Map::LogX() + Map::LogY();
911 /* After getting map size, it needs to be scaled appropriately and divided by 31,
912 * which stands for the days in a month.
913 * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
914 * would not be needed.
915 * Since it is based on "fractional parts", the leftover days will not make much of a difference
916 * on the overall total number of changes performed */
917 _economy.industry_daily_increment = (1 << map_size) / 31;
918
919 if (init_counter) {
920 /* A new game or a savegame from an older version will require the counter to be initialized */
921 _economy.industry_daily_change_counter = 0;
922 }
923 }
924
925 void StartupEconomy()
926 {
927 _economy.interest_rate = _settings_game.difficulty.initial_interest;
928 _economy.infl_amount = _settings_game.difficulty.initial_interest;
929 _economy.infl_amount_pr = std::max(0, _settings_game.difficulty.initial_interest - 1);
930 _economy.fluct = GB(Random(), 0, 8) + 168;
931
932 if (_settings_game.economy.inflation) {
933 /* Apply inflation that happened before our game start year. */
934 int months = (std::min(TimerGameCalendar::year, CalendarTime::ORIGINAL_MAX_YEAR) - CalendarTime::ORIGINAL_BASE_YEAR).base() * 12;
935 for (int i = 0; i < months; i++) {
936 AddInflation(false);
937 }
938 }
939
940 /* Set up prices */
941 RecomputePrices();
942
943 StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
944
945 }
946
950 void InitializeEconomy()
951 {
952 _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
953 ClearCargoPickupMonitoring();
954 ClearCargoDeliveryMonitoring();
955 }
956
965 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
966 {
967 if (index >= PR_END) return 0;
968
969 Money cost = _price[index] * cost_factor;
970 if (grf_file != nullptr) shift += grf_file->price_base_multipliers[index];
971
972 if (shift >= 0) {
973 cost <<= shift;
974 } else {
975 cost >>= -shift;
976 }
977
978 return cost;
979 }
980
981 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, uint16_t transit_periods, CargoID cargo_type)
982 {
983 const CargoSpec *cs = CargoSpec::Get(cargo_type);
984 if (!cs->IsValid()) {
985 /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
986 return 0;
987 }
988
989 /* Use callback to calculate cargo profit, if available */
990 if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
991 uint32_t var18 = ClampTo<uint16_t>(dist) | (ClampTo<uint8_t>(num_pieces) << 16) | (ClampTo<uint8_t>(transit_periods) << 24);
992 uint16_t callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
993 if (callback != CALLBACK_FAILED) {
994 int result = GB(callback, 0, 14);
995
996 /* Simulate a 15 bit signed value */
997 if (HasBit(callback, 14)) result -= 0x4000;
998
999 /* "The result should be a signed multiplier that gets multiplied
1000 * by the amount of cargo moved and the price factor, then gets
1001 * divided by 8192." */
1002 return result * num_pieces * cs->current_payment / 8192;
1003 }
1004 }
1005
1006 static const int MIN_TIME_FACTOR = 31;
1007 static const int MAX_TIME_FACTOR = 255;
1008 static const int TIME_FACTOR_FRAC_BITS = 4;
1009 static const int TIME_FACTOR_FRAC = 1 << TIME_FACTOR_FRAC_BITS;
1010
1011 const int periods1 = cs->transit_periods[0];
1012 const int periods2 = cs->transit_periods[1];
1013 const int periods_over_periods1 = std::max(transit_periods - periods1, 0);
1014 const int periods_over_periods2 = std::max(periods_over_periods1 - periods2, 0);
1015 int periods_over_max = MIN_TIME_FACTOR - MAX_TIME_FACTOR;
1016 if (periods2 > -periods_over_max) {
1017 periods_over_max += transit_periods - periods1;
1018 } else {
1019 periods_over_max += 2 * (transit_periods - periods1) - periods2;
1020 }
1021
1022 /*
1023 * The time factor is calculated based on the time it took
1024 * (transit_periods) compared two cargo-depending values. The
1025 * range is divided into four parts:
1026 *
1027 * - constant for fast transits
1028 * - linear decreasing with time with a slope of -1 for medium transports
1029 * - linear decreasing with time with a slope of -2 for slow transports
1030 * - after hitting MIN_TIME_FACTOR, the time factor will be asymptotically decreased to a limit of 1 with a scaled 1/(x+1) function.
1031 *
1032 */
1033 if (periods_over_max > 0) {
1034 const int time_factor = std::max(2 * MIN_TIME_FACTOR * TIME_FACTOR_FRAC * TIME_FACTOR_FRAC / (periods_over_max + 2 * TIME_FACTOR_FRAC), 1); // MIN_TIME_FACTOR / (x/(2 * TIME_FACTOR_FRAC) + 1) + 1, expressed as fixed point with TIME_FACTOR_FRAC_BITS.
1035 return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21 + TIME_FACTOR_FRAC_BITS);
1036 } else {
1037 const int time_factor = std::max(MAX_TIME_FACTOR - periods_over_periods1 - periods_over_periods2, MIN_TIME_FACTOR);
1038 return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
1039 }
1040 }
1041
1043 static SmallIndustryList _cargo_delivery_destinations;
1044
1055 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source, CompanyID company)
1056 {
1057 /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1058 * This fails in three cases:
1059 * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1060 * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1061 * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1062 */
1063
1064 uint accepted = 0;
1065
1066 for (const auto &i : st->industries_near) {
1067 if (num_pieces == 0) break;
1068
1069 Industry *ind = i.industry;
1070 if (ind->index == source) continue;
1071
1072 auto it = ind->GetCargoAccepted(cargo_type);
1073 /* Check if matching cargo has been found */
1074 if (it == std::end(ind->accepted)) continue;
1075
1076 /* Check if industry temporarily refuses acceptance */
1077 if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
1078
1079 if (ind->exclusive_supplier != INVALID_OWNER && ind->exclusive_supplier != st->owner) continue;
1080
1081 /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1082 include(_cargo_delivery_destinations, ind);
1083
1084 uint amount = std::min(num_pieces, 0xFFFFu - it->waiting);
1085 it->waiting += amount;
1086 it->last_accepted = TimerGameEconomy::date;
1087 num_pieces -= amount;
1088 accepted += amount;
1089
1090 /* Update the cargo monitor. */
1091 AddCargoDelivery(cargo_type, company, amount, SourceType::Industry, source, st, ind->index);
1092 }
1093
1094 return accepted;
1095 }
1096
1110 static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID dest, uint distance, uint16_t periods_in_transit, Company *company, SourceType src_type, SourceID src)
1111 {
1112 assert(num_pieces > 0);
1113
1114 Station *st = Station::Get(dest);
1115
1116 /* Give the goods to the industry. */
1117 uint accepted_ind = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == SourceType::Industry ? src : INVALID_INDUSTRY, company->index);
1118
1119 /* If this cargo type is always accepted, accept all */
1120 uint accepted_total = HasBit(st->always_accepted, cargo_type) ? num_pieces : accepted_ind;
1121
1122 /* Update station statistics */
1123 if (accepted_total > 0) {
1124 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_EVER_ACCEPTED);
1125 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_CURRENT_MONTH);
1126 SetBit(st->goods[cargo_type].status, GoodsEntry::GES_ACCEPTED_BIGTICK);
1127 }
1128
1129 /* Update company statistics */
1130 company->cur_economy.delivered_cargo[cargo_type] += accepted_total;
1131
1132 /* Increase town's counter for town effects */
1133 const CargoSpec *cs = CargoSpec::Get(cargo_type);
1134 st->town->received[cs->town_acceptance_effect].new_act += accepted_total;
1135
1136 /* Determine profit */
1137 Money profit = GetTransportedGoodsIncome(accepted_total, distance, periods_in_transit, cargo_type);
1138
1139 /* Update the cargo monitor. */
1140 AddCargoDelivery(cargo_type, company->index, accepted_total - accepted_ind, src_type, src, st);
1141
1142 /* Modify profit if a subsidy is in effect */
1143 if (CheckSubsidised(cargo_type, company->index, src_type, src, st)) {
1144 switch (_settings_game.difficulty.subsidy_multiplier) {
1145 case 0: profit += profit >> 1; break;
1146 case 1: profit *= 2; break;
1147 case 2: profit *= 3; break;
1148 default: profit *= 4; break;
1149 }
1150 }
1151
1152 return profit;
1153 }
1154
1160 static void TriggerIndustryProduction(Industry *i)
1161 {
1162 const IndustrySpec *indspec = GetIndustrySpec(i->type);
1163 uint16_t callback = indspec->callback_mask;
1164
1165 i->was_cargo_delivered = true;
1166
1167 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
1168 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
1169 IndustryProductionCallback(i, 0);
1170 } else {
1171 SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
1172 }
1173 } else {
1174 for (auto ita = std::begin(i->accepted); ita != std::end(i->accepted); ++ita) {
1175 if (ita->waiting == 0 || !IsValidCargoID(ita->cargo)) continue;
1176
1177 for (auto itp = std::begin(i->produced); itp != std::end(i->produced); ++itp) {
1178 if (!IsValidCargoID(itp->cargo)) continue;
1179 itp->waiting = ClampTo<uint16_t>(itp->waiting + (ita->waiting * indspec->input_cargo_multiplier[ita - std::begin(i->accepted)][itp - std::begin(i->produced)] / 256));
1180 }
1181
1182 ita->waiting = 0;
1183 }
1184 }
1185
1186 TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO);
1187 StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
1188 }
1189
1194 CargoPayment::CargoPayment(Vehicle *front) :
1195 current_station(front->last_station_visited),
1196 front(front)
1197 {
1198 }
1199
1200 CargoPayment::~CargoPayment()
1201 {
1202 if (this->CleaningPool()) return;
1203
1204 this->front->cargo_payment = nullptr;
1205
1206 if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1207
1208 Backup<CompanyID> cur_company(_current_company, this->front->owner, FILE_LINE);
1209
1210 SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit));
1211 this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1212
1213 if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
1214 SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1215 }
1216
1217 if (this->visual_transfer != 0) {
1218 ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos,
1219 this->front->z_pos, this->visual_transfer, -this->visual_profit);
1220 } else {
1221 ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos,
1222 this->front->z_pos, -this->visual_profit);
1223 }
1224
1225 cur_company.Restore();
1226 }
1227
1234 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count, TileIndex current_tile)
1235 {
1236 if (this->owner == nullptr) {
1237 this->owner = Company::Get(this->front->owner);
1238 }
1239
1240 /* Handle end of route payment */
1241 Money profit = DeliverGoods(count, this->ct, this->current_station, cp->GetDistance(current_tile), cp->GetPeriodsInTransit(), this->owner, cp->GetSourceType(), cp->GetSourceID());
1242 this->route_profit += profit;
1243
1244 /* The vehicle's profit is whatever route profit there is minus feeder shares. */
1245 this->visual_profit += profit - cp->GetFeederShare(count);
1246 }
1247
1255 Money CargoPayment::PayTransfer(const CargoPacket *cp, uint count, TileIndex current_tile)
1256 {
1257 /* Pay transfer vehicle the difference between the payment for the journey from
1258 * the source to the current point, and the sum of the previous transfer payments */
1259 Money profit = -cp->GetFeederShare(count) + GetTransportedGoodsIncome(
1260 count,
1261 cp->GetDistance(current_tile),
1262 cp->GetPeriodsInTransit(),
1263 this->ct);
1264
1265 profit = profit * _settings_game.economy.feeder_payment_share / 100;
1266
1267 this->visual_transfer += profit; // accumulate transfer profits for whole vehicle
1268 return profit; // account for the (virtual) profit already made for the cargo packet
1269 }
1270
1275 void PrepareUnload(Vehicle *front_v)
1276 {
1277 Station *curr_station = Station::Get(front_v->last_station_visited);
1278 curr_station->loading_vehicles.push_back(front_v);
1279
1280 /* At this moment loading cannot be finished */
1281 ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED);
1282
1283 /* Start unloading at the first possible moment */
1284 front_v->load_unload_ticks = 1;
1285
1286 assert(front_v->cargo_payment == nullptr);
1287 /* One CargoPayment per vehicle and the vehicle limit equals the
1288 * limit in number of CargoPayments. Can't go wrong. */
1289 static_assert(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
1290 assert(CargoPayment::CanAllocateItem());
1291 front_v->cargo_payment = new CargoPayment(front_v);
1292
1293 StationIDStack next_station = front_v->GetNextStoppingStation();
1294 if (front_v->orders == nullptr || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1295 Station *st = Station::Get(front_v->last_station_visited);
1296 for (Vehicle *v = front_v; v != nullptr; v = v->Next()) {
1297 const GoodsEntry *ge = &st->goods[v->cargo_type];
1298 if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1299 v->cargo.Stage(
1300 HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE),
1301 front_v->last_station_visited, next_station,
1302 front_v->current_order.GetUnloadType(), ge,
1303 front_v->cargo_payment,
1304 v->tile);
1305 if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1306 }
1307 }
1308 }
1309 }
1310
1317 static uint GetLoadAmount(Vehicle *v)
1318 {
1319 const Engine *e = v->GetEngine();
1320 uint load_amount = e->info.load_amount;
1321
1322 /* The default loadamount for mail is 1/4 of the load amount for passengers */
1323 bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft();
1324 if (air_mail) load_amount = CeilDiv(load_amount, 4);
1325
1326 if (_settings_game.order.gradual_loading) {
1327 uint16_t cb_load_amount = CALLBACK_FAILED;
1328 if (e->GetGRF() != nullptr && e->GetGRF()->grf_version >= 8) {
1329 /* Use callback 36 */
1330 cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1331 } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
1332 /* Use callback 12 */
1333 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1334 }
1335 if (cb_load_amount != CALLBACK_FAILED) {
1336 if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1337 if (cb_load_amount >= 0x100) {
1338 ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT, cb_load_amount);
1339 } else if (cb_load_amount != 0) {
1340 load_amount = cb_load_amount;
1341 }
1342 }
1343 }
1344
1345 /* Scale load amount the same as capacity */
1346 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);
1347
1348 /* Zero load amount breaks a lot of things. */
1349 return std::max(1u, load_amount);
1350 }
1351
1361 template<class Taction>
1362 bool IterateVehicleParts(Vehicle *v, Taction action)
1363 {
1364 for (Vehicle *w = v; w != nullptr;
1365 w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : nullptr) {
1366 if (!action(w)) return false;
1367 if (w->type == VEH_TRAIN) {
1368 Train *train = Train::From(w);
1369 if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false;
1370 }
1371 }
1372 if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next());
1373 return true;
1374 }
1375
1379 struct IsEmptyAction
1380 {
1386 bool operator()(const Vehicle *v)
1387 {
1388 return v->cargo.StoredCount() == 0;
1389 }
1390 };
1391
1395 struct PrepareRefitAction
1396 {
1397 CargoArray &consist_capleft;
1398 CargoTypes &refit_mask;
1399
1405 PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask) :
1406 consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1407
1414 bool operator()(const Vehicle *v)
1415 {
1416 this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount();
1417 this->refit_mask |= EngInfo(v->engine_type)->refit_mask;
1418 return true;
1419 }
1420 };
1421
1425 struct ReturnCargoAction
1426 {
1427 Station *st;
1428 StationID next_hop;
1429
1435 ReturnCargoAction(Station *st, StationID next_one) : st(st), next_hop(next_one) {}
1436
1442 bool operator()(Vehicle *v)
1443 {
1444 v->cargo.Return(UINT_MAX, &this->st->goods[v->cargo_type].cargo, this->next_hop, v->tile);
1445 return true;
1446 }
1447 };
1448
1452 struct FinalizeRefitAction
1453 {
1454 CargoArray &consist_capleft;
1455 Station *st;
1456 StationIDStack &next_station;
1457 bool do_reserve;
1458
1466 FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve) :
1467 consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve) {}
1468
1475 bool operator()(Vehicle *v)
1476 {
1477 if (this->do_reserve) {
1478 this->st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1479 &v->cargo, this->next_station, v->tile);
1480 }
1481 this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1482 return true;
1483 }
1484 };
1485
1494 static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
1495 {
1496 Vehicle *v_start = v->GetFirstEnginePart();
1497 if (!IterateVehicleParts(v_start, IsEmptyAction())) return;
1498
1499 Backup<CompanyID> cur_company(_current_company, v->owner, FILE_LINE);
1500
1501 CargoTypes refit_mask = v->GetEngine()->info.refit_mask;
1502
1503 /* Remove old capacity from consist capacity and collect refit mask. */
1504 IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask));
1505
1506 bool is_auto_refit = new_cid == CARGO_AUTO_REFIT;
1507 if (is_auto_refit) {
1508 /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1509 new_cid = v_start->cargo_type;
1510 for (CargoID cid : SetCargoBitIterator(refit_mask)) {
1511 if (st->goods[cid].cargo.HasCargoFor(next_station)) {
1512 /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1513 * the returned refit capacity will be greater than zero. */
1514 auto [cc, refit_capacity, mail_capacity, cargo_capacities] = Command<CMD_REFIT_VEHICLE>::Do(DC_QUERY_COST, v_start->index, cid, 0xFF, true, false, 1); // Auto-refit and only this vehicle including artic parts.
1515 /* Try to balance different loadable cargoes between parts of the consist, so that
1516 * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1517 * to the first loadable cargo for which there is only one packet. If the capacities
1518 * are equal refit to the cargo of which most is available. This is important for
1519 * consists of only a single vehicle as those will generally have a consist_capleft
1520 * of 0 for all cargoes. */
1521 if (refit_capacity > 0 && (consist_capleft[cid] < consist_capleft[new_cid] ||
1522 (consist_capleft[cid] == consist_capleft[new_cid] &&
1523 st->goods[cid].cargo.AvailableCount() > st->goods[new_cid].cargo.AvailableCount()))) {
1524 new_cid = cid;
1525 }
1526 }
1527 }
1528 }
1529
1530 /* Refit if given a valid cargo. */
1531 if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1532 /* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
1533 * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1534 * "via any station" before reserving. We rather produce some more "any station" cargo than
1535 * misrouting it. */
1536 IterateVehicleParts(v_start, ReturnCargoAction(st, INVALID_STATION));
1537 CommandCost cost = std::get<0>(Command<CMD_REFIT_VEHICLE>::Do(DC_EXEC, v_start->index, new_cid, 0xFF, true, false, 1)); // Auto-refit and only this vehicle including artic parts.
1538 if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
1539 }
1540
1541 /* Add new capacity to consist capacity and reserve cargo */
1542 IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station,
1543 is_auto_refit || (v->First()->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0));
1544
1545 cur_company.Restore();
1546 }
1547
1554 static bool MayLoadUnderExclusiveRights(const Station *st, const Vehicle *v)
1555 {
1556 return st->owner != OWNER_NONE || st->town->exclusive_counter == 0 || st->town->exclusivity == v->owner;
1557 }
1558
1559 struct ReserveCargoAction {
1560 Station *st;
1561 StationIDStack *next_station;
1562
1563 ReserveCargoAction(Station *st, StationIDStack *next_station) :
1564 st(st), next_station(next_station) {}
1565
1566 bool operator()(Vehicle *v)
1567 {
1568 if (v->cargo_cap > v->cargo.RemainingCount() && MayLoadUnderExclusiveRights(st, v)) {
1569 st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1570 &v->cargo, *next_station, v->tile);
1571 }
1572
1573 return true;
1574 }
1575
1576 };
1577
1586 static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station)
1587 {
1588 /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1589 * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1590 * a vehicle belongs to already has the right cargo. */
1591 bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == nullptr;
1592 for (Vehicle *v = u; v != nullptr; v = v->Next()) {
1593 assert(v->cargo_cap >= v->cargo.RemainingCount());
1594
1595 /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1596 * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1597 * to a different cargo and hasn't tried to do so, yet. */
1598 if (!v->IsArticulatedPart() &&
1599 (v->type != VEH_TRAIN || !Train::From(v)->IsRearDualheaded()) &&
1600 (v->type != VEH_AIRCRAFT || Aircraft::From(v)->IsNormalAircraft()) &&
1601 (must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) {
1602 IterateVehicleParts(v, ReserveCargoAction(st, next_station));
1603 }
1604 if (consist_capleft == nullptr || v->cargo_cap == 0) continue;
1605 (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1606 }
1607 }
1608
1616 static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
1617 {
1618 if (front->type == VEH_TRAIN && _settings_game.order.station_length_loading_penalty) {
1619 /* Each platform tile is worth 2 rail vehicles. */
1620 int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE;
1621 if (overhang > 0) {
1622 ticks <<= 1;
1623 ticks += (overhang * ticks) / 8;
1624 }
1625 }
1626 /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1627 front->load_unload_ticks = std::max(1, ticks);
1628 }
1629
1634 static void LoadUnloadVehicle(Vehicle *front)
1635 {
1636 assert(front->current_order.IsType(OT_LOADING));
1637
1638 StationID last_visited = front->last_station_visited;
1639 Station *st = Station::Get(last_visited);
1640
1641 StationIDStack next_station = front->GetNextStoppingStation();
1642 bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CARGO_AUTO_REFIT;
1643 CargoArray consist_capleft{};
1644 if (_settings_game.order.improved_load && use_autorefit ?
1645 front->cargo_payment == nullptr : (front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0) {
1646 ReserveConsist(st, front,
1647 (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : nullptr,
1648 &next_station);
1649 }
1650
1651 /* We have not waited enough time till the next round of loading/unloading */
1652 if (front->load_unload_ticks != 0) return;
1653
1654 if (front->type == VEH_TRAIN && (!IsTileType(front->tile, MP_STATION) || GetStationIndex(front->tile) != st->index)) {
1655 /* The train reversed in the station. Take the "easy" way
1656 * out and let the train just leave as it always did. */
1657 SetBit(front->vehicle_flags, VF_LOADING_FINISHED);
1658 front->load_unload_ticks = 1;
1659 return;
1660 }
1661
1662 int new_load_unload_ticks = 0;
1663 bool dirty_vehicle = false;
1664 bool dirty_station = false;
1665
1666 bool completely_emptied = true;
1667 bool anything_unloaded = false;
1668 bool anything_loaded = false;
1669 CargoTypes full_load_amount = 0;
1670 CargoTypes cargo_not_full = 0;
1671 CargoTypes cargo_full = 0;
1672 CargoTypes reservation_left = 0;
1673
1674 front->cur_speed = 0;
1675
1676 CargoPayment *payment = front->cargo_payment;
1677
1678 uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1679 for (Vehicle *v = front; v != nullptr; v = v->Next()) {
1680 if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
1681 if (v->cargo_cap == 0) continue;
1682 artic_part++;
1683
1684 GoodsEntry *ge = &st->goods[v->cargo_type];
1685
1686 if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1687 uint cargo_count = v->cargo.UnloadCount();
1688 uint amount_unloaded = _settings_game.order.gradual_loading ? std::min(cargo_count, GetLoadAmount(v)) : cargo_count;
1689 bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1690
1691 assert(payment != nullptr);
1692 payment->SetCargo(v->cargo_type);
1693
1694 if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
1695 /* The station does not accept our goods anymore. */
1696 if (front->current_order.GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) {
1697 /* Transfer instead of delivering. */
1698 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_TRANSFER>(
1699 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER));
1700 } else {
1701 uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
1702 if (v->cargo_cap < new_remaining) {
1703 /* Return some of the reserved cargo to not overload the vehicle. */
1704 v->cargo.Return(new_remaining - v->cargo_cap, &ge->cargo, INVALID_STATION, v->tile);
1705 }
1706
1707 /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1708 v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_KEEP>(
1709 v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER));
1710
1711 /* ... say we unloaded something, otherwise we'll think we didn't unload
1712 * something and we didn't load something, so we must be finished
1713 * at this station. Setting the unloaded means that we will get a
1714 * retry for loading in the next cycle. */
1715 anything_unloaded = true;
1716 }
1717 }
1718
1719 if (v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0) {
1720 /* Mark the station dirty if we transfer, but not if we only deliver. */
1721 dirty_station = true;
1722
1723 if (!ge->HasRating()) {
1724 /* Upon transferring cargo, make sure the station has a rating. Fake a pickup for the
1725 * first unload to prevent the cargo from quickly decaying after the initial drop. */
1726 ge->time_since_pickup = 0;
1727 SetBit(ge->status, GoodsEntry::GES_RATING);
1728 }
1729 }
1730
1731 amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment, v->tile);
1732 remaining = v->cargo.UnloadCount() > 0;
1733 if (amount_unloaded > 0) {
1734 dirty_vehicle = true;
1735 anything_unloaded = true;
1736 new_load_unload_ticks += amount_unloaded;
1737
1738 /* Deliver goods to the station */
1739 st->time_since_unload = 0;
1740 }
1741
1742 if (_settings_game.order.gradual_loading && remaining) {
1743 completely_emptied = false;
1744 } else {
1745 /* We have finished unloading (cargo count == 0) */
1746 ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1747 }
1748
1749 continue;
1750 }
1751
1752 /* Do not pick up goods when we have no-load set or loading is stopped. */
1753 if (front->current_order.GetLoadType() & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
1754
1755 /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1756 if (front->current_order.IsRefit() && artic_part == 1) {
1757 HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo());
1758 ge = &st->goods[v->cargo_type];
1759 }
1760
1761 /* As we're loading here the following link can carry the full capacity of the vehicle. */
1762 v->refit_cap = v->cargo_cap;
1763
1764 /* update stats */
1765 int t;
1766 switch (front->type) {
1767 case VEH_TRAIN:
1768 case VEH_SHIP:
1769 t = front->vcache.cached_max_speed;
1770 break;
1771
1772 case VEH_ROAD:
1773 t = front->vcache.cached_max_speed / 2;
1774 break;
1775
1776 case VEH_AIRCRAFT:
1777 t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units.
1778 break;
1779
1780 default: NOT_REACHED();
1781 }
1782
1783 /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1784 ge->last_speed = ClampTo<uint8_t>(t);
1785 ge->last_age = ClampTo<uint8_t>(TimerGameCalendar::year - front->build_year);
1786
1787 assert(v->cargo_cap >= v->cargo.StoredCount());
1788 /* Capacity available for loading more cargo. */
1789 uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1790
1791 if (cap_left > 0) {
1792 /* If vehicle can load cargo, reset time_since_pickup. */
1793 ge->time_since_pickup = 0;
1794
1795 /* If there's goods waiting at the station, and the vehicle
1796 * has capacity for it, load it on the vehicle. */
1797 if ((v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0) && MayLoadUnderExclusiveRights(st, v)) {
1798 if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1799 if (_settings_game.order.gradual_loading) cap_left = std::min(cap_left, GetLoadAmount(v));
1800
1801 uint loaded = ge->cargo.Load(cap_left, &v->cargo, next_station, v->tile);
1802 if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
1803 /* Remember if there are reservations left so that we don't stop
1804 * loading before they're loaded. */
1805 SetBit(reservation_left, v->cargo_type);
1806 }
1807
1808 /* Store whether the maximum possible load amount was loaded or not.*/
1809 if (loaded == cap_left) {
1810 SetBit(full_load_amount, v->cargo_type);
1811 } else {
1812 ClrBit(full_load_amount, v->cargo_type);
1813 }
1814
1815 /* TODO: Regarding this, when we do gradual loading, we
1816 * should first unload all vehicles and then start
1817 * loading them. Since this will cause
1818 * VEHICLE_TRIGGER_EMPTY to be called at the time when
1819 * the whole vehicle chain is really totally empty, the
1820 * completely_emptied assignment can then be safely
1821 * removed; that's how TTDPatch behaves too. --pasky */
1822 if (loaded > 0) {
1823 completely_emptied = false;
1824 anything_loaded = true;
1825
1826 st->time_since_load = 0;
1827 st->last_vehicle_type = v->type;
1828
1829 if (ge->cargo.TotalCount() == 0) {
1830 TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type);
1831 TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1832 AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
1833 TriggerRoadStopRandomisation(st, st->xy, RSRT_CARGO_TAKEN, v->cargo_type);
1834 TriggerRoadStopAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1835 }
1836
1837 new_load_unload_ticks += loaded;
1838
1839 dirty_vehicle = dirty_station = true;
1840 }
1841 }
1842 }
1843
1844 if (v->cargo.StoredCount() >= v->cargo_cap) {
1845 SetBit(cargo_full, v->cargo_type);
1846 } else {
1847 SetBit(cargo_not_full, v->cargo_type);
1848 }
1849 }
1850
1851 if (anything_loaded || anything_unloaded) {
1852 if (front->type == VEH_TRAIN) {
1853 TriggerStationRandomisation(st, front->tile, SRT_TRAIN_LOADS);
1854 TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS);
1855 } else if (front->type == VEH_ROAD) {
1856 TriggerRoadStopRandomisation(st, front->tile, RSRT_VEH_LOADS);
1857 TriggerRoadStopAnimation(st, front->tile, SAT_TRAIN_LOADS);
1858 }
1859 }
1860
1861 /* Only set completely_emptied, if we just unloaded all remaining cargo */
1862 completely_emptied &= anything_unloaded;
1863
1864 if (!anything_unloaded) delete payment;
1865
1866 ClrBit(front->vehicle_flags, VF_STOP_LOADING);
1867 if (anything_loaded || anything_unloaded) {
1868 if (_settings_game.order.gradual_loading) {
1869 /* The time it takes to load one 'slice' of cargo or passengers depends
1870 * on the vehicle type - the values here are those found in TTDPatch */
1871 const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1872
1873 new_load_unload_ticks = gradual_loading_wait_time[front->type];
1874 }
1875 /* We loaded less cargo than possible for all cargo types and it's not full
1876 * load and we're not supposed to wait any longer: stop loading. */
1877 if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) &&
1878 front->current_order_time >= std::max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
1879 SetBit(front->vehicle_flags, VF_STOP_LOADING);
1880 }
1881
1882 UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
1883 } else {
1884 UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
1885 bool finished_loading = true;
1886 if (front->current_order.GetLoadType() & OLFB_FULL_LOAD) {
1887 if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
1888 /* if the aircraft carries passengers and is NOT full, then
1889 * continue loading, no matter how much mail is in */
1890 if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) ||
1891 (cargo_not_full != 0 && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
1892 finished_loading = false;
1893 }
1894 } else if (cargo_not_full != 0) {
1895 finished_loading = false;
1896 }
1897
1898 /* Refresh next hop stats if we're full loading to make the links
1899 * known to the distribution algorithm and allow cargo to be sent
1900 * along them. Otherwise the vehicle could wait for cargo
1901 * indefinitely if it hasn't visited the other links yet, or if the
1902 * links die while it's loading. */
1903 if (!finished_loading) LinkRefresher::Run(front, true, true);
1904 }
1905
1906 SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
1907 }
1908
1909 /* Calculate the loading indicator fill percent and display
1910 * In the Game Menu do not display indicators
1911 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
1912 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
1913 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
1914 */
1915 if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
1916 StringID percent_up_down = STR_NULL;
1917 int percent = CalcPercentVehicleFilled(front, &percent_up_down);
1918 if (front->fill_percent_te_id == INVALID_TE_ID) {
1919 front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
1920 } else {
1921 UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
1922 }
1923 }
1924
1925 if (completely_emptied) {
1926 /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
1927 * properties such as weight, power and TE whenever the trigger runs. */
1928 dirty_vehicle = true;
1929 TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
1930 }
1931
1932 if (dirty_vehicle) {
1933 SetWindowDirty(GetWindowClassForVehicleType(front->type), front->owner);
1934 SetWindowDirty(WC_VEHICLE_DETAILS, front->index);
1935 front->MarkDirty();
1936 }
1937 if (dirty_station) {
1938 st->MarkTilesDirty(true);
1939 SetWindowDirty(WC_STATION_VIEW, st->index);
1940 SetWindowDirty(WC_STATION_LIST, st->owner);
1941 }
1942 }
1943
1949 void LoadUnloadStation(Station *st)
1950 {
1951 /* No vehicle is here... */
1952 if (st->loading_vehicles.empty()) return;
1953
1954 Vehicle *last_loading = nullptr;
1955
1956 /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
1957 for (Vehicle *v : st->loading_vehicles) {
1958 if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
1959
1960 assert(v->load_unload_ticks != 0);
1961 if (--v->load_unload_ticks == 0) last_loading = v;
1962 }
1963
1964 /* We only need to reserve and load/unload up to the last loading vehicle.
1965 * Anything else will be forgotten anyway after returning from this function.
1966 *
1967 * Especially this means we do _not_ need to reserve cargo for a single
1968 * consist in a station which is not allowed to load yet because its
1969 * load_unload_ticks is still not 0.
1970 */
1971 if (last_loading == nullptr) return;
1972
1973 for (Vehicle *v : st->loading_vehicles) {
1974 if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v);
1975 if (v == last_loading) break;
1976 }
1977
1978 /* Call the production machinery of industries */
1979 for (Industry *iid : _cargo_delivery_destinations) {
1980 TriggerIndustryProduction(iid);
1981 }
1982 _cargo_delivery_destinations.clear();
1983 }
1984
1988 static IntervalTimer<TimerGameCalendar> _calendar_inflation_monthly({TimerGameCalendar::MONTH, TimerGameCalendar::Priority::COMPANY}, [](auto)
1989 {
1990 if (_settings_game.economy.inflation) {
1991 AddInflation();
1992 RecomputePrices();
1993 }
1994 });
1995
1999 static IntervalTimer<TimerGameEconomy> _economy_companies_monthly({ TimerGameEconomy::MONTH, TimerGameEconomy::Priority::COMPANY }, [](auto)
2000 {
2001 CompaniesGenStatistics();
2002 CompaniesPayInterest();
2003 HandleEconomyFluctuations();
2004 });
2005
2006 static void DoAcquireCompany(Company *c, bool hostile_takeover)
2007 {
2008 CompanyID ci = c->index;
2009
2010 CompanyNewsInformation *cni = new CompanyNewsInformation(c, Company::Get(_current_company));
2011
2012 SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
2013 SetDParam(1, hostile_takeover ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
2014 SetDParamStr(2, cni->company_name);
2015 SetDParamStr(3, cni->other_company_name);
2016 SetDParam(4, c->bankrupt_value);
2017 AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
2018 AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
2019 Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
2020
2021 ChangeOwnershipOfCompanyItems(ci, _current_company);
2022
2023 if (c->is_ai) AI::Stop(c->index);
2024
2025 CloseCompanyWindows(ci);
2026 InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
2027 InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
2028 InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
2029 InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
2030
2031 delete c;
2032 }
2033
2044 CommandCost CmdBuyCompany(DoCommandFlag flags, CompanyID target_company, bool hostile_takeover)
2045 {
2046 Company *c = Company::GetIfValid(target_company);
2047 if (c == nullptr) return CMD_ERROR;
2048
2049 /* If you do a hostile takeover but the company went bankrupt, buy it via bankruptcy rules. */
2050 if (hostile_takeover && HasBit(c->bankrupt_asked, _current_company)) hostile_takeover = false;
2051
2052 /* Disable takeovers when not asked */
2053 if (!hostile_takeover && !HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
2054
2055 /* Only allow hostile takeover of AI companies and when in single player */
2056 if (hostile_takeover && !c->is_ai) return CMD_ERROR;
2057 if (hostile_takeover && _networking) return CMD_ERROR;
2058
2059 /* Disable taking over the local company in singleplayer mode */
2060 if (!_networking && _local_company == c->index) return CMD_ERROR;
2061
2062 /* Do not allow companies to take over themselves */
2063 if (target_company == _current_company) return CMD_ERROR;
2064
2065 /* Disable taking over when not allowed. */
2066 if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR;
2067
2068 /* Get the cost here as the company is deleted in DoAcquireCompany.
2069 * For bankruptcy this amount is calculated when the offer was made;
2070 * for hostile takeover you pay the current price. */
2071 CommandCost cost(EXPENSES_OTHER, hostile_takeover ? CalculateHostileTakeoverValue(c) : c->bankrupt_value);
2072
2073 if (flags & DC_EXEC) {
2074 DoAcquireCompany(c, hostile_takeover);
2075 }
2076 return cost;
2077 }
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
game.hpp
Vehicle::GetGroundVehicleCache
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
Definition: vehicle.cpp:3131
Backup::Change
void Change(const U &new_value)
Change the value of the variable.
Definition: backup_type.hpp:84
CompanyProperties::is_ai
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
Definition: company_base.h:108
OrderSettings::improved_load
bool improved_load
improved loading algorithm
Definition: settings_type.h:505
Order::IsRefit
bool IsRefit() const
Is this order a refit order.
Definition: order_base.h:118
PrepareRefitAction::refit_mask
CargoTypes & refit_mask
Bitmask of possible refit cargoes.
Definition: economy.cpp:1398
WC_ROADVEH_LIST
@ WC_ROADVEH_LIST
Road vehicle list; Window numbers:
Definition: window_type.h:314
VehicleCargoList::StoredCount
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:434
IterateVehicleParts
bool IterateVehicleParts(Vehicle *v, Taction action)
Iterate the articulated parts of a vehicle, also considering the special cases of "normal" aircraft a...
Definition: economy.cpp:1362
CargoArray::GetSum
const T GetSum() const
Get the sum of all cargo amounts.
Definition: cargo_type.h:120
InvalidateWindowData
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition: window.cpp:3204
Goal
Struct about goals, current and completed.
Definition: goal_base.h:21
sound_func.h
SmallStack
Minimal stack that uses a pool to avoid pointers.
Definition: smallstack_type.hpp:135
CBM_IND_PRODUCTION_CARGO_ARRIVAL
@ CBM_IND_PRODUCTION_CARGO_ARRIVAL
call production callback when cargo arrives at the industry
Definition: newgrf_callbacks.h:365
Station::goods
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:471
CompanyEconomyEntry::company_value
Money company_value
The value of the company.
Definition: company_base.h:29
TRACK_BIT_NONE
@ TRACK_BIT_NONE
No track.
Definition: track_type.h:36
ROADTYPE_END
@ ROADTYPE_END
Used for iterations.
Definition: road_type.h:29
OUFB_UNLOAD
@ OUFB_UNLOAD
Force unloading all cargo onto the platform, possibly not getting paid.
Definition: order_type.h:54
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
newgrf_station.h
economy_cmd.h
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:71
Pool::PoolItem<&_company_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:339
PrepareUnload
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
Definition: economy.cpp:1275
CBM_CARGO_PROFIT_CALC
@ CBM_CARGO_PROFIT_CALC
custom profit calculation
Definition: newgrf_callbacks.h:356
CargoPayment::visual_profit
Money visual_profit
The visual profit to show.
Definition: economy_base.h:32
SetWindowDirty
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3086
water.h
Station::GetPlatformLength
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const override
Determines the REMAINING length of a platform, starting at (and including) the given tile.
Definition: station.cpp:293
FinalizeRefitAction
Action for finalizing a refit.
Definition: economy.cpp:1452
GroupStatistics::CountEngine
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
Definition: group_cmd.cpp:158
GetPrice
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition: economy.cpp:965
CompanyAdminUpdate
void CompanyAdminUpdate(const Company *company)
Called whenever company related information changes in order to notify admins.
Definition: company_cmd.cpp:838
train.h
UpdateSignalsInBuffer
static SigSegState UpdateSignalsInBuffer(Owner owner)
Updates blocks in _globset buffer.
Definition: signal.cpp:468
command_func.h
Pool::PoolItem<&_company_pool >::GetIfValid
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:350
CMD_ERROR
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:28
OrderSettings::station_length_loading_penalty
bool station_length_loading_penalty
make trains longer than the station load more slowly
Definition: settings_type.h:510
CargoPayment::front
Vehicle * front
The front vehicle to do the payment of.
Definition: economy_base.h:30
Vehicle::cargo_cap
uint16_t cargo_cap
total capacity
Definition: vehicle_base.h:339
CargoPayment::current_station
StationID current_station
NOSAVE: The current station.
Definition: economy_base.h:26
StationCargoList::Load
uint Load(uint max_move, VehicleCargoList *dest, StationIDStack next, TileIndex current_tile)
Loads cargo onto a vehicle.
Definition: cargopacket.cpp:834
UpdateFillingPercent
void UpdateFillingPercent(TextEffectID te_id, uint8_t percent, StringID string)
Update vehicle loading indicators.
Definition: misc_gui.cpp:634
Vehicle::Previous
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
Definition: vehicle_base.h:635
SCORE_TOTAL
@ SCORE_TOTAL
This must always be the last entry.
Definition: economy_type.h:71
CargoPayment::visual_transfer
Money visual_transfer
The transfer credits to be shown.
Definition: economy_base.h:33
Backup
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
GRFFile::price_base_multipliers
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition: newgrf.h:149
Map::LogX
static debug_inline uint LogX()
Logarithm of the map size along the X side.
Definition: map_func.h:251
CanalMaintenanceCost
Money CanalMaintenanceCost(uint32_t num)
Calculates the maintenance cost of a number of canal tiles.
Definition: water.h:52
CargoPayment::CargoPayment
CargoPayment()
Constructor for pool saveload.
Definition: economy_base.h:36
Vehicle::Next
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:628
EXPENSES_OTHER
@ EXPENSES_OTHER
Other expenses.
Definition: economy_type.h:185
GUISettings::loading_indicators
uint8_t loading_indicators
show loading indicators
Definition: settings_type.h:151
OUFB_TRANSFER
@ OUFB_TRANSFER
Transfer all cargo onto the platform.
Definition: order_type.h:55
PrepareRefitAction::consist_capleft
CargoArray & consist_capleft
Capacities left in the consist.
Definition: economy.cpp:1397
BaseStation::town
Town * town
The town this station is associated with.
Definition: base_station_base.h:73
LOAN_INTERVAL
static const int LOAN_INTERVAL
The "steps" in loan size, in British Pounds!
Definition: economy_type.h:215
timer_game_calendar.h
CargoArray::GetCount
uint GetCount() const
Get the amount of cargos that have an amount.
Definition: cargo_type.h:129
Economy::interest_rate
byte interest_rate
Interest.
Definition: economy_type.h:46
OLFB_FULL_LOAD
@ OLFB_FULL_LOAD
Full load all cargoes of the consist.
Definition: order_type.h:64
Station
Station data structure.
Definition: station_base.h:442
ClearCargoDeliveryMonitoring
void ClearCargoDeliveryMonitoring(CompanyID company)
Clear all delivery cargo monitors.
Definition: cargomonitor.cpp:57
economy_base.h
company_gui.h
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
Price
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:89
Economy::inflation_payment
uint64_t inflation_payment
Cumulated inflation of cargo payment since game start; 16 bit fractional part.
Definition: economy_type.h:52
_network_server
bool _network_server
network-server is active
Definition: network.cpp:60
RSRT_CARGO_TAKEN
@ RSRT_CARGO_TAKEN
Trigger roadstop when cargo is completely taken.
Definition: newgrf_roadstop.h:36
Vehicle::vehstatus
byte vehstatus
Status.
Definition: vehicle_base.h:349
WC_INDUSTRY_VIEW
@ WC_INDUSTRY_VIEW
Industry view; Window numbers:
Definition: window_type.h:363
IntervalTimer< TimerGameCalendar >
GB
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:238
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:131
LoadUnloadVehicle
static void LoadUnloadVehicle(Vehicle *front)
Loads/unload the vehicle if possible.
Definition: economy.cpp:1634
TimerGameEconomy::month
static Month month
Current month (0..11).
Definition: timer_game_economy.h:36
CargoArray
Class for storing amounts of cargo.
Definition: cargo_type.h:114
Industry::was_cargo_delivered
byte was_cargo_delivered
flag that indicate this has been the closest industry chosen for cargo delivery by a station....
Definition: industry.h:108
_economy_companies_monthly
static IntervalTimer< TimerGameEconomy > _economy_companies_monthly({ TimerGameEconomy::MONTH, TimerGameEconomy::Priority::COMPANY }, [](auto) { CompaniesGenStatistics();CompaniesPayInterest();HandleEconomyFluctuations();})
Every economy month update of company economic data, plus economy fluctuations.
WC_PERFORMANCE_HISTORY
@ WC_PERFORMANCE_HISTORY
Performance history graph; Window numbers:
Definition: window_type.h:552
VehicleCargoList::ReservedCount
uint ReservedCount() const
Returns sum of reserved cargo.
Definition: cargopacket.h:452
HandleStationRefit
static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
Refit a vehicle in a station.
Definition: economy.cpp:1494
SAT_CARGO_TAKEN
@ SAT_CARGO_TAKEN
Trigger station when cargo is completely taken.
Definition: newgrf_animation_type.h:29
GameSettings::difficulty
DifficultySettings difficulty
settings related to the difficulty
Definition: settings_type.h:617
GroupStatistics::CountVehicle
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
Definition: group_cmd.cpp:133
AAT_STATION_CARGO_TAKEN
@ AAT_STATION_CARGO_TAKEN
Triggered when a cargo type is completely removed from the station (for all tiles at the same time).
Definition: newgrf_animation_type.h:50
ResetPriceBaseMultipliers
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
Definition: economy.cpp:886
BaseConsist::vehicle_flags
uint16_t vehicle_flags
Used for gradual loading and other miscellaneous things (.
Definition: base_consist.h:34
Order::GetUnloadType
OrderUnloadFlags GetUnloadType() const
How must the consist be unloaded?
Definition: order_base.h:139
pricebase.h
CompanySettings::vehicle
VehicleDefaultSettings vehicle
default settings for vehicles
Definition: settings_type.h:612
SetLocalCompany
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
Definition: company_cmd.cpp:115
DifficultySettings::vehicle_costs
byte vehicle_costs
amount of money spent on vehicle running cost
Definition: settings_type.h:105
Waypoint
Representation of a waypoint.
Definition: waypoint_base.h:16
MP_RAILWAY
@ MP_RAILWAY
A railway.
Definition: tile_type.h:49
BaseConsist::lateness_counter
TimerGameTick::Ticks lateness_counter
How many ticks late (or early if negative) this vehicle is.
Definition: base_consist.h:22
CompanyProperties::bankrupt_timeout
int16_t bankrupt_timeout
If bigger than 0, amount of time to wait for an answer on an offer to buy this company.
Definition: company_base.h:96
VF_LOADING_FINISHED
@ VF_LOADING_FINISHED
Vehicle has finished loading.
Definition: vehicle_base.h:45
RoadMaintenanceCost
Money RoadMaintenanceCost(RoadType roadtype, uint32_t num, uint32_t total_num)
Calculates the maintenance cost of a number of road bits.
Definition: road_func.h:125
aircraft.h
TILE_SIZE
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
IsLevelCrossingTile
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
Definition: road_map.h:95
CeilDiv
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:320
goal_base.h
Economy::max_loan
Money max_loan
NOSAVE: Maximum possible loan.
Definition: economy_type.h:44
Industry::produced
ProducedCargoArray produced
INDUSTRY_NUM_OUTPUTS production cargo slots.
Definition: industry.h:99
CargoSpec::Iterate
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:187
SpecializedStation< Station, false >::Get
static Station * Get(size_t index)
Gets station with given index.
Definition: base_station_base.h:259
FinalizeRefitAction::st
Station * st
Station to reserve cargo from.
Definition: economy.cpp:1455
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:54
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:68
MIN_PRICE_MODIFIER
static const int MIN_PRICE_MODIFIER
Maximum NewGRF price modifiers.
Definition: economy_type.h:236
BaseConsist::current_order_time
TimerGameTick::Ticks current_order_time
How many ticks have passed since this order started.
Definition: base_consist.h:21
town.h
CBM_IND_PRODUCTION_256_TICKS
@ CBM_IND_PRODUCTION_256_TICKS
call production callback every 256 ticks
Definition: newgrf_callbacks.h:366
CloseCompanyWindows
void CloseCompanyWindows(CompanyID company)
Close all windows of a company.
Definition: window.cpp:1169
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
GroundVehicle::IsRearDualheaded
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
Definition: ground_vehicle.hpp:333
FinalizeRefitAction::next_station
StationIDStack & next_station
Next hops to reserve cargo for.
Definition: economy.cpp:1456
WC_STATION_VIEW
@ WC_STATION_VIEW
Station view; Window numbers:
Definition: window_type.h:345
DeliverGoodsToIndustry
static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source, CompanyID company)
Transfer goods from station to industry.
Definition: economy.cpp:1055
VehicleCargoList::Return
uint Return(uint max_move, StationCargoList *dest, StationID next_station, TileIndex current_tile)
Returns reserved cargo to the station and removes it from the cache.
Definition: cargopacket.cpp:597
Engine
Definition: engine_base.h:37
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
CC_PASSENGERS
@ CC_PASSENGERS
Passengers.
Definition: cargotype.h:50
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:240
Industry
Defines the internal data of a functional industry.
Definition: industry.h:68
Vehicle::owner
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:305
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
DC_EXEC
@ DC_EXEC
execute the given command
Definition: command_type.h:371
Engine::GetGRFID
uint32_t GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition: engine.cpp:157
CompanyCheckBankrupt
static void CompanyCheckBankrupt(Company *c)
Check for bankruptcy of a company.
Definition: economy.cpp:564
TriggerRoadStopRandomisation
void TriggerRoadStopRandomisation(Station *st, TileIndex tile, RoadStopRandomTrigger trigger, CargoID cargo_type=INVALID_CARGO)
Trigger road stop randomisation.
Definition: newgrf_roadstop.cpp:392
BaseStation::owner
Owner owner
The owner of this station.
Definition: base_station_base.h:74
WC_COMPANY_LEAGUE
@ WC_COMPANY_LEAGUE
Company league window; Window numbers:
Definition: window_type.h:564
UpdateCompanyHQ
void UpdateCompanyHQ(TileIndex tile, uint score)
Update the CompanyHQ to the state associated with the given score.
Definition: object_cmd.cpp:162
TriggerIndustry
void TriggerIndustry(Industry *ind, IndustryTileTrigger trigger)
Trigger a random trigger for all industry tiles.
Definition: newgrf_industrytiles.cpp:372
Economy::fluct
int16_t fluct
Economy fluctuation status.
Definition: economy_type.h:45
DifficultySettings::initial_interest
byte initial_interest
amount of interest (to pay over the loan)
Definition: settings_type.h:104
GoodsEntry::status
byte status
Status of this cargo, see GoodsEntryStatus.
Definition: station_base.h:217
DoCommandFlag
DoCommandFlag
List of flags for a command.
Definition: command_type.h:369
RSRT_VEH_LOADS
@ RSRT_VEH_LOADS
Trigger roadstop when road vehicle loads.
Definition: newgrf_roadstop.h:39
CompanyProperties::current_loan
Money current_loan
Amount of money borrowed from the bank.
Definition: company_base.h:82
VSE_LOAD_UNLOAD
@ VSE_LOAD_UNLOAD
Whenever cargo payment is made for a vehicle.
Definition: newgrf_sound.h:27
GoodsEntry::time_since_pickup
uint8_t time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
Definition: station_base.h:224
CargoPayment::ct
CargoID ct
NOSAVE: The currently handled cargo type.
Definition: economy_base.h:27
CompanyEconomyEntry
Statistics about the economy.
Definition: company_base.h:24
StationCargoList::TotalCount
uint TotalCount() const
Returns total count of cargo at the station, including cargo which is already reserved for loading.
Definition: cargopacket.h:607
CommandCost::Succeeded
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:162
MayCompanyTakeOver
bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
May company cbig buy company csmall?
Definition: company_cmd.cpp:674
Vehicle::x_pos
int32_t x_pos
x coordinate.
Definition: vehicle_base.h:300
FinalizeRefitAction::FinalizeRefitAction
FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve)
Create a finalizing action.
Definition: economy.cpp:1466
SpecializedStation< Station, false >::Iterate
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
Definition: base_station_base.h:310
ai.hpp
RATING_INITIAL
@ RATING_INITIAL
initial rating
Definition: town_type.h:44
WC_DELIVERED_CARGO
@ WC_DELIVERED_CARGO
Delivered cargo graph; Window numbers:
Definition: window_type.h:546
IAT_INDUSTRY_RECEIVED_CARGO
@ IAT_INDUSTRY_RECEIVED_CARGO
Trigger when cargo is received .
Definition: newgrf_animation_type.h:41
ScoreInfo::score
int score
How much score it will give.
Definition: economy_type.h:82
VF_STOP_LOADING
@ VF_STOP_LOADING
Don't load anymore during the next load cycle.
Definition: vehicle_base.h:51
ChangeTileOwner
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
Definition: landscape.cpp:567
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:167
GoodsEntry::cargo
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Definition: station_base.h:210
Pool::MAX_SIZE
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:84
PrepareRefitAction
Refit preparation action.
Definition: economy.cpp:1395
Group
Group data.
Definition: group.h:72
include
bool include(Container &container, typename Container::const_reference &item)
Helper function to append an item to a container if it is not already contained.
Definition: container_func.hpp:24
FreeUnitIDGenerator::UseID
UnitID UseID(UnitID index)
Use a unit number.
Definition: vehicle.cpp:1849
CargoPayment::PayFinalDelivery
void PayFinalDelivery(const CargoPacket *cp, uint count, TileIndex current_tile)
Handle payment for final delivery of the given cargo packet.
Definition: economy.cpp:1234
company_cmd.h
VehicleCache::cached_max_speed
uint16_t cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Definition: vehicle_base.h:124
StationMaintenanceCost
Money StationMaintenanceCost(uint32_t num)
Calculates the maintenance cost of a number of station tiles.
Definition: station_func.h:59
CompanyNewsInformation::other_company_name
std::string other_company_name
The name of the company taking over this one.
Definition: news_type.h:164
newgrf_airporttiles.h
GameSettings::order
OrderSettings order
settings related to orders
Definition: settings_type.h:625
FinalizeRefitAction::operator()
bool operator()(Vehicle *v)
Reserve cargo from the station and update the remaining consist capacities with the vehicle's remaini...
Definition: economy.cpp:1475
InitializeEconomy
void InitializeEconomy()
Resets economy to initial values.
Definition: economy.cpp:950
Economy::infl_amount_pr
byte infl_amount_pr
inflation rate for payment rates
Definition: economy_type.h:48
CompanyNewsInformation::company_name
std::string company_name
The name of the company.
Definition: news_type.h:162
OLF_FULL_LOAD_ANY
@ OLF_FULL_LOAD_ANY
Full load a single cargo of the consist.
Definition: order_type.h:65
CBM_VEHICLE_LOAD_AMOUNT
@ CBM_VEHICLE_LOAD_AMOUNT
Load amount.
Definition: newgrf_callbacks.h:297
Subsidy
Struct about subsidies, offered and awarded.
Definition: subsidy_base.h:22
EngineInfo::callback_mask
uint16_t callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:156
Order::GetRefitCargo
CargoID GetRefitCargo() const
Get the cargo to to refit to.
Definition: order_base.h:132
DifficultySettings::subsidy_multiplier
byte subsidy_multiplier
payment multiplier for subsidized deliveries
Definition: settings_type.h:108
ShowFillingPercent
TextEffectID ShowFillingPercent(int x, int y, int z, uint8_t percent, StringID string)
Display vehicle loading indicators.
Definition: misc_gui.cpp:619
IsEmptyAction::operator()
bool operator()(const Vehicle *v)
Checks if the vehicle has stored cargo.
Definition: economy.cpp:1386
RailType
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
INDUSTRY_TRIGGER_RECEIVED_CARGO
@ INDUSTRY_TRIGGER_RECEIVED_CARGO
Cargo has been delivered.
Definition: newgrf_industrytiles.h:73
CommandCost
Common return value for all commands.
Definition: command_type.h:23
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition: bitmath_func.hpp:282
RemoveFirstTrack
Track RemoveFirstTrack(TrackBits *tracks)
Removes first Track from TrackBits and returns it.
Definition: track_func.h:131
CompanyProperties::num_valid_stat_ent
byte num_valid_stat_ent
Number of valid statistical entries in old_economy.
Definition: company_base.h:113
PrepareRefitAction::PrepareRefitAction
PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask)
Create a refit preparation action.
Definition: economy.cpp:1405
_cargo_payment_pool
CargoPaymentPool _cargo_payment_pool("CargoPayment")
The actual pool to store cargo payments in.
newgrf_engine.h
SignalMaintenanceCost
Money SignalMaintenanceCost(uint32_t num)
Calculates the maintenance cost of a number of signals.
Definition: rail.h:441
GoodsEntry::GES_EVER_ACCEPTED
@ GES_EVER_ACCEPTED
Set when a vehicle ever delivered cargo to the station for final delivery.
Definition: station_base.h:189
CompaniesPayInterest
static void CompaniesPayInterest()
Let all companies pay the monthly interest on their loan.
Definition: economy.cpp:825
CargoPacket::GetFeederShare
Money GetFeederShare() const
Gets the amount of money already paid to earlier vehicles in the feeder chain.
Definition: cargopacket.h:168
CargoPacket::GetSourceType
SourceType GetSourceType() const
Gets the type of the cargo's source.
Definition: cargopacket.h:200
SetPriceBaseMultiplier
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
Definition: economy.cpp:898
Industry::exclusive_supplier
Owner exclusive_supplier
Which company has exclusive rights to deliver cargo (INVALID_OWNER = anyone)
Definition: industry.h:119
SCORE_END
@ SCORE_END
How many scores are there..
Definition: economy_type.h:72
Industry::type
IndustryType type
type of industry.
Definition: industry.h:104
VF_CARGO_UNLOADING
@ VF_CARGO_UNLOADING
Vehicle is unloading cargo.
Definition: vehicle_base.h:46
GoodsEntry::HasRating
bool HasRating() const
Does this cargo have a rating at this station?
Definition: station_base.h:258
Vehicle::tile
TileIndex tile
Current tile index.
Definition: vehicle_base.h:260
CargoPayment::PayTransfer
Money PayTransfer(const CargoPacket *cp, uint count, TileIndex current_tile)
Handle payment for transfer of the given cargo packet.
Definition: economy.cpp:1255
CargoSpec::IsValid
bool IsValid() const
Tests for validity of this cargospec.
Definition: cargotype.h:112
StationCargoList::HasCargoFor
bool HasCargoFor(StationIDStack next) const
Check for cargo headed for a specific station.
Definition: cargopacket.h:565
Station::MarkTilesDirty
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Definition: station.cpp:244
Vehicle::engine_type
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:319
PrepareRefitAction::operator()
bool operator()(const Vehicle *v)
Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and adding th...
Definition: economy.cpp:1414
CompanyProperties::months_of_bankruptcy
byte months_of_bankruptcy
Number of months that the company is unable to pay its debts.
Definition: company_base.h:94
VS_CRASHED
@ VS_CRASHED
Vehicle is crashed.
Definition: vehicle_base.h:40
GoodsEntry::GES_ACCEPTED_BIGTICK
@ GES_ACCEPTED_BIGTICK
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval.
Definition: station_base.h:207
Vehicle::last_station_visited
StationID last_station_visited
The last station we stopped at.
Definition: vehicle_base.h:333
cargo_type.h
INVALID_OWNER
@ INVALID_OWNER
An invalid owner.
Definition: company_type.h:29
CompanyProperties::money
Money money
Money owned by the company.
Definition: company_base.h:80
CargoPayment
Helper class to perform the cargo payment.
Definition: economy_base.h:24
ReserveConsist
static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station)
Reserves cargo if the full load order and improved_load is set or if the current order allows autoref...
Definition: economy.cpp:1586
HasSignalOnTrack
bool HasSignalOnTrack(Tile tile, Track track)
Checks for the presence of signals (either way) on the given track on the given rail tile.
Definition: rail_map.h:413
Vehicle::cargo
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:341
ChangeOwnershipOfCompanyItems
void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
Change the ownership of all the items of a company.
Definition: economy.cpp:334
Vehicle::current_order
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:350
WC_REPLACE_VEHICLE
@ WC_REPLACE_VEHICLE
Replace vehicle window; Window numbers:
Definition: window_type.h:218
Vehicle::GetExpenseType
virtual ExpensesType GetExpenseType([[maybe_unused]] bool income) const
Sets the expense type associated to this vehicle type.
Definition: vehicle_base.h:462
SourceID
uint16_t SourceID
Contains either industry ID, town ID or company ID (or INVALID_SOURCE)
Definition: cargo_type.h:143
StoryPage
Struct about stories, current and completed.
Definition: story_base.h:164
Vehicle::cur_speed
uint16_t cur_speed
current speed
Definition: vehicle_base.h:324
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:55
IsCompanyBuildableVehicleType
bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
Definition: vehicle_func.h:91
Vehicle::build_year
TimerGameCalendar::Year build_year
Year the vehicle has been built.
Definition: vehicle_base.h:287
CompanyProperties::settings
CompanySettings settings
settings specific for each company
Definition: company_base.h:118
Industry::accepted
AcceptedCargoArray accepted
INDUSTRY_NUM_INPUTS input cargo slots.
Definition: industry.h:100
_calendar_inflation_monthly
static IntervalTimer< TimerGameCalendar > _calendar_inflation_monthly({TimerGameCalendar::MONTH, TimerGameCalendar::Priority::COMPANY}, [](auto) { if(_settings_game.economy.inflation) { AddInflation();RecomputePrices();} })
Every calendar month update of inflation.
TimerGameConst< struct Calendar >::ORIGINAL_MAX_YEAR
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: timer_game_common.h:167
CargoPacket::GetDistance
uint GetDistance(TileIndex current_tile) const
Get the current distance the cargo has traveled.
Definition: cargopacket.h:229
WC_VEHICLE_DETAILS
@ WC_VEHICLE_DETAILS
Vehicle details; Window numbers:
Definition: window_type.h:200
Game::NewEvent
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:146
NetworkClientsToSpectators
void NetworkClientsToSpectators(CompanyID cid)
Move the clients of a company to the spectators.
Definition: network_client.cpp:1286
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:627
VS_STOPPED
@ VS_STOPPED
Vehicle is stopped by the player.
Definition: vehicle_base.h:34
MAX_COMPANIES
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
_local_company
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:50
Vehicle::GetEngine
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:747
AI::BroadcastNewEvent
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:269
IsEmptyAction
Action to check if a vehicle has no stored cargo.
Definition: economy.cpp:1379
industry.h
safeguards.h
GroupStatistics::UpdateAutoreplace
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Definition: group_cmd.cpp:221
timer.h
Train
'Train' is either a loco or a wagon.
Definition: train.h:89
vehicle_cmd.h
CommandCost::GetCost
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:83
WC_SHIPS_LIST
@ WC_SHIPS_LIST
Ships list; Window numbers:
Definition: window_type.h:320
Vehicle::profit_this_year
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
Definition: vehicle_base.h:269
UpdateCompanyRatingAndValue
int UpdateCompanyRatingAndValue(Company *c, bool update)
if update is set to true, the economy is updated with this score (also the house is updated,...
Definition: economy.cpp:201
CompanyProperties::location_of_HQ
TileIndex location_of_HQ
Northern tile of HQ; INVALID_TILE when there is none.
Definition: company_base.h:89
CargoList< VehicleCargoList, CargoPacketList >::MTA_TRANSFER
@ MTA_TRANSFER
Transfer the cargo to the station.
Definition: cargopacket.h:297
VehicleDefaultSettings::servint_aircraft
uint16_t servint_aircraft
service interval for aircraft
Definition: settings_type.h:602
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:59
GetLoadAmount
static uint GetLoadAmount(Vehicle *v)
Gets the amount of cargo the given vehicle can load in the current tick.
Definition: economy.cpp:1317
CargoSpec::callback_mask
uint8_t callback_mask
Bitmask of cargo callbacks that have to be called.
Definition: cargotype.h:83
CRR_BANKRUPT
@ CRR_BANKRUPT
The company went belly-up.
Definition: company_type.h:59
SAT_TRAIN_LOADS
@ SAT_TRAIN_LOADS
Trigger platform when train loads/unloads.
Definition: newgrf_animation_type.h:32
AirportMaintenanceCost
Money AirportMaintenanceCost(Owner owner)
Calculates the maintenance cost of all airports of a company.
Definition: station.cpp:703
PCAT_CONSTRUCTION
@ PCAT_CONSTRUCTION
Price is affected by "construction cost" difficulty setting.
Definition: economy_type.h:201
MAX_HISTORY_QUARTERS
static const uint MAX_HISTORY_QUARTERS
The maximum number of quarters kept as performance's history.
Definition: company_type.h:43
CargoID
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
Company::GetMaxLoan
Money GetMaxLoan() const
Calculate the max allowed loan for this company.
Definition: company_cmd.cpp:103
SourceType::Industry
@ Industry
Source/destination is an industry.
WC_TRAINS_LIST
@ WC_TRAINS_LIST
Trains list; Window numbers:
Definition: window_type.h:308
StationCargoList::AvailableCount
uint AvailableCount() const
Returns sum of cargo still available for loading at the sation.
Definition: cargopacket.h:588
newgrf_roadstop.h
Station::always_accepted
CargoTypes always_accepted
Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn't accept c...
Definition: station_base.h:472
CommandCost::AddCost
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:63
WC_INCOME_GRAPH
@ WC_INCOME_GRAPH
Income graph; Window numbers:
Definition: window_type.h:534
stdafx.h
ShowCostOrIncomeAnimation
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Definition: misc_gui.cpp:568
CalculateCompanyValue
Money CalculateCompanyValue(const Company *c, bool including_loan)
Calculate the value of the company.
Definition: economy.cpp:149
CargoPacket::GetSourceID
SourceID GetSourceID() const
Gets the ID of the cargo's source.
Definition: cargopacket.h:209
IndustrySpec
Defines the data structure for constructing industry.
Definition: industrytype.h:105
CountBits
constexpr uint CountBits(T value)
Counts the number of set bits in a variable.
Definition: bitmath_func.hpp:243
PriceBaseSpec::start_price
Money start_price
Default value at game start, before adding multipliers.
Definition: economy_type.h:208
DC_BANKRUPT
@ DC_BANKRUPT
company bankrupts, skip money check, skip vehicle on tile check in some cases
Definition: command_type.h:377
EngineInfo::misc_flags
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:155
NF_NORMAL
@ NF_NORMAL
Normal news item. (Newspaper with text only)
Definition: news_type.h:81
SCORE_MAX
@ SCORE_MAX
The max score that can be in the performance history.
Definition: economy_type.h:74
CompanyProperties::bankrupt_asked
CompanyMask bankrupt_asked
which companies were asked about buying it?
Definition: company_base.h:95
MayLoadUnderExclusiveRights
static bool MayLoadUnderExclusiveRights(const Station *st, const Vehicle *v)
Test whether a vehicle can load cargo at a station even if exclusive transport rights are present.
Definition: economy.cpp:1554
Vehicle::z_pos
int32_t z_pos
z coordinate.
Definition: vehicle_base.h:302
CompanyEconomyEntry::delivered_cargo
CargoArray delivered_cargo
The amount of delivered cargo.
Definition: company_base.h:27
GetTrackBits
TrackBits GetTrackBits(Tile tile)
Gets the track bits of the given tile.
Definition: rail_map.h:136
IndustrySpec::callback_mask
uint16_t callback_mask
Bitmask of industry callbacks that have to be called.
Definition: industrytype.h:138
WC_PAYMENT_RATES
@ WC_PAYMENT_RATES
Payment rates graph; Window numbers:
Definition: window_type.h:570
CargoPacket::GetPeriodsInTransit
uint16_t GetPeriodsInTransit() const
Gets the number of cargo aging periods this cargo has been in transit.
Definition: cargopacket.h:191
StartupIndustryDailyChanges
void StartupIndustryDailyChanges(bool init_counter)
Initialize the variables that will maintain the daily industry change system.
Definition: economy.cpp:908
RailMaintenanceCost
Money RailMaintenanceCost(RailType railtype, uint32_t num, uint32_t total_num)
Calculates the maintenance cost of a number of track bits.
Definition: rail.h:430
IndustryTemporarilyRefusesCargo
bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoID cargo_type)
Check whether an industry temporarily refuses to accept a certain cargo.
Definition: newgrf_industries.cpp:683
CARGO_AUTO_REFIT
static const CargoID CARGO_AUTO_REFIT
Automatically choose cargo type when doing auto refitting.
Definition: cargo_type.h:77
CalculateHostileTakeoverValue
Money CalculateHostileTakeoverValue(const Company *c)
Calculate what you have to pay to take over a company.
Definition: economy.cpp:176
DifficultySettings::economy
bool economy
how volatile is the economy
Definition: settings_type.h:113
EconomySettings::infrastructure_maintenance
bool infrastructure_maintenance
enable monthly maintenance fee for owner infrastructure
Definition: settings_type.h:559
WC_COMPANY_VALUE
@ WC_COMPANY_VALUE
Company value graph; Window numbers:
Definition: window_type.h:558
Vehicle::load_unload_ticks
uint16_t load_unload_ticks
Ticks to wait before starting next cycle.
Definition: vehicle_base.h:357
SRT_CARGO_TAKEN
@ SRT_CARGO_TAKEN
Trigger station when cargo is completely taken.
Definition: newgrf_station.h:104
Economy::industry_daily_increment
uint32_t industry_daily_increment
The value which will increment industry_daily_change_counter. Computed value. NOSAVE.
Definition: economy_type.h:50
ReturnCargoAction
Action for returning reserved cargo.
Definition: economy.cpp:1425
GoodsEntry::GES_CURRENT_MONTH
@ GES_CURRENT_MONTH
Set when cargo was delivered for final delivery this month.
Definition: station_base.h:201
CALLBACK_FAILED
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
Definition: newgrf_callbacks.h:420
CompanyEconomyEntry::expenses
Money expenses
The amount of expenses.
Definition: company_base.h:26
Station::industries_near
IndustryList industries_near
Cached list of industries near the station that can accept cargo,.
Definition: station_base.h:474
Vehicle::vcache
VehicleCache vcache
Cache of often used vehicle values.
Definition: vehicle_base.h:362
GoodsEntry
Stores station stats for a single cargo.
Definition: station_base.h:166
LoadUnloadStation
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
Definition: economy.cpp:1949
_current_company
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:51
TransportedCargoStat::new_act
Tstorage new_act
Actually transported this month.
Definition: town_type.h:118
vehicle_func.h
PROP_VEHICLE_LOAD_AMOUNT
@ PROP_VEHICLE_LOAD_AMOUNT
Loading speed.
Definition: newgrf_properties.h:19
station_base.h
SourceType
SourceType
Types of cargo source and destination.
Definition: cargo_type.h:137
ShowFeederIncomeAnimation
void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
Display animated feeder income.
Definition: misc_gui.cpp:592
newgrf_sound.h
Pool::PoolItem<&_vehicle_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:388
CompanyNewsInformation
Data that needs to be stored for company news messages.
Definition: news_type.h:161
strings_func.h
CompanyEconomyEntry::performance_history
int32_t performance_history
Company score (scale 0-1000)
Definition: company_base.h:28
Pool
Base class for all pools.
Definition: pool_type.hpp:80
Vehicle::First
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:641
newgrf_industrytiles.h
CompanyProperties::cur_economy
CompanyEconomyEntry cur_economy
Economic data of the company of this quarter.
Definition: company_base.h:111
ReturnCargoAction::ReturnCargoAction
ReturnCargoAction(Station *st, StationID next_one)
Construct a cargo return action.
Definition: economy.cpp:1435
WC_PERFORMANCE_DETAIL
@ WC_PERFORMANCE_DETAIL
Performance detail window; Window numbers:
Definition: window_type.h:576
CmdBuyCompany
CommandCost CmdBuyCompany(DoCommandFlag flags, CompanyID target_company, bool hostile_takeover)
Buy up another company.
Definition: economy.cpp:2044
subsidy_func.h
RebuildSubsidisedSourceAndDestinationCache
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
Definition: subsidy.cpp:135
refresh.h
WC_BUILD_VEHICLE
@ WC_BUILD_VEHICLE
Build vehicle; Window numbers:
Definition: window_type.h:383
Economy::inflation_prices
uint64_t inflation_prices
Cumulated inflation of prices since game start; 16 bit fractional part.
Definition: economy_type.h:51
DifficultySettings::infinite_money
bool infinite_money
whether spending money despite negative balance is allowed
Definition: settings_type.h:117
Backup::Restore
void Restore()
Restore the variable.
Definition: backup_type.hpp:112
SpecializedVehicle< Aircraft, VEH_AIRCRAFT >::From
static Aircraft * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Definition: vehicle_base.h:1206
Map::Size
static debug_inline uint Size()
Get the size of the map.
Definition: map_func.h:288
SND_14_CASHTILL
@ SND_14_CASHTILL
18 == 0x12 Income from cargo delivery
Definition: sound_type.h:57
Vehicle::GetFirstEnginePart
Vehicle * GetFirstEnginePart()
Get the first part of an articulated engine.
Definition: vehicle_base.h:974
SetDParam
void SetDParam(size_t n, uint64_t v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings.cpp:104
COMPANY_SPECTATOR
@ COMPANY_SPECTATOR
The client is spectating.
Definition: company_type.h:35
RAILTYPE_END
@ RAILTYPE_END
Used for iterations.
Definition: rail_type.h:33
GetStationIndex
StationID GetStationIndex(Tile t)
Get StationID from a tile.
Definition: station_map.h:28
CompanyServiceInterval
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
Definition: company_cmd.cpp:1197
EF_NO_DEFAULT_CARGO_MULTIPLIER
@ EF_NO_DEFAULT_CARGO_MULTIPLIER
Use the new capacity algorithm. The default cargotype of the vehicle does not affect capacity multipl...
Definition: engine_type.h:174
OUFB_NO_UNLOAD
@ OUFB_NO_UNLOAD
Totally no unloading will be done.
Definition: order_type.h:56
Industry::GetCargoAccepted
AcceptedCargoArray::iterator GetCargoAccepted(CargoID cargo)
Get accepted cargo slot for a specific cargo type.
Definition: industry.h:169
InvalidateWindowClassesData
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition: window.cpp:3221
Order::GetTimetabledWait
uint16_t GetTimetabledWait() const
Get the time in ticks a vehicle should wait at the destination or 0 if it's not timetabled.
Definition: order_base.h:189
Aircraft::IsNormalAircraft
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow.
Definition: aircraft.h:122
GoodsEntry::last_age
uint8_t last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
Definition: station_base.h:243
Vehicle::cargo_payment
CargoPayment * cargo_payment
The cargo payment we're currently in.
Definition: vehicle_base.h:273
Pool::PoolItem<&_cargo_payment_pool >::CleaningPool
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:318
HasSignals
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition: rail_map.h:72
OWNER_NONE
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
AddNewsItem
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32_t ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32_t ref2=UINT32_MAX, const NewsAllocatedData *data=nullptr)
Add a new newsitem to be shown.
Definition: news_gui.cpp:827
CargoList< VehicleCargoList, CargoPacketList >::MTA_LOAD
@ MTA_LOAD
Load the cargo from the station.
Definition: cargopacket.h:300
NT_ECONOMY
@ NT_ECONOMY
Economic changes (recession, industry up/dowm)
Definition: news_type.h:31
VehicleCargoList::RemainingCount
uint RemainingCount() const
Returns the sum of cargo to be kept in the vehicle at the current station.
Definition: cargopacket.h:470
MP_STATION
@ MP_STATION
A tile of a station.
Definition: tile_type.h:53
PCAT_RUNNING
@ PCAT_RUNNING
Price is affected by "vehicle running cost" difficulty setting.
Definition: economy_type.h:200
WC_COMPANY_INFRASTRUCTURE
@ WC_COMPANY_INFRASTRUCTURE
Company infrastructure overview; Window numbers:
Definition: window_type.h:582
DifficultySettings::max_loan
uint32_t max_loan
the maximum initial loan
Definition: settings_type.h:103
GoodsEntry::GES_ACCEPTANCE
@ GES_ACCEPTANCE
Set when the station accepts the cargo currently for final deliveries.
Definition: station_base.h:173
waypoint_base.h
Vehicle::HasArticulatedPart
bool HasArticulatedPart() const
Check if an engine has an articulated part.
Definition: vehicle_base.h:954
Economy::infl_amount
byte infl_amount
inflation amount
Definition: economy_type.h:47
Pool::PoolItem<&_cargo_payment_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:309
ClearCargoPickupMonitoring
void ClearCargoPickupMonitoring(CompanyID company)
Clear all pick-up cargo monitors.
Definition: cargomonitor.cpp:47
ScoreInfo::needed
int needed
How much you need to get the perfect score.
Definition: economy_type.h:81
Sign
Definition: signs_base.h:21
Economy
Data of the economy.
Definition: economy_type.h:43
subsidy_base.h
MAX_UVALUE
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:388
_cargo_delivery_destinations
static SmallIndustryList _cargo_delivery_destinations
The industries we've currently brought cargo to.
Definition: economy.cpp:1043
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:25
DeliverGoods
static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID dest, uint distance, uint16_t periods_in_transit, Company *company, SourceType src_type, SourceID src)
Delivers goods to industries/towns and calculates the payment.
Definition: economy.cpp:1110
SetDParamStr
void SetDParamStr(size_t n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:352
RecomputePrices
void RecomputePrices()
Computes all prices, payments and maximum loan.
Definition: economy.cpp:758
INVALID_CLIENT_ID
@ INVALID_CLIENT_ID
Client is not part of anything.
Definition: network_type.h:50
BaseStation::xy
TileIndex xy
Base tile of the station.
Definition: base_station_base.h:65
AddTrackToSignalBuffer
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
Definition: signal.cpp:578
EXPENSES_PROPERTY
@ EXPENSES_PROPERTY
Property costs.
Definition: economy_type.h:179
container_func.hpp
VehicleDefaultSettings::servint_trains
uint16_t servint_trains
service interval for trains
Definition: settings_type.h:600
company_func.h
CalculateCompanyAssetValue
static Money CalculateCompanyAssetValue(const Company *c)
Calculate the value of the assets of a company.
Definition: economy.cpp:114
RemoveAllEngineReplacementForCompany
void RemoveAllEngineReplacementForCompany(Company *c)
Remove all engine replacement settings for the given company.
Definition: autoreplace_func.h:25
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition: pool_func.hpp:237
Vehicle::y_pos
int32_t y_pos
y coordinate.
Definition: vehicle_base.h:301
UpdateLoadUnloadTicks
static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload again.
Definition: economy.cpp:1616
PlayVehicleSound
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event, bool force)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Definition: newgrf_sound.cpp:187
UpdateLevelCrossing
void UpdateLevelCrossing(TileIndex tile, bool sound=true, bool force_bar=false)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
Definition: train_cmd.cpp:1773
ErrorUnknownCallbackResult
void ErrorUnknownCallbackResult(uint32_t grfid, uint16_t cbid, uint16_t cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Definition: newgrf_commons.cpp:499
TriggerStationRandomisation
void TriggerStationRandomisation(Station *st, TileIndex trigger_tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
Definition: newgrf_station.cpp:923
ScoreID
ScoreID
Score categories in the detailed performance rating.
Definition: economy_type.h:60
ReturnCargoAction::operator()
bool operator()(Vehicle *v)
Return all reserved cargo from a vehicle.
Definition: economy.cpp:1442
CompanyEconomyEntry::income
Money income
The amount of income.
Definition: company_base.h:25
ReserveCargoAction
Definition: economy.cpp:1559
network.h
TriggerIndustryProduction
static void TriggerIndustryProduction(Industry *i)
Inform the industry about just delivered cargo DeliverGoodsToIndustry() silently incremented incoming...
Definition: economy.cpp:1160
TrackBits
TrackBits
Allow incrementing of Track variables.
Definition: track_type.h:35
ChangeWindowOwner
void ChangeWindowOwner(Owner old_owner, Owner new_owner)
Change the owner of all the windows one company can take over from another company in the case of a c...
Definition: window.cpp:1189
VehicleDefaultSettings::servint_ships
uint16_t servint_ships
service interval for ships
Definition: settings_type.h:603
CommandHelper
Definition: command_func.h:93
ground_vehicle.hpp
VehicleDefaultSettings::servint_ispercent
bool servint_ispercent
service intervals are in percents
Definition: settings_type.h:599
CompaniesGenStatistics
static void CompaniesGenStatistics()
Update the finances of all companies.
Definition: economy.cpp:657
CargoPayment::route_profit
Money route_profit
The amount of money to add/remove from the bank account.
Definition: economy_base.h:31
Town
Town data structure.
Definition: town.h:50
LinkRefresher::Run
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
Definition: refresh.cpp:26
CargoPacket
Container for cargo from the same location and time.
Definition: cargopacket.h:40
Map::LogY
static uint LogY()
Logarithm of the map size along the y side.
Definition: map_func.h:261
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1548
BigMulS
static int32_t BigMulS(const int32_t a, const int32_t b, const uint8_t shift)
Multiply two integer values and shift the results to right.
Definition: economy.cpp:80
CargoList< VehicleCargoList, CargoPacketList >::MTA_KEEP
@ MTA_KEEP
Keep the cargo in the vehicle.
Definition: cargopacket.h:299
TimerGameConst< struct Calendar >::ORIGINAL_BASE_YEAR
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: timer_game_common.h:163
OverflowSafeInt< int64_t >
Economy::industry_daily_change_counter
uint32_t industry_daily_change_counter
Bits 31-16 are number of industry to be performed, 15-0 are fractional collected daily.
Definition: economy_type.h:49
ReturnCargoAction::next_hop
StationID next_hop
Next hop the cargo should be assigned to.
Definition: economy.cpp:1428
Town::received
TransportedCargoStat< uint16_t > received[NUM_TAE]
Cargo statistics about received cargotypes.
Definition: town.h:76
INVALID_COMPANY
@ INVALID_COMPANY
An invalid company.
Definition: company_type.h:30
engine_base.h
CargoList< VehicleCargoList, CargoPacketList >::MTA_DELIVER
@ MTA_DELIVER
Deliver the cargo to some town or industry.
Definition: cargopacket.h:298
Vehicle::cargo_type
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:337
CBID_VEHICLE_LOAD_AMOUNT
@ CBID_VEHICLE_LOAD_AMOUNT
Determine the amount of cargo to load per unit of time when using gradual loading.
Definition: newgrf_callbacks.h:36
IsValidCargoID
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition: cargo_type.h:107
SB
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
Definition: bitmath_func.hpp:58
EconomySettings::inflation
bool inflation
disable inflation
Definition: settings_type.h:538
AddCargoDelivery
void AddCargoDelivery(CargoID cargo_type, CompanyID company, uint32_t amount, SourceType src_type, SourceID src, const Station *st, IndustryID dest)
Cargo was delivered to its final destination, update the pickup and delivery maps.
Definition: cargomonitor.cpp:119
CargoPayment::SetCargo
void SetCargo(CargoID ct)
Sets the currently handled cargo type.
Definition: economy_base.h:47
CalcPercentVehicleFilled
uint8_t CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
Calculates how full a vehicle is.
Definition: vehicle.cpp:1486
GetIndustrySpec
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
Definition: industry_cmd.cpp:123
StationCargoList::Reserve
uint Reserve(uint max_move, VehicleCargoList *dest, StationIDStack next, TileIndex current_tile)
Reserves cargo for loading onto the vehicle.
Definition: cargopacket.cpp:817
IsTileType
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
EconomyIsInRecession
bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:49
GetAvailableMoney
Money GetAvailableMoney(CompanyID company)
Get the amount of money that a company has available, or INT64_MAX if there is no such valid company.
Definition: company_cmd.cpp:214
BaseVehicle::type
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:51
SubtractMoneyFromCompany
void SubtractMoneyFromCompany(const CommandCost &cost)
Subtract money from the _current_company, if the company is valid.
Definition: company_cmd.cpp:287
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
AI::Stop
static void Stop(CompanyID company)
Stop a company to be controlled by an AI.
Definition: ai_core.cpp:107
DC_QUERY_COST
@ DC_QUERY_COST
query cost only, don't build.
Definition: command_type.h:373
CBID_CARGO_PROFIT_CALC
@ CBID_CARGO_PROFIT_CALC
Called to calculate the income of delivered cargo.
Definition: newgrf_callbacks.h:168
CheckSubsidised
bool CheckSubsidised(CargoID cargo_type, CompanyID company, SourceType src_type, SourceID src, const Station *st)
Tests whether given delivery is subsidised and possibly awards the subsidy to delivering company.
Definition: subsidy.cpp:565
autoreplace_func.h
Track
Track
These are used to specify a single track.
Definition: track_type.h:19
pool_func.hpp
WC_OPERATING_PROFIT
@ WC_OPERATING_PROFIT
Operating profit graph; Window numbers:
Definition: window_type.h:540
GetVehicleCallback
uint16_t GetVehicleCallback(CallbackID callback, uint32_t param1, uint32_t param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
Definition: newgrf_engine.cpp:1149
story_base.h
CCA_DELETE
@ CCA_DELETE
Delete a company.
Definition: company_type.h:70
ReturnCargoAction::st
Station * st
Station to give the returned cargo to.
Definition: economy.cpp:1427
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
IsCargoInClass
bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
Definition: cargotype.h:230
Company
Definition: company_base.h:129
IsLocalCompany
bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:47
Town::exclusivity
CompanyID exclusivity
which company has exclusivity
Definition: town.h:71
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
IsTileOwner
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
Vehicle::orders
OrderList * orders
Pointer to the order list for this vehicle.
Definition: vehicle_base.h:353
MAX_INFLATION
static const uint64_t MAX_INFLATION
Maximum inflation (including fractional part) without causing overflows in int64_t price computations...
Definition: economy_type.h:229
SetWindowClassesDirty
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3112
WC_AIRCRAFT_LIST
@ WC_AIRCRAFT_LIST
Aircraft list; Window numbers:
Definition: window_type.h:326
CompanyProperties::old_economy
CompanyEconomyEntry old_economy[MAX_HISTORY_QUARTERS]
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
Definition: company_base.h:112
CargoPayment::owner
Company * owner
NOSAVE: The owner of the vehicle.
Definition: economy_base.h:28
AddInflation
bool AddInflation(bool check_year)
Add monthly inflation.
Definition: economy.cpp:720
GroundVehicleCache::cached_total_length
uint16_t cached_total_length
Length of the whole vehicle (valid only for the first engine).
Definition: ground_vehicle.hpp:42
WC_STATION_LIST
@ WC_STATION_LIST
Station list; Window numbers:
Definition: window_type.h:302
ROADTYPE_BEGIN
@ ROADTYPE_BEGIN
Used for iterations.
Definition: road_type.h:26
Vehicle::fill_percent_te_id
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
Definition: vehicle_base.h:321
IndustrySpec::input_cargo_multiplier
uint16_t input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]
Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes)
Definition: industrytype.h:122
newgrf_cargo.h
IndustryProductionCallback
void IndustryProductionCallback(Industry *ind, int reason)
Get the industry production callback and apply it to the industry.
Definition: newgrf_industries.cpp:603
VehicleDefaultSettings::servint_roadveh
uint16_t servint_roadveh
service interval for road vehicles
Definition: settings_type.h:601
GoodsEntry::GES_RATING
@ GES_RATING
This indicates whether a cargo has a rating at the station.
Definition: station_base.h:183
VEHICLE_PROFIT_MIN_AGE
static const TimerGameEconomy::Date VEHICLE_PROFIT_MIN_AGE
Only vehicles older than this have a meaningful profit.
Definition: vehicle_func.h:28
network_func.h
Town::exclusive_counter
uint8_t exclusive_counter
months till the exclusivity expires
Definition: town.h:72
FinalizeRefitAction::do_reserve
bool do_reserve
If the vehicle should reserve.
Definition: economy.cpp:1457
cargomonitor.h
CargoSpec::multiplier
uint16_t multiplier
Capacity multiplier for vehicles. (8 fractional bits)
Definition: cargotype.h:74
EXPENSES_LOAN_INTEREST
@ EXPENSES_LOAN_INTEREST
Interest payments over the loan.
Definition: economy_type.h:184
signs_base.h
FinalizeRefitAction::consist_capleft
CargoArray & consist_capleft
Capacities left in the consist.
Definition: economy.cpp:1454
timer_game_economy.h
OrderSettings::gradual_loading
bool gradual_loading
load vehicles gradually
Definition: settings_type.h:506
GoodsEntry::last_speed
uint8_t last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
Definition: station_base.h:237
Vehicle::MarkDirty
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
Definition: vehicle_base.h:403
GRFFile
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:107
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition: settings_type.h:635
object.h
Prices
Money Prices[PR_END]
Prices of everything.
Definition: economy_type.h:168
GetWindowClassForVehicleType
WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition: vehicle_gui.h:97
ScoreInfo
Data structure for storing how the score is computed for a single score id.
Definition: economy_type.h:80
SRT_TRAIN_LOADS
@ SRT_TRAIN_LOADS
Trigger platform when train loads/unloads.
Definition: newgrf_station.h:107
GroundVehicle::IsMultiheaded
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
Definition: ground_vehicle.hpp:327
OLFB_NO_LOAD
@ OLFB_NO_LOAD
Do not load anything.
Definition: order_type.h:66
_score_info
const ScoreInfo _score_info[]
Score info, values used for computing the detailed performance rating.
Definition: economy.cpp:90
Order::GetLoadType
OrderLoadFlags GetLoadType() const
How must the consist be loaded?
Definition: order_base.h:137
Vehicle::GetNextStoppingStation
StationIDStack GetNextStoppingStation() const
Get the next station the vehicle will stop at.
Definition: vehicle_base.h:746
news_func.h
EconomySettings::feeder_payment_share
uint8_t feeder_payment_share
percentage of leg payment to virtually pay in feeder systems
Definition: settings_type.h:541
TimerGameCalendar::year
static Year year
Current year, starting at 0.
Definition: timer_game_calendar.h:32
backup_type.hpp
DifficultySettings::construction_cost
byte construction_cost
how expensive is building
Definition: settings_type.h:110
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition: timer_game_economy.h:37
RAILTYPE_BEGIN
@ RAILTYPE_BEGIN
Used for iterations.
Definition: rail_type.h:28
CargoSpec::town_acceptance_effect
TownAcceptanceEffect town_acceptance_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition: cargotype.h:80
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103