OpenTTD
economy.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #include "stdafx.h"
13 #include "company_func.h"
14 #include "command_func.h"
15 #include "industry.h"
16 #include "town.h"
17 #include "news_func.h"
18 #include "network/network.h"
19 #include "network/network_func.h"
20 #include "ai/ai.hpp"
21 #include "aircraft.h"
22 #include "train.h"
23 #include "newgrf_engine.h"
24 #include "engine_base.h"
25 #include "ground_vehicle.hpp"
26 #include "newgrf_cargo.h"
27 #include "newgrf_sound.h"
28 #include "newgrf_industrytiles.h"
29 #include "newgrf_station.h"
30 #include "newgrf_airporttiles.h"
31 #include "object.h"
32 #include "strings_func.h"
33 #include "date_func.h"
34 #include "vehicle_func.h"
35 #include "sound_func.h"
36 #include "autoreplace_func.h"
37 #include "company_gui.h"
38 #include "signs_base.h"
39 #include "subsidy_base.h"
40 #include "subsidy_func.h"
41 #include "station_base.h"
42 #include "waypoint_base.h"
43 #include "economy_base.h"
44 #include "core/pool_func.hpp"
45 #include "core/backup_type.hpp"
46 #include "cargo_type.h"
47 #include "water.h"
48 #include "game/game.hpp"
49 #include "cargomonitor.h"
50 #include "goal_base.h"
51 #include "story_base.h"
52 #include "linkgraph/refresh.h"
53 
54 #include "table/strings.h"
55 #include "table/pricebase.h"
56 
57 #include "safeguards.h"
58 
59 
60 /* Initialize the cargo payment-pool */
63 
64 
75 static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
76 {
77  return (int32)((int64)a * (int64)b >> shift);
78 }
79 
81 
86  { 120, 100}, // SCORE_VEHICLES
87  { 80, 100}, // SCORE_STATIONS
88  { 10000, 100}, // SCORE_MIN_PROFIT
89  { 50000, 50}, // SCORE_MIN_INCOME
90  { 100000, 100}, // SCORE_MAX_INCOME
91  { 40000, 400}, // SCORE_DELIVERED
92  { 8, 50}, // SCORE_CARGO
93  {10000000, 50}, // SCORE_MONEY
94  { 250000, 50}, // SCORE_LOAN
95  { 0, 0} // SCORE_TOTAL
96 };
97 
98 int64 _score_part[MAX_COMPANIES][SCORE_END];
99 Economy _economy;
100 Prices _price;
101 Money _additional_cash_required;
102 static PriceMultipliers _price_base_multiplier;
103 
113 Money CalculateCompanyValue(const Company *c, bool including_loan)
114 {
115  Owner owner = c->index;
116 
117  Station *st;
118  uint num = 0;
119 
120  FOR_ALL_STATIONS(st) {
121  if (st->owner == owner) num += CountBits((byte)st->facilities);
122  }
123 
124  Money value = num * _price[PR_STATION_VALUE] * 25;
125 
126  Vehicle *v;
127  FOR_ALL_VEHICLES(v) {
128  if (v->owner != owner) continue;
129 
130  if (v->type == VEH_TRAIN ||
131  v->type == VEH_ROAD ||
133  v->type == VEH_SHIP) {
134  value += v->value * 3 >> 1;
135  }
136  }
137 
138  /* Add real money value */
139  if (including_loan) value -= c->current_loan;
140  value += c->money;
141 
142  return max(value, (Money)1);
143 }
144 
154 {
155  Owner owner = c->index;
156  int score = 0;
157 
158  memset(_score_part[owner], 0, sizeof(_score_part[owner]));
159 
160  /* Count vehicles */
161  {
162  Vehicle *v;
163  Money min_profit = 0;
164  bool min_profit_first = true;
165  uint num = 0;
166 
167  FOR_ALL_VEHICLES(v) {
168  if (v->owner != owner) continue;
170  if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles
171  if (v->age > 730) {
172  /* Find the vehicle with the lowest amount of profit */
173  if (min_profit_first || min_profit > v->profit_last_year) {
174  min_profit = v->profit_last_year;
175  min_profit_first = false;
176  }
177  }
178  }
179  }
180 
181  min_profit >>= 8; // remove the fract part
182 
183  _score_part[owner][SCORE_VEHICLES] = num;
184  /* Don't allow negative min_profit to show */
185  if (min_profit > 0) {
186  _score_part[owner][SCORE_MIN_PROFIT] = min_profit;
187  }
188  }
189 
190  /* Count stations */
191  {
192  uint num = 0;
193  const Station *st;
194 
195  FOR_ALL_STATIONS(st) {
196  /* Only count stations that are actually serviced */
197  if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
198  }
199  _score_part[owner][SCORE_STATIONS] = num;
200  }
201 
202  /* Generate statistics depending on recent income statistics */
203  {
204  int numec = min(c->num_valid_stat_ent, 12);
205  if (numec != 0) {
206  const CompanyEconomyEntry *cee = c->old_economy;
207  Money min_income = cee->income + cee->expenses;
208  Money max_income = cee->income + cee->expenses;
209 
210  do {
211  min_income = min(min_income, cee->income + cee->expenses);
212  max_income = max(max_income, cee->income + cee->expenses);
213  } while (++cee, --numec);
214 
215  if (min_income > 0) {
216  _score_part[owner][SCORE_MIN_INCOME] = min_income;
217  }
218 
219  _score_part[owner][SCORE_MAX_INCOME] = max_income;
220  }
221  }
222 
223  /* Generate score depending on amount of transported cargo */
224  {
225  int numec = min(c->num_valid_stat_ent, 4);
226  if (numec != 0) {
227  const CompanyEconomyEntry *cee = c->old_economy;
228  OverflowSafeInt64 total_delivered = 0;
229  do {
230  total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>();
231  } while (++cee, --numec);
232 
233  _score_part[owner][SCORE_DELIVERED] = total_delivered;
234  }
235  }
236 
237  /* Generate score for variety of cargo */
238  {
239  _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount();
240  }
241 
242  /* Generate score for company's money */
243  {
244  if (c->money > 0) {
245  _score_part[owner][SCORE_MONEY] = c->money;
246  }
247  }
248 
249  /* Generate score for loan */
250  {
251  _score_part[owner][SCORE_LOAN] = _score_info[SCORE_LOAN].needed - c->current_loan;
252  }
253 
254  /* Now we calculate the score for each item.. */
255  {
256  int total_score = 0;
257  int s;
258  score = 0;
259  for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
260  /* Skip the total */
261  if (i == SCORE_TOTAL) continue;
262  /* Check the score */
263  s = Clamp<int64>(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
264  score += s;
265  total_score += _score_info[i].score;
266  }
267 
268  _score_part[owner][SCORE_TOTAL] = score;
269 
270  /* We always want the score scaled to SCORE_MAX (1000) */
271  if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
272  }
273 
274  if (update) {
275  c->old_economy[0].performance_history = score;
276  UpdateCompanyHQ(c->location_of_HQ, score);
278  }
279 
281  return score;
282 }
283 
289 void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
290 {
291  /* We need to set _current_company to old_owner before we try to move
292  * the client. This is needed as it needs to know whether "you" really
293  * are the current local company. */
294  Backup<CompanyByte> cur_company(_current_company, old_owner, FILE_LINE);
295 #ifdef ENABLE_NETWORK
296  /* In all cases, make spectators of clients connected to that company */
297  if (_networking) NetworkClientsToSpectators(old_owner);
298 #endif /* ENABLE_NETWORK */
299  if (old_owner == _local_company) {
300  /* Single player cheated to AI company.
301  * There are no spectators in single player, so we must pick some other company. */
302  assert(!_networking);
303  Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
304  Company *c;
305  FOR_ALL_COMPANIES(c) {
306  if (c->index != old_owner) {
308  break;
309  }
310  }
311  cur_company2.Restore();
312  assert(old_owner != _local_company);
313  }
314 
315  Town *t;
316 
317  assert(old_owner != new_owner);
318 
319  {
320  Company *c;
321  uint i;
322 
323  /* See if the old_owner had shares in other companies */
324  FOR_ALL_COMPANIES(c) {
325  for (i = 0; i < 4; i++) {
326  if (c->share_owners[i] == old_owner) {
327  /* Sell his shares */
329  /* Because we are in a DoCommand, we can't just execute another one and
330  * expect the money to be removed. We need to do it ourself! */
332  }
333  }
334  }
335 
336  /* Sell all the shares that people have on this company */
337  Backup<CompanyByte> cur_company2(_current_company, FILE_LINE);
338  c = Company::Get(old_owner);
339  for (i = 0; i < 4; i++) {
340  cur_company2.Change(c->share_owners[i]);
342  /* Sell the shares */
344  /* Because we are in a DoCommand, we can't just execute another one and
345  * expect the money to be removed. We need to do it ourself! */
347  }
348  }
349  cur_company2.Restore();
350  }
351 
352  /* Temporarily increase the company's money, to be sure that
353  * removing his/her property doesn't fail because of lack of money.
354  * Not too drastically though, because it could overflow */
355  if (new_owner == INVALID_OWNER) {
356  Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
357  }
358 
359  Subsidy *s;
360  FOR_ALL_SUBSIDIES(s) {
361  if (s->awarded == old_owner) {
362  if (new_owner == INVALID_OWNER) {
363  delete s;
364  } else {
365  s->awarded = new_owner;
366  }
367  }
368  }
370 
371  /* Take care of rating and transport rights in towns */
372  FOR_ALL_TOWNS(t) {
373  /* If a company takes over, give the ratings to that company. */
374  if (new_owner != INVALID_OWNER) {
375  if (HasBit(t->have_ratings, old_owner)) {
376  if (HasBit(t->have_ratings, new_owner)) {
377  /* use max of the two ratings. */
378  t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]);
379  } else {
380  SetBit(t->have_ratings, new_owner);
381  t->ratings[new_owner] = t->ratings[old_owner];
382  }
383  }
384  }
385 
386  /* Reset the ratings for the old owner */
387  t->ratings[old_owner] = RATING_INITIAL;
388  ClrBit(t->have_ratings, old_owner);
389 
390  /* Transfer exclusive rights */
391  if (t->exclusive_counter > 0 && t->exclusivity == old_owner) {
392  if (new_owner != INVALID_OWNER) {
393  t->exclusivity = new_owner;
394  } else {
395  t->exclusive_counter = 0;
397  }
398  }
399  }
400 
401  {
402  Vehicle *v;
403  FOR_ALL_VEHICLES(v) {
404  if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
405  if (new_owner == INVALID_OWNER) {
406  if (v->Previous() == NULL) delete v;
407  } else {
410  }
411  }
412  }
413  }
414 
415  /* In all cases clear replace engine rules.
416  * Even if it was copied, it could interfere with new owner's rules */
418 
419  if (new_owner == INVALID_OWNER) {
420  RemoveAllGroupsForCompany(old_owner);
421  } else {
422  Group *g;
423  FOR_ALL_GROUPS(g) {
424  if (g->owner == old_owner) g->owner = new_owner;
425  }
426  }
427 
428  {
429  FreeUnitIDGenerator unitidgen[] = {
432  };
433 
434  /* Override company settings to new company defaults in case we need to convert them.
435  * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom
436  */
437  if (new_owner != INVALID_OWNER) {
438  Company *old_company = Company::Get(old_owner);
439  Company *new_company = Company::Get(new_owner);
440 
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;
446  }
447 
448  Vehicle *v;
449  FOR_ALL_VEHICLES(v) {
450  if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
451  assert(new_owner != INVALID_OWNER);
452 
453  /* Correct default values of interval settings while maintaining custom set ones.
454  * This prevents invalid values on mismatching company defaults being accepted.
455  */
456  if (!v->ServiceIntervalIsCustom()) {
457  Company *new_company = Company::Get(new_owner);
458 
459  /* Technically, passing the interval is not needed as the command will query the default value itself.
460  * However, do not rely on that behaviour.
461  */
462  int interval = CompanyServiceInterval(new_company, v->type);
463  DoCommand(v->tile, v->index, interval | (new_company->settings.vehicle.servint_ispercent << 17), DC_EXEC | DC_BANKRUPT, CMD_CHANGE_SERVICE_INT);
464  }
465 
466  v->owner = new_owner;
467 
468  /* Owner changes, clear cache */
469  v->colourmap = PAL_NONE;
471 
472  if (v->IsEngineCountable()) {
474  }
475  if (v->IsPrimaryVehicle()) {
477  v->unitnumber = unitidgen[v->type].NextID();
478  }
479 
480  /* Invalidate the vehicle's cargo payment "owner cache". */
481  if (v->cargo_payment != NULL) v->cargo_payment->owner = NULL;
482  }
483  }
484 
485  if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner);
486  }
487 
488  /* Change ownership of tiles */
489  {
490  TileIndex tile = 0;
491  do {
492  ChangeTileOwner(tile, old_owner, new_owner);
493  } while (++tile != MapSize());
494 
495  if (new_owner != INVALID_OWNER) {
496  /* Update all signals because there can be new segment that was owned by two companies
497  * and signals were not propagated
498  * Similar with crossings - it is needed to bar crossings that weren't before
499  * because of different owner of crossing and approaching train */
500  tile = 0;
501 
502  do {
503  if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
504  TrackBits tracks = GetTrackBits(tile);
505  do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
506  Track track = RemoveFirstTrack(&tracks);
507  if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
508  } while (tracks != TRACK_BIT_NONE);
509  } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
510  UpdateLevelCrossing(tile);
511  }
512  } while (++tile != MapSize());
513  }
514 
515  /* update signals in buffer */
517  }
518 
519  /* Add airport infrastructure count of the old company to the new one. */
520  if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport;
521 
522  /* convert owner of stations (including deleted ones, but excluding buoys) */
523  Station *st;
524  FOR_ALL_STATIONS(st) {
525  if (st->owner == old_owner) {
526  /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
527  * also, drawing station window would cause reading invalid company's colour */
528  st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
529  }
530  }
531 
532  /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
533  Waypoint *wp;
534  FOR_ALL_WAYPOINTS(wp) {
535  if (wp->owner == old_owner) {
536  wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
537  }
538  }
539 
540  Sign *si;
541  FOR_ALL_SIGNS(si) {
542  if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
543  }
544 
545  /* Remove Game Script created Goals, CargoMonitors and Story pages. */
546  Goal *g;
547  FOR_ALL_GOALS(g) {
548  if (g->company == old_owner) delete g;
549  }
550 
551  ClearCargoPickupMonitoring(old_owner);
552  ClearCargoDeliveryMonitoring(old_owner);
553 
554  StoryPage *sp;
555  FOR_ALL_STORY_PAGES(sp) {
556  if (sp->company == old_owner) delete sp;
557  }
558 
559  /* Change colour of existing windows */
560  if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
561 
562  cur_company.Restore();
563 
565 }
566 
572 {
573  /* If the company has money again, it does not go bankrupt */
574  if (c->money - c->current_loan >= -_economy.max_loan) {
575  int previous_months_of_bankruptcy = CeilDiv(c->months_of_bankruptcy, 3);
576  c->months_of_bankruptcy = 0;
577  c->bankrupt_asked = 0;
578  if (previous_months_of_bankruptcy != 0) CompanyAdminUpdate(c);
579  return;
580  }
581 
583 
584  switch (c->months_of_bankruptcy) {
585  /* All the boring cases (months) with a bad balance where no action is taken */
586  case 0:
587  case 1:
588  case 2:
589  case 3:
590 
591  case 5:
592  case 6:
593 
594  case 8:
595  case 9:
596  break;
597 
598  /* Warn about bankruptcy after 3 months */
599  case 4: {
600  CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
601  cni->FillData(c);
602  SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
603  SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
604  SetDParamStr(2, cni->company_name);
605  AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
606  AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index));
607  Game::NewEvent(new ScriptEventCompanyInTrouble(c->index));
608  break;
609  }
610 
611  /* Offer company for sale after 6 months */
612  case 7: {
613  /* Don't consider the loan */
614  Money val = CalculateCompanyValue(c, false);
615 
616  c->bankrupt_value = val;
617  c->bankrupt_asked = 1 << c->index; // Don't ask the owner
618  c->bankrupt_timeout = 0;
619 
620  /* The company assets should always have some value */
621  assert(c->bankrupt_value > 0);
622  break;
623  }
624 
625  /* Bankrupt company after 6 months (if the company has no value) or latest
626  * after 9 months (if it still had value after 6 months) */
627  default:
628  case 10: {
629  if (!_networking && _local_company == c->index) {
630  /* If we are in offline mode, leave the company playing. Eg. there
631  * is no THE-END, otherwise mark the client as spectator to make sure
632  * he/she is no long in control of this company. However... when you
633  * join another company (cheat) the "unowned" company can bankrupt. */
634  c->bankrupt_asked = MAX_UVALUE(CompanyMask);
635  break;
636  }
637 
638  /* Actually remove the company, but not when we're a network client.
639  * In case of network clients we will be getting a command from the
640  * server. It is done in this way as we are called from the
641  * StateGameLoop which can't change the current company, and thus
642  * updating the local company triggers an assert later on. In the
643  * case of a network game the command will be processed at a time
644  * that changing the current company is okay. In case of single
645  * player we are sure (the above check) that we are not the local
646  * company and thus we won't be moved. */
647  if (!_networking || _network_server) {
648  DoCommandP(0, CCA_DELETE | (c->index << 16) | (CRR_BANKRUPT << 24), 0, CMD_COMPANY_CTRL);
649  return;
650  }
651  break;
652  }
653  }
654 
656 }
657 
663 {
664  /* Check for bankruptcy each month */
665  Company *c;
666  FOR_ALL_COMPANIES(c) {
668  }
669 
670  Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
671 
673  Station *st;
674  FOR_ALL_STATIONS(st) {
675  cur_company.Change(st->owner);
676  CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1);
678  }
679  } else {
680  /* Improved monthly infrastructure costs. */
681  FOR_ALL_COMPANIES(c) {
682  cur_company.Change(c->index);
683 
685  uint32 rail_total = c->infrastructure.GetRailTotal();
686  for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) {
687  if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total));
688  }
690  for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) {
691  if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt]));
692  }
696 
698  }
699  }
700  cur_company.Restore();
701 
702  /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */
703  if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return;
704 
705  FOR_ALL_COMPANIES(c) {
706  /* Drop the oldest history off the end */
707  std::copy_backward(c->old_economy, c->old_economy + MAX_HISTORY_QUARTERS - 1, c->old_economy + MAX_HISTORY_QUARTERS);
708  c->old_economy[0] = c->cur_economy;
709  c->cur_economy = {};
710 
712 
714  if (c->block_preview != 0) c->block_preview--;
715  }
716 
723 }
724 
730 bool AddInflation(bool check_year)
731 {
732  /* The cargo payment inflation differs from the normal inflation, so the
733  * relative amount of money you make with a transport decreases slowly over
734  * the 170 years. After a few hundred years we reach a level in which the
735  * games will become unplayable as the maximum income will be less than
736  * the minimum running cost.
737  *
738  * Furthermore there are a lot of inflation related overflows all over the
739  * place. Solving them is hardly possible because inflation will always
740  * reach the overflow threshold some day. So we'll just perform the
741  * inflation mechanism during the first 170 years (the amount of years that
742  * one had in the original TTD) and stop doing the inflation after that
743  * because it only causes problems that can't be solved nicely and the
744  * inflation doesn't add anything after that either; it even makes playing
745  * it impossible due to the diverging cost and income rates.
746  */
748 
749  if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true;
750 
751  /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100%
752  * scaled by 65536
753  * 12 -> months per year
754  * This is only a good approximation for small values
755  */
756  _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16;
757  _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16;
758 
761 
762  return false;
763 }
764 
769 {
770  /* Setup maximum loan */
771  _economy.max_loan = (_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000;
772 
773  /* Setup price bases */
774  for (Price i = PR_BEGIN; i < PR_END; i++) {
775  Money price = _price_base_specs[i].start_price;
776 
777  /* Apply difficulty settings */
778  uint mod = 1;
779  switch (_price_base_specs[i].category) {
780  case PCAT_RUNNING:
782  break;
783 
784  case PCAT_CONSTRUCTION:
786  break;
787 
788  default: break;
789  }
790  switch (mod) {
791  case 0: price *= 6; break;
792  case 1: price *= 8; break; // normalised to 1 below
793  case 2: price *= 9; break;
794  default: NOT_REACHED();
795  }
796 
797  /* Apply inflation */
798  price = (int64)price * _economy.inflation_prices;
799 
800  /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */
801  int shift = _price_base_multiplier[i] - 16 - 3;
802  if (shift >= 0) {
803  price <<= shift;
804  } else {
805  price >>= -shift;
806  }
807 
808  /* Make sure the price does not get reduced to zero.
809  * Zero breaks quite a few commands that use a zero
810  * cost to see whether something got changed or not
811  * and based on that cause an error. When the price
812  * is zero that fails even when things are done. */
813  if (price == 0) {
814  price = Clamp(_price_base_specs[i].start_price, -1, 1);
815  /* No base price should be zero, but be sure. */
816  assert(price != 0);
817  }
818  /* Store value */
819  _price[i] = price;
820  }
821 
822  /* Setup cargo payment */
823  CargoSpec *cs;
824  FOR_ALL_CARGOSPECS(cs) {
825  cs->current_payment = ((int64)cs->initial_payment * _economy.inflation_payment) >> 16;
826  }
827 
833 }
834 
836 static void CompaniesPayInterest()
837 {
838  const Company *c;
839 
840  Backup<CompanyByte> cur_company(_current_company, FILE_LINE);
841  FOR_ALL_COMPANIES(c) {
842  cur_company.Change(c->index);
843 
844  /* Over a year the paid interest should be "loan * interest percentage",
845  * but... as that number is likely not dividable by 12 (pay each month),
846  * one needs to account for that in the monthly fee calculations.
847  * To easily calculate what one should pay "this" month, you calculate
848  * what (total) should have been paid up to this month and you subtract
849  * whatever has been paid in the previous months. This will mean one month
850  * it'll be a bit more and the other it'll be a bit less than the average
851  * monthly fee, but on average it will be exact.
852  * In order to prevent cheating or abuse (just not paying interest by not
853  * taking a loan we make companies pay interest on negative cash as well
854  */
855  Money yearly_fee = c->current_loan * _economy.interest_rate / 100;
856  if (c->money < 0) {
857  yearly_fee += -c->money *_economy.interest_rate / 100;
858  }
859  Money up_to_previous_month = yearly_fee * _cur_month / 12;
860  Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12;
861 
862  SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month));
863 
864  SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2));
865  }
866  cur_company.Restore();
867 }
868 
869 static void HandleEconomyFluctuations()
870 {
871  if (_settings_game.difficulty.economy != 0) {
872  /* When economy is Fluctuating, decrease counter */
873  _economy.fluct--;
874  } else if (EconomyIsInRecession()) {
875  /* When it's Steady and we are in recession, end it now */
876  _economy.fluct = -12;
877  } else {
878  /* No need to do anything else in other cases */
879  return;
880  }
881 
882  if (_economy.fluct == 0) {
883  _economy.fluct = -(int)GB(Random(), 0, 2);
884  AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
885  } else if (_economy.fluct == -12) {
886  _economy.fluct = GB(Random(), 0, 8) + 312;
887  AddNewsItem(STR_NEWS_END_OF_RECESSION, NT_ECONOMY, NF_NORMAL);
888  }
889 }
890 
891 
896 {
897  memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier));
898 }
899 
907 void SetPriceBaseMultiplier(Price price, int factor)
908 {
909  assert(price < PR_END);
910  _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER);
911 }
912 
917 void StartupIndustryDailyChanges(bool init_counter)
918 {
919  uint map_size = MapLogX() + MapLogY();
920  /* After getting map size, it needs to be scaled appropriately and divided by 31,
921  * which stands for the days in a month.
922  * Using just 31 will make it so that a monthly reset (based on the real number of days of that month)
923  * would not be needed.
924  * Since it is based on "fractional parts", the leftover days will not make much of a difference
925  * on the overall total number of changes performed */
926  _economy.industry_daily_increment = (1 << map_size) / 31;
927 
928  if (init_counter) {
929  /* A new game or a savegame from an older version will require the counter to be initialized */
930  _economy.industry_daily_change_counter = 0;
931  }
932 }
933 
934 void StartupEconomy()
935 {
939  _economy.fluct = GB(Random(), 0, 8) + 168;
940 
941  /* Set up prices */
942  RecomputePrices();
943 
944  StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
945 
946 }
947 
952 {
953  _economy.inflation_prices = _economy.inflation_payment = 1 << 16;
956 }
957 
966 Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
967 {
968  if (index >= PR_END) return 0;
969 
970  Money cost = _price[index] * cost_factor;
971  if (grf_file != NULL) shift += grf_file->price_base_multipliers[index];
972 
973  if (shift >= 0) {
974  cost <<= shift;
975  } else {
976  cost >>= -shift;
977  }
978 
979  return cost;
980 }
981 
982 Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
983 {
984  const CargoSpec *cs = CargoSpec::Get(cargo_type);
985  if (!cs->IsValid()) {
986  /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */
987  return 0;
988  }
989 
990  /* Use callback to calculate cargo profit, if available */
992  uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
993  uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
994  if (callback != CALLBACK_FAILED) {
995  int result = GB(callback, 0, 14);
996 
997  /* Simulate a 15 bit signed value */
998  if (HasBit(callback, 14)) result -= 0x4000;
999 
1000  /* "The result should be a signed multiplier that gets multiplied
1001  * by the amount of cargo moved and the price factor, then gets
1002  * divided by 8192." */
1003  return result * num_pieces * cs->current_payment / 8192;
1004  }
1005  }
1006 
1007  static const int MIN_TIME_FACTOR = 31;
1008  static const int MAX_TIME_FACTOR = 255;
1009 
1010  const int days1 = cs->transit_days[0];
1011  const int days2 = cs->transit_days[1];
1012  const int days_over_days1 = max( transit_days - days1, 0);
1013  const int days_over_days2 = max(days_over_days1 - days2, 0);
1014 
1015  /*
1016  * The time factor is calculated based on the time it took
1017  * (transit_days) compared two cargo-depending values. The
1018  * range is divided into three parts:
1019  *
1020  * - constant for fast transits
1021  * - linear decreasing with time with a slope of -1 for medium transports
1022  * - linear decreasing with time with a slope of -2 for slow transports
1023  *
1024  */
1025  const int time_factor = max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
1026 
1027  return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21);
1028 }
1029 
1032 
1043 static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source, CompanyID company)
1044 {
1045  /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
1046  * This fails in three cases:
1047  * 1) The station accepts the cargo because there are enough houses around it accepting the cargo.
1048  * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
1049  * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
1050  */
1051 
1052  uint accepted = 0;
1053 
1054  for (uint i = 0; i < st->industries_near.Length() && num_pieces != 0; i++) {
1055  Industry *ind = st->industries_near[i];
1056  if (ind->index == source) continue;
1057 
1058  uint cargo_index;
1059  for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
1060  if (cargo_type == ind->accepts_cargo[cargo_index]) break;
1061  }
1062  /* Check if matching cargo has been found */
1063  if (cargo_index >= lengthof(ind->accepts_cargo)) continue;
1064 
1065  /* Check if industry temporarily refuses acceptance */
1066  if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue;
1067 
1068  /* Insert the industry into _cargo_delivery_destinations, if not yet contained */
1069  _cargo_delivery_destinations.Include(ind);
1070 
1071  uint amount = min(num_pieces, 0xFFFFU - ind->incoming_cargo_waiting[cargo_index]);
1072  ind->incoming_cargo_waiting[cargo_index] += amount;
1073  ind->last_cargo_accepted_at[cargo_index] = _date;
1074  num_pieces -= amount;
1075  accepted += amount;
1076 
1077  /* Update the cargo monitor. */
1078  AddCargoDelivery(cargo_type, company, amount, ST_INDUSTRY, source, st, ind->index);
1079  }
1080 
1081  return accepted;
1082 }
1083 
1097 static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID dest, TileIndex source_tile, byte days_in_transit, Company *company, SourceType src_type, SourceID src)
1098 {
1099  assert(num_pieces > 0);
1100 
1101  Station *st = Station::Get(dest);
1102 
1103  /* Give the goods to the industry. */
1104  uint accepted_ind = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == ST_INDUSTRY ? src : INVALID_INDUSTRY, company->index);
1105 
1106  /* If this cargo type is always accepted, accept all */
1107  uint accepted_total = HasBit(st->always_accepted, cargo_type) ? num_pieces : accepted_ind;
1108 
1109  /* Update station statistics */
1110  if (accepted_total > 0) {
1114  }
1115 
1116  /* Update company statistics */
1117  company->cur_economy.delivered_cargo[cargo_type] += accepted_total;
1118 
1119  /* Increase town's counter for town effects */
1120  const CargoSpec *cs = CargoSpec::Get(cargo_type);
1121  st->town->received[cs->town_effect].new_act += accepted_total;
1122 
1123  /* Determine profit */
1124  Money profit = GetTransportedGoodsIncome(accepted_total, DistanceManhattan(source_tile, st->xy), days_in_transit, cargo_type);
1125 
1126  /* Update the cargo monitor. */
1127  AddCargoDelivery(cargo_type, company->index, accepted_total - accepted_ind, src_type, src, st);
1128 
1129  /* Modify profit if a subsidy is in effect */
1130  if (CheckSubsidised(cargo_type, company->index, src_type, src, st)) {
1132  case 0: profit += profit >> 1; break;
1133  case 1: profit *= 2; break;
1134  case 2: profit *= 3; break;
1135  default: profit *= 4; break;
1136  }
1137  }
1138 
1139  return profit;
1140 }
1141 
1148 {
1149  const IndustrySpec *indspec = GetIndustrySpec(i->type);
1150  uint16 callback = indspec->callback_mask;
1151 
1152  i->was_cargo_delivered = true;
1153 
1155  if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
1157  } else {
1159  }
1160  } else {
1161  for (uint ci_in = 0; ci_in < lengthof(i->incoming_cargo_waiting); ci_in++) {
1162  uint cargo_waiting = i->incoming_cargo_waiting[ci_in];
1163  if (cargo_waiting == 0) continue;
1164 
1165  for (uint ci_out = 0; ci_out < lengthof(i->produced_cargo_waiting); ci_out++) {
1166  i->produced_cargo_waiting[ci_out] = min(i->produced_cargo_waiting[ci_out] + (cargo_waiting * indspec->input_cargo_multiplier[ci_in][ci_out] / 256), 0xFFFF);
1167  }
1168 
1169  i->incoming_cargo_waiting[ci_in] = 0;
1170  }
1171  }
1172 
1174  StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
1175 }
1176 
1182  front(front),
1183  current_station(front->last_station_visited)
1184 {
1185 }
1186 
1187 CargoPayment::~CargoPayment()
1188 {
1189  if (this->CleaningPool()) return;
1190 
1191  this->front->cargo_payment = NULL;
1192 
1193  if (this->visual_profit == 0 && this->visual_transfer == 0) return;
1194 
1195  Backup<CompanyByte> cur_company(_current_company, this->front->owner, FILE_LINE);
1196 
1198  this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8;
1199 
1200  if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
1201  SndPlayVehicleFx(SND_14_CASHTILL, this->front);
1202  }
1203 
1204  if (this->visual_transfer != 0) {
1205  ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos,
1206  this->front->z_pos, this->visual_transfer, -this->visual_profit);
1207  } else if (this->visual_profit != 0) {
1208  ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos,
1209  this->front->z_pos, -this->visual_profit);
1210  }
1211 
1212  cur_company.Restore();
1213 }
1214 
1220 void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count)
1221 {
1222  if (this->owner == NULL) {
1223  this->owner = Company::Get(this->front->owner);
1224  }
1225 
1226  /* Handle end of route payment */
1227  Money profit = DeliverGoods(count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->SourceSubsidyType(), cp->SourceSubsidyID());
1228  this->route_profit += profit;
1229 
1230  /* The vehicle's profit is whatever route profit there is minus feeder shares. */
1231  this->visual_profit += profit - cp->FeederShare(count);
1232 }
1233 
1241 {
1242  Money profit = GetTransportedGoodsIncome(
1243  count,
1244  /* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */
1246  cp->DaysInTransit(),
1247  this->ct);
1248 
1249  profit = profit * _settings_game.economy.feeder_payment_share / 100;
1250 
1251  this->visual_transfer += profit; // accumulate transfer profits for whole vehicle
1252  return profit; // account for the (virtual) profit already made for the cargo packet
1253 }
1254 
1259 void PrepareUnload(Vehicle *front_v)
1260 {
1261  Station *curr_station = Station::Get(front_v->last_station_visited);
1262  curr_station->loading_vehicles.push_back(front_v);
1263 
1264  /* At this moment loading cannot be finished */
1266 
1267  /* Start unloading at the first possible moment */
1268  front_v->load_unload_ticks = 1;
1269 
1270  assert(front_v->cargo_payment == NULL);
1271  /* One CargoPayment per vehicle and the vehicle limit equals the
1272  * limit in number of CargoPayments. Can't go wrong. */
1275  front_v->cargo_payment = new CargoPayment(front_v);
1276 
1277  StationIDStack next_station = front_v->GetNextStoppingStation();
1278  if (front_v->orders.list == NULL || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1279  Station *st = Station::Get(front_v->last_station_visited);
1280  for (Vehicle *v = front_v; v != NULL; v = v->Next()) {
1281  const GoodsEntry *ge = &st->goods[v->cargo_type];
1282  if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) {
1283  v->cargo.Stage(
1285  front_v->last_station_visited, next_station,
1286  front_v->current_order.GetUnloadType(), ge,
1287  front_v->cargo_payment);
1288  if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1289  }
1290  }
1291  }
1292 }
1293 
1300 static uint GetLoadAmount(Vehicle *v)
1301 {
1302  const Engine *e = v->GetEngine();
1303  uint load_amount = e->info.load_amount;
1304 
1305  /* The default loadamount for mail is 1/4 of the load amount for passengers */
1306  bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft();
1307  if (air_mail) load_amount = CeilDiv(load_amount, 4);
1308 
1310  uint16 cb_load_amount = CALLBACK_FAILED;
1311  if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) {
1312  /* Use callback 36 */
1313  cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED);
1314  } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) {
1315  /* Use callback 12 */
1316  cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
1317  }
1318  if (cb_load_amount != CALLBACK_FAILED) {
1319  if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8);
1320  if (cb_load_amount >= 0x100) {
1322  } else if (cb_load_amount != 0) {
1323  load_amount = cb_load_amount;
1324  }
1325  }
1326  }
1327 
1328  /* Scale load amount the same as capacity */
1329  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);
1330 
1331  /* Zero load amount breaks a lot of things. */
1332  return max(1u, load_amount);
1333 }
1334 
1344 template<class Taction>
1345 bool IterateVehicleParts(Vehicle *v, Taction action)
1346 {
1347  for (Vehicle *w = v; w != NULL;
1348  w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : NULL) {
1349  if (!action(w)) return false;
1350  if (w->type == VEH_TRAIN) {
1351  Train *train = Train::From(w);
1352  if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false;
1353  }
1354  }
1355  if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next());
1356  return true;
1357 }
1358 
1363 {
1369  bool operator()(const Vehicle *v)
1370  {
1371  return v->cargo.StoredCount() == 0;
1372  }
1373 };
1374 
1379 {
1381  CargoTypes &refit_mask;
1382 
1388  PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask) :
1389  consist_capleft(consist_capleft), refit_mask(refit_mask) {}
1390 
1397  bool operator()(const Vehicle *v)
1398  {
1399  this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount();
1400  this->refit_mask |= EngInfo(v->engine_type)->refit_mask;
1401  return true;
1402  }
1403 };
1404 
1409 {
1411  StationID next_hop;
1412 
1418  ReturnCargoAction(Station *st, StationID next_one) : st(st), next_hop(next_one) {}
1419 
1426  {
1427  v->cargo.Return(UINT_MAX, &this->st->goods[v->cargo_type].cargo, this->next_hop);
1428  return true;
1429  }
1430 };
1431 
1436 {
1440  bool do_reserve;
1441 
1449  FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve) :
1450  consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve) {}
1451 
1459  {
1460  if (this->do_reserve) {
1461  this->st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(),
1462  &v->cargo, st->xy, this->next_station);
1463  }
1464  this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1465  return true;
1466  }
1467 };
1468 
1477 static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid)
1478 {
1479  Vehicle *v_start = v->GetFirstEnginePart();
1480  if (!IterateVehicleParts(v_start, IsEmptyAction())) return;
1481 
1482  Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE);
1483 
1484  CargoTypes refit_mask = v->GetEngine()->info.refit_mask;
1485 
1486  /* Remove old capacity from consist capacity and collect refit mask. */
1487  IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask));
1488 
1489  bool is_auto_refit = new_cid == CT_AUTO_REFIT;
1490  if (is_auto_refit) {
1491  /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */
1492  CargoID cid;
1493  new_cid = v_start->cargo_type;
1494  FOR_EACH_SET_CARGO_ID(cid, refit_mask) {
1495  if (st->goods[cid].cargo.HasCargoFor(next_station)) {
1496  /* Try to find out if auto-refitting would succeed. In case the refit is allowed,
1497  * the returned refit capacity will be greater than zero. */
1498  DoCommand(v_start->tile, v_start->index, cid | 1U << 24 | 0xFF << 8 | 1U << 16, DC_QUERY_COST, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
1499  /* Try to balance different loadable cargoes between parts of the consist, so that
1500  * all of them can be loaded. Avoid a situation where all vehicles suddenly switch
1501  * to the first loadable cargo for which there is only one packet. If the capacities
1502  * are equal refit to the cargo of which most is available. This is important for
1503  * consists of only a single vehicle as those will generally have a consist_capleft
1504  * of 0 for all cargoes. */
1505  if (_returned_refit_capacity > 0 && (consist_capleft[cid] < consist_capleft[new_cid] ||
1506  (consist_capleft[cid] == consist_capleft[new_cid] &&
1507  st->goods[cid].cargo.AvailableCount() > st->goods[new_cid].cargo.AvailableCount()))) {
1508  new_cid = cid;
1509  }
1510  }
1511  }
1512  }
1513 
1514  /* Refit if given a valid cargo. */
1515  if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) {
1516  /* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC
1517  * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been
1518  * "via any station" before reserving. We rather produce some more "any station" cargo than
1519  * misrouting it. */
1520  IterateVehicleParts(v_start, ReturnCargoAction(st, INVALID_STATION));
1521  CommandCost cost = DoCommand(v_start->tile, v_start->index, new_cid | 1U << 24 | 0xFF << 8 | 1U << 16, DC_EXEC, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts.
1522  if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8;
1523  }
1524 
1525  /* Add new capacity to consist capacity and reserve cargo */
1526  IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station,
1527  is_auto_refit || (v->First()->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0));
1528 
1529  cur_company.Restore();
1530 }
1531 
1538 static bool MayLoadUnderExclusiveRights(const Station *st, const Vehicle *v)
1539 {
1540  return st->owner != OWNER_NONE || st->town->exclusive_counter == 0 || st->town->exclusivity == v->owner;
1541 }
1542 
1544  Station *st;
1545  StationIDStack *next_station;
1546 
1547  ReserveCargoAction(Station *st, StationIDStack *next_station) :
1548  st(st), next_station(next_station) {}
1549 
1550  bool operator()(Vehicle *v)
1551  {
1552  if (v->cargo_cap > v->cargo.RemainingCount() && MayLoadUnderExclusiveRights(st, v)) {
1554  &v->cargo, st->xy, *next_station);
1555  }
1556 
1557  return true;
1558  }
1559 
1560 };
1561 
1570 static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station)
1571 {
1572  /* If there is a cargo payment not all vehicles of the consist have tried to do the refit.
1573  * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain"
1574  * a vehicle belongs to already has the right cargo. */
1575  bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == NULL;
1576  for (Vehicle *v = u; v != NULL; v = v->Next()) {
1577  assert(v->cargo_cap >= v->cargo.RemainingCount());
1578 
1579  /* Exclude various ways in which the vehicle might not be the head of an equivalent of
1580  * "articulated chain". Also don't do the reservation if the vehicle is going to refit
1581  * to a different cargo and hasn't tried to do so, yet. */
1582  if (!v->IsArticulatedPart() &&
1583  (v->type != VEH_TRAIN || !Train::From(v)->IsRearDualheaded()) &&
1584  (v->type != VEH_AIRCRAFT || Aircraft::From(v)->IsNormalAircraft()) &&
1585  (must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) {
1586  IterateVehicleParts(v, ReserveCargoAction(st, next_station));
1587  }
1588  if (consist_capleft == NULL || v->cargo_cap == 0) continue;
1589  (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount();
1590  }
1591 }
1592 
1600 static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
1601 {
1602  if (front->type == VEH_TRAIN) {
1603  /* Each platform tile is worth 2 rail vehicles. */
1604  int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE;
1605  if (overhang > 0) {
1606  ticks <<= 1;
1607  ticks += (overhang * ticks) / 8;
1608  }
1609  }
1610  /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */
1611  front->load_unload_ticks = max(1, ticks);
1612 }
1613 
1619 {
1620  assert(front->current_order.IsType(OT_LOADING));
1621 
1622  StationID last_visited = front->last_station_visited;
1623  Station *st = Station::Get(last_visited);
1624 
1625  StationIDStack next_station = front->GetNextStoppingStation();
1626  bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CT_AUTO_REFIT;
1627  CargoArray consist_capleft;
1628  if (_settings_game.order.improved_load && use_autorefit ?
1629  front->cargo_payment == NULL : (front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0) {
1630  ReserveConsist(st, front,
1631  (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : NULL,
1632  &next_station);
1633  }
1634 
1635  /* We have not waited enough time till the next round of loading/unloading */
1636  if (front->load_unload_ticks != 0) return;
1637 
1638  if (front->type == VEH_TRAIN && (!IsTileType(front->tile, MP_STATION) || GetStationIndex(front->tile) != st->index)) {
1639  /* The train reversed in the station. Take the "easy" way
1640  * out and let the train just leave as it always did. */
1642  front->load_unload_ticks = 1;
1643  return;
1644  }
1645 
1646  int new_load_unload_ticks = 0;
1647  bool dirty_vehicle = false;
1648  bool dirty_station = false;
1649 
1650  bool completely_emptied = true;
1651  bool anything_unloaded = false;
1652  bool anything_loaded = false;
1653  CargoTypes full_load_amount = 0;
1654  CargoTypes cargo_not_full = 0;
1655  CargoTypes cargo_full = 0;
1656  CargoTypes reservation_left = 0;
1657 
1658  front->cur_speed = 0;
1659 
1660  CargoPayment *payment = front->cargo_payment;
1661 
1662  uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity)
1663  for (Vehicle *v = front; v != NULL; v = v->Next()) {
1664  if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0;
1665  if (v->cargo_cap == 0) continue;
1666  artic_part++;
1667 
1668  GoodsEntry *ge = &st->goods[v->cargo_type];
1669 
1670  if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
1671  uint cargo_count = v->cargo.UnloadCount();
1672  uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, GetLoadAmount(v)) : cargo_count;
1673  bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
1674 
1675  assert(payment != NULL);
1676  payment->SetCargo(v->cargo_type);
1677 
1678  if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) {
1679  /* The station does not accept our goods anymore. */
1681  /* Transfer instead of delivering. */
1683  v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER), INVALID_STATION);
1684  } else {
1685  uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER);
1686  if (v->cargo_cap < new_remaining) {
1687  /* Return some of the reserved cargo to not overload the vehicle. */
1688  v->cargo.Return(new_remaining - v->cargo_cap, &ge->cargo, INVALID_STATION);
1689  }
1690 
1691  /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/
1693  v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER));
1694 
1695  /* ... say we unloaded something, otherwise we'll think we didn't unload
1696  * something and we didn't load something, so we must be finished
1697  * at this station. Setting the unloaded means that we will get a
1698  * retry for loading in the next cycle. */
1699  anything_unloaded = true;
1700  }
1701  }
1702 
1703  if (v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0) {
1704  /* Mark the station dirty if we transfer, but not if we only deliver. */
1705  dirty_station = true;
1706 
1707  if (!ge->HasRating()) {
1708  /* Upon transfering cargo, make sure the station has a rating. Fake a pickup for the
1709  * first unload to prevent the cargo from quickly decaying after the initial drop. */
1710  ge->time_since_pickup = 0;
1712  }
1713  }
1714 
1715  amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment);
1716  remaining = v->cargo.UnloadCount() > 0;
1717  if (amount_unloaded > 0) {
1718  dirty_vehicle = true;
1719  anything_unloaded = true;
1720  new_load_unload_ticks += amount_unloaded;
1721 
1722  /* Deliver goods to the station */
1723  st->time_since_unload = 0;
1724  }
1725 
1726  if (_settings_game.order.gradual_loading && remaining) {
1727  completely_emptied = false;
1728  } else {
1729  /* We have finished unloading (cargo count == 0) */
1730  ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
1731  }
1732 
1733  continue;
1734  }
1735 
1736  /* Do not pick up goods when we have no-load set or loading is stopped. */
1737  if (front->current_order.GetLoadType() & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue;
1738 
1739  /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */
1740  if (front->current_order.IsRefit() && artic_part == 1) {
1741  HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo());
1742  ge = &st->goods[v->cargo_type];
1743  }
1744 
1745  /* As we're loading here the following link can carry the full capacity of the vehicle. */
1746  v->refit_cap = v->cargo_cap;
1747 
1748  /* update stats */
1749  int t;
1750  switch (front->type) {
1751  case VEH_TRAIN:
1752  case VEH_SHIP:
1753  t = front->vcache.cached_max_speed;
1754  break;
1755 
1756  case VEH_ROAD:
1757  t = front->vcache.cached_max_speed / 2;
1758  break;
1759 
1760  case VEH_AIRCRAFT:
1761  t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units.
1762  break;
1763 
1764  default: NOT_REACHED();
1765  }
1766 
1767  /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
1768  ge->last_speed = min(t, 255);
1769  ge->last_age = min(_cur_year - front->build_year, 255);
1770  ge->time_since_pickup = 0;
1771 
1772  assert(v->cargo_cap >= v->cargo.StoredCount());
1773  /* If there's goods waiting at the station, and the vehicle
1774  * has capacity for it, load it on the vehicle. */
1775  uint cap_left = v->cargo_cap - v->cargo.StoredCount();
1776  if (cap_left > 0 && (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0) && MayLoadUnderExclusiveRights(st, v)) {
1777  if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO);
1778  if (_settings_game.order.gradual_loading) cap_left = min(cap_left, GetLoadAmount(v));
1779 
1780  uint loaded = ge->cargo.Load(cap_left, &v->cargo, st->xy, next_station);
1781  if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) {
1782  /* Remember if there are reservations left so that we don't stop
1783  * loading before they're loaded. */
1784  SetBit(reservation_left, v->cargo_type);
1785  }
1786 
1787  /* Store whether the maximum possible load amount was loaded or not.*/
1788  if (loaded == cap_left) {
1789  SetBit(full_load_amount, v->cargo_type);
1790  } else {
1791  ClrBit(full_load_amount, v->cargo_type);
1792  }
1793 
1794  /* TODO: Regarding this, when we do gradual loading, we
1795  * should first unload all vehicles and then start
1796  * loading them. Since this will cause
1797  * VEHICLE_TRIGGER_EMPTY to be called at the time when
1798  * the whole vehicle chain is really totally empty, the
1799  * completely_emptied assignment can then be safely
1800  * removed; that's how TTDPatch behaves too. --pasky */
1801  if (loaded > 0) {
1802  completely_emptied = false;
1803  anything_loaded = true;
1804 
1805  st->time_since_load = 0;
1806  st->last_vehicle_type = v->type;
1807 
1808  if (ge->cargo.TotalCount() == 0) {
1809  TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type);
1810  TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type);
1811  AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type);
1812  }
1813 
1814  new_load_unload_ticks += loaded;
1815 
1816  dirty_vehicle = dirty_station = true;
1817  }
1818  }
1819 
1820  if (v->cargo.StoredCount() >= v->cargo_cap) {
1821  SetBit(cargo_full, v->cargo_type);
1822  } else {
1823  SetBit(cargo_not_full, v->cargo_type);
1824  }
1825  }
1826 
1827  if (anything_loaded || anything_unloaded) {
1828  if (front->type == VEH_TRAIN) {
1830  TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS);
1831  }
1832  }
1833 
1834  /* Only set completely_emptied, if we just unloaded all remaining cargo */
1835  completely_emptied &= anything_unloaded;
1836 
1837  if (!anything_unloaded) delete payment;
1838 
1840  if (anything_loaded || anything_unloaded) {
1842  /* The time it takes to load one 'slice' of cargo or passengers depends
1843  * on the vehicle type - the values here are those found in TTDPatch */
1844  const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 };
1845 
1846  new_load_unload_ticks = gradual_loading_wait_time[front->type];
1847  }
1848  /* We loaded less cargo than possible for all cargo types and it's not full
1849  * load and we're not supposed to wait any longer: stop loading. */
1850  if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) &&
1851  front->current_order_time >= (uint)max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) {
1853  }
1854 
1855  UpdateLoadUnloadTicks(front, st, new_load_unload_ticks);
1856  } else {
1857  UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing.
1858  bool finished_loading = true;
1859  if (front->current_order.GetLoadType() & OLFB_FULL_LOAD) {
1860  if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) {
1861  /* if the aircraft carries passengers and is NOT full, then
1862  * continue loading, no matter how much mail is in */
1863  if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) ||
1864  (cargo_not_full != 0 && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes
1865  finished_loading = false;
1866  }
1867  } else if (cargo_not_full != 0) {
1868  finished_loading = false;
1869  }
1870 
1871  /* Refresh next hop stats if we're full loading to make the links
1872  * known to the distribution algorithm and allow cargo to be sent
1873  * along them. Otherwise the vehicle could wait for cargo
1874  * indefinitely if it hasn't visited the other links yet, or if the
1875  * links die while it's loading. */
1876  if (!finished_loading) LinkRefresher::Run(front, true, true);
1877  }
1878 
1879  SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
1880  }
1881 
1882  /* Calculate the loading indicator fill percent and display
1883  * In the Game Menu do not display indicators
1884  * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
1885  * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
1886  * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
1887  */
1888  if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) {
1889  StringID percent_up_down = STR_NULL;
1890  int percent = CalcPercentVehicleFilled(front, &percent_up_down);
1891  if (front->fill_percent_te_id == INVALID_TE_ID) {
1892  front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down);
1893  } else {
1894  UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down);
1895  }
1896  }
1897 
1898  if (completely_emptied) {
1899  /* Make sure the vehicle is marked dirty, since we need to update the NewGRF
1900  * properties such as weight, power and TE whenever the trigger runs. */
1901  dirty_vehicle = true;
1902  TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY);
1903  }
1904 
1905  if (dirty_vehicle) {
1908  front->MarkDirty();
1909  }
1910  if (dirty_station) {
1911  st->MarkTilesDirty(true);
1912  SetWindowDirty(WC_STATION_VIEW, last_visited);
1913  InvalidateWindowData(WC_STATION_LIST, last_visited);
1914  }
1915 }
1916 
1923 {
1924  /* No vehicle is here... */
1925  if (st->loading_vehicles.empty()) return;
1926 
1927  Vehicle *last_loading = NULL;
1928  std::list<Vehicle *>::iterator iter;
1929 
1930  /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */
1931  for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1932  Vehicle *v = *iter;
1933 
1934  if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue;
1935 
1936  assert(v->load_unload_ticks != 0);
1937  if (--v->load_unload_ticks == 0) last_loading = v;
1938  }
1939 
1940  /* We only need to reserve and load/unload up to the last loading vehicle.
1941  * Anything else will be forgotten anyway after returning from this function.
1942  *
1943  * Especially this means we do _not_ need to reserve cargo for a single
1944  * consist in a station which is not allowed to load yet because its
1945  * load_unload_ticks is still not 0.
1946  */
1947  if (last_loading == NULL) return;
1948 
1949  for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
1950  Vehicle *v = *iter;
1951  if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v);
1952  if (v == last_loading) break;
1953  }
1954 
1955  /* Call the production machinery of industries */
1956  const Industry * const *isend = _cargo_delivery_destinations.End();
1957  for (Industry **iid = _cargo_delivery_destinations.Begin(); iid != isend; iid++) {
1959  }
1960  _cargo_delivery_destinations.Clear();
1961 }
1962 
1967 {
1970  AddInflation();
1971  RecomputePrices();
1972  }
1974  HandleEconomyFluctuations();
1975 }
1976 
1977 static void DoAcquireCompany(Company *c)
1978 {
1979  CompanyID ci = c->index;
1980 
1981  CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
1983 
1984  SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
1985  SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION);
1986  SetDParamStr(2, cni->company_name);
1988  SetDParam(4, c->bankrupt_value);
1989  AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
1990  AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1991  Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company));
1992 
1994 
1995  if (c->bankrupt_value == 0) {
1997  owner->current_loan += c->current_loan;
1998  }
1999 
2000  if (c->is_ai) AI::Stop(c->index);
2001 
2007 
2008  delete c;
2009 }
2010 
2011 extern int GetAmountOwnedBy(const Company *c, Owner owner);
2012 
2022 CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2023 {
2025  CompanyID target_company = (CompanyID)p1;
2026  Company *c = Company::GetIfValid(target_company);
2027 
2028  /* Check if buying shares is allowed (protection against modified clients)
2029  * Cannot buy own shares */
2030  if (c == NULL || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR;
2031 
2032  /* Protect new companies from hostile takeovers */
2033  if (_cur_year - c->inaugurated_year < 6) return_cmd_error(STR_ERROR_PROTECTED);
2034 
2035  /* Those lines are here for network-protection (clients can be slow) */
2036  if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost;
2037 
2038  if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) {
2039  if (!c->is_ai) return cost; // We can not buy out a real company (temporarily). TODO: well, enable it obviously.
2040 
2041  if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
2042  }
2043 
2044 
2045  cost.AddCost(CalculateCompanyValue(c) >> 2);
2046  if (flags & DC_EXEC) {
2047  OwnerByte *b = c->share_owners;
2048 
2049  while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR
2050  *b = _current_company;
2051 
2052  for (int i = 0; c->share_owners[i] == _current_company;) {
2053  if (++i == 4) {
2054  c->bankrupt_value = 0;
2055  DoAcquireCompany(c);
2056  break;
2057  }
2058  }
2059  InvalidateWindowData(WC_COMPANY, target_company);
2060  CompanyAdminUpdate(c);
2061  }
2062  return cost;
2063 }
2064 
2074 CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2075 {
2076  CompanyID target_company = (CompanyID)p1;
2077  Company *c = Company::GetIfValid(target_company);
2078 
2079  /* Cannot sell own shares */
2080  if (c == NULL || _current_company == target_company) return CMD_ERROR;
2081 
2082  /* Check if selling shares is allowed (protection against modified clients).
2083  * However, we must sell shares of companies being closed down. */
2084  if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CMD_ERROR;
2085 
2086  /* Those lines are here for network-protection (clients can be slow) */
2087  if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost();
2088 
2089  /* adjust it a little to make it less profitable to sell and buy */
2090  Money cost = CalculateCompanyValue(c) >> 2;
2091  cost = -(cost - (cost >> 7));
2092 
2093  if (flags & DC_EXEC) {
2094  OwnerByte *b = c->share_owners;
2095  while (*b != _current_company) b++; // share owners is guaranteed to contain company
2096  *b = COMPANY_SPECTATOR;
2097  InvalidateWindowData(WC_COMPANY, target_company);
2098  CompanyAdminUpdate(c);
2099  }
2100  return CommandCost(EXPENSES_OTHER, cost);
2101 }
2102 
2115 CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
2116 {
2117  CompanyID target_company = (CompanyID)p1;
2118  Company *c = Company::GetIfValid(target_company);
2119  if (c == NULL) return CMD_ERROR;
2120 
2121  /* Disable takeovers when not asked */
2122  if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR;
2123 
2124  /* Disable taking over the local company in single player */
2125  if (!_networking && _local_company == c->index) return CMD_ERROR;
2126 
2127  /* Do not allow companies to take over themselves */
2128  if (target_company == _current_company) return CMD_ERROR;
2129 
2130  /* Disable taking over when not allowed. */
2131  if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR;
2132 
2133  /* Get the cost here as the company is deleted in DoAcquireCompany. */
2134  CommandCost cost(EXPENSES_OTHER, c->bankrupt_value);
2135 
2136  if (flags & DC_EXEC) {
2137  DoAcquireCompany(c);
2138  }
2139  return cost;
2140 }
Used for iterations.
Definition: rail_type.h:35
Functions related to OTTD&#39;s strings.
void TriggerStationRandomisation(Station *st, TileIndex tile, StationRandomTrigger trigger, CargoID cargo_type)
Trigger station randomisation.
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
Definition: landscape.cpp:602
byte infl_amount_pr
inflation rate for payment rates
Definition: economy_type.h:26
static bool IsLocalCompany()
Is the current company the local company?
Definition: company_func.h:45
uint RemainingCount() const
Returns the sum of cargo to be kept in the vehicle at the current station.
Definition: cargopacket.h:402
Vehicle * Previous() const
Get the previous vehicle of this vehicle.
Definition: vehicle_base.h:588
Vehicle is stopped by the player.
Definition: vehicle_base.h:33
Money Prices[PR_END]
Prices of everything.
Definition: economy_type.h:146
void AddTrackToSignalBuffer(TileIndex tile, Track track, Owner owner)
Add track to signal update buffer.
Definition: signal.cpp:582
int CompanyServiceInterval(const Company *c, VehicleType type)
Get the service interval for the given company and vehicle type.
Trigger station when cargo is completely taken.
VehicleCargoList cargo
The cargo this vehicle is carrying.
Definition: vehicle_base.h:309
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:77
static void NewEvent(class ScriptEvent *event)
Queue a new event for a Game Script.
Definition: game_core.cpp:143
used in multiplayer to create a new companies etc.
Definition: command_type.h:279
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:257
IndustryVector industries_near
Cached list of industries near the station that can accept cargo,.
Definition: station_base.h:475
const ScoreInfo _score_info[]
Score info, values used for computing the detailed performance rating.
Definition: economy.cpp:85
Money value
Value of the vehicle.
Definition: vehicle_base.h:241
bool _networking
are we in networking mode?
Definition: network.cpp:56
bool operator()(Vehicle *v)
Reserve cargo from the station and update the remaining consist capacities with the vehicle&#39;s remaini...
Definition: economy.cpp:1458
Functions for NewGRF engines.
static void CompaniesGenStatistics()
Update the finances of all companies.
Definition: economy.cpp:662
void FillData(const struct Company *c, const struct Company *other=NULL)
Fill the CompanyNewsInformation struct with the required data.
static const uint CALLBACK_FAILED
Different values for Callback result evaluations.
void LoadUnloadStation(Station *st)
Load/unload the vehicles in this station according to the order they entered.
Definition: economy.cpp:1922
virtual void MarkDirty()
Marks the vehicles to be redrawn and updates cached variables.
Definition: vehicle_base.h:364
TransportedCargoStat< uint16 > received[NUM_TE]
Cargo statistics about received cargotypes.
Definition: town.h:80
byte infl_amount
inflation amount
Definition: economy_type.h:25
Definition of link refreshing utility.
Station * st
Station to give the returned cargo to.
Definition: economy.cpp:1410
Minimal stack that uses a pool to avoid pointers.
Money start_price
Default value at game start, before adding multipliers.
Definition: economy_type.h:185
static int32 BigMulS(const int32 a, const int32 b, const uint8 shift)
Multiply two integer values and shift the results to right.
Definition: economy.cpp:75
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition: window.cpp:3201
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:29
Vehicle * GetFirstEnginePart()
Get the first part of an articulated engine.
Definition: vehicle_base.h:921
byte GetCount() const
Get the amount of cargos that have an amount.
Definition: cargo_type.h:136
EconomySettings economy
settings to change the economy
Vehicle has finished loading.
Definition: vehicle_base.h:44
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:246
int32 performance_history
Company score (scale 0-1000)
Definition: company_base.h:27
Functions related to dates.
static const Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: date_type.h:55
CompanyByte exclusivity
which company has exclusivity
Definition: town.h:75
Cargo has been delivered.
Company * owner
The owner of the vehicle.
Definition: economy_base.h:33
uint32 GetRailTotal() const
Get total sum of all owned track bits.
Definition: company_base.h:40
Base for the train class.
static uint MapLogX()
Logarithm of the map size along the X side.
Definition: map_func.h:53
Year inaugurated_year
Year of starting the company.
Definition: company_base.h:77
static bool HasSignalOnTrack(TileIndex tile, Track track)
Checks for the presence of signals (either way) on the given track on the given rail tile...
Definition: rail_map.h:414
static T SetBit(T &x, const uint8 y)
Set a bit in a variable.
change the server interval of a vehicle
Definition: command_type.h:231
Track
These are used to specify a single track.
Definition: track_type.h:21
uint16 cur_speed
current speed
Definition: vehicle_base.h:293
static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID dest, TileIndex source_tile, byte days_in_transit, Company *company, SourceType src_type, SourceID src)
Delivers goods to industries/towns and calculates the payment.
Definition: economy.cpp:1097
query cost only, don&#39;t build.
Definition: command_type.h:347
static const CommandCost CMD_ERROR
Define a default return value for a failed command.
Definition: command_func.h:25
Replace vehicle window; Window numbers:
Definition: window_type.h:213
uint64 inflation_prices
Cumulated inflation of prices since game start; 16 bit fractional part.
Definition: economy_type.h:29
Set when cargo was delivered for final delivery during the current STATION_ACCEPTANCE_TICKS interval...
Definition: station_base.h:211
uint16 _returned_refit_capacity
Stores the capacity after a refit operation.
Definition: vehicle.cpp:87
Used for iterations.
Definition: road_type.h:26
Specification of a cargo type.
Definition: cargotype.h:56
Money FeederShare() const
Gets the amount of money already paid to earlier vehicles in the feeder chain.
Definition: cargopacket.h:111
OrderList * list
Pointer to the order list for this vehicle.
Definition: vehicle_base.h:321
byte block_preview
Number of quarters that the company is not allowed to get new exclusive engine previews (see Companie...
Definition: company_base.h:70
byte interest_rate
Interest.
Definition: economy_type.h:24
CompanyMask bankrupt_asked
which companies were asked about buying it?
Definition: company_base.h:80
Functions related to vehicles.
Set when cargo was delivered for final delivery this month.
Definition: station_base.h:205
uint16 callback_mask
Bitmask of industry callbacks that have to be called.
Definition: industrytype.h:135
uint32 current_order_time
How many ticks have passed since this order started.
Definition: base_consist.h:23
uint TotalCount() const
Returns total count of cargo at the station, including cargo which is already reserved for loading...
Definition: cargopacket.h:541
Struct about goals, current and completed.
Definition: goal_base.h:23
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:67
CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Acquire shares in an opposing company.
Definition: economy.cpp:2022
Build vehicle; Window numbers:
Definition: window_type.h:378
Vehicle data structure.
Definition: vehicle_base.h:212
Called to calculate the income of delivered cargo.
void Clear()
Remove all items from the list.
Action for returning reserved cargo.
Definition: economy.cpp:1408
void Change(const U &new_value)
Change the value of the variable.
Definition: backup_type.hpp:86
Defines the internal data of a functional industry.
Definition: industry.h:41
const T * Begin() const
Get the pointer to the first item (const)
custom profit calculation
DifficultySettings difficulty
settings related to the difficulty
static void BroadcastNewEvent(ScriptEvent *event, CompanyID skip_company=MAX_COMPANIES)
Broadcast a new event to all active AIs.
Definition: ai_core.cpp:263
Stores station stats for a single cargo.
Definition: station_base.h:170
Tindex index
Index of this pool item.
Definition: pool_type.hpp:147
void IndustryProductionCallback(Industry *ind, int reason)
Get the industry production callback and apply it to the industry.
static Money SignalMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of signals.
Definition: rail.h:412
byte months_of_bankruptcy
Number of months that the company is unable to pay its debts.
Definition: company_base.h:79
This must always be the last entry.
Definition: economy_type.h:49
TileIndex SourceStationXY() const
Gets the coordinates of the cargo&#39;s source station.
Definition: cargopacket.h:169
Payment rates graph; Window numbers:
Definition: window_type.h:560
Company value graph; Window numbers:
Definition: window_type.h:548
byte subsidy_multiplier
amount of subsidy
Definition: settings_type.h:64
Date last_cargo_accepted_at[INDUSTRY_NUM_INPUTS]
Last day each cargo type was accepted by this industry.
Definition: industry.h:68
static SigSegState UpdateSignalsInBuffer(Owner owner)
Updates blocks in _globset buffer.
Definition: signal.cpp:472
Vehicle is unloading cargo.
Definition: vehicle_base.h:45
bool IsMultiheaded() const
Check if the vehicle is a multiheaded engine.
Base for aircraft.
Representation of a waypoint.
Definition: waypoint_base.h:18
StationID last_station_visited
The last station we stopped at.
Definition: vehicle_base.h:302
uint16 input_cargo_multiplier[INDUSTRY_NUM_INPUTS][INDUSTRY_NUM_OUTPUTS]
Input cargo multipliers (multiply amount of incoming cargo for the produced cargoes) ...
Definition: industrytype.h:119
The client is spectating.
Definition: company_type.h:37
Simple vector template class.
void MarkTilesDirty(bool cargo_change) const
Marks the tiles of the station as dirty.
Definition: station.cpp:200
Data that needs to be stored for company news messages.
Definition: news_type.h:150
A railway.
Definition: tile_type.h:44
Money GetCost() const
The costs as made up to this moment.
Definition: command_type.h:84
initial rating
Definition: town_type.h:46
byte was_cargo_delivered
flag that indicate this has been the closest industry chosen for cargo delivery by a station...
Definition: industry.h:61
Refit preparation action.
Definition: economy.cpp:1378
static uint MapLogY()
Logarithm of the map size along the y side.
Definition: map_func.h:64
int32 lateness_counter
How many ticks late (or early if negative) this vehicle is.
Definition: base_consist.h:24
FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve)
Create a finalizing action.
Definition: economy.cpp:1449
uint32 station
Count of company owned station tiles.
Definition: company_base.h:36
Automatically choose cargo type when doing auto refitting.
Definition: cargo_type.h:68
Common return value for all commands.
Definition: command_type.h:25
StationIDStack & next_station
Next hops to reserve cargo for.
Definition: economy.cpp:1439
RoadType
The different roadtypes we support.
Definition: road_type.h:22
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Definition: station_base.h:255
static T max(const T a, const T b)
Returns the maximum of two values.
Definition: math_func.hpp:26
Town * town
The town this station is associated with.
static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks)
Update the vehicle&#39;s load_unload_ticks, the time it will wait until it tries to load or unload again...
Definition: economy.cpp:1600
bool HasRating() const
Does this cargo have a rating at this station?
Definition: station_base.h:273
byte vehstatus
Status.
Definition: vehicle_base.h:317
uint32 max_loan
the maximum initial loan
Definition: settings_type.h:59
Types related to cargoes...
Year _cur_year
Current year, starting at 0.
Definition: date.cpp:26
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:1538
uint StoredCount() const
Returns sum of cargo on board the vehicle (ie not only reserved).
Definition: cargopacket.h:366
bool improved_load
improved loading algorithm
uint Return(uint max_move, StationCargoList *dest, StationID next_station)
Returns reserved cargo to the station and removes it from the cache.
bool infrastructure_maintenance
enable monthly maintenance fee for owner infrastructure
static Aircraft * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
Tstorage new_act
Actually transported this month.
Definition: town_type.h:116
static const int MIN_PRICE_MODIFIER
Maximum NewGRF price modifiers.
Definition: economy_type.h:209
uint16 cached_max_speed
Maximum speed of the consist (minimum of the max speed of all vehicles in the consist).
Definition: vehicle_base.h:123
CompanySettings settings
settings specific for each company
Definition: company_base.h:126
const T * End() const
Get the pointer behind the last valid item (const)
Trigger platform when train loads/unloads.
Generates sequence of free UnitID numbers.
const Engine * GetEngine() const
Retrieves the engine of the vehicle.
Definition: vehicle.cpp:744
uint Load(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next)
Loads cargo onto a vehicle.
void DeleteCompanyWindows(CompanyID company)
Delete all windows of a company.
Definition: window.cpp:1181
bool IsNormalAircraft() const
Check if the aircraft type is a normal flying device; eg not a rotor or a shadow. ...
Definition: aircraft.h:123
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
GoodsEntry goods[NUM_CARGO]
Goods at this station.
Definition: station_base.h:472
uint32 industry_daily_increment
The value which will increment industry_daily_change_counter. Computed value. NOSAVE.
Definition: economy_type.h:28
bool operator()(const Vehicle *v)
Checks if the vehicle has stored cargo.
Definition: economy.cpp:1369
Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift)
Determine a certain price.
Definition: economy.cpp:966
CargoArray & consist_capleft
Capacities left in the consist.
Definition: economy.cpp:1437
void AddCost(const Money &cost)
Adds the given cost to the cost of the command.
Definition: command_type.h:64
static T SB(T &x, const uint8 s, const uint8 n, const U d)
Set n bits in x starting at bit s to d.
bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoID cargo_type)
Check whether an industry temporarily refuses to accept a certain cargo.
uint32 GetGRFID() const
Retrieve the GRF ID of the NewGRF the engine is tied to.
Definition: engine.cpp:162
uint16 servint_ships
service interval for ships
Money profit_last_year
Profit last year << 8, low 8 bits are fract.
Definition: vehicle_base.h:240
CargoID ct
The currently handled cargo type.
Definition: economy_base.h:35
void InitializeEconomy()
Resets economy to initial values.
Definition: economy.cpp:951
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:23
CompanyByte _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
company bankrupts, skip money check, skip vehicle on tile check in some cases
Definition: command_type.h:351
bool allow_shares
allow the buying/selling of shares
char company_name[64]
The name of the company.
Definition: news_type.h:151
uint16 multiplier
Capacity multiplier for vehicles. (8 fractional bits)
Definition: cargotype.h:62
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition: newgrf.h:139
Income graph; Window numbers:
Definition: window_type.h:524
Money expenses
The amount of expenses.
Definition: company_base.h:25
static const size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:87
SourceID SourceSubsidyID() const
Gets the ID of the cargo&#39;s source.
Definition: cargopacket.h:151
TextEffectID fill_percent_te_id
a text-effect id to a loading indicator object
Definition: vehicle_base.h:290
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:3319
TrackBits
Bitfield corresponding to Track.
Definition: track_type.h:41
TextEffectID ShowFillingPercent(int x, int y, int z, uint8 percent, StringID string)
Display vehicle loading indicators.
Definition: misc_gui.cpp:601
uint16 cargo_cap
total capacity
Definition: vehicle_base.h:307
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
Definition: economy.cpp:907
static bool IsTileOwner(TileIndex tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:216
void SetDParamStr(uint n, const char *str)
This function is used to "bind" a C string to a OpenTTD dparam slot.
Definition: strings.cpp:282
Aircraft vehicle type.
Definition: vehicle_type.h:29
Struct about stories, current and completed.
Definition: story_base.h:70
Some methods of Pool are placed here in order to reduce compilation time and binary size...
Vehicle is crashed.
Definition: vehicle_base.h:39
uint32 signal
Count of company owned signals.
Definition: company_base.h:33
virtual bool IsPrimaryVehicle() const
Whether this is the primary vehicle in the chain.
Definition: vehicle_base.h:433
static bool IsTileType(TileIndex tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:152
Triggered when a cargo type is completely removed from the station (for all tiles at the same time)...
How many scores are there..
Definition: economy_type.h:50
bool MayCompanyTakeOver(CompanyID cbig, CompanyID csmall)
May company cbig buy company csmall?
byte num_valid_stat_ent
Number of valid statistical entries in old_economy.
Definition: company_base.h:97
static void LoadUnloadVehicle(Vehicle *front)
Loads/unload the vehicle if possible.
Definition: economy.cpp:1618
UnitID unitnumber
unit number, for display purposes only
Definition: vehicle_base.h:291
CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags)
Shorthand for calling the long DoCommand with a container.
Definition: command.cpp:440
This indicates whether a cargo has a rating at the station.
Definition: station_base.h:187
uint Length() const
Get the number of items in the list.
byte DaysInTransit() const
Gets the number of days this cargo has been in transit.
Definition: cargopacket.h:133
Vehicle * front
The front vehicle to do the payment of.
Definition: economy_base.h:27
bool IsRefit() const
Is this order a refit order.
Definition: order_base.h:110
Price is affected by "construction cost" difficulty setting.
Definition: economy_type.h:178
int16 ratings[MAX_COMPANIES]
ratings of each company for this town
Definition: town.h:77
VehicleDefaultSettings vehicle
default settings for vehicles
GroundVehicleCache * GetGroundVehicleCache()
Access the ground vehicle cache of the vehicle.
Definition: vehicle.cpp:2826
CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Buy up another company.
Definition: economy.cpp:2115
Do not load anything.
Definition: order_type.h:72
Don&#39;t load anymore during the next load cycle.
Definition: vehicle_base.h:50
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:63
DoCommandFlag
List of flags for a command.
Definition: command_type.h:343
Money current_loan
Amount of money borrowed from the bank.
Definition: company_base.h:66
Money PayTransfer(const CargoPacket *cp, uint count)
Handle payment for transfer of the given cargo packet.
Definition: economy.cpp:1240
byte callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:143
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:76
bool operator()(const Vehicle *v)
Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and adding th...
Definition: economy.cpp:1397
byte status
Status of this cargo, see GoodsEntryStatus.
Definition: station_base.h:226
Money visual_profit
The visual profit to show.
Definition: economy_base.h:29
void UpdateCompanyHQ(TileIndex tile, uint score)
Update the CompanyHQ to the state associated with the given score.
Definition: object_cmd.cpp:157
Money AirportMaintenanceCost(Owner owner)
Calculates the maintenance cost of all airports of a company.
Definition: station.cpp:555
bool Succeeded() const
Did this command succeed?
Definition: command_type.h:152
Container for cargo from the same location and time.
Definition: cargopacket.h:44
void PrepareUnload(Vehicle *front_v)
Prepare the vehicle to be unloaded.
Definition: economy.cpp:1259
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
TileIndex location_of_HQ
Northern tile of HQ; INVALID_TILE when there is none.
Definition: company_base.h:72
Definition of base types and functions in a cross-platform compatible way.
virtual ExpensesType GetExpenseType(bool income) const
Sets the expense type associated to this vehicle type.
Definition: vehicle_base.h:423
void NetworkClientsToSpectators(CompanyID cid)
Move the clients of a company to the spectators.
uint32 road[ROADTYPE_END]
Count of company owned track bits for each road type.
Definition: company_base.h:32
A number of safeguards to prevent using unsafe methods.
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
static void Run(Vehicle *v, bool allow_merge=true, bool is_full_loading=false)
Refresh all links the given vehicle will visit.
Definition: refresh.cpp:28
IndustryType type
type of industry.
Definition: industry.h:57
Base of waypoints.
void PayFinalDelivery(const CargoPacket *cp, uint count)
Handle payment for final delivery of the given cargo packet.
Definition: economy.cpp:1220
bool inflation
disable inflation
static uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:316
int score
How much score it will give.
Definition: economy_type.h:60
uint8 callback_mask
Bitmask of cargo callbacks that have to be called.
Definition: cargotype.h:69
Money route_profit
The amount of money to add/remove from the bank account.
Definition: economy_base.h:28
Station * st
Station to reserve cargo from.
Definition: economy.cpp:1438
Operating profit graph; Window numbers:
Definition: window_type.h:530
Company league window; Window numbers:
Definition: window_type.h:554
CargoID cargo_type
type of cargo this vehicle is carrying
Definition: vehicle_base.h:305
CargoPayment()
Constructor for pool saveload.
Definition: economy_base.h:38
GUI Functions related to companies.
Trigger when cargo is received .
uint16 load_unload_ticks
Ticks to wait before starting next cycle.
Definition: vehicle_base.h:325
Normal news item. (Newspaper with text only)
Definition: news_type.h:80
CompanyByte awarded
Subsidy is awarded to this company; INVALID_COMPANY if it&#39;s not awarded to anyone.
Definition: subsidy_base.h:27
Money CalculateCompanyValue(const Company *c, bool including_loan)
Calculate the value of the company.
Definition: economy.cpp:113
byte misc_flags
Miscellaneous flags.
Definition: engine_type.h:142
byte vehicle_costs
amount of money spent on vehicle running cost
Definition: settings_type.h:61
TileIndex tile
Current tile index.
Definition: vehicle_base.h:230
Road vehicle list; Window numbers:
Definition: window_type.h:309
Defines the data structure for constructing industry.
Definition: industrytype.h:103
void ClearCargoPickupMonitoring(CompanyID company)
Clear all pick-up cargo monitors.
static void CountVehicle(const Vehicle *v, int delta)
Update num_vehicle when adding or removing a vehicle.
Definition: group_cmd.cpp:138
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
Definition: company_base.h:92
The tile has no ownership.
Definition: company_type.h:27
bool HasArticulatedPart() const
Check if an engine has an articulated part.
Definition: vehicle_base.h:901
Money money
Money owned by the company.
Definition: company_base.h:64
Station view; Window numbers:
Definition: window_type.h:340
OrderLoadFlags GetLoadType() const
How must the consist be loaded?
Definition: order_base.h:129
Basic functions/variables used all over the place.
bool IsRearDualheaded() const
Tell if we are dealing with the rear end of a multiheaded engine.
CargoID accepts_cargo[INDUSTRY_NUM_INPUTS]
16 input cargo slots
Definition: industry.h:49
StationFacilityByte facilities
The facilities that this station has.
bool DoCommandP(const CommandContainer *container, bool my_cmd)
Shortcut for the long DoCommandP when having a container with the data.
Definition: command.cpp:531
Industry view; Window numbers:
Definition: window_type.h:358
uint16 incoming_cargo_waiting[INDUSTRY_NUM_INPUTS]
incoming cargo waiting to be processed
Definition: industry.h:46
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:42
byte last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
Definition: station_base.h:246
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:1570
Road vehicle type.
Definition: vehicle_type.h:27
CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
Sell shares in an opposing company.
Definition: economy.cpp:2074
SourceType SourceSubsidyType() const
Gets the type of the cargo&#39;s source.
Definition: cargopacket.h:142
uint Reserve(uint max_move, VehicleCargoList *dest, TileIndex load_place, StationIDStack next)
Reserves cargo for loading onto the vehicle.
static T min(const T a, const T b)
Returns the minimum of two values.
Definition: math_func.hpp:42
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:500
static bool EconomyIsInRecession()
Is the economy in recession?
Definition: economy_func.h:49
Helper class to perform the cargo payment.
Definition: economy_base.h:26
Deliver the cargo to some town or industry.
Definition: cargopacket.h:230
static bool IsCargoInClass(CargoID c, CargoClass cc)
Does cargo c have cargo class cc?
Definition: cargotype.h:150
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:552
Functions related to sound.
static void RemoveAllEngineReplacementForCompany(Company *c)
Remove all engine replacement settings for the given company.
void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
Change the ownership of all the items of a company.
Definition: economy.cpp:289
static const Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: date_type.h:51
uint32 StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:18
Money max_loan
NOSAVE: Maximum possible loan.
Definition: economy_type.h:22
Vehicle * First() const
Get the first vehicle of this vehicle chain.
Definition: vehicle_base.h:594
void CompanyAdminUpdate(const Company *company)
Called whenever company related information changes in order to notify admins.
NewGRF handling of industry tiles.
Delete a company.
Definition: company_type.h:71
The max score that can be in the performance history.
Definition: economy_type.h:52
Data of the economy.
Definition: economy_type.h:21
byte last_age
Age in years (up to 255) of the last vehicle that tried to load this cargo.
Definition: station_base.h:252
CompanyByte company
StoryPage is for a specific company; INVALID_COMPANY if it is global.
Definition: story_base.h:73
Action for finalizing a refit.
Definition: economy.cpp:1435
void UpdateLevelCrossing(TileIndex tile, bool sound=true)
Sets correct crossing state.
Definition: train_cmd.cpp:1679
static void Stop(CompanyID company)
Stop a company to be controlled by an AI.
Definition: ai_core.cpp:105
Maximum number of companies.
Definition: company_type.h:25
void ClearCargoDeliveryMonitoring(CompanyID company)
Clear all delivery cargo monitors.
ReturnCargoAction(Station *st, StationID next_one)
Construct a cargo return action.
Definition: economy.cpp:1418
int16 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:81
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:1345
Year build_year
Year the vehicle has been built.
Definition: vehicle_base.h:257
bool PlayVehicleSound(const Vehicle *v, VehicleSoundEvent event)
Checks whether a NewGRF wants to play a different vehicle sound effect.
Transfer all cargo onto the platform.
Definition: order_type.h:61
NewGRF handling of airport tiles.
#define return_cmd_error(errcode)
Returns from a function with a specific StringID as error.
Definition: command_func.h:35
StationID next_hop
Next hop the cargo should be assigned to.
Definition: economy.cpp:1411
Base class for all pools.
Definition: pool_type.hpp:83
Station list; Window numbers:
Definition: window_type.h:297
Ship vehicle type.
Definition: vehicle_type.h:28
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:139
static bool HasSignals(TileIndex t)
Checks if a rail tile has signals.
Definition: rail_map.h:73
OrderUnloadFlags GetUnloadType() const
How must the consist be unloaded?
Definition: order_base.h:131
Struct about subsidies, offered and awarded.
Definition: subsidy_base.h:24
&#39;Train&#39; is either a loco or a wagon.
Definition: train.h:88
SourceType
Types of cargo source and destination.
Definition: cargo_type.h:148
Performance detail window; Window numbers:
Definition: window_type.h:566
bool IsEngineCountable() const
Check if a vehicle is counted in num_engines in each company struct.
Definition: vehicle.cpp:711
void UpdateFillingPercent(TextEffectID te_id, uint8 percent, StringID string)
Update vehicle loading indicators.
Definition: misc_gui.cpp:616
Month _cur_month
Current month (0..11)
Definition: date.cpp:27
OwnerByte owner
The owner of this station.
static TrackBits GetTrackBits(TileIndex tile)
Gets the track bits of the given tile.
Definition: rail_map.h:137
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don&#39;t get linker errors.
Definition: pool_func.hpp:226
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
Definition: company_base.h:130
uint32 rail[RAILTYPE_END]
Count of company owned track bits for each rail type.
Definition: company_base.h:34
union Vehicle::@47 orders
The orders currently assigned to the vehicle.
CargoTypes & refit_mask
Bitmask of possible refit cargoes.
Definition: economy.cpp:1381
static void TriggerIndustryProduction(Industry *i)
Inform the industry about just delivered cargo DeliverGoodsToIndustry() silently incremented incoming...
Definition: economy.cpp:1147
execute the given command
Definition: command_type.h:345
Company infrastructure overview; Window numbers:
Definition: window_type.h:572
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition: pool_type.hpp:225
Set when a vehicle ever delivered cargo to the station for final delivery.
Definition: station_base.h:193
static uint GetLoadAmount(Vehicle *v)
Gets the amount of cargo the given vehicle can load in the current tick.
Definition: economy.cpp:1300
Price Bases.
Functions related to companies.
void TriggerIndustry(Industry *ind, IndustryTileTrigger trigger)
Trigger a random trigger for all industry tiles.
TileIndex LoadedAtXY() const
Gets the coordinates of the cargo&#39;s last loading station.
Definition: cargopacket.h:178
static StationID GetStationIndex(TileIndex t)
Get StationID from a tile.
Definition: station_map.h:29
void SetCargo(CargoID ct)
Sets the currently handled cargo type.
Definition: economy_base.h:49
uint16 GetTimetabledWait() const
Get the time in ticks a vehicle should wait at the destination or 0 if it&#39;s not timetabled.
Definition: order_base.h:181
static uint MapSize()
Get the size of the map.
Definition: map_func.h:94
TownEffect town_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies...
Definition: cargotype.h:67
void ErrorUnknownCallbackResult(uint32 grfid, uint16 cbid, uint16 cb_res)
Record that a NewGRF returned an unknown/invalid callback result.
Class for storing amounts of cargo.
Definition: cargo_type.h:83
Determine the amount of cargo to load per unit of time when using gradual loading.
Used for iterations.
Definition: road_type.h:23
Base class for engines.
static const uint MAX_HISTORY_QUARTERS
The maximum number of quarters kept as performance&#39;s history.
Definition: company_type.h:44
Header file for NewGRF stations.
static void CompanyCheckBankrupt(Company *c)
Check for bankruptcy of a company.
Definition: economy.cpp:571
static T ClrBit(T &x, const uint8 y)
Clears a bit in a variable.
void CompaniesMonthlyLoop()
Monthly update of the economic data (of the companies as well as economic fluctuations).
Definition: economy.cpp:1966
uint16 produced_cargo_waiting[INDUSTRY_NUM_OUTPUTS]
amount of cargo produced per cargo
Definition: industry.h:45
GUISettings gui
settings related to the GUI
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:140
Subsidy base class.
CompanyByte company
Goal is for a specific company; INVALID_COMPANY if it is global.
Definition: goal_base.h:24
static Track RemoveFirstTrack(TrackBits *tracks)
Removes first Track from TrackBits and returns it.
Definition: track_func.h:141
void RecomputePrices()
Computes all prices, payments and maximum loan.
Definition: economy.cpp:768
Whenever cargo payment is made for a vehicle.
Definition: newgrf_sound.h:29
static Money StationMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of station tiles.
Definition: station_func.h:61
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:118
Action to check if a vehicle has no stored cargo.
Definition: economy.cpp:1362
bool gradual_loading
load vehicles gradually
CompanyByte _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
static SmallIndustryList _cargo_delivery_destinations
The industries we&#39;ve currently brought cargo to.
Definition: economy.cpp:1031
Ships list; Window numbers:
Definition: window_type.h:315
uint32 TileIndex
The index/ID of a Tile.
Definition: tile_type.h:80
Functions related to objects.
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:159
Cargo support for NewGRFs.
OwnerByte share_owners[4]
Owners of the 4 shares of the company. INVALID_OWNER if nobody has bought them yet.
Definition: company_base.h:75
uint16 servint_trains
service interval for trains
static const uint64 MAX_INFLATION
Maximum inflation (including fractional part) without causing overflows in int64 price computations...
Definition: economy_type.h:202
void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceType reftype1=NR_NONE, uint32 ref1=UINT32_MAX, NewsReferenceType reftype2=NR_NONE, uint32 ref2=UINT32_MAX, void *free_data=NULL)
Add a new newsitem to be shown.
Definition: news_gui.cpp:659
Vehicle * Next() const
Get the next vehicle of this vehicle.
Definition: vehicle_base.h:581
sell a share from a company
Definition: command_type.h:258
The company went belly-up.
Definition: company_type.h:62
CargoPayment * cargo_payment
The cargo payment we&#39;re currently in.
Definition: vehicle_base.h:243
static bool IsLevelCrossingTile(TileIndex t)
Return whether a tile is a level crossing tile.
Definition: road_map.h:78
OrderSettings order
settings related to orders
CargoArray delivered_cargo
The amount of delivered cargo.
Definition: company_base.h:26
Source/destination is an industry.
Definition: cargo_type.h:149
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:153
uint16 SourceID
Contains either industry ID, town ID or company ID (or INVALID_SOURCE)
Definition: cargo_type.h:155
Cargo transport monitoring declarations.
bool servint_ispercent
service intervals are in percents
void AddCargoDelivery(CargoID cargo_type, CompanyID company, uint32 amount, SourceType src_type, SourceID src, const Station *st, IndustryID dest)
Cargo was delivered to its final destination, update the pickup and delivery maps.
Property costs.
Definition: economy_type.h:157
OwnerByte owner
Which company owns the vehicle?
Definition: vehicle_base.h:273
StationIDStack GetNextStoppingStation() const
Get the next station the vehicle will stop at.
Definition: vehicle_base.h:699
UnitID NextID()
Returns next free UnitID.
Definition: vehicle.cpp:1713
TileIndex xy
Base tile of the station.
Trigger platform when train loads/unloads.
static void UpdateAutoreplace(CompanyID company)
Update autoreplace_defined and autoreplace_finished of all statistics of a company.
Definition: group_cmd.cpp:212
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
Definition: subsidy.cpp:133
static uint GB(const T x, const uint8 s, const uint8 n)
Fetch n bits from x, started at bit s.
uint16 cached_total_length
Length of the whole vehicle (valid only for the first engine).
Trains list; Window numbers:
Definition: window_type.h:303
CompanyEconomyEntry old_economy[MAX_HISTORY_QUARTERS]
Economic data of the company of the last MAX_HISTORY_QUARTERS quarters.
Definition: company_base.h:96
Full load all cargoes of the consist.
Definition: order_type.h:70
void SubtractMoneyFromCompany(CommandCost cost)
Subtract money from the _current_company, if the company is valid.
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
Definition: economy.cpp:895
A tile of a station.
Definition: tile_type.h:48
Goal base class.
PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask)
Create a refit preparation action.
Definition: economy.cpp:1388
bool Include(const T &item)
Tests whether a item is present in the vector, and appends it to the end if not.
call production callback when cargo arrives at the industry
Town data structure.
Definition: town.h:55
uint32 industry_daily_change_counter
Bits 31-16 are number of industry to be performed, 15-0 are fractional collected daily.
Definition: economy_type.h:27
int16 fluct
Economy fluctuation status.
Definition: economy_type.h:23
uint8 loading_indicators
show loading indicators
uint64 inflation_payment
Cumulated inflation of cargo paypent since game start; 16 bit fractional part.
Definition: economy_type.h:30
uint16 servint_aircraft
service interval for aircraft
Group data.
Definition: group.h:67
uint8 exclusive_counter
months till the exclusivity expires
Definition: town.h:76
Totally no unloading will be done.
Definition: order_type.h:62
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function() ...
Definition: pool_type.hpp:216
static Money CanalMaintenanceCost(uint32 num)
Calculates the maintenance cost of a number of canal tiles.
Definition: water.h:52
Aircraft list; Window numbers:
Definition: window_type.h:321
int32 z_pos
z coordinate.
Definition: vehicle_base.h:270
Vehicle details; Window numbers:
Definition: window_type.h:195
static uint CountBits(T value)
Counts the number of set bits in a variable.
Base functions for all Games.
Functions related to commands.
Network functions used by other parts of OpenTTD.
bool _network_server
network-server is active
Definition: network.cpp:57
CargoPaymentPool _cargo_payment_pool("CargoPayment")
The actual pool to store cargo payments in.
uint8 CalcPercentVehicleFilled(const Vehicle *front, StringID *colour)
Calculates how full a vehicle is.
Definition: vehicle.cpp:1378
bool HasCargoFor(StationIDStack next) const
Check for cargo headed for a specific station.
Definition: cargopacket.h:499
static void CountEngine(const Vehicle *v, int delta)
Update num_engines when adding/removing an engine.
Definition: group_cmd.cpp:161
Base classes related to the economy.
uint ReservedCount() const
Returns sum of reserved cargo.
Definition: cargopacket.h:384
static WindowClass GetWindowClassForVehicleType(VehicleType vt)
Get WindowClass for vehicle list of given vehicle type.
Definition: vehicle_gui.h:85
void StartupIndustryDailyChanges(bool init_counter)
Initialize the variables that will maintain the daily industry change system.
Definition: economy.cpp:917
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
Evaluate a newgrf callback for vehicles.
StoryPage base class.
Delivered cargo graph; Window numbers:
Definition: window_type.h:536
ScoreID
Score categories in the detailed performance rating.
Definition: economy_type.h:38
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:1207
Base of all industries.
bool economy
how volatile is the economy
Definition: settings_type.h:68
void ShowFeederIncomeAnimation(int x, int y, int z, Money transfer, Money income)
Display animated feeder income.
Definition: misc_gui.cpp:574
Price is affected by "vehicle running cost" difficulty setting.
Definition: economy_type.h:177
Statistics about the economy.
Definition: company_base.h:23
EngineID engine_type
The type of engine used for this vehicle.
Definition: vehicle_base.h:288
OwnerByte owner
Group Owner.
Definition: group.h:69
Passengers.
Definition: cargotype.h:40
int32 x_pos
x coordinate.
Definition: vehicle_base.h:268
byte initial_interest
amount of interest (to pay over the loan)
Definition: settings_type.h:60
uint16 vehicle_flags
Used for gradual loading and other miscellaneous things (.
Definition: base_consist.h:32
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
bool IsValid() const
Tests for validity of this cargospec.
Definition: cargotype.h:99
Functions related to NewGRF provided sounds.
void Restore()
Restore the variable.
Base functions for all AIs.
#define FOR_ALL_VEHICLES(var)
Iterate over all vehicles.
Definition: vehicle_base.h:987
Base of the town class.
Data structure for storing how the score is computed for a single score id.
Definition: economy_type.h:58
bool AddInflation(bool check_year)
Add monthly inflation.
Definition: economy.cpp:730
Used for iterations.
Definition: rail_type.h:30
int needed
How much you need to get the perfect score.
Definition: economy_type.h:59
GameCreationSettings game_creation
settings used during the creation of a game (map)
uint AvailableCount() const
Returns sum of cargo still available for loading at the sation.
Definition: cargopacket.h:522
uint16 servint_roadveh
service interval for road vehicles
byte CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
Money income
The amount of income.
Definition: company_base.h:24
int32 y_pos
y coordinate.
Definition: vehicle_base.h:269
Other expenses.
Definition: economy_type.h:163
Owner
Enum for all companies/owners.
Definition: company_type.h:20
static void CompaniesPayInterest()
Let all companies pay the monthly interest on their loan.
Definition: economy.cpp:836
Money company_value
The value of the company.
Definition: company_base.h:28
byte time_since_pickup
Number of rating-intervals (up to 255) since the last vehicle tried to load this cargo.
Definition: station_base.h:233
Functions related to water (management)
void ShowCostOrIncomeAnimation(int x, int y, int z, Money cost)
Display animated income or costs on the map.
Definition: misc_gui.cpp:553
Force unloading all cargo onto the platform, possibly not getting paid.
Definition: order_type.h:60
Money profit_this_year
Profit this year << 8, low 8 bits are fract.
Definition: vehicle_base.h:239
CompanyEconomyEntry cur_economy
Economic data of the company of this quarter.
Definition: company_base.h:95
Use the new capacity algorithm. The default cargotype of the vehicle does not affect capacity multipl...
Definition: engine_type.h:159
static Money RailMaintenanceCost(RailType railtype, uint32 num, uint32 total_num)
Calculates the maintenance cost of a number of track bits.
Definition: rail.h:401
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting)
Definition: window.cpp:3229
Trigger station when cargo is completely taken.
Functions related to news.
Base classes/functions for stations.
call production callback every 256 ticks
CargoArray & consist_capleft
Capacities left in the consist.
Definition: economy.cpp:1380
VehicleCache vcache
Cache of often used vehicle values.
Definition: vehicle_base.h:330
static Station * Get(size_t index)
Gets station with given index.
Date _date
Current date in days (day counter)
Definition: date.cpp:28
uint GetPlatformLength(TileIndex tile, DiagDirection dir) const
Determines the REMAINING length of a platform, starting at (and including) the given tile...
Definition: station.cpp:249
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:1043
Functions related to autoreplacing.
StationID current_station
The current station.
Definition: economy_base.h:34
Company view; Window numbers:
Definition: window_type.h:364
An invalid company.
Definition: company_type.h:32
Date age
Age in days.
Definition: vehicle_base.h:258
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:1477
byte construction_cost
how expensive is building
Definition: settings_type.h:65
Full load a single cargo of the consist.
Definition: order_type.h:71
uint8 feeder_payment_share
percentage of leg payment to virtually pay in feeder systems
static bool IsCompanyBuildableVehicleType(VehicleType type)
Is the given vehicle type buildable by a company?
Definition: vehicle_func.h:91
VehicleTypeByte type
Type of vehicle.
Definition: vehicle_type.h:56
Year starting_year
starting date
Base class and functions for all vehicles that move through ground.
Class for backupping variables and making sure they are restored later.
Station data structure.
Definition: station_base.h:446
No track.
Definition: track_type.h:42
char other_company_name[64]
The name of the company taking over this one.
Definition: news_type.h:153
Functions related to subsidies.
void InvalidateNewGRFCache()
Invalidates cached NewGRF variables.
Definition: vehicle_base.h:451
static Money RoadMaintenanceCost(RoadType roadtype, uint32 num)
Calculates the maintenance cost of a number of road bits.
Definition: road_func.h:172
Set when the station accepts the cargo currently for final deliveries.
Definition: station_base.h:177
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:318
bool do_reserve
If the vehicle should reserve.
Definition: economy.cpp:1440
const T GetSum() const
Get the sum of all cargo amounts.
Definition: cargo_type.h:123
Performance history graph; Window numbers:
Definition: window_type.h:542
#define FOR_ALL_WAYPOINTS(var)
Iterate over all waypoints.
Definition: waypoint_base.h:74
An invalid owner.
Definition: company_type.h:31
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:3301
CompanyMask have_ratings
which companies have a rating
Definition: town.h:73
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1463
CargoID GetRefitCargo() const
Get the cargo to to refit to.
Definition: order_base.h:124
bool operator()(Vehicle *v)
Return all reserved cargo from a vehicle.
Definition: economy.cpp:1425
SpriteID colourmap
NOSAVE: cached colour mapping.
Definition: vehicle_base.h:254
Economic changes (recession, industry up/dowm)
Definition: news_type.h:30
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:104
Base class for signs.
Train vehicle type.
Definition: vehicle_type.h:26
static void SetDParam(uint n, uint64 v)
Set a string parameter v at index n in the global string parameter array.
Definition: strings_func.h:201
CargoTypes always_accepted
Bitmask of always accepted cargo types (by houses, HQs, industry tiles when industry doesn&#39;t accept c...
Definition: station_base.h:473
Interest payments over the loan.
Definition: economy_type.h:162
uint32 water
Count of company owned track bits for canals.
Definition: company_base.h:35
Money visual_transfer
The transfer credits to be shown.
Definition: economy_base.h:30