OpenTTD Source  20241120-master-g6d3adc6169
afterload.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "../stdafx.h"
11 #include "../void_map.h"
12 #include "../signs_base.h"
13 #include "../depot_base.h"
14 #include "../fios.h"
15 #include "../gamelog_internal.h"
16 #include "../network/network.h"
17 #include "../network/network_func.h"
18 #include "../gfxinit.h"
19 #include "../viewport_func.h"
20 #include "../viewport_kdtree.h"
21 #include "../industry.h"
22 #include "../clear_map.h"
23 #include "../vehicle_func.h"
24 #include "../string_func.h"
25 #include "../roadveh.h"
26 #include "../roadveh_cmd.h"
27 #include "../train.h"
28 #include "../station_base.h"
29 #include "../waypoint_base.h"
30 #include "../roadstop_base.h"
31 #include "../tunnelbridge_map.h"
32 #include "../pathfinder/yapf/yapf_cache.h"
33 #include "../elrail_func.h"
34 #include "../signs_func.h"
35 #include "../aircraft.h"
36 #include "../object_map.h"
37 #include "../object_base.h"
38 #include "../tree_map.h"
39 #include "../company_func.h"
40 #include "../road_cmd.h"
41 #include "../ai/ai.hpp"
42 #include "../script/script_gui.h"
43 #include "../game/game.hpp"
44 #include "../town.h"
45 #include "../economy_base.h"
46 #include "../animated_tile_func.h"
47 #include "../subsidy_base.h"
48 #include "../subsidy_func.h"
49 #include "../newgrf.h"
50 #include "../newgrf_station.h"
51 #include "../engine_func.h"
52 #include "../rail_gui.h"
53 #include "../core/backup_type.hpp"
54 #include "../smallmap_gui.h"
55 #include "../news_func.h"
56 #include "../order_backup.h"
57 #include "../error.h"
58 #include "../disaster_vehicle.h"
59 #include "../ship.h"
60 #include "../water.h"
61 #include "../timer/timer.h"
62 #include "../timer/timer_game_calendar.h"
63 #include "../timer/timer_game_economy.h"
64 #include "../timer/timer_game_tick.h"
65 
66 #include "saveload_internal.h"
67 
68 #include <signal.h>
69 
70 #include "../safeguards.h"
71 #include "window_func.h"
72 
73 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
74 
85 void SetWaterClassDependingOnSurroundings(Tile t, bool include_invalid_water_class)
86 {
87  /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
88  * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
89  if (!IsTileFlat(t)) {
90  if (include_invalid_water_class) {
92  return;
93  } else {
94  SlErrorCorrupt("Invalid water class for dry tile");
95  }
96  }
97 
98  /* Mark tile dirty in all cases */
100 
101  if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == Map::MaxX() - 1 || TileY(t) == Map::MaxY() - 1) {
102  /* tiles at map borders are always WATER_CLASS_SEA */
104  return;
105  }
106 
107  bool has_water = false;
108  bool has_canal = false;
109  bool has_river = false;
110 
111  for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
112  Tile neighbour = TileAddByDiagDir(t, dir);
113  switch (GetTileType(neighbour)) {
114  case MP_WATER:
115  /* clear water and shipdepots have already a WaterClass associated */
116  if (IsCoast(neighbour)) {
117  has_water = true;
118  } else if (!IsLock(neighbour)) {
119  switch (GetWaterClass(neighbour)) {
120  case WATER_CLASS_SEA: has_water = true; break;
121  case WATER_CLASS_CANAL: has_canal = true; break;
122  case WATER_CLASS_RIVER: has_river = true; break;
123  default: SlErrorCorrupt("Invalid water class for tile");
124  }
125  }
126  break;
127 
128  case MP_RAILWAY:
129  /* Shore or flooded halftile */
130  has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
131  break;
132 
133  case MP_TREES:
134  /* trees on shore */
135  has_water |= (GB(neighbour.m2(), 4, 2) == TREE_GROUND_SHORE);
136  break;
137 
138  default: break;
139  }
140  }
141 
142  if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
144  return;
145  }
146 
147  if (has_river && !has_canal) {
149  } else if (has_canal || !has_water) {
151  } else {
153  }
154 }
155 
156 static void ConvertTownOwner()
157 {
158  for (auto tile : Map::Iterate()) {
159  switch (GetTileType(tile)) {
160  case MP_ROAD:
161  if (GB(tile.m5(), 4, 2) == ROAD_TILE_CROSSING && HasBit(tile.m3(), 7)) {
162  tile.m3() = OWNER_TOWN;
163  }
164  [[fallthrough]];
165 
166  case MP_TUNNELBRIDGE:
167  if (tile.m1() & 0x80) SetTileOwner(tile, OWNER_TOWN);
168  break;
169 
170  default: break;
171  }
172  }
173 }
174 
175 /* since savegame version 4.1, exclusive transport rights are stored at towns */
176 static void UpdateExclusiveRights()
177 {
178  for (Town *t : Town::Iterate()) {
179  t->exclusivity = INVALID_COMPANY;
180  }
181 
182  /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
183  * could be implemented this way:
184  * 1.) Go through all stations
185  * Build an array town_blocked[ town_id ][ company_id ]
186  * that stores if at least one station in that town is blocked for a company
187  * 2.) Go through that array, if you find a town that is not blocked for
188  * one company, but for all others, then give it exclusivity.
189  */
190 }
191 
192 static const uint8_t convert_currency[] = {
193  0, 1, 12, 8, 3,
194  10, 14, 19, 4, 5,
195  9, 11, 13, 6, 17,
196  16, 22, 21, 7, 15,
197  18, 2, 20,
198 };
199 
200 /* since savegame version 4.2 the currencies are arranged differently */
201 static void UpdateCurrencies()
202 {
204 }
205 
206 /* Up to revision 1413 the invisible tiles at the southern border have not been
207  * MP_VOID, even though they should have. This is fixed by this function
208  */
209 static void UpdateVoidTiles()
210 {
211  for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, Map::MaxY()));
212  for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(Map::MaxX(), y));
213 }
214 
215 static inline RailType UpdateRailType(RailType rt, RailType min)
216 {
217  return rt >= min ? (RailType)(rt + 1): rt;
218 }
219 
224 {
228  UpdateAllTextEffectVirtCoords();
229  RebuildViewportKdtree();
230 }
231 
232 void ClearAllCachedNames()
233 {
234  ClearAllStationCachedNames();
236  ClearAllIndustryCachedNames();
237 }
238 
249 {
250  /* Initialize windows */
253 
254  /* Update coordinates of the signs. */
255  ClearAllCachedNames();
257  ResetViewportAfterLoadGame();
258 
259  for (Company *c : Company::Iterate()) {
260  /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
261  * accordingly if it is not the case. No need to set it on companies that are not been used already,
262  * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
263  if (_file_to_saveload.abstract_ftype == FT_SCENARIO && c->inaugurated_year != EconomyTime::MIN_YEAR) {
264  c->inaugurated_year = TimerGameEconomy::year;
265  }
266  }
267 
268  /* Count number of objects per type */
269  for (Object *o : Object::Iterate()) {
270  Object::IncTypeCount(o->type);
271  }
272 
273  /* Identify owners of persistent storage arrays */
274  for (Industry *i : Industry::Iterate()) {
275  if (i->psa != nullptr) {
276  i->psa->feature = GSF_INDUSTRIES;
277  i->psa->tile = i->location.tile;
278  }
279  }
280  for (Station *s : Station::Iterate()) {
281  if (s->airport.psa != nullptr) {
282  s->airport.psa->feature = GSF_AIRPORTS;
283  s->airport.psa->tile = s->airport.tile;
284  }
285  }
286  for (Town *t : Town::Iterate()) {
287  for (auto &it : t->psa_list) {
288  it->feature = GSF_FAKE_TOWNS;
289  it->tile = t->xy;
290  }
291  }
292  for (RoadVehicle *rv : RoadVehicle::Iterate()) {
293  if (rv->IsFrontEngine()) {
294  rv->CargoChanged();
295  }
296  }
297 
298  RecomputePrices();
299 
301 
303 
304  /* Towns have a noise controlled number of airports system
305  * So each airport's noise value must be added to the town->noise_reached value
306  * Reset each town's noise_reached value to '0' before. */
308 
310  ShowNewGRFError();
311 
312  /* Rebuild the smallmap list of owners. */
314 }
315 
316 typedef void (CDECL *SignalHandlerPointer)(int);
317 static SignalHandlerPointer _prev_segfault = nullptr;
318 static SignalHandlerPointer _prev_abort = nullptr;
319 static SignalHandlerPointer _prev_fpe = nullptr;
320 
321 static void CDECL HandleSavegameLoadCrash(int signum);
322 
327 static void SetSignalHandlers()
328 {
329  _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
330  _prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
331  _prev_fpe = signal(SIGFPE, HandleSavegameLoadCrash);
332 }
333 
337 static void ResetSignalHandlers()
338 {
339  signal(SIGSEGV, _prev_segfault);
340  signal(SIGABRT, _prev_abort);
341  signal(SIGFPE, _prev_fpe);
342 }
343 
346 
353 {
355 }
356 
363 static void CDECL HandleSavegameLoadCrash(int signum)
364 {
366 
367  std::string message;
368  message.reserve(1024);
369  message += "Loading your savegame caused OpenTTD to crash.\n";
370 
371  for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != nullptr; c = c->next) {
373  }
374 
376  message +=
377  "This is most likely caused by a missing NewGRF or a NewGRF that\n"
378  "has been loaded as replacement for a missing NewGRF. OpenTTD\n"
379  "cannot easily determine whether a replacement NewGRF is of a newer\n"
380  "or older version.\n"
381  "It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
382  "This means that if the author makes incompatible NewGRFs with the\n"
383  "same GRF ID, OpenTTD cannot magically do the right thing. In most\n"
384  "cases, OpenTTD will load the savegame and not crash, but this is an\n"
385  "exception.\n"
386  "Please load the savegame with the appropriate NewGRFs installed.\n"
387  "The missing/compatible NewGRFs are:\n";
388 
389  for (const GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
390  if (HasBit(c->flags, GCF_COMPATIBLE)) {
391  const GRFIdentifier *replaced = _gamelog.GetOverriddenIdentifier(c);
392  fmt::format_to(std::back_inserter(message), "NewGRF {:08X} (checksum {}) not found.\n Loaded NewGRF \"{}\" (checksum {}) with same GRF ID instead.\n",
393  BSWAP32(c->ident.grfid), FormatArrayAsHex(c->original_md5sum), c->filename, FormatArrayAsHex(replaced->md5sum));
394  }
395  if (c->status == GCS_NOT_FOUND) {
396  fmt::format_to(std::back_inserter(message), "NewGRF {:08X} ({}) not found; checksum {}.\n",
397  BSWAP32(c->ident.grfid), c->filename, FormatArrayAsHex(c->ident.md5sum));
398  }
399  }
400  } else {
401  message +=
402  "This is probably caused by a corruption in the savegame.\n"
403  "Please file a bug report and attach this savegame.\n";
404  }
405 
406  ShowInfoI(message);
407 
408  SignalHandlerPointer call = nullptr;
409  switch (signum) {
410  case SIGSEGV: call = _prev_segfault; break;
411  case SIGABRT: call = _prev_abort; break;
412  case SIGFPE: call = _prev_fpe; break;
413  default: NOT_REACHED();
414  }
415  if (call != nullptr) call(signum);
416 }
417 
423 static void FixOwnerOfRailTrack(Tile t)
424 {
426 
427  /* remove leftover rail piece from crossing (from very old savegames) */
428  Train *v = nullptr;
429  for (Train *w : Train::Iterate()) {
430  if (w->tile == TileIndex(t)) {
431  v = w;
432  break;
433  }
434  }
435 
436  if (v != nullptr) {
437  /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
438  SetTileOwner(t, v->owner);
439  return;
440  }
441 
442  /* try to find any connected rail */
443  for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
444  TileIndex tt = t + TileOffsByDiagDir(dd);
445  if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
448  SetTileOwner(t, GetTileOwner(tt));
449  return;
450  }
451  }
452 
453  if (IsLevelCrossingTile(t)) {
454  /* else change the crossing to normal road (road vehicles won't care) */
455  Owner road = GetRoadOwner(t, RTT_ROAD);
456  Owner tram = GetRoadOwner(t, RTT_TRAM);
457  RoadBits bits = GetCrossingRoadBits(t);
458  bool hasroad = HasBit(t.m7(), 6);
459  bool hastram = HasBit(t.m7(), 7);
460 
461  /* MakeRoadNormal */
462  SetTileType(t, MP_ROAD);
463  SetTileOwner(t, road);
464  t.m3() = (hasroad ? bits : 0);
465  t.m5() = (hastram ? bits : 0) | ROAD_TILE_NORMAL << 6;
466  SB(t.m6(), 2, 4, 0);
467  SetRoadOwner(t, RTT_TRAM, tram);
468  return;
469  }
470 
471  /* if it's not a crossing, make it clean land */
472  MakeClear(t, CLEAR_GRASS, 0);
473 }
474 
482 {
483  /* Compute place where this vehicle entered the tile */
484  int entry_x = v->x_pos;
485  int entry_y = v->y_pos;
486  switch (dir) {
487  case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
488  case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
489  case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
490  case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
491  case INVALID_DIR: break;
492  default: NOT_REACHED();
493  }
494  uint8_t entry_z = GetSlopePixelZ(entry_x, entry_y, true);
495 
496  /* Compute middle of the tile. */
497  int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
498  int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
499  uint8_t middle_z = GetSlopePixelZ(middle_x, middle_y, true);
500 
501  /* middle_z == entry_z, no height change. */
502  if (middle_z == entry_z) return 0;
503 
504  /* middle_z < entry_z, we are going downwards. */
505  if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
506 
507  /* middle_z > entry_z, we are going upwards. */
508  return 1U << GVF_GOINGUP_BIT;
509 }
510 
517 {
518  for (Vehicle *v : Vehicle::Iterate()) {
519  if (v->IsGroundVehicle()) {
520  /*
521  * Either the vehicle is not actually on the given tile, i.e. it is
522  * in the wormhole of a bridge or a tunnel, or the Z-coordinate must
523  * be the same as when it would be recalculated right now.
524  */
525  assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos, true));
526  }
527  }
528 }
529 
536 static inline bool MayHaveBridgeAbove(Tile t)
537 {
538  return IsTileType(t, MP_CLEAR) || IsTileType(t, MP_RAILWAY) || IsTileType(t, MP_ROAD) ||
540 }
541 
545 static void StartScripts()
546 {
547  /* Script debug window requires AIs to be started before trying to start GameScript. */
548 
549  /* Start the AIs. */
550  for (const Company *c : Company::Iterate()) {
551  if (Company::IsValidAiID(c->index)) AI::StartNew(c->index);
552  }
553 
554  /* Start the GameScript. */
555  Game::StartNew();
556 
558 }
559 
566 {
568 
569  extern TileIndex _cur_tileloop_tile; // From landscape.cpp.
570  /* The LFSR used in RunTileLoop iteration cannot have a zeroed state, make it non-zeroed. */
571  if (_cur_tileloop_tile == 0) _cur_tileloop_tile = 1;
572 
574 
576  _gamelog.TestMode();
577 
578  RebuildTownKdtree();
579  RebuildStationKdtree();
580  /* This needs to be done even before conversion, because some conversions will destroy objects
581  * that otherwise won't exist in the tree. */
582  RebuildViewportKdtree();
583 
585 
588  } else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
589  Debug(net, 0, "The loading savegame was paused due to an error state");
590  Debug(net, 0, " This savegame cannot be used for multiplayer");
591  /* Restore the signals */
593  return false;
594  } else if (!_networking || _network_server) {
595  /* If we are in singleplayer mode, i.e. not networking, and loading the
596  * savegame or we are loading the savegame as network server we do
597  * not want to be bothered by being paused because of the automatic
598  * reason of a network server, e.g. joining clients or too few
599  * active clients. Note that resetting these values for a network
600  * client are very bad because then the client is going to execute
601  * the game loop when the server is not, i.e. it desyncs. */
603  }
604 
605  /* In very old versions, size of train stations was stored differently.
606  * They had swapped width and height if station was built along the Y axis.
607  * TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
608  * Because the data stored by TTDPatch are unusable for rail stations > 7x7,
609  * recompute the width and height. Doing this unconditionally for all old
610  * savegames simplifies the code. */
612  for (Station *st : Station::Iterate()) {
613  st->train_station.w = st->train_station.h = 0;
614  }
615  for (auto t : Map::Iterate()) {
616  if (!IsTileType(t, MP_STATION)) continue;
617  if (t.m5() > 7) continue; // is it a rail station tile?
618  Station *st = Station::Get(t.m2());
619  assert(st->train_station.tile != 0);
620  int dx = TileX(t) - TileX(st->train_station.tile);
621  int dy = TileY(t) - TileY(st->train_station.tile);
622  assert(dx >= 0 && dy >= 0);
623  st->train_station.w = std::max<uint>(st->train_station.w, dx + 1);
624  st->train_station.h = std::max<uint>(st->train_station.h, dy + 1);
625  }
626  }
627 
630 
631  /* In old savegame versions, the heightlevel was coded in bits 0..3 of the type field */
632  for (auto t : Map::Iterate()) {
633  t.height() = GB(t.type(), 0, 4);
634  SB(t.type(), 0, 2, GB(t.m6(), 0, 2));
635  SB(t.m6(), 0, 2, 0);
636  if (MayHaveBridgeAbove(t)) {
637  SB(t.type(), 2, 2, GB(t.m6(), 6, 2));
638  SB(t.m6(), 6, 2, 0);
639  } else {
640  SB(t.type(), 2, 2, 0);
641  }
642  }
643  }
644 
645  /* in version 2.1 of the savegame, town owner was unified. */
646  if (IsSavegameVersionBefore(SLV_2, 1)) ConvertTownOwner();
647 
648  /* from version 4.1 of the savegame, exclusive rights are stored at towns */
649  if (IsSavegameVersionBefore(SLV_4, 1)) UpdateExclusiveRights();
650 
651  /* from version 4.2 of the savegame, currencies are in a different order */
652  if (IsSavegameVersionBefore(SLV_4, 2)) UpdateCurrencies();
653 
654  /* In old version there seems to be a problem that water is owned by
655  * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
656  * (4.3) version, so I just check when versions are older, and then
657  * walk through the whole map.. */
658  if (IsSavegameVersionBefore(SLV_4, 3)) {
659  for (auto t : Map::Iterate()) {
660  if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
662  }
663  }
664  }
665 
667  for (Company *c : Company::Iterate()) {
668  c->name = CopyFromOldName(c->name_1);
669  if (!c->name.empty()) c->name_1 = STR_SV_UNNAMED;
670  c->president_name = CopyFromOldName(c->president_name_1);
671  if (!c->president_name.empty()) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
672  }
673 
674  for (Station *st : Station::Iterate()) {
675  st->name = CopyFromOldName(st->string_id);
676  /* generating new name would be too much work for little effect, use the station name fallback */
677  if (!st->name.empty()) st->string_id = STR_SV_STNAME_FALLBACK;
678  }
679 
680  for (Town *t : Town::Iterate()) {
681  t->name = CopyFromOldName(t->townnametype);
682  if (!t->name.empty()) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
683  }
684  }
685 
686  /* From this point the old names array is cleared. */
687  ResetOldNames();
688 
690  /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
691  for (Station *st : Station::Iterate()) {
692  if (st->airport.tile == 0) st->airport.tile = INVALID_TILE;
693  if (st->train_station.tile == 0) st->train_station.tile = INVALID_TILE;
694  }
695 
696  /* the same applies to Company::location_of_HQ */
697  for (Company *c : Company::Iterate()) {
698  if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(SLV_4) && c->location_of_HQ == 0xFFFF)) {
699  c->location_of_HQ = INVALID_TILE;
700  }
701  }
702  }
703 
704  /* convert road side to my format. */
706 
707  /* Check if all NewGRFs are present, we are very strict in MP mode */
709  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
710  if (c->status == GCS_NOT_FOUND) {
711  _gamelog.GRFRemove(c->ident.grfid);
712  } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
713  _gamelog.GRFCompatible(&c->ident);
714  }
715  }
716 
717  if (_networking && gcf_res != GLC_ALL_GOOD) {
718  SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
719  /* Restore the signals */
721  return false;
722  }
723 
724  switch (gcf_res) {
725  case GLC_COMPATIBLE: ShowErrorMessage(STR_NEWGRF_COMPATIBLE_LOAD_WARNING, INVALID_STRING_ID, WL_CRITICAL); break;
726  case GLC_NOT_FOUND: ShowErrorMessage(STR_NEWGRF_DISABLED_WARNING, INVALID_STRING_ID, WL_CRITICAL); _pause_mode = PM_PAUSED_ERROR; break;
727  default: break;
728  }
729 
730  /* The value of TimerGameCalendar::date_fract got divided, so make sure that old games are converted correctly. */
732 
733  /* Update current year
734  * must be done before loading sprites as some newgrfs check it */
736 
737  /* Only new games can use wallclock units. */
739 
740  /* Update economy year. If we don't have a separate economy date saved, follow the calendar date. */
743  } else {
745  }
746 
747  /*
748  * Force the old behaviour for compatibility reasons with old savegames. As new
749  * settings can only be loaded from new savegames loading old savegames with new
750  * versions of OpenTTD will normally initialize settings newer than the savegame
751  * version with "new game" defaults which the player can define to their liking.
752  * For some settings we override that to keep the behaviour the same as when the
753  * game was saved.
754  *
755  * Note that there is no non-stop in here. This is because the setting could have
756  * either value in TTDPatch. To convert it properly the user has to make sure the
757  * right value has been chosen in the settings. Otherwise we will be converting
758  * it incorrectly in half of the times without a means to correct that.
759  */
768  }
774  }
780  }
787  }
788 
791  }
792 
793  /* Convert linkgraph update settings from days to seconds. */
797  }
798 
799  /* Load the sprites */
800  GfxLoadSprites();
802 
803  /* Copy temporary data to Engine pool */
805 
806  /* Connect front and rear engines of multiheaded trains and converts
807  * subtype to the new format */
809 
810  /* Connect front and rear engines of multiheaded trains */
812 
813  /* Fix the CargoPackets *and* fix the caches of CargoLists.
814  * If this isn't done before Stations and especially Vehicles are
815  * running their AfterLoad we might get in trouble. In the case of
816  * vehicles we could give the wrong (cached) count of items in a
817  * vehicle which causes different results when getting their caches
818  * filled; and that could eventually lead to desyncs. */
820 
821  /* Update all vehicles: Phase 1 */
823 
824  /* make sure there is a town in the game */
825  if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
826  SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
827  /* Restore the signals */
829  return false;
830  }
831 
832  /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
833  * This problem appears in savegame version 21 too, see r3455. But after loading the
834  * savegame and saving again, the buggy map array could be converted to new savegame
835  * version. It didn't show up before r12070. */
836  if (IsSavegameVersionBefore(SLV_87)) UpdateVoidTiles();
837 
838  /* Fix the cache for cargo payments. */
839  for (CargoPayment *cp : CargoPayment::Iterate()) {
840  cp->front->cargo_payment = cp;
841  cp->current_station = cp->front->last_station_visited;
842  }
843 
844 
846  /* Prior to SLV_WATER_TILE_TYPE, the water tile type was stored differently from the enumeration. This has to be
847  * converted before SLV_72 and SLV_82 conversions which use GetWaterTileType. */
848  static constexpr uint8_t WBL_COAST_FLAG = 0;
849 
850  for (auto t : Map::Iterate()) {
851  if (!IsTileType(t, MP_WATER)) continue;
852 
853  switch (GB(t.m5(), 4, 4)) {
854  case 0x0: /* Previously WBL_TYPE_NORMAL, Clear water or coast. */
855  SetWaterTileType(t, HasBit(t.m5(), WBL_COAST_FLAG) ? WATER_TILE_COAST : WATER_TILE_CLEAR);
856  break;
857 
858  case 0x1: SetWaterTileType(t, WATER_TILE_LOCK); break; /* Previously WBL_TYPE_LOCK */
859  case 0x8: SetWaterTileType(t, WATER_TILE_DEPOT); break; /* Previously WBL_TYPE_DEPOT */
860  default: SetWaterTileType(t, WATER_TILE_CLEAR); break; /* Shouldn't happen... */
861  }
862  }
863  }
864 
866  /* Locks in very old savegames had OWNER_WATER as owner */
867  for (auto t : Map::Iterate()) {
868  switch (GetTileType(t)) {
869  default: break;
870 
871  case MP_WATER:
873  break;
874 
875  case MP_STATION: {
876  if (HasBit(t.m6(), 3)) SetBit(t.m6(), 2);
877  StationGfx gfx = GetStationGfx(t);
878  StationType st;
879  if ( IsInsideMM(gfx, 0, 8)) { // Rail station
880  st = STATION_RAIL;
881  SetStationGfx(t, gfx - 0);
882  } else if (IsInsideMM(gfx, 8, 67)) { // Airport
883  st = STATION_AIRPORT;
884  SetStationGfx(t, gfx - 8);
885  } else if (IsInsideMM(gfx, 67, 71)) { // Truck
886  st = STATION_TRUCK;
887  SetStationGfx(t, gfx - 67);
888  } else if (IsInsideMM(gfx, 71, 75)) { // Bus
889  st = STATION_BUS;
890  SetStationGfx(t, gfx - 71);
891  } else if (gfx == 75) { // Oil rig
892  st = STATION_OILRIG;
893  SetStationGfx(t, gfx - 75);
894  } else if (IsInsideMM(gfx, 76, 82)) { // Dock
895  st = STATION_DOCK;
896  SetStationGfx(t, gfx - 76);
897  } else if (gfx == 82) { // Buoy
898  st = STATION_BUOY;
899  SetStationGfx(t, gfx - 82);
900  } else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
901  st = STATION_AIRPORT;
902  SetStationGfx(t, gfx - 83 + 67 - 8);
903  } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
904  st = STATION_TRUCK;
906  } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
907  st = STATION_BUS;
909  } else {
910  /* Restore the signals */
912  return false;
913  }
914  SB(t.m6(), 3, 3, st);
915  break;
916  }
917  }
918  }
919  }
920 
922  /* Expansion of station type field in m6 */
923  for (auto t : Map::Iterate()) {
924  if (IsTileType(t, MP_STATION)) {
925  ClrBit(t.m6(), 6);
926  }
927  }
928  }
929 
930  for (auto t : Map::Iterate()) {
931  switch (GetTileType(t)) {
932  case MP_STATION: {
934 
935  /* Sanity check */
936  if (!IsBuoy(t) && bst->owner != GetTileOwner(t)) SlErrorCorrupt("Wrong owner for station tile");
937 
938  /* Set up station spread */
939  bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
940 
941  /* Waypoints don't have road stops/oil rigs in the old format */
942  if (!Station::IsExpected(bst)) break;
943  Station *st = Station::From(bst);
944 
945  switch (GetStationType(t)) {
946  case STATION_TRUCK:
947  case STATION_BUS:
949  /* Before version 5 you could not have more than 250 stations.
950  * Version 6 adds large maps, so you could only place 253*253
951  * road stops on a map (no freeform edges) = 64009. So, yes
952  * someone could in theory create such a full map to trigger
953  * this assertion, it's safe to assume that's only something
954  * theoretical and does not happen in normal games. */
955  assert(RoadStop::CanAllocateItem());
956 
957  /* From this version on there can be multiple road stops of the
958  * same type per station. Convert the existing stops to the new
959  * internal data structure. */
960  RoadStop *rs = new RoadStop(t);
961 
962  RoadStop **head =
963  IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
964  *head = rs;
965  }
966  break;
967 
968  case STATION_OILRIG: {
969  /* The internal encoding of oil rigs was changed twice.
970  * It was 3 (till 2.2) and later 5 (till 5.1).
971  * DeleteOilRig asserts on the correct type, and
972  * setting it unconditionally does not hurt.
973  */
975 
976  /* Very old savegames sometimes have phantom oil rigs, i.e.
977  * an oil rig which got shut down, but not completely removed from
978  * the map
979  */
980  TileIndex t1 = TileAddXY(t, 0, 1);
981  if (!IsTileType(t1, MP_INDUSTRY) || GetIndustryGfx(t1) != GFX_OILRIG_1) {
982  DeleteOilRig(t);
983  }
984  break;
985  }
986 
987  default: break;
988  }
989  break;
990  }
991 
992  default: break;
993  }
994  }
995 
996  /* In version 6.1 we put the town index in the map-array. To do this, we need
997  * to use m2 (16bit big), so we need to clean m2, and that is where this is
998  * all about ;) */
999  if (IsSavegameVersionBefore(SLV_6, 1)) {
1000  for (auto t : Map::Iterate()) {
1001  switch (GetTileType(t)) {
1002  case MP_HOUSE:
1003  t.m4() = t.m2();
1004  SetTownIndex(t, CalcClosestTownFromTile(t)->index);
1005  break;
1006 
1007  case MP_ROAD:
1008  t.m4() |= (t.m2() << 4);
1009  if ((GB(t.m5(), 4, 2) == ROAD_TILE_CROSSING ? (Owner)t.m3() : GetTileOwner(t)) == OWNER_TOWN) {
1010  SetTownIndex(t, CalcClosestTownFromTile(t)->index);
1011  } else {
1012  SetTownIndex(t, 0);
1013  }
1014  break;
1015 
1016  default: break;
1017  }
1018  }
1019  }
1020 
1021  /* Force the freeform edges to false for old savegames. */
1024  }
1025 
1026  /* From version 9.0, we update the max passengers of a town (was sometimes negative
1027  * before that. */
1029  for (Town *t : Town::Iterate()) UpdateTownMaxPass(t);
1030  }
1031 
1032  /* From version 16.0, we included autorenew on engines, which are now saved, but
1033  * of course, we do need to initialize them for older savegames. */
1035  for (Company *c : Company::Iterate()) {
1036  c->engine_renew_list = nullptr;
1037  c->settings.engine_renew = false;
1038  c->settings.engine_renew_months = 6;
1039  c->settings.engine_renew_money = 100000;
1040  }
1041 
1042  /* When loading a game, _local_company is not yet set to the correct value.
1043  * However, in a dedicated server we are a spectator, so nothing needs to
1044  * happen. In case we are not a dedicated server, the local company always
1045  * becomes the first available company, unless we are in the scenario editor
1046  * where all the companies are 'invalid'.
1047  */
1049  if (!_network_dedicated && c != nullptr) {
1051  }
1052  }
1053 
1055  for (auto t : Map::Iterate()) {
1056  switch (GetTileType(t)) {
1057  case MP_RAILWAY:
1058  if (IsPlainRail(t)) {
1059  /* Swap ground type and signal type for plain rail tiles, so the
1060  * ground type uses the same bits as for depots and waypoints. */
1061  uint tmp = GB(t.m4(), 0, 4);
1062  SB(t.m4(), 0, 4, GB(t.m2(), 0, 4));
1063  SB(t.m2(), 0, 4, tmp);
1064  } else if (HasBit(t.m5(), 2)) {
1065  /* Split waypoint and depot rail type and remove the subtype. */
1066  ClrBit(t.m5(), 2);
1067  ClrBit(t.m5(), 6);
1068  }
1069  break;
1070 
1071  case MP_ROAD:
1072  /* Swap m3 and m4, so the track type for rail crossings is the
1073  * same as for normal rail. */
1074  Swap(t.m3(), t.m4());
1075  break;
1076 
1077  default: break;
1078  }
1079  }
1080  }
1081 
1083  /* Added the RoadType */
1084  bool old_bridge = IsSavegameVersionBefore(SLV_42);
1085  for (auto t : Map::Iterate()) {
1086  switch (GetTileType(t)) {
1087  case MP_ROAD:
1088  SB(t.m5(), 6, 2, GB(t.m5(), 4, 2));
1089  switch (GetRoadTileType(t)) {
1090  default: SlErrorCorrupt("Invalid road tile type");
1091  case ROAD_TILE_NORMAL:
1092  SB(t.m4(), 0, 4, GB(t.m5(), 0, 4));
1093  SB(t.m4(), 4, 4, 0);
1094  SB(t.m6(), 2, 4, 0);
1095  break;
1096  case ROAD_TILE_CROSSING:
1097  SB(t.m4(), 5, 2, GB(t.m5(), 2, 2));
1098  break;
1099  case ROAD_TILE_DEPOT: break;
1100  }
1101  SB(t.m7(), 6, 2, 1); // Set pre-NRT road type bits for conversion later.
1102  break;
1103 
1104  case MP_STATION:
1105  if (IsStationRoadStop(t)) SB(t.m7(), 6, 2, 1);
1106  break;
1107 
1108  case MP_TUNNELBRIDGE:
1109  /* Middle part of "old" bridges */
1110  if (old_bridge && IsBridge(t) && HasBit(t.m5(), 6)) break;
1111  if (((old_bridge && IsBridge(t)) ? (TransportType)GB(t.m5(), 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1112  SB(t.m7(), 6, 2, 1); // Set pre-NRT road type bits for conversion later.
1113  }
1114  break;
1115 
1116  default: break;
1117  }
1118  }
1119  }
1120 
1122  bool fix_roadtypes = !IsSavegameVersionBefore(SLV_61);
1123  bool old_bridge = IsSavegameVersionBefore(SLV_42);
1124 
1125  for (auto t : Map::Iterate()) {
1126  switch (GetTileType(t)) {
1127  case MP_ROAD:
1128  if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m7(), 5, 3));
1129  SB(t.m7(), 5, 1, GB(t.m3(), 7, 1)); // snow/desert
1130  switch (GetRoadTileType(t)) {
1131  default: SlErrorCorrupt("Invalid road tile type");
1132  case ROAD_TILE_NORMAL:
1133  SB(t.m7(), 0, 4, GB(t.m3(), 0, 4)); // road works
1134  SB(t.m6(), 3, 3, GB(t.m3(), 4, 3)); // ground
1135  SB(t.m3(), 0, 4, GB(t.m4(), 4, 4)); // tram bits
1136  SB(t.m3(), 4, 4, GB(t.m5(), 0, 4)); // tram owner
1137  SB(t.m5(), 0, 4, GB(t.m4(), 0, 4)); // road bits
1138  break;
1139 
1140  case ROAD_TILE_CROSSING:
1141  SB(t.m7(), 0, 5, GB(t.m4(), 0, 5)); // road owner
1142  SB(t.m6(), 3, 3, GB(t.m3(), 4, 3)); // ground
1143  SB(t.m3(), 4, 4, GB(t.m5(), 0, 4)); // tram owner
1144  SB(t.m5(), 0, 1, GB(t.m4(), 6, 1)); // road axis
1145  SB(t.m5(), 5, 1, GB(t.m4(), 5, 1)); // crossing state
1146  break;
1147 
1148  case ROAD_TILE_DEPOT:
1149  break;
1150  }
1151  if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1152  const Town *town = CalcClosestTownFromTile(t);
1153  if (town != nullptr) SetTownIndex(t, town->index);
1154  }
1155  t.m4() = 0;
1156  break;
1157 
1158  case MP_STATION:
1159  if (!IsStationRoadStop(t)) break;
1160 
1161  if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m3(), 0, 3));
1162  SB(t.m7(), 0, 5, HasBit(t.m6(), 2) ? OWNER_TOWN : GetTileOwner(t));
1163  SB(t.m3(), 4, 4, t.m1());
1164  t.m4() = 0;
1165  break;
1166 
1167  case MP_TUNNELBRIDGE:
1168  if (old_bridge && IsBridge(t) && HasBit(t.m5(), 6)) break;
1169  if (((old_bridge && IsBridge(t)) ? (TransportType)GB(t.m5(), 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1170  if (fix_roadtypes) SB(t.m7(), 6, 2, (RoadTypes)GB(t.m3(), 0, 3));
1171 
1172  Owner o = GetTileOwner(t);
1173  SB(t.m7(), 0, 5, o); // road owner
1174  SB(t.m3(), 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
1175  }
1176  SB(t.m6(), 2, 4, GB(t.m2(), 4, 4)); // bridge type
1177  SB(t.m7(), 5, 1, GB(t.m4(), 7, 1)); // snow/desert
1178 
1179  t.m2() = 0;
1180  t.m4() = 0;
1181  break;
1182 
1183  default: break;
1184  }
1185  }
1186  }
1187 
1188  /* Railtype moved from m3 to m8 in version SLV_EXTEND_RAILTYPES. */
1190  for (auto t : Map::Iterate()) {
1191  switch (GetTileType(t)) {
1192  case MP_RAILWAY:
1193  SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1194  break;
1195 
1196  case MP_ROAD:
1197  if (IsLevelCrossing(t)) {
1198  SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1199  }
1200  break;
1201 
1202  case MP_STATION:
1203  if (HasStationRail(t)) {
1204  SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1205  }
1206  break;
1207 
1208  case MP_TUNNELBRIDGE:
1210  SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1211  }
1212  break;
1213 
1214  default:
1215  break;
1216  }
1217  }
1218  }
1219 
1221  for (auto t : Map::Iterate()) {
1223  if (IsBridgeTile(t)) {
1224  if (HasBit(t.m5(), 6)) { // middle part
1225  Axis axis = (Axis)GB(t.m5(), 0, 1);
1226 
1227  if (HasBit(t.m5(), 5)) { // transport route under bridge?
1228  if (GB(t.m5(), 3, 2) == TRANSPORT_RAIL) {
1229  MakeRailNormal(
1230  t,
1231  GetTileOwner(t),
1232  axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
1233  GetRailType(t)
1234  );
1235  } else {
1236  TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
1237 
1238  /* MakeRoadNormal */
1239  SetTileType(t, MP_ROAD);
1240  t.m2() = town;
1241  t.m3() = 0;
1242  t.m5() = (axis == AXIS_X ? ROAD_Y : ROAD_X) | ROAD_TILE_NORMAL << 6;
1243  SB(t.m6(), 2, 4, 0);
1244  t.m7() = 1 << 6;
1245  SetRoadOwner(t, RTT_TRAM, OWNER_NONE);
1246  }
1247  } else {
1248  if (GB(t.m5(), 3, 2) == 0) {
1249  MakeClear(t, CLEAR_GRASS, 3);
1250  } else {
1251  if (!IsTileFlat(t)) {
1252  MakeShore(t);
1253  } else {
1254  if (GetTileOwner(t) == OWNER_WATER) {
1255  MakeSea(t);
1256  } else {
1257  MakeCanal(t, GetTileOwner(t), Random());
1258  }
1259  }
1260  }
1261  }
1262  SetBridgeMiddle(t, axis);
1263  } else { // ramp
1264  Axis axis = (Axis)GB(t.m5(), 0, 1);
1265  uint north_south = GB(t.m5(), 5, 1);
1266  DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
1267  TransportType type = (TransportType)GB(t.m5(), 1, 2);
1268 
1269  t.m5() = 1 << 7 | type << 2 | dir;
1270  }
1271  }
1272  }
1273 
1274  for (Vehicle *v : Vehicle::Iterate()) {
1275  if (!v->IsGroundVehicle()) continue;
1276  if (IsBridgeTile(v->tile)) {
1277  DiagDirection dir = GetTunnelBridgeDirection(v->tile);
1278 
1279  if (dir != DirToDiagDir(v->direction)) continue;
1280  switch (dir) {
1281  default: SlErrorCorrupt("Invalid vehicle direction");
1282  case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
1283  case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
1284  case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
1285  case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
1286  }
1287  } else if (v->z_pos > GetTileMaxPixelZ(TileVirtXY(v->x_pos, v->y_pos))) {
1288  v->tile = GetNorthernBridgeEnd(v->tile);
1289  v->UpdatePosition();
1290  } else {
1291  continue;
1292  }
1293  if (v->type == VEH_TRAIN) {
1294  Train::From(v)->track = TRACK_BIT_WORMHOLE;
1295  } else {
1296  RoadVehicle::From(v)->state = RVSB_WORMHOLE;
1297  }
1298  }
1299  }
1300 
1302  /* Add road subtypes */
1303  for (auto t : Map::Iterate()) {
1304  bool has_road = false;
1305  switch (GetTileType(t)) {
1306  case MP_ROAD:
1307  has_road = true;
1308  break;
1309  case MP_STATION:
1310  has_road = IsAnyRoadStop(t);
1311  break;
1312  case MP_TUNNELBRIDGE:
1314  break;
1315  default:
1316  break;
1317  }
1318 
1319  if (has_road) {
1320  RoadType road_rt = HasBit(t.m7(), 6) ? ROADTYPE_ROAD : INVALID_ROADTYPE;
1321  RoadType tram_rt = HasBit(t.m7(), 7) ? ROADTYPE_TRAM : INVALID_ROADTYPE;
1322 
1323  assert(road_rt != INVALID_ROADTYPE || tram_rt != INVALID_ROADTYPE);
1324  SetRoadTypes(t, road_rt, tram_rt);
1325  SB(t.m7(), 6, 2, 0); // Clear pre-NRT road type bits.
1326  }
1327  }
1328  }
1329 
1330  /* Elrails got added in rev 24 */
1332  RailType min_rail = RAILTYPE_ELECTRIC;
1333 
1334  for (Train *v : Train::Iterate()) {
1335  RailType rt = RailVehInfo(v->engine_type)->railtype;
1336 
1337  v->railtype = rt;
1338  if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
1339  }
1340 
1341  /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
1342  for (auto t : Map::Iterate()) {
1343  switch (GetTileType(t)) {
1344  case MP_RAILWAY:
1345  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1346  break;
1347 
1348  case MP_ROAD:
1349  if (IsLevelCrossing(t)) {
1350  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1351  }
1352  break;
1353 
1354  case MP_STATION:
1355  if (HasStationRail(t)) {
1356  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1357  }
1358  break;
1359 
1360  case MP_TUNNELBRIDGE:
1362  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1363  }
1364  break;
1365 
1366  default:
1367  break;
1368  }
1369  }
1370  }
1371 
1372  /* In version 16.1 of the savegame a company can decide if trains, which get
1373  * replaced, shall keep their old length. In all prior versions, just default
1374  * to false */
1375  if (IsSavegameVersionBefore(SLV_16, 1)) {
1376  for (Company *c : Company::Iterate()) c->settings.renew_keep_length = false;
1377  }
1378 
1380  /* Waypoints became subclasses of stations ... */
1382  /* ... and buoys were moved to waypoints. */
1384  }
1385 
1386  /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
1387  * room for PBS. Now in version 21 move it back :P. */
1389  for (auto t : Map::Iterate()) {
1390  switch (GetTileType(t)) {
1391  case MP_RAILWAY:
1392  if (HasSignals(t)) {
1393  /* Original signal type/variant was stored in m4 but since saveload
1394  * version 48 they are in m2. The bits has been already moved to m2
1395  * (see the code somewhere above) so don't use m4, use m2 instead. */
1396 
1397  /* convert PBS signals to combo-signals */
1398  if (HasBit(t.m2(), 2)) SB(t.m2(), 0, 2, SIGTYPE_COMBO);
1399 
1400  /* move the signal variant back */
1401  SB(t.m2(), 2, 1, HasBit(t.m2(), 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1402  ClrBit(t.m2(), 3);
1403  }
1404 
1405  /* Clear PBS reservation on track */
1406  if (!IsRailDepotTile(t)) {
1407  SB(t.m4(), 4, 4, 0);
1408  } else {
1409  ClrBit(t.m3(), 6);
1410  }
1411  break;
1412 
1413  case MP_STATION: // Clear PBS reservation on station
1414  ClrBit(t.m3(), 6);
1415  break;
1416 
1417  default: break;
1418  }
1419  }
1420  }
1421 
1423  for (RoadVehicle *rv : RoadVehicle::Iterate()) {
1424  rv->vehstatus &= ~0x40;
1425  }
1426  }
1427 
1429  for (Station *st : Station::Iterate()) {
1430  st->last_vehicle_type = VEH_INVALID;
1431  }
1432  }
1433 
1435 
1438  }
1439 
1440  for (Company *c : Company::Iterate()) {
1441  c->avail_railtypes = GetCompanyRailTypes(c->index);
1442  c->avail_roadtypes = GetCompanyRoadTypes(c->index);
1443  }
1444 
1445  AfterLoadStations();
1446 
1447  /* Time starts at 0 instead of 1920.
1448  * Account for this in older games by adding an offset */
1454 
1458  for (Company *c : Company::Iterate()) c->inaugurated_year += EconomyTime::ORIGINAL_BASE_YEAR;
1459  for (Industry *i : Industry::Iterate()) i->last_prod_year += EconomyTime::ORIGINAL_BASE_YEAR;
1460 
1461  for (Vehicle *v : Vehicle::Iterate()) {
1462  v->date_of_last_service += EconomyTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1463  v->build_year += CalendarTime::ORIGINAL_BASE_YEAR;
1464  }
1465  }
1466 
1467  /* From 32 on we save the industry who made the farmland.
1468  * To give this prettiness to old savegames, we remove all farmfields and
1469  * plant new ones. */
1471  for (auto t : Map::Iterate()) {
1472  if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
1473  /* remove fields */
1474  MakeClear(t, CLEAR_GRASS, 3);
1475  }
1476  }
1477 
1478  for (Industry *i : Industry::Iterate()) {
1479  uint j;
1480 
1482  for (j = 0; j != 50; j++) PlantRandomFarmField(i);
1483  }
1484  }
1485  }
1486 
1487  /* Setting no refit flags to all orders in savegames from before refit in orders were added */
1489  for (Order *order : Order::Iterate()) {
1490  order->SetRefit(CARGO_NO_REFIT);
1491  }
1492 
1493  for (Vehicle *v : Vehicle::Iterate()) {
1494  v->current_order.SetRefit(CARGO_NO_REFIT);
1495  }
1496  }
1497 
1498  /* from version 38 we have optional elrails, since we cannot know the
1499  * preference of a user, let elrails enabled; it can be disabled manually */
1501  /* do the same as when elrails were enabled/disabled manually just now */
1502  UpdateDisableElrailSettingState(_settings_game.vehicle.disable_elrails, false);
1504 
1505  /* From version 53, the map array was changed for house tiles to allow
1506  * space for newhouses grf features. A new byte, m7, was also added. */
1508  for (auto t : Map::Iterate()) {
1509  if (IsTileType(t, MP_HOUSE)) {
1510  if (GB(t.m3(), 6, 2) != TOWN_HOUSE_COMPLETED) {
1511  /* Move the construction stage from m3[7..6] to m5[5..4].
1512  * The construction counter does not have to move. */
1513  SB(t.m5(), 3, 2, GB(t.m3(), 6, 2));
1514  SB(t.m3(), 6, 2, 0);
1515 
1516  /* The "house is completed" bit is now in m6[2]. */
1517  SetHouseCompleted(t, false);
1518  } else {
1519  /* The "lift has destination" bit has been moved from
1520  * m5[7] to m7[0]. */
1521  AssignBit(t.m7(), 0, HasBit(t.m5(), 7));
1522  ClrBit(t.m5(), 7);
1523 
1524  /* The "lift is moving" bit has been removed, as it does
1525  * the same job as the "lift has destination" bit. */
1526  ClrBit(t.m1(), 7);
1527 
1528  /* The position of the lift goes from m1[7..0] to m6[7..2],
1529  * making m1 totally free, now. The lift position does not
1530  * have to be a full byte since the maximum value is 36. */
1531  SetLiftPosition(t, GB(t.m1(), 0, 6 ));
1532 
1533  t.m1() = 0;
1534  t.m3() = 0;
1535  SetHouseCompleted(t, true);
1536  }
1537  }
1538  }
1539  }
1540 
1541  /* Check and update house and town values */
1543 
1545  for (auto t : Map::Iterate()) {
1546  if (IsTileType(t, MP_INDUSTRY)) {
1547  switch (GetIndustryGfx(t)) {
1548  case GFX_POWERPLANT_SPARKS:
1549  t.m3() = GB(t.m1(), 2, 5);
1550  break;
1551 
1552  case GFX_OILWELL_ANIMATED_1:
1553  case GFX_OILWELL_ANIMATED_2:
1554  case GFX_OILWELL_ANIMATED_3:
1555  t.m3() = GB(t.m1(), 0, 2);
1556  break;
1557 
1558  case GFX_COAL_MINE_TOWER_ANIMATED:
1559  case GFX_COPPER_MINE_TOWER_ANIMATED:
1560  case GFX_GOLD_MINE_TOWER_ANIMATED:
1561  t.m3() = t.m1();
1562  break;
1563 
1564  default: // No animation states to change
1565  break;
1566  }
1567  }
1568  }
1569  }
1570 
1572  /* Originally just the fact that some cargo had been paid for was
1573  * stored to stop people cheating and cashing in several times. This
1574  * wasn't enough though as it was cleared when the vehicle started
1575  * loading again, even if it didn't actually load anything, so now the
1576  * amount that has been paid is stored. */
1577  for (Vehicle *v : Vehicle::Iterate()) {
1578  ClrBit(v->vehicle_flags, 2);
1579  }
1580  }
1581 
1582  /* Buoys do now store the owner of the previous water tile, which can never
1583  * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
1585  for (Waypoint *wp : Waypoint::Iterate()) {
1586  if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
1587  }
1588  }
1589 
1591  /* Aircraft units changed from 8 mph to 1 km-ish/h */
1592  for (Aircraft *v : Aircraft::Iterate()) {
1593  if (v->subtype <= AIR_AIRCRAFT) {
1594  const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
1595  v->cur_speed *= 128;
1596  v->cur_speed /= 10;
1597  v->acceleration = avi->acceleration;
1598  }
1599  }
1600  }
1601 
1603 
1605  for (auto t : Map::Iterate()) {
1606  if (IsTileType(t, MP_OBJECT) && t.m5() == OBJECT_STATUE) {
1607  t.m2() = CalcClosestTownFromTile(t)->index;
1608  }
1609  }
1610  }
1611 
1612  /* A setting containing the proportion of towns that grow twice as
1613  * fast was added in version 54. From version 56 this is now saved in the
1614  * town as cities can be built specifically in the scenario editor. */
1616  for (Town *t : Town::Iterate()) {
1617  if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
1618  t->larger_town = true;
1619  }
1620  }
1621  }
1622 
1624  /* Added a FIFO queue of vehicles loading at stations */
1625  for (Vehicle *v : Vehicle::Iterate()) {
1626  if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) && // for all locs
1627  !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
1628  v->current_order.IsType(OT_LOADING)) { // loading
1629  Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
1630 
1631  /* The loading finished flag is *only* set when actually completely
1632  * finished. Because the vehicle is loading, it is not finished. */
1633  ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
1634  }
1635  }
1636  } else if (IsSavegameVersionBefore(SLV_59)) {
1637  /* For some reason non-loading vehicles could be in the station's loading vehicle list */
1638 
1639  for (Station *st : Station::Iterate()) {
1640  for (auto iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); /* nothing */) {
1641  Vehicle *v = *iter;
1642  if (!v->current_order.IsType(OT_LOADING)) {
1643  iter = st->loading_vehicles.erase(iter);
1644  } else {
1645  ++iter;
1646  }
1647  }
1648  }
1649  }
1650 
1652  /* Setting difficulty industry_density other than zero get bumped to +1
1653  * since a new option (very low at position 1) has been added */
1656  }
1657 
1658  /* Same goes for number of towns, although no test is needed, just an increment */
1660  }
1661 
1663  /* Since now we allow different signal types and variants on a single tile.
1664  * Move signal states to m4 to make room and clone the signal type/variant. */
1665  for (auto t : Map::Iterate()) {
1666  if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
1667  /* move signal states */
1668  SetSignalStates(t, GB(t.m2(), 4, 4));
1669  SB(t.m2(), 4, 4, 0);
1670  /* clone signal type and variant */
1671  SB(t.m2(), 4, 3, GB(t.m2(), 0, 3));
1672  }
1673  }
1674  }
1675 
1677  /* In some old savegames a bit was cleared when it should not be cleared */
1678  for (RoadVehicle *rv : RoadVehicle::Iterate()) {
1679  if (rv->state == 250 || rv->state == 251) {
1680  SetBit(rv->state, 2);
1681  }
1682  }
1683  }
1684 
1686  /* Added variables to support newindustries */
1687  for (Industry *i : Industry::Iterate()) i->founder = OWNER_NONE;
1688  }
1689 
1690  /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
1691  Replace the owner for those by OWNER_NONE. */
1693  for (auto t : Map::Iterate()) {
1694  if (IsTileType(t, MP_WATER) &&
1696  GetTileOwner(t) == OWNER_WATER &&
1697  TileHeight(t) != 0) {
1699  }
1700  }
1701  }
1702 
1703  /*
1704  * Add the 'previous' owner to the ship depots so we can reset it with
1705  * the correct values when it gets destroyed. This prevents that
1706  * someone can remove canals owned by somebody else and it prevents
1707  * making floods using the removal of ship depots.
1708  */
1710  for (auto t : Map::Iterate()) {
1711  if (IsShipDepotTile(t)) {
1712  t.m4() = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
1713  }
1714  }
1715  }
1716 
1718  for (Station *st : Station::Iterate()) {
1719  for (GoodsEntry &ge : st->goods) {
1720  ge.last_speed = 0;
1722  }
1723  }
1724  }
1725 
1726  /* At version 78, industry cargo types can be changed, and are stored with the industry. For older save versions
1727  * copy the IndustrySpec's cargo types over to the Industry. */
1729  for (Industry *i : Industry::Iterate()) {
1730  const IndustrySpec *indsp = GetIndustrySpec(i->type);
1731  for (uint j = 0; j < std::size(i->produced); j++) {
1732  i->produced[j].cargo = indsp->produced_cargo[j];
1733  }
1734  for (uint j = 0; j < std::size(i->accepted); j++) {
1735  i->accepted[j].cargo = indsp->accepts_cargo[j];
1736  }
1737  }
1738  }
1739 
1740  /* Industry cargo slots were fixed size before (and including) SLV_VEHICLE_ECONOMY_AGE (either 2/3 or 16/16),
1741  * after this they are dynamic. Trim excess slots. */
1743  for (Industry *i : Industry::Iterate()) {
1745  }
1746  }
1747 
1748  /* Before version 81, the density of grass was always stored as zero, and
1749  * grassy trees were always drawn fully grassy. Furthermore, trees on rough
1750  * land used to have zero density, now they have full density. Therefore,
1751  * make all grassy/rough land trees have a density of 3. */
1753  for (auto t : Map::Iterate()) {
1754  if (GetTileType(t) == MP_TREES) {
1755  TreeGround groundType = (TreeGround)GB(t.m2(), 4, 2);
1756  if (groundType != TREE_GROUND_SNOW_DESERT) SB(t.m2(), 6, 2, 3);
1757  }
1758  }
1759  }
1760 
1761 
1763  /* Rework of orders. */
1764  for (Order *order : Order::Iterate()) order->ConvertFromOldSavegame();
1765 
1766  for (Vehicle *v : Vehicle::Iterate()) {
1767  if (v->orders != nullptr && v->orders->GetFirstOrder() != nullptr && v->orders->GetFirstOrder()->IsType(OT_NOTHING)) {
1768  v->orders->FreeChain();
1769  v->orders = nullptr;
1770  }
1771 
1772  v->current_order.ConvertFromOldSavegame();
1773  if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
1774  for (Order *order : v->Orders()) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
1775  }
1776  }
1777  } else if (IsSavegameVersionBefore(SLV_94)) {
1778  /* Unload and transfer are now mutual exclusive. */
1779  for (Order *order : Order::Iterate()) {
1780  if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1781  order->SetUnloadType(OUFB_TRANSFER);
1782  order->SetLoadType(OLFB_NO_LOAD);
1783  }
1784  }
1785 
1786  for (Vehicle *v : Vehicle::Iterate()) {
1787  if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1788  v->current_order.SetUnloadType(OUFB_TRANSFER);
1789  v->current_order.SetLoadType(OLFB_NO_LOAD);
1790  }
1791  }
1793  /* OrderDepotActionFlags were moved, instead of starting at bit 4 they now start at bit 3. */
1794  for (Order *order : Order::Iterate()) {
1795  if (!order->IsType(OT_GOTO_DEPOT)) continue;
1796  order->SetDepotActionType((OrderDepotActionFlags)(order->GetDepotActionType() >> 1));
1797  }
1798 
1799  for (Vehicle *v : Vehicle::Iterate()) {
1800  if (!v->current_order.IsType(OT_GOTO_DEPOT)) continue;
1801  v->current_order.SetDepotActionType((OrderDepotActionFlags)(v->current_order.GetDepotActionType() >> 1));
1802  }
1803  }
1804 
1805  /* The water class was moved/unified. */
1807  for (auto t : Map::Iterate()) {
1808  switch (GetTileType(t)) {
1809  case MP_STATION:
1810  switch (GetStationType(t)) {
1811  case STATION_OILRIG:
1812  case STATION_DOCK:
1813  case STATION_BUOY:
1814  SetWaterClass(t, (WaterClass)GB(t.m3(), 0, 2));
1815  SB(t.m3(), 0, 2, 0);
1816  break;
1817 
1818  default:
1820  break;
1821  }
1822  break;
1823 
1824  case MP_WATER:
1825  SetWaterClass(t, (WaterClass)GB(t.m3(), 0, 2));
1826  SB(t.m3(), 0, 2, 0);
1827  break;
1828 
1829  case MP_OBJECT:
1831  break;
1832 
1833  default:
1834  /* No water class. */
1835  break;
1836  }
1837  }
1838  }
1839 
1841  for (auto t : Map::Iterate()) {
1842  /* Move river flag and update canals to use water class */
1843  if (IsTileType(t, MP_WATER)) {
1844  if (GetWaterClass(t) != WATER_CLASS_RIVER) {
1845  if (IsWater(t)) {
1846  Owner o = GetTileOwner(t);
1847  if (o == OWNER_WATER) {
1848  MakeSea(t);
1849  } else {
1850  MakeCanal(t, o, Random());
1851  }
1852  } else if (IsShipDepot(t)) {
1853  Owner o = (Owner)t.m4(); // Original water owner
1855  }
1856  }
1857  }
1858  }
1859 
1860  /* Update locks, depots, docks and buoys to have a water class based
1861  * on its neighbouring tiles. Done after river and canal updates to
1862  * ensure neighbours are correct. */
1863  for (auto t : Map::Iterate()) {
1864  if (!IsTileFlat(t)) continue;
1865 
1867  if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
1868  }
1869  }
1870 
1872  for (auto t : Map::Iterate()) {
1873  /* skip oil rigs at borders! */
1874  if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
1875  (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == Map::MaxX() - 1 || TileY(t) == Map::MaxY() - 1)) {
1876  /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
1877  * This conversion has to be done before buoys with invalid owner are removed. */
1879  }
1880 
1881  if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
1882  Owner o = GetTileOwner(t);
1883  if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
1884  Backup<CompanyID> cur_company(_current_company, o);
1886  cur_company.Restore();
1887  }
1888  if (IsBuoyTile(t)) {
1889  /* reset buoy owner to OWNER_NONE in the station struct
1890  * (even if it is owned by active company) */
1892  }
1893  } else if (IsTileType(t, MP_ROAD)) {
1894  /* works for all RoadTileType */
1895  for (RoadTramType rtt : _roadtramtypes) {
1896  /* update even non-existing road types to update tile owner too */
1897  Owner o = GetRoadOwner(t, rtt);
1898  if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rtt, OWNER_NONE);
1899  }
1900  if (IsLevelCrossing(t)) {
1902  }
1903  } else if (IsPlainRailTile(t)) {
1905  }
1906  }
1907  }
1908 
1910  /* Profits are now with 8 bit fract */
1911  for (Vehicle *v : Vehicle::Iterate()) {
1912  v->profit_this_year <<= 8;
1913  v->profit_last_year <<= 8;
1914  v->running_ticks = 0;
1915  }
1916  }
1917 
1919  /* Increase HouseAnimationFrame from 5 to 7 bits */
1920  for (auto t : Map::Iterate()) {
1921  if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
1922  SB(t.m6(), 2, 6, GB(t.m6(), 3, 5));
1923  SB(t.m3(), 5, 1, 0);
1924  }
1925  }
1926  }
1927 
1929  GroupStatistics::UpdateAfterLoad(); // Ensure statistics pool is initialised before trying to delete vehicles
1930  /* Remove all trams from savegames without tram support.
1931  * There would be trams without tram track under causing crashes sooner or later. */
1932  for (RoadVehicle *v : RoadVehicle::Iterate()) {
1933  if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
1934  ShowErrorMessage(STR_WARNING_LOADGAME_REMOVED_TRAMS, INVALID_STRING_ID, WL_CRITICAL);
1935  delete v;
1936  }
1937  }
1938  }
1939 
1941  for (auto t : Map::Iterate()) {
1942  /* Set newly introduced WaterClass of industry tiles */
1943  if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
1945  }
1946  if (IsTileType(t, MP_INDUSTRY)) {
1947  if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
1949  } else {
1951  }
1952  }
1953 
1954  /* Replace "house construction year" with "house age" */
1955  if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
1956  t.m5() = ClampTo<uint8_t>(TimerGameCalendar::year - (t.m5() + CalendarTime::ORIGINAL_BASE_YEAR));
1957  }
1958  }
1959  }
1960 
1961  /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
1962  * format here, as an old layout wouldn't work properly anyway. To be safe, we
1963  * clear any possible PBS reservations as well. */
1965  for (auto t : Map::Iterate()) {
1966  switch (GetTileType(t)) {
1967  case MP_RAILWAY:
1968  if (HasSignals(t)) {
1969  /* move the signal variant */
1970  SetSignalVariant(t, TRACK_UPPER, HasBit(t.m2(), 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1971  SetSignalVariant(t, TRACK_LOWER, HasBit(t.m2(), 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1972  ClrBit(t.m2(), 2);
1973  ClrBit(t.m2(), 6);
1974  }
1975 
1976  /* Clear PBS reservation on track */
1977  if (IsRailDepot(t)) {
1978  SetDepotReservation(t, false);
1979  } else {
1981  }
1982  break;
1983 
1984  case MP_ROAD: // Clear PBS reservation on crossing
1985  if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
1986  break;
1987 
1988  case MP_STATION: // Clear PBS reservation on station
1989  if (HasStationRail(t)) SetRailStationReservation(t, false);
1990  break;
1991 
1992  case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/bridges
1994  break;
1995 
1996  default: break;
1997  }
1998  }
1999  }
2000 
2001  /* Reserve all tracks trains are currently on. */
2003  for (const Train *t : Train::Iterate()) {
2004  if (t->First() == t) t->ReserveTrackUnderConsist();
2005  }
2006  }
2007 
2009  /* Non-town-owned roads now store the closest town */
2011 
2012  /* signs with invalid owner left from older savegames */
2013  for (Sign *si : Sign::Iterate()) {
2014  if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
2015  }
2016 
2017  /* Station can get named based on an industry type, but the current ones
2018  * are not, so mark them as if they are not named by an industry. */
2019  for (Station *st : Station::Iterate()) {
2020  st->indtype = IT_INVALID;
2021  }
2022  }
2023 
2025  for (Aircraft *a : Aircraft::Iterate()) {
2026  /* Set engine_type of shadow and rotor */
2027  if (!a->IsNormalAircraft()) {
2028  a->engine_type = a->First()->engine_type;
2029  }
2030  }
2031 
2032  /* More companies ... */
2033  for (Company *c : Company::Iterate()) {
2034  if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = MAX_UVALUE(CompanyMask);
2035  }
2036 
2037  for (Engine *e : Engine::Iterate()) {
2038  if (e->company_avail == 0xFF) e->company_avail = MAX_UVALUE(CompanyMask);
2039  }
2040 
2041  for (Town *t : Town::Iterate()) {
2042  if (t->have_ratings == 0xFF) t->have_ratings = MAX_UVALUE(CompanyMask);
2043  for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
2044  }
2045  }
2046 
2048  for (auto t : Map::Iterate()) {
2049  /* Check for HQ bit being set, instead of using map accessor,
2050  * since we've already changed it code-wise */
2051  if (IsTileType(t, MP_OBJECT) && HasBit(t.m5(), 7)) {
2052  /* Move size and part identification of HQ out of the m5 attribute,
2053  * on new locations */
2054  t.m3() = GB(t.m5(), 0, 5);
2055  t.m5() = OBJECT_HQ;
2056  }
2057  }
2058  }
2060  for (auto t : Map::Iterate()) {
2061  if (!IsTileType(t, MP_OBJECT)) continue;
2062 
2063  /* Reordering/generalisation of the object bits. */
2064  ObjectType type = t.m5();
2065  SB(t.m6(), 2, 4, type == OBJECT_HQ ? GB(t.m3(), 2, 3) : 0);
2066  t.m3() = type == OBJECT_HQ ? GB(t.m3(), 1, 1) | GB(t.m3(), 0, 1) << 4 : 0;
2067 
2068  /* Make sure those bits are clear as well! */
2069  t.m4() = 0;
2070  t.m7() = 0;
2071  }
2072  }
2073 
2075  /* Make real objects for object tiles. */
2076  for (auto t : Map::Iterate()) {
2077  if (!IsTileType(t, MP_OBJECT)) continue;
2078 
2079  if (Town::GetNumItems() == 0) {
2080  /* No towns, so remove all objects! */
2081  DoClearSquare(t);
2082  } else {
2083  uint offset = t.m3();
2084 
2085  /* Also move the animation state. */
2086  t.m3() = GB(t.m6(), 2, 4);
2087  SB(t.m6(), 2, 4, 0);
2088 
2089  if (offset == 0) {
2090  /* No offset, so make the object. */
2091  ObjectType type = t.m5();
2092  int size = type == OBJECT_HQ ? 2 : 1;
2093 
2094  if (!Object::CanAllocateItem()) {
2095  /* Nice... you managed to place 64k lighthouses and
2096  * antennae on the map... boohoo. */
2097  SlError(STR_ERROR_TOO_MANY_OBJECTS);
2098  }
2099 
2100  Object *o = new Object();
2101  o->location.tile = (TileIndex)t;
2102  o->location.w = size;
2103  o->location.h = size;
2105  o->town = type == OBJECT_STATUE ? Town::Get(t.m2()) : CalcClosestTownFromTile(t, UINT_MAX);
2106  t.m2() = o->index;
2107  Object::IncTypeCount(type);
2108  } else {
2109  /* We're at an offset, so get the ID from our "root". */
2110  Tile northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
2111  assert(IsTileType(northern_tile, MP_OBJECT));
2112  t.m2() = northern_tile.m2();
2113  }
2114  }
2115  }
2116  }
2117 
2119  /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
2120  if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
2123  } else {
2126  }
2127 
2128  /* Initialize layout of all towns. Older versions were using different
2129  * generator for random town layout, use it if needed. */
2130  for (Town *t : Town::Iterate()) {
2132  t->layout = _settings_game.economy.town_layout;
2133  continue;
2134  }
2135 
2136  /* Use old layout randomizer code */
2137  uint8_t layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
2138  switch (layout) {
2139  default: break;
2140  case 5: layout = 1; break;
2141  case 0: layout = 2; break;
2142  }
2143  t->layout = static_cast<TownLayout>(layout - 1);
2144  }
2145  }
2146 
2148  /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
2149  * The conversion affects oil rigs and buoys too, but it doesn't matter as
2150  * they have st->owner == OWNER_NONE already. */
2151  for (Station *st : Station::Iterate()) {
2152  if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
2153  }
2154  }
2155 
2156  /* Trains could now stop in a specific location. */
2158  for (Order *o : Order::Iterate()) {
2159  if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
2160  }
2161  }
2162 
2165  for (Company *c : Company::Iterate()) {
2166  c->settings.vehicle = _old_vds;
2167  }
2168  }
2169 
2171  /* Delete small ufos heading for non-existing vehicles */
2173  if (v->subtype == 2 /* ST_SMALL_UFO */ && v->state != 0) {
2174  const Vehicle *u = Vehicle::GetIfValid(v->dest_tile.base());
2175  if (u == nullptr || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
2176  delete v;
2177  }
2178  }
2179  }
2180 
2181  /* We didn't store cargo payment yet, so make them for vehicles that are
2182  * currently at a station and loading/unloading. If they don't get any
2183  * payment anymore they just removed in the next load/unload cycle.
2184  * However, some 0.7 versions might have cargo payment. For those we just
2185  * add cargopayment for the vehicles that don't have it.
2186  */
2187  for (Station *st : Station::Iterate()) {
2188  for (Vehicle *v : st->loading_vehicles) {
2189  /* There are always as many CargoPayments as Vehicles. We need to make the
2190  * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
2193  if (v->cargo_payment == nullptr) v->cargo_payment = new CargoPayment(v);
2194  }
2195  }
2196  }
2197 
2199  /* Animated tiles would sometimes not be actually animated or
2200  * in case of old savegames duplicate. */
2201 
2202  extern std::vector<TileIndex> _animated_tiles;
2203 
2204  for (auto tile = _animated_tiles.begin(); tile < _animated_tiles.end(); /* Nothing */) {
2205  /* Remove if tile is not animated */
2206  bool remove = _tile_type_procs[GetTileType(*tile)]->animate_tile_proc == nullptr;
2207 
2208  /* and remove if duplicate */
2209  for (auto j = _animated_tiles.begin(); !remove && j < tile; j++) {
2210  remove = *tile == *j;
2211  }
2212 
2213  if (remove) {
2214  tile = _animated_tiles.erase(tile);
2215  } else {
2216  tile++;
2217  }
2218  }
2219  }
2220 
2222  for (auto t : Map::Iterate()) {
2223  if (!IsTileType(t, MP_WATER)) continue;
2224  SetNonFloodingWaterTile(t, false);
2225  }
2226  }
2227 
2229  /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
2230  for (Waypoint *wp : Waypoint::Iterate()) {
2231  if (wp->facilities & FACIL_TRAIN) {
2232  wp->train_station.tile = wp->xy;
2233  wp->train_station.w = 1;
2234  wp->train_station.h = 1;
2235  } else {
2236  wp->train_station.tile = INVALID_TILE;
2237  wp->train_station.w = 0;
2238  wp->train_station.h = 0;
2239  }
2240  }
2241  }
2242 
2244  /* Convert old subsidies */
2245  for (Subsidy *s : Subsidy::Iterate()) {
2246  if (s->remaining < 12) {
2247  /* Converting nonawarded subsidy */
2248  s->remaining = 12 - s->remaining; // convert "age" to "remaining"
2249  s->awarded = INVALID_COMPANY; // not awarded to anyone
2250  const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2251  switch (cs->town_acceptance_effect) {
2252  case TAE_PASSENGERS:
2253  case TAE_MAIL:
2254  /* Town -> Town */
2255  s->src_type = s->dst_type = SourceType::Town;
2256  if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2257  break;
2258  case TAE_GOODS:
2259  case TAE_FOOD:
2260  /* Industry -> Town */
2261  s->src_type = SourceType::Industry;
2262  s->dst_type = SourceType::Town;
2263  if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2264  break;
2265  default:
2266  /* Industry -> Industry */
2267  s->src_type = s->dst_type = SourceType::Industry;
2268  if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
2269  break;
2270  }
2271  } else {
2272  /* Do our best for awarded subsidies. The original source or destination industry
2273  * can't be determined anymore for awarded subsidies, so invalidate them.
2274  * Town -> Town subsidies are converted using simple heuristic */
2275  s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
2276  const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2277  switch (cs->town_acceptance_effect) {
2278  case TAE_PASSENGERS:
2279  case TAE_MAIL: {
2280  /* Town -> Town */
2281  const Station *ss = Station::GetIfValid(s->src);
2282  const Station *sd = Station::GetIfValid(s->dst);
2283  if (ss != nullptr && sd != nullptr && ss->owner == sd->owner &&
2284  Company::IsValidID(ss->owner)) {
2285  s->src_type = s->dst_type = SourceType::Town;
2286  s->src = ss->town->index;
2287  s->dst = sd->town->index;
2288  s->awarded = ss->owner;
2289  continue;
2290  }
2291  break;
2292  }
2293  default:
2294  break;
2295  }
2296  }
2297  /* Awarded non-town subsidy or invalid source/destination, invalidate */
2298  delete s;
2299  }
2300  }
2301 
2303  /* Recompute inflation based on old unround loan limit
2304  * Note: Max loan is 500000. With an inflation of 4% across 170 years
2305  * that results in a max loan of about 0.7 * 2^31.
2306  * So taking the 16 bit fractional part into account there are plenty of bits left
2307  * for unmodified savegames ...
2308  */
2309  uint64_t aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
2310 
2311  /* ... well, just clamp it then. */
2312  if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
2313 
2314  /* Simulate the inflation, so we also get the payment inflation */
2315  while (_economy.inflation_prices < aimed_inflation) {
2316  if (AddInflation(false)) break;
2317  }
2318  }
2319 
2321  for (const Depot *d : Depot::Iterate()) {
2322  Tile tile = d->xy;
2323  /* At some point, invalid depots were saved into the game (possibly those removed in the past?)
2324  * Remove them here, so they don't cause issues further down the line */
2325  if (!IsDepotTile(tile)) {
2326  Debug(sl, 0, "Removing invalid depot {} at {}, {}", d->index, TileX(d->xy), TileY(d->xy));
2327  delete d;
2328  d = nullptr;
2329  continue;
2330  }
2331  tile.m2() = d->index;
2332  if (IsTileType(tile, MP_WATER)) Tile(GetOtherShipDepotTile(tile)).m2() = d->index;
2333  }
2334  }
2335 
2336  /* The behaviour of force_proceed has been changed. Now
2337  * it counts signals instead of some random time out. */
2339  for (Train *t : Train::Iterate()) {
2340  if (t->force_proceed != TFP_NONE) {
2341  t->force_proceed = TFP_STUCK;
2342  }
2343  }
2344  }
2345 
2346  /* The bits for the tree ground and tree density have
2347  * been swapped (m2 bits 7..6 and 5..4. */
2349  for (auto t : Map::Iterate()) {
2350  if (IsTileType(t, MP_CLEAR)) {
2351  if (GetRawClearGround(t) == CLEAR_SNOW) {
2353  SetBit(t.m3(), 4);
2354  } else {
2355  ClrBit(t.m3(), 4);
2356  }
2357  }
2358  if (IsTileType(t, MP_TREES)) {
2359  uint density = GB(t.m2(), 6, 2);
2360  uint ground = GB(t.m2(), 4, 2);
2361  t.m2() = ground << 6 | density << 4;
2362  }
2363  }
2364  }
2365 
2366  /* Wait counter and load/unload ticks got split. */
2368  for (Aircraft *a : Aircraft::Iterate()) {
2369  a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
2370  }
2371 
2372  for (Train *t : Train::Iterate()) {
2373  t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
2374  }
2375  }
2376 
2377  /* Airport tile animation uses animation frame instead of other graphics id */
2379  struct AirportTileConversion {
2380  uint8_t old_start;
2381  uint8_t num_frames;
2382  };
2383  static const AirportTileConversion atcs[] = {
2384  {31, 12}, // APT_RADAR_GRASS_FENCE_SW
2385  {50, 4}, // APT_GRASS_FENCE_NE_FLAG
2386  {62, 2}, // 1 unused tile
2387  {66, 12}, // APT_RADAR_FENCE_SW
2388  {78, 12}, // APT_RADAR_FENCE_NE
2389  {101, 10}, // 9 unused tiles
2390  {111, 8}, // 7 unused tiles
2391  {119, 15}, // 14 unused tiles (radar)
2392  {140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
2393  };
2394  for (auto t : Map::Iterate()) {
2395  if (IsAirportTile(t)) {
2396  StationGfx old_gfx = GetStationGfx(t);
2397  uint8_t offset = 0;
2398  for (const auto &atc : atcs) {
2399  if (old_gfx < atc.old_start) {
2400  SetStationGfx(t, old_gfx - offset);
2401  break;
2402  }
2403  if (old_gfx < atc.old_start + atc.num_frames) {
2404  SetAnimationFrame(t, old_gfx - atc.old_start);
2405  SetStationGfx(t, atc.old_start - offset);
2406  break;
2407  }
2408  offset += atc.num_frames - 1;
2409  }
2410  }
2411  }
2412  }
2413 
2414  /* Oilrig was moved from id 15 to 9. */
2416  for (Station *st : Station::Iterate()) {
2417  if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
2418  st->airport.type = AT_OILRIG;
2419  }
2420  }
2421  }
2422 
2424  for (Station *st : Station::Iterate()) {
2425  if (st->airport.tile != INVALID_TILE) {
2426  st->airport.w = st->airport.GetSpec()->size_x;
2427  st->airport.h = st->airport.GetSpec()->size_y;
2428  }
2429  }
2430  }
2431 
2433  for (auto t : Map::Iterate()) {
2434  /* Reset tropic zone for VOID tiles, they shall not have any. */
2436  }
2437 
2438  /* We need to properly number/name the depots.
2439  * The first step is making sure none of the depots uses the
2440  * 'default' names, after that we can assign the names. */
2441  for (Depot *d : Depot::Iterate()) d->town_cn = UINT16_MAX;
2442 
2443  for (Depot *d : Depot::Iterate()) MakeDefaultName(d);
2444  }
2445 
2447  for (Depot *d : Depot::Iterate()) d->build_date = TimerGameCalendar::date;
2448  }
2449 
2450  /* In old versions it was possible to remove an airport while a plane was
2451  * taking off or landing. This gives all kind of problems when building
2452  * another airport in the same station so we don't allow that anymore.
2453  * For old savegames with such aircraft we just throw them in the air and
2454  * treat the aircraft like they were flying already. */
2456  for (Aircraft *v : Aircraft::Iterate()) {
2457  if (!v->IsNormalAircraft()) continue;
2459  if (st == nullptr && v->state != FLYING) {
2460  v->state = FLYING;
2463  /* get aircraft back on running altitude */
2464  if ((v->vehstatus & VS_CRASHED) == 0) {
2465  GetAircraftFlightLevelBounds(v, &v->z_pos, nullptr);
2466  SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
2467  }
2468  }
2469  }
2470  }
2471 
2472  /* Move the animation frame to the same location (m7) for all objects. */
2474  for (auto t : Map::Iterate()) {
2475  switch (GetTileType(t)) {
2476  case MP_HOUSE:
2477  if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
2478  uint per_proc = t.m7();
2479  t.m7() = GB(t.m6(), 2, 6) | (GB(t.m3(), 5, 1) << 6);
2480  SB(t.m3(), 5, 1, 0);
2481  SB(t.m6(), 2, 6, std::min(per_proc, 63U));
2482  }
2483  break;
2484 
2485  case MP_INDUSTRY: {
2486  uint rand = t.m7();
2487  t.m7() = t.m3();
2488  t.m3() = rand;
2489  break;
2490  }
2491 
2492  case MP_OBJECT:
2493  t.m7() = t.m3();
2494  t.m3() = 0;
2495  break;
2496 
2497  default:
2498  /* For stations/airports it's already at m7 */
2499  break;
2500  }
2501  }
2502  }
2503 
2504  /* Add (random) colour to all objects. */
2506  for (Object *o : Object::Iterate()) {
2507  Owner owner = GetTileOwner(o->location.tile);
2508  o->colour = (owner == OWNER_NONE) ? static_cast<Colours>(GB(Random(), 0, 4)) : Company::Get(owner)->livery->colour1;
2509  }
2510  }
2511 
2513  for (auto t : Map::Iterate()) {
2514  if (!IsTileType(t, MP_STATION)) continue;
2515  if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && IsTileFlat(t))) {
2517  }
2518  }
2519 
2520  /* Waypoints with custom name may have a non-unique town_cn,
2521  * renumber those. First set all affected waypoints to the
2522  * highest possible number to get them numbered in the
2523  * order they have in the pool. */
2524  for (Waypoint *wp : Waypoint::Iterate()) {
2525  if (!wp->name.empty()) wp->town_cn = UINT16_MAX;
2526  }
2527 
2528  for (Waypoint *wp : Waypoint::Iterate()) {
2529  if (!wp->name.empty()) MakeDefaultName(wp);
2530  }
2531  }
2532 
2534  _industry_builder.Reset(); // Initialize industry build data.
2535 
2536  /* The moment vehicles go from hidden to visible changed. This means
2537  * that vehicles don't always get visible anymore causing things to
2538  * get messed up just after loading the savegame. This fixes that. */
2539  for (Vehicle *v : Vehicle::Iterate()) {
2540  /* Not all vehicle types can be inside a tunnel. Furthermore,
2541  * testing IsTunnelTile() for invalid tiles causes a crash. */
2542  if (!v->IsGroundVehicle()) continue;
2543 
2544  /* Is the vehicle in a tunnel? */
2545  if (!IsTunnelTile(v->tile)) continue;
2546 
2547  /* Is the vehicle actually at a tunnel entrance/exit? */
2548  TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
2549  if (!IsTunnelTile(vtile)) continue;
2550 
2551  /* Are we actually in this tunnel? Or maybe a lower tunnel? */
2552  if (GetSlopePixelZ(v->x_pos, v->y_pos, true) != v->z_pos) continue;
2553 
2554  /* What way are we going? */
2555  const DiagDirection dir = GetTunnelBridgeDirection(vtile);
2556  const DiagDirection vdir = DirToDiagDir(v->direction);
2557 
2558  /* Have we passed the visibility "switch" state already? */
2559  uint8_t pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
2560  uint8_t frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2561  extern const uint8_t _tunnel_visibility_frame[DIAGDIR_END];
2562 
2563  /* Should the vehicle be hidden or not? */
2564  bool hidden;
2565  if (dir == vdir) { // Entering tunnel
2566  hidden = frame >= _tunnel_visibility_frame[dir];
2567  v->tile = vtile;
2568  } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
2569  hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
2570  /* v->tile changes at the moment when the vehicle leaves the tunnel. */
2571  v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
2572  } else {
2573  /* We could get here in two cases:
2574  * - for road vehicles, it is reversing at the end of the tunnel
2575  * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
2576  * Whatever case it is, do not change anything and use the old values.
2577  * Especially changing RV's state would break its reversing in the middle. */
2578  continue;
2579  }
2580 
2581  if (hidden) {
2582  v->vehstatus |= VS_HIDDEN;
2583 
2584  switch (v->type) {
2585  case VEH_TRAIN: Train::From(v)->track = TRACK_BIT_WORMHOLE; break;
2586  case VEH_ROAD: RoadVehicle::From(v)->state = RVSB_WORMHOLE; break;
2587  default: NOT_REACHED();
2588  }
2589  } else {
2590  v->vehstatus &= ~VS_HIDDEN;
2591 
2592  switch (v->type) {
2593  case VEH_TRAIN: Train::From(v)->track = DiagDirToDiagTrackBits(vdir); break;
2594  case VEH_ROAD: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
2595  default: NOT_REACHED();
2596  }
2597  }
2598  }
2599  }
2600 
2602  for (RoadVehicle *rv : RoadVehicle::Iterate()) {
2603  if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
2604 
2605  bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
2606  if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
2607  extern const uint8_t _road_stop_stop_frame[];
2608  SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > _road_stop_stop_frame[rv->state - RVSB_IN_ROAD_STOP + (_settings_game.vehicle.road_side << RVS_DRIVE_SIDE)]);
2609  } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
2610  SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
2611  }
2612  }
2613  }
2614 
2616  /* The train's pathfinder lost flag got moved. */
2617  for (Train *t : Train::Iterate()) {
2618  if (!HasBit(t->flags, 5)) continue;
2619 
2620  ClrBit(t->flags, 5);
2621  SetBit(t->vehicle_flags, VF_PATHFINDER_LOST);
2622  }
2623 
2624  /* Introduced terraform/clear limits. */
2625  for (Company *c : Company::Iterate()) {
2626  c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
2627  c->clear_limit = _settings_game.construction.clear_frame_burst << 16;
2628  }
2629  }
2630 
2631 
2633  /*
2634  * The logic of GetPartialPixelZ has been changed, so the resulting Zs on
2635  * the map are consistent. This requires that the Z position of some
2636  * vehicles is updated to reflect this new situation.
2637  *
2638  * This needs to be before SLV_158, because that performs asserts using
2639  * GetSlopePixelZ which internally uses GetPartialPixelZ.
2640  */
2641  for (Vehicle *v : Vehicle::Iterate()) {
2642  if (v->IsGroundVehicle() && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2643  /* Vehicle is on the ground, and not in a wormhole. */
2644  v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos, true);
2645  }
2646  }
2647  }
2648 
2650  for (Vehicle *v : Vehicle::Iterate()) {
2651  switch (v->type) {
2652  case VEH_TRAIN: {
2653  Train *t = Train::From(v);
2654 
2655  /* Clear old GOINGUP / GOINGDOWN flags.
2656  * It was changed in savegame version 139, but savegame
2657  * version 158 doesn't use these bits, so it doesn't hurt
2658  * to clear them unconditionally. */
2659  ClrBit(t->flags, 1);
2660  ClrBit(t->flags, 2);
2661 
2662  /* Clear both bits first. */
2665 
2666  /* Crashed vehicles can't be going up/down. */
2667  if (t->vehstatus & VS_CRASHED) break;
2668 
2669  /* Only X/Y tracks can be sloped. */
2670  if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
2671 
2673  break;
2674  }
2675  case VEH_ROAD: {
2676  RoadVehicle *rv = RoadVehicle::From(v);
2679 
2680  /* Crashed vehicles can't be going up/down. */
2681  if (rv->vehstatus & VS_CRASHED) break;
2682 
2683  if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
2684 
2685  TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, GetRoadTramType(rv->roadtype));
2686  TrackBits trackbits = TrackStatusToTrackBits(ts);
2687 
2688  /* Only X/Y tracks can be sloped. */
2689  if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
2690 
2691  Direction dir = rv->direction;
2692 
2693  /* Test if we are reversing. */
2694  Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
2695  if (AxisToDirection(a) != dir &&
2696  AxisToDirection(a) != ReverseDir(dir)) {
2697  /* When reversing, the road vehicle is on the edge of the tile,
2698  * so it can be safely compared to the middle of the tile. */
2699  dir = INVALID_DIR;
2700  }
2701 
2702  rv->gv_flags |= FixVehicleInclination(rv, dir);
2703  break;
2704  }
2705  case VEH_SHIP:
2706  break;
2707 
2708  default:
2709  continue;
2710  }
2711 
2712  if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2713  /* In old versions, z_pos was 1 unit lower on bridge heads.
2714  * However, this invalid state could be converted to new savegames
2715  * by loading and saving the game in a new version. */
2716  v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos, true);
2717  DiagDirection dir = GetTunnelBridgeDirection(v->tile);
2718  if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
2719  v->direction != DiagDirToDir(dir)) {
2720  /* If the train has left the bridge, it shouldn't have
2721  * track == TRACK_BIT_WORMHOLE - this could happen
2722  * when the train was reversed while on the last "tick"
2723  * on the ramp before leaving the ramp to the bridge. */
2724  Train::From(v)->track = DiagDirToDiagTrackBits(dir);
2725  }
2726  }
2727 
2728  /* If the vehicle is really above v->tile (not in a wormhole),
2729  * it should have set v->z_pos correctly. */
2730  assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos, true));
2731  }
2732 
2733  /* Fill Vehicle::cur_real_order_index */
2734  for (Vehicle *v : Vehicle::Iterate()) {
2735  if (!v->IsPrimaryVehicle()) continue;
2736 
2737  /* Older versions are less strict with indices being in range and fix them on the fly */
2738  if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
2739 
2740  v->cur_real_order_index = v->cur_implicit_order_index;
2741  v->UpdateRealOrderIndex();
2742  }
2743  }
2744 
2746  /* If the savegame is old (before version 100), then the value of 255
2747  * for these settings did not mean "disabled". As such everything
2748  * before then did reverse.
2749  * To simplify stuff we disable all turning around or we do not
2750  * disable anything at all. So, if some reversing was disabled we
2751  * will keep reversing disabled, otherwise it'll be turned on. */
2753 
2754  for (Train *t : Train::Iterate()) {
2755  _settings_game.vehicle.max_train_length = std::max<uint8_t>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
2756  }
2757  }
2758 
2760  /* Setting difficulty industry_density other than zero get bumped to +1
2761  * since a new option (minimal at position 1) has been added */
2764  }
2765  }
2766 
2768  /* Before savegame version 161, persistent storages were not stored in a pool. */
2769 
2771  for (Industry *ind : Industry::Iterate()) {
2772  assert(ind->psa != nullptr);
2773 
2774  /* Check if the old storage was empty. */
2775  bool is_empty = true;
2776  for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
2777  if (ind->psa->GetValue(i) != 0) {
2778  is_empty = false;
2779  break;
2780  }
2781  }
2782 
2783  if (!is_empty) {
2784  ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
2785  } else {
2786  delete ind->psa;
2787  ind->psa = nullptr;
2788  }
2789  }
2790  }
2791 
2793  for (Station *st : Station::Iterate()) {
2794  if (!(st->facilities & FACIL_AIRPORT)) continue;
2795  assert(st->airport.psa != nullptr);
2796 
2797  /* Check if the old storage was empty. */
2798  bool is_empty = true;
2799  for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
2800  if (st->airport.psa->GetValue(i) != 0) {
2801  is_empty = false;
2802  break;
2803  }
2804  }
2805 
2806  if (!is_empty) {
2807  st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
2808  } else {
2809  delete st->airport.psa;
2810  st->airport.psa = nullptr;
2811 
2812  }
2813  }
2814  }
2815  }
2816 
2817  /* This triggers only when old snow_lines were copied into the snow_line_height. */
2820  }
2821 
2823  /* We store 4 fences in the field tiles instead of only SE and SW. */
2824  for (auto t : Map::Iterate()) {
2825  if (!IsTileType(t, MP_CLEAR) && !IsTileType(t, MP_TREES)) continue;
2826  if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) continue;
2827  uint fence = GB(t.m4(), 5, 3);
2828  if (fence != 0 && IsTileType(TileAddXY(t, 1, 0), MP_CLEAR) && IsClearGround(TileAddXY(t, 1, 0), CLEAR_FIELDS)) {
2829  SetFence(TileAddXY(t, 1, 0), DIAGDIR_NE, fence);
2830  }
2831  fence = GB(t.m4(), 2, 3);
2832  if (fence != 0 && IsTileType(TileAddXY(t, 0, 1), MP_CLEAR) && IsClearGround(TileAddXY(t, 0, 1), CLEAR_FIELDS)) {
2833  SetFence(TileAddXY(t, 0, 1), DIAGDIR_NW, fence);
2834  }
2835  SB(t.m4(), 2, 3, 0);
2836  SB(t.m4(), 5, 3, 0);
2837  }
2838  }
2839 
2841  for (Town *t : Town::Iterate()) {
2842  /* Set the default cargo requirement for town growth */
2844  case LT_ARCTIC:
2846  break;
2847 
2848  case LT_TROPIC:
2851  break;
2852  }
2853  }
2854  }
2855 
2857  /* Adjust zoom level to account for new levels */
2858  _saved_scrollpos_zoom = static_cast<ZoomLevel>(_saved_scrollpos_zoom + ZOOM_BASE_SHIFT);
2859  _saved_scrollpos_x *= ZOOM_BASE;
2860  _saved_scrollpos_y *= ZOOM_BASE;
2861  }
2862 
2863  /* When any NewGRF has been changed the availability of some vehicles might
2864  * have been changed too. e->company_avail must be set to 0 in that case
2865  * which is done by StartupEngines(). */
2866  if (gcf_res != GLC_ALL_GOOD) StartupEngines();
2867 
2868  /* The road owner of standard road stops was not properly accounted for. */
2870  for (auto t : Map::Iterate()) {
2871  if (!IsBayRoadStopTile(t)) continue;
2872  Owner o = GetTileOwner(t);
2873  SetRoadOwner(t, RTT_ROAD, o);
2874  SetRoadOwner(t, RTT_TRAM, o);
2875  }
2876  }
2877 
2879  /* Introduced tree planting limit. */
2880  for (Company *c : Company::Iterate()) c->tree_limit = _settings_game.construction.tree_frame_burst << 16;
2881  }
2882 
2884  /* Fix too high inflation rates */
2885  if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
2887 
2888  /* We have to convert the quarters of bankruptcy into months of bankruptcy */
2889  for (Company *c : Company::Iterate()) {
2890  c->months_of_bankruptcy = 3 * c->months_of_bankruptcy;
2891  }
2892  }
2893 
2894  {
2895  /* Station blocked, wires and pylon flags need to be stored in the map. This is effectively cached data, so no
2896  * version check is necessary. This is done here as the SLV_182 check below needs the blocked status. */
2897  for (auto t : Map::Iterate()) {
2898  if (HasStationTileRail(t)) SetRailStationTileFlags(t, GetStationSpec(t));
2899  }
2900  }
2901 
2903  /* Aircraft acceleration variable was bonkers */
2904  for (Aircraft *v : Aircraft::Iterate()) {
2905  if (v->subtype <= AIR_AIRCRAFT) {
2906  const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
2907  v->acceleration = avi->acceleration;
2908  }
2909  }
2910 
2911  /* Blocked tiles could be reserved due to a bug, which causes
2912  * other places to assert upon e.g. station reconstruction. */
2913  for (auto t : Map::Iterate()) {
2915  SetRailStationReservation(t, false);
2916  }
2917  }
2918  }
2919 
2921  /* The global units configuration is split up in multiple configurations. */
2922  extern uint8_t _old_units;
2923  _settings_game.locale.units_velocity = Clamp(_old_units, 0, 2);
2924  _settings_game.locale.units_power = Clamp(_old_units, 0, 2);
2925  _settings_game.locale.units_weight = Clamp(_old_units, 1, 2);
2926  _settings_game.locale.units_volume = Clamp(_old_units, 1, 2);
2928  _settings_game.locale.units_height = Clamp(_old_units, 0, 2);
2929  }
2930 
2932  /* Match nautical velocity with land velocity units. */
2934  }
2935 
2937  /* Move ObjectType from map to pool */
2938  for (auto t : Map::Iterate()) {
2939  if (IsTileType(t, MP_OBJECT)) {
2940  Object *o = Object::Get(t.m2());
2941  o->type = t.m5();
2942  t.m5() = 0; // zero upper bits of (now bigger) ObjectID
2943  }
2944  }
2945  }
2946 
2947  /* Beyond this point, tile types which can be accessed by vehicles must be in a valid state. */
2948 
2949  /* Update all vehicles: Phase 2 */
2951 
2952  /* The center of train vehicles was changed, fix up spacing. */
2954 
2955  /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
2956  * This has to be called after all map array updates */
2958 
2960  /* Fix articulated road vehicles.
2961  * Some curves were shorter than other curves.
2962  * Now they have the same length, but that means that trailing articulated parts will
2963  * take longer to go through the curve than the parts in front which already left the courve.
2964  * So, make articulated parts catch up. */
2965  bool roadside = _settings_game.vehicle.road_side == 1;
2966  std::vector<uint> skip_frames;
2967  for (RoadVehicle *v : RoadVehicle::Iterate()) {
2968  if (!v->IsFrontEngine()) continue;
2969  skip_frames.clear();
2970  TileIndex prev_tile = v->tile;
2971  uint prev_tile_skip = 0;
2972  uint cur_skip = 0;
2973  for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
2974  if (u->tile != prev_tile) {
2975  prev_tile_skip = cur_skip;
2976  prev_tile = u->tile;
2977  } else {
2978  cur_skip = prev_tile_skip;
2979  }
2980 
2981  uint &this_skip = skip_frames.emplace_back(prev_tile_skip);
2982 
2983  /* The following 3 curves now take longer than before */
2984  switch (u->state) {
2985  case 2:
2986  cur_skip++;
2987  if (u->frame <= (roadside ? 9 : 5)) this_skip = cur_skip;
2988  break;
2989 
2990  case 4:
2991  cur_skip++;
2992  if (u->frame <= (roadside ? 5 : 9)) this_skip = cur_skip;
2993  break;
2994 
2995  case 5:
2996  cur_skip++;
2997  if (u->frame <= (roadside ? 4 : 2)) this_skip = cur_skip;
2998  break;
2999 
3000  default:
3001  break;
3002  }
3003  }
3004  while (cur_skip > skip_frames[0]) {
3005  RoadVehicle *u = v;
3006  RoadVehicle *prev = nullptr;
3007  for (uint sf : skip_frames) {
3008  if (sf >= cur_skip) IndividualRoadVehicleController(u, prev);
3009 
3010  prev = u;
3011  u = u->Next();
3012  }
3013  cur_skip--;
3014  }
3015  }
3016  }
3017 
3019  for (Order *order : Order::Iterate()) {
3020  order->SetTravelTimetabled(order->GetTravelTime() > 0);
3021  order->SetWaitTimetabled(order->GetWaitTime() > 0);
3022  }
3023  for (OrderList *orderlist : OrderList::Iterate()) {
3024  orderlist->RecalculateTimetableDuration();
3025  }
3026  }
3027 
3028  /*
3029  * Only keep order-backups for network clients (and when replaying).
3030  * If we are a network server or not networking, then we just loaded a previously
3031  * saved-by-server savegame. There are no clients with a backup, so clear it.
3032  * Furthermore before savegame version SLV_192 the actual content was always corrupt.
3033  */
3035 #ifndef DEBUG_DUMP_COMMANDS
3036  /* Note: We cannot use CleanPool since that skips part of the destructor
3037  * and then leaks un-reachable Orders in the order pool. */
3038  for (OrderBackup *ob : OrderBackup::Iterate()) {
3039  delete ob;
3040  }
3041 #endif
3042  }
3043 
3045  /* Convert towns growth_rate and grow_counter to ticks */
3046  for (Town *t : Town::Iterate()) {
3047  /* 0x8000 = TOWN_GROWTH_RATE_CUSTOM previously */
3048  if (t->growth_rate & 0x8000) SetBit(t->flags, TOWN_CUSTOM_GROWTH);
3049  if (t->growth_rate != TOWN_GROWTH_RATE_NONE) {
3050  t->growth_rate = TownTicksToGameTicks(t->growth_rate & ~0x8000);
3051  }
3052  /* Add t->index % TOWN_GROWTH_TICKS to spread growth across ticks. */
3053  t->grow_counter = TownTicksToGameTicks(t->grow_counter) + t->index % Ticks::TOWN_GROWTH_TICKS;
3054  }
3055  }
3056 
3058  /* Make sure added industry cargo slots are cleared */
3059  for (Industry *i : Industry::Iterate()) {
3060  /* Make sure last_cargo_accepted_at is copied to elements for every valid input cargo.
3061  * The loading routine should put the original singular value into the first array element. */
3062  for (auto &a : i->accepted) {
3063  if (IsValidCargoID(a.cargo)) {
3064  a.last_accepted = i->GetAccepted(0).last_accepted;
3065  } else {
3066  a.last_accepted = 0;
3067  }
3068  }
3069  }
3070  }
3071 
3073  /* Move ships from lock slope to upper or lower position. */
3074  for (Ship *s : Ship::Iterate()) {
3075  /* Suitable tile? */
3076  if (!IsTileType(s->tile, MP_WATER) || !IsLock(s->tile) || GetLockPart(s->tile) != LOCK_PART_MIDDLE) continue;
3077 
3078  /* We don't need to adjust position when at the tile centre */
3079  int x = s->x_pos & 0xF;
3080  int y = s->y_pos & 0xF;
3081  if (x == 8 && y == 8) continue;
3082 
3083  /* Test if ship is on the second half of the tile */
3084  bool second_half;
3085  DiagDirection shipdiagdir = DirToDiagDir(s->direction);
3086  switch (shipdiagdir) {
3087  default: NOT_REACHED();
3088  case DIAGDIR_NE: second_half = x < 8; break;
3089  case DIAGDIR_NW: second_half = y < 8; break;
3090  case DIAGDIR_SW: second_half = x > 8; break;
3091  case DIAGDIR_SE: second_half = y > 8; break;
3092  }
3093 
3094  DiagDirection slopediagdir = GetInclinedSlopeDirection(GetTileSlope(s->tile));
3095 
3096  /* Heading up slope == passed half way */
3097  if ((shipdiagdir == slopediagdir) == second_half) {
3098  /* On top half of lock */
3099  s->z_pos = GetTileMaxZ(s->tile) * (int)TILE_HEIGHT;
3100  } else {
3101  /* On lower half of lock */
3102  s->z_pos = GetTileZ(s->tile) * (int)TILE_HEIGHT;
3103  }
3104  }
3105  }
3106 
3108  /* Ensure the original cargo generation mode is used */
3110  }
3111 
3113  /* Ensure the original neutral industry/station behaviour is used */
3115 
3116  /* Link oil rigs to their industry and back. */
3117  for (Station *st : Station::Iterate()) {
3118  if (IsTileType(st->xy, MP_STATION) && IsOilRig(st->xy)) {
3119  /* Industry tile is always adjacent during construction by TileDiffXY(0, 1) */
3120  st->industry = Industry::GetByTile(st->xy + TileDiffXY(0, 1));
3121  st->industry->neutral_station = st;
3122  }
3123  }
3124  } else {
3125  /* Link neutral station back to industry, as this is not saved. */
3126  for (Industry *ind : Industry::Iterate()) if (ind->neutral_station != nullptr) ind->neutral_station->industry = ind;
3127  }
3128 
3130  /* Update water class for trees. */
3131  for (auto t : Map::Iterate()) {
3133  }
3134  }
3135 
3136  /* Update structures for multitile docks */
3138  for (auto t : Map::Iterate()) {
3139  /* Clear docking tile flag from relevant tiles as it
3140  * was not previously cleared. */
3142  SetDockingTile(t, false);
3143  }
3144  /* Add docks and oilrigs to Station::ship_station. */
3145  if (IsTileType(t, MP_STATION)) {
3146  if (IsDock(t) || IsOilRig(t)) Station::GetByTile(t)->ship_station.Add(t);
3147  }
3148  }
3149  }
3150 
3152  /* Placing objects on docking tiles was not updating adjacent station's docking tiles. */
3153  for (Station *st : Station::Iterate()) {
3154  if (st->ship_station.tile != INVALID_TILE) UpdateStationDockingTiles(st);
3155  }
3156  }
3157 
3159  /* Reset roadtype/streetcartype info for non-road bridges. */
3160  for (auto t : Map::Iterate()) {
3163  }
3164  }
3165  }
3166 
3167  /* Make sure all industries exclusive supplier/consumer set correctly. */
3169  for (Industry *i : Industry::Iterate()) {
3170  i->exclusive_supplier = INVALID_OWNER;
3171  i->exclusive_consumer = INVALID_OWNER;
3172  }
3173  }
3174 
3176  /* Propagate wagon removal flag for compatibility */
3177  /* Temporary bitmask of company wagon removal setting */
3178  uint16_t wagon_removal = 0;
3179  for (const Company *c : Company::Iterate()) {
3180  if (c->settings.renew_keep_length) SetBit(wagon_removal, c->index);
3181  }
3182  for (Group *g : Group::Iterate()) {
3183  if (g->flags != 0) {
3184  /* Convert old replace_protection value to flag. */
3185  g->flags = 0;
3187  }
3188  if (HasBit(wagon_removal, g->owner)) SetBit(g->flags, GroupFlags::GF_REPLACE_WAGON_REMOVAL);
3189  }
3190  }
3191 
3192  /* Use current order time to approximate last loading time */
3194  for (Vehicle *v : Vehicle::Iterate()) {
3195  v->last_loading_tick = std::max(TimerGameTick::counter, static_cast<uint64_t>(v->current_order_time)) - v->current_order_time;
3196  }
3197  }
3198 
3199  /* Road stops is 'only' updating some caches, but they are needed for PF calls in SLV_MULTITRACK_LEVEL_CROSSINGS teleporting. */
3201 
3202  /* Road vehicles stopped on multitrack level crossings need teleporting to a depot
3203  * to avoid crashing into the side of the train they're waiting for. */
3205  /* Teleport road vehicles to the nearest depot. */
3206  for (RoadVehicle *rv : RoadVehicle::Iterate()) {
3207  /* Ignore trailers of articulated vehicles. */
3208  if (rv->IsArticulatedPart()) continue;
3209 
3210  /* Ignore moving vehicles. */
3211  if (rv->cur_speed > 0) continue;
3212 
3213  /* Ignore crashed vehicles. */
3214  if (rv->vehstatus & VS_CRASHED) continue;
3215 
3216  /* Ignore vehicles not on level crossings. */
3217  TileIndex cur_tile = rv->tile;
3218  if (!IsLevelCrossingTile(cur_tile)) continue;
3219 
3220  ClosestDepot closestDepot = rv->FindClosestDepot();
3221 
3222  /* Try to find a depot with a distance limit of 512 tiles (Manhattan distance). */
3223  if (closestDepot.found && DistanceManhattan(rv->tile, closestDepot.location) < 512u) {
3224  /* Teleport all parts of articulated vehicles. */
3225  for (RoadVehicle *u = rv; u != nullptr; u = u->Next()) {
3226  u->tile = closestDepot.location;
3227  int x = TileX(closestDepot.location) * TILE_SIZE + TILE_SIZE / 2;
3228  int y = TileY(closestDepot.location) * TILE_SIZE + TILE_SIZE / 2;
3229  u->x_pos = x;
3230  u->y_pos = y;
3231  u->z_pos = GetSlopePixelZ(x, y, true);
3232 
3233  u->vehstatus |= VS_HIDDEN;
3234  u->state = RVSB_IN_DEPOT;
3235  u->UpdatePosition();
3236  }
3237  RoadVehLeaveDepot(rv, false);
3238  }
3239  }
3240 
3242  /* Reset unused tree counters to reduce the savegame size. */
3243  for (auto t : Map::Iterate()) {
3244  if (IsTileType(t, MP_TREES)) {
3245  SB(t.m2(), 0, 4, 0);
3246  }
3247  }
3248  }
3249 
3250  /* Refresh all level crossings to bar adjacent crossing tiles, if needed. */
3251  for (auto tile : Map::Iterate()) {
3252  if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile, false);
3253  }
3254  }
3255 
3256  /* Compute station catchment areas. This is needed here in case UpdateStationAcceptance is called below. */
3258 
3259  /* Station acceptance is some kind of cache */
3261  for (Station *st : Station::Iterate()) UpdateStationAcceptance(st, false);
3262  }
3263 
3266  }
3267 
3269  /* For older savegames, we don't now the actual interval; so set it to the newgame value. */
3271 
3272  /* We did load the "period" of the timer, but not the fired/elapsed. We can deduce that here. */
3274  _new_competitor_timeout.storage.elapsed = 0;
3275  _new_competitor_timeout.fired = _new_competitor_timeout.period.value == 0;
3276  }
3277 
3279  /* Set service date provided to NewGRF. */
3280  for (Vehicle *v : Vehicle::Iterate()) {
3281  v->date_of_last_service_newgrf = v->date_of_last_service.base();
3282  }
3283  }
3284 
3286  /* NewGRF acceleration information was added to ships. */
3287  for (Ship *s : Ship::Iterate()) {
3288  if (s->acceleration == 0) s->acceleration = ShipVehInfo(s->engine_type)->acceleration;
3289  }
3290  }
3291 
3293  for (Company *c : Company::Iterate()) {
3294  c->max_loan = COMPANY_MAX_LOAN_DEFAULT;
3295  }
3296  }
3297 
3299  ScriptObject::InitializeRandomizers();
3300  }
3301 
3303  for (Company *c : Company::Iterate()) {
3304  c->inaugurated_year_calendar = _settings_game.game_creation.starting_year;
3305  }
3306  }
3307 
3308  for (Company *c : Company::Iterate()) {
3310  }
3311 
3312  /* Update free group numbers data for each company, required regardless of savegame version. */
3313  for (Group *g : Group::Iterate()) {
3314  Company *c = Company::Get(g->owner);
3316  /* Use the index as group number when converting old savegames. */
3317  g->number = c->freegroups.UseID(g->index);
3318  } else {
3319  c->freegroups.UseID(g->number);
3320  }
3321  }
3322 
3326 
3327  _gamelog.PrintDebug(1);
3328 
3330  /* Restore the signals */
3332 
3334 
3336 
3337  /* Start the scripts. This MUST happen after everything else except
3338  * starting a new company. */
3339  StartScripts();
3340 
3341  /* If Load Scenario / New (Scenario) Game is used,
3342  * a company does not exist yet. So create one here.
3343  * 1 exception: network-games. Those can have 0 companies
3344  * But this exception is not true for non-dedicated network servers! */
3346  CompanyID first_human_company = GetFirstPlayableCompanyID();
3347  if (!Company::IsValidID(first_human_company)) {
3348  Company *c = DoStartupNewCompany(false, first_human_company);
3350  }
3351  }
3352 
3353  return true;
3354 }
3355 
3365 {
3366  /* reload grf data */
3367  GfxLoadSprites();
3369  RecomputePrices();
3370  /* reload vehicles */
3371  ResetVehicleHash();
3373  AfterLoadVehiclesPhase1(false);
3374  AfterLoadVehiclesPhase2(false);
3375  StartupEngines();
3377  /* update station graphics */
3378  AfterLoadStations();
3379  /* Update company statistics. */
3381  /* Check and update house and town values */
3383  /* Delete news referring to no longer existing entities */
3385  /* Update livery selection windows */
3387  /* Update company infrastructure counts. */
3390  /* redraw the whole screen */
3393 }
static void SetSignalHandlers()
Replaces signal handlers of SIGSEGV and SIGABRT and stores pointers to original handlers in memory.
Definition: afterload.cpp:327
static uint FixVehicleInclination(Vehicle *v, Direction dir)
Fixes inclination of a vehicle.
Definition: afterload.cpp:481
static void InitializeWindowsAndCaches()
Initialization of the windows and several kinds of caches.
Definition: afterload.cpp:248
static void CheckGroundVehiclesAtCorrectZ()
Check whether the ground vehicles are at the correct Z-coordinate.
Definition: afterload.cpp:516
static bool _saveload_crash_with_missing_newgrfs
Was the saveload crash because of missing NewGRFs?
Definition: afterload.cpp:345
static void FixOwnerOfRailTrack(Tile t)
Tries to change owner of this rail tile to a valid owner.
Definition: afterload.cpp:423
static void CDECL HandleSavegameLoadCrash(int signum)
Signal handler used to give a user a more useful report for crashes during the savegame loading proce...
Definition: afterload.cpp:363
static bool MayHaveBridgeAbove(Tile t)
Checks for the possibility that a bridge may be on this tile These are in fact all the tile types on ...
Definition: afterload.cpp:536
void SetWaterClassDependingOnSurroundings(Tile t, bool include_invalid_water_class)
Makes a tile canal or water depending on the surroundings.
Definition: afterload.cpp:85
static void StartScripts()
Start the scripts.
Definition: afterload.cpp:545
Company * DoStartupNewCompany(bool is_ai, CompanyID company=INVALID_COMPANY)
Create a new company and sets all company variables default values.
bool SaveloadCrashWithMissingNewGRFs()
Did loading the savegame cause a crash? If so, were NewGRFs missing?
Definition: afterload.cpp:352
void UpdateAllVirtCoords()
Update the viewport coordinates of all signs.
Definition: afterload.cpp:223
bool AfterLoadGame()
Perform a (large) amount of savegame conversion magic in order to load older savegames and to fill th...
Definition: afterload.cpp:565
void ReloadNewGRFData()
Reload all NewGRF files during a running game.
Definition: afterload.cpp:3364
static void ResetSignalHandlers()
Resets signal handlers back to original handlers.
Definition: afterload.cpp:337
void GetAircraftFlightLevelBounds(const Vehicle *v, int *min, int *max)
Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular vehicle for normal flight si...
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
void AircraftNextAirportPos_and_Order(Aircraft *v)
set the right pos when heading to other airports after takeoff
void SetAircraftPosition(Aircraft *v, int x, int y, int z)
Set aircraft position.
@ AIR_AIRCRAFT
an airplane
Definition: aircraft.h:30
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
@ AT_OILRIG
Oilrig airport.
Definition: airport.h:38
@ FLYING
Vehicle is flying in the air.
Definition: airport.h:75
std::vector< TileIndex > _animated_tiles
The table/list with animated tiles.
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
static uint32_t BSWAP32(uint32_t x)
Perform a 32 bits endianness bitswap on x.
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
TileIndex GetNorthernBridgeEnd(TileIndex t)
Finds the northern end of a bridge starting at a middle tile.
Definition: bridge_map.cpp:39
void SetBridgeMiddle(Tile t, Axis a)
Set that there is a bridge over the given axis.
Definition: bridge_map.h:114
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
Definition: bridge_map.h:35
void ClearBridgeMiddle(Tile t)
Removes bridges from the given, that is bridges along the X and Y axis.
Definition: bridge_map.h:103
bool IsBridge(Tile t)
Checks if this is a bridge, instead of a tunnel.
Definition: bridge_map.h:24
void AfterLoadCompanyStats()
Rebuilding of company statistics after loading a savegame.
Definition: company_sl.cpp:96
static const CargoID CARGO_NO_REFIT
Do not refit cargo of a vehicle (used in vehicle orders and auto-replace/auto-renew).
Definition: cargo_type.h:78
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition: cargo_type.h:107
@ Industry
Source/destination is an industry.
@ Town
Source/destination is a town.
@ TAE_GOODS
Cargo behaves goods/candy-like.
Definition: cargotype.h:26
@ TAE_PASSENGERS
Cargo behaves passenger-like.
Definition: cargotype.h:24
@ TAE_MAIL
Cargo behaves mail-like.
Definition: cargotype.h:25
@ TAE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:28
@ TAE_WATER
Cargo behaves water-like.
Definition: cargotype.h:27
static void StartNew(CompanyID company)
Start a new AI company.
Definition: ai_core.cpp:36
UnitID UseID(UnitID index)
Use a unit number.
Definition: vehicle.cpp:1863
static void StartNew()
Start up a new GameScript.
Definition: game_core.cpp:72
void TestRevision()
Finds out if current revision is different than last revision stored in the savegame.
Definition: gamelog.cpp:425
void PrintDebug(int level)
Prints gamelog to debug output.
Definition: gamelog.cpp:323
void GRFAddList(const GRFConfig *newg)
Logs adding of list of GRFs.
Definition: gamelog.cpp:578
void GRFCompatible(const GRFIdentifier *newg)
Logs loading compatible GRF (the same ID, but different MD5 hash)
Definition: gamelog.cpp:542
const GRFIdentifier * GetOverriddenIdentifier(const GRFConfig *c)
Try to find the overridden GRF identifier of the given GRF.
Definition: gamelog.cpp:712
void GRFRemove(uint32_t grfid)
Logs removal of a GRF.
Definition: gamelog.cpp:517
void Oldver()
Logs loading from savegame without gamelog.
Definition: gamelog.cpp:399
void TestMode()
Finds last stored game mode or landscape.
Definition: gamelog.cpp:446
uint32_t GetGRFID(uint16_t entity_id) const
Gives the GRFID of the file the entity belongs to.
uint AvailableCount() const
Returns sum of cargo still available for loading at the sation.
Definition: cargopacket.h:588
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static constexpr TimerGameTick::Ticks TOWN_GROWTH_TICKS
Cycle duration for towns trying to grow (this originates from the size of the town array in TTD).
Wrapper class to abstract away the way the tiles are stored.
Definition: map_func.h:25
debug_inline uint8_t & m7()
Primarily used for newgrf support.
Definition: map_func.h:185
debug_inline uint8_t & m5()
General purpose.
Definition: map_func.h:161
debug_inline uint16_t & m2()
Primarily used for indices to towns, industries and stations.
Definition: map_func.h:125
debug_inline uint8_t & m6()
General purpose.
Definition: map_func.h:173
debug_inline uint8_t & m3()
General purpose.
Definition: map_func.h:137
A timeout timer will fire once after the interval.
Definition: timer.h:116
static void SetDate(Date date, DateFract fract)
Set the date.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static DateFract date_fract
Fractional part of the day.
static constexpr TimerGame< struct Calendar >::Year DEF_END_YEAR
The default scoring end year.
static constexpr TimerGame< struct Economy >::Year MIN_YEAR
The absolute minimum year in OTTD.
static constexpr int SECONDS_PER_DAY
approximate seconds per day, not for precise calculations
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
The date of the first day of the original base year.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static DateFract date_fract
Fractional part of the day.
static void SetDate(Date date, DateFract fract)
Set the date.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
ClearGround GetRawClearGround(Tile t)
Get the type of clear tile but never return CLEAR_SNOW.
Definition: clear_map.h:47
bool IsClearGround(Tile t, ClearGround ct)
Set the type of clear tile.
Definition: clear_map.h:71
@ CLEAR_GRASS
0-3
Definition: clear_map.h:20
@ CLEAR_FIELDS
3
Definition: clear_map.h:23
@ CLEAR_SNOW
0-3
Definition: clear_map.h:24
void SetFence(Tile t, DiagDirection side, uint h)
Sets the type of fence (and whether there is one) for the given border.
Definition: clear_map.h:240
void MakeClear(Tile t, ClearGround g, uint density)
Make a clear tile.
Definition: clear_map.h:259
void SetClearGroundDensity(Tile t, ClearGround type, uint density)
Sets ground type and density in one go, also sets the counter to 0.
Definition: clear_map.h:158
uint GetClearDensity(Tile t)
Get the density of a non-field clear tile.
Definition: clear_map.h:83
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company's primary colour.
void UpdateCompanyLiveries(Company *c)
Update liveries for a company.
TimeoutTimer< TimerGameTick > _new_competitor_timeout({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, 0 }, []() { if(_game_mode==GM_MENU||!AI::CanStartNew()) return;if(_networking &&Company::GetNumItems() >=_settings_client.network.max_companies) return;uint8_t n=0;for(const Company *c :Company::Iterate()) { if(c->is_ai) n++;} if(n >=_settings_game.difficulty.max_no_competitors) return;Command< CMD_COMPANY_CTRL >::Post(CCA_NEW_AI, INVALID_COMPANY, CRR_NONE, INVALID_CLIENT_ID);})
Start a new competitor company if possible.
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:53
CompanyManagerFace ConvertFromOldCompanyManagerFace(uint32_t face)
Converts an old company manager's face format to the new company manager's face format.
Definition: company_sl.cpp:45
Owner
Enum for all companies/owners.
Definition: company_type.h:18
@ INVALID_COMPANY
An invalid company.
Definition: company_type.h:30
@ INVALID_OWNER
An invalid owner.
Definition: company_type.h:29
@ COMPANY_FIRST
First company, same as owner.
Definition: company_type.h:22
@ OWNER_NONE
The tile has no ownership.
Definition: company_type.h:25
@ OWNER_WATER
The tile/execution is done by "water".
Definition: company_type.h:26
@ OWNER_TOWN
A town owns the tile, or a town is expanding.
Definition: company_type.h:24
@ MAX_COMPANIES
Maximum number of companies.
Definition: company_type.h:23
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
bool IsDepotTile(Tile tile)
Is the given tile a tile with a depot on it?
Definition: depot_map.h:41
Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Direction ReverseDir(Direction d)
Return the reverse of a direction.
Direction AxisToDirection(Axis a)
Converts an Axis to a Direction.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
DiagDirection XYNSToDiagDir(Axis xy, uint ns)
Convert an axis and a flag for north/south into a DiagDirection.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Direction
Defines the 8 directions on the map.
@ DIR_SW
Southwest.
@ DIR_NW
Northwest.
@ INVALID_DIR
Flag for an invalid direction.
@ DIR_SE
Southeast.
@ DIR_NE
Northeast.
Axis
Allow incrementing of DiagDirDiff variables.
@ AXIS_X
The X axis.
@ AXIS_Y
The y axis.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_NE
Northeast, upper right on your monitor.
@ DIAGDIR_NW
Northwest.
@ DIAGDIR_SE
Southeast.
@ DIAGDIR_END
Used for iterations.
@ DIAGDIR_BEGIN
Used for iterations.
@ DIAGDIR_SW
Southwest.
void RecomputePrices()
Computes all prices, payments and maximum loan.
Definition: economy.cpp:762
bool AddInflation(bool check_year)
Add monthly inflation.
Definition: economy.cpp:724
static const uint64_t MAX_INFLATION
Maximum inflation (including fractional part) without causing overflows in int64_t price computations...
Definition: economy_type.h:229
void StartupEngines()
Start/initialise all our engines.
Definition: engine.cpp:763
void CopyTempEngineData()
Copy data from temporary engine array into the real engine pool.
Definition: engine_sl.cpp:121
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
Definition: engine_type.h:169
void ShowErrorMessage(StringID summary_msg, int x, int y, CommandCost cc)
Display an error message in a window.
Definition: error_gui.cpp:367
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition: error.h:27
@ FT_SCENARIO
old or new scenario
Definition: fileio_type.h:19
Gamelog _gamelog
Gamelog instance.
Definition: gamelog.cpp:31
PauseMode _pause_mode
The current pause mode.
Definition: gfx.cpp:50
void LoadStringWidthTable(bool monospace)
Initialize _stringwidth_table cache.
Definition: gfx.cpp:1210
void GfxLoadSprites()
Initialise and load all the sprites.
Definition: gfxinit.cpp:323
@ GVF_GOINGDOWN_BIT
Vehicle is currently going downhill. (Cached track information for acceleration)
@ GVF_GOINGUP_BIT
Vehicle is currently going uphill. (Cached track information for acceleration)
@ GF_REPLACE_PROTECTION
If set to true, the global autoreplace has no effect on the group.
Definition: group.h:66
@ GF_REPLACE_WAGON_REMOVAL
If set, autoreplace will perform wagon removal on vehicles in this group.
Definition: group.h:67
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1529
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
Definition: viewport.cpp:2057
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:28
static const uint8_t TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition: house.h:23
IndustryBuildData _industry_builder
In-game manager of industries.
void TrimIndustryAcceptedProduced(Industry *ind)
Remove unused industry accepted/produced slots – entries after the last slot with valid cargo.
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
IndustryType GetIndustryType(Tile tile)
Retrieve the type for this industry.
IndustryGfx GetIndustryGfx(Tile t)
Get the industry graphics ID for the given industry tile.
Definition: industry_map.h:137
@ INDUSTRYBEH_PLANT_ON_BUILT
Fields are planted around when built (all farms)
Definition: industrytype.h:63
@ INDUSTRYBEH_BUILT_ONWATER
is built on water (oil rig)
Definition: industrytype.h:59
void AfterLoadLabelMaps()
Perform rail type and road type conversion if necessary.
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
Definition: landscape.cpp:554
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
Definition: landscape.cpp:565
const TileTypeProcs *const _tile_type_procs[16]
Tile callback functions for each type of tile.
Definition: landscape.cpp:65
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
Definition: landscape.cpp:303
void AfterLoadLinkGraphs()
Spawn the threads for running link graph calculations.
@ DT_MANUAL
Manual distribution. No link graph calculations are run.
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
Definition: main_gui.cpp:546
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition: map.cpp:146
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
Definition: map_func.h:467
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:373
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition: map_func.h:608
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition: map_func.h:389
static debug_inline uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition: map_func.h:425
static debug_inline uint TileX(TileIndex tile)
Get the X component of a tile.
Definition: map_func.h:415
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition: map_func.h:567
static debug_inline TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition: map_func.h:404
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition: math_func.hpp:320
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
Definition: math_func.hpp:268
constexpr void Swap(T &a, T &b)
Type safe swap operation.
Definition: math_func.hpp:283
void GenerateSavegameId()
Generate an unique savegame ID.
Definition: misc.cpp:87
bool _networking
are we in networking mode?
Definition: network.cpp:65
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:68
bool _network_server
network-server is active
Definition: network.cpp:66
@ GSF_FAKE_TOWNS
Fake town GrfSpecFeature for NewGRF debugging (parent scope)
Definition: newgrf.h:91
void ShowNewGRFError()
Show the first NewGRF error we can find.
Definition: newgrf_gui.cpp:45
uint8_t StationGfx
Copy from station_map.h.
GRFConfig * _grfconfig
First item in list of current GRF set up.
GRFListCompatibility IsGoodGRFConfigList(GRFConfig *grfconfig)
Check if all GRFs in the GRF config from a savegame can be loaded.
GRFListCompatibility
Status of post-gameload GRF compatibility check.
Definition: newgrf_config.h:51
@ GLC_COMPATIBLE
Compatible (eg. the same ID, but different checksum) GRF found in at least one case.
Definition: newgrf_config.h:53
@ GLC_ALL_GOOD
All GRF needed by game are present.
Definition: newgrf_config.h:52
@ GLC_NOT_FOUND
At least one GRF couldn't be found (higher priority than GLC_COMPATIBLE)
Definition: newgrf_config.h:54
@ GCF_COMPATIBLE
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches)
Definition: newgrf_config.h:25
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
Definition: newgrf_config.h:36
void DeleteInvalidEngineNews()
Remove engine announcements for invalid engines.
Definition: news_gui.cpp:963
uint16_t ObjectType
Types of objects.
Definition: object_type.h:14
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition: object_type.h:18
static const ObjectType OBJECT_HQ
HeadQuarter of a player.
Definition: object_type.h:20
@ PM_UNPAUSED
A normal unpaused game.
Definition: openttd.h:69
@ PM_PAUSED_ERROR
A game paused because a (critical) error.
Definition: openttd.h:73
@ PMB_PAUSED_NETWORK
Pause mode bits when paused for network reasons.
Definition: openttd.h:80
@ PM_PAUSED_NORMAL
A game normally paused.
Definition: openttd.h:70
OrderDepotActionFlags
Actions that can be performed when the vehicle enters the depot.
Definition: order_type.h:102
@ OLFB_NO_LOAD
Do not load anything.
Definition: order_type.h:66
@ OSL_PLATFORM_FAR_END
Stop at the far end of the platform.
Definition: order_type.h:86
@ OUFB_TRANSFER
Transfer all cargo onto the platform.
Definition: order_type.h:55
@ OUFB_UNLOAD
Force unloading all cargo onto the platform, possibly not getting paid.
Definition: order_type.h:54
@ ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS
The vehicle will not stop at any stations it passes except the destination.
Definition: order_type.h:74
RailTypes GetCompanyRailTypes(CompanyID company, bool introduces)
Get the rail types the given company can build.
Definition: rail.cpp:251
void InitializeRailGUI()
Resets the rail GUI - sets default railtype to build and resets the signal GUI.
Definition: rail_gui.cpp:1996
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition: rail_map.h:115
static debug_inline bool IsRailDepotTile(Tile t)
Is this tile rail tile and a rail depot?
Definition: rail_map.h:105
@ RAIL_GROUND_WATER
Grass with a fence and shore or water on the free halftile.
Definition: rail_map.h:499
void SetTrackReservation(Tile t, TrackBits b)
Sets the reserved track bits of the tile.
Definition: rail_map.h:209
static debug_inline bool IsRailDepot(Tile t)
Is this rail tile a rail depot?
Definition: rail_map.h:95
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
Definition: rail_map.h:270
static debug_inline bool IsPlainRail(Tile t)
Returns whether this is plain rails, with or without signals.
Definition: rail_map.h:49
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition: rail_map.h:72
static debug_inline bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition: rail_map.h:60
void SetSignalStates(Tile tile, uint state)
Set the states of the signals (Along/AgainstTrackDir)
Definition: rail_map.h:352
void SetRailType(Tile t, RailType r)
Sets the rail type of the given tile.
Definition: rail_map.h:125
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
@ RAILTYPE_ELECTRIC
Electric rails.
Definition: rail_type.h:30
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition: rail_type.h:29
RoadTypes GetCompanyRoadTypes(CompanyID company, bool introduces)
Get the road types the given company can build.
Definition: road.cpp:199
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Definition: road_cmd.cpp:1918
void UpdateLevelCrossing(TileIndex tile, bool sound=true, bool force_bar=false)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
Definition: train_cmd.cpp:1773
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition: road_map.h:251
bool HasTownOwnedRoad(Tile t)
Checks if given tile has town owned road.
Definition: road_map.h:280
static debug_inline bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
Definition: road_map.h:106
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
Definition: road_map.h:95
@ ROAD_TILE_NORMAL
Normal road.
Definition: road_map.h:23
@ ROAD_TILE_DEPOT
Depot (one entrance)
Definition: road_map.h:25
@ ROAD_TILE_CROSSING
Level crossing.
Definition: road_map.h:24
void SetRoadTypes(Tile t, RoadType road_rt, RoadType tram_rt)
Set the present road types of a tile.
Definition: road_map.h:619
RoadBits GetCrossingRoadBits(Tile tile)
Get the road bits of a level crossing.
Definition: road_map.h:348
Owner GetRoadOwner(Tile t, RoadTramType rtt)
Get the owner of a specific road type.
Definition: road_map.h:234
static debug_inline RoadTileType GetRoadTileType(Tile t)
Get the type of the road tile.
Definition: road_map.h:52
void SetCrossingReservation(Tile t, bool b)
Set the reservation state of the rail crossing.
Definition: road_map.h:393
bool IsLevelCrossing(Tile t)
Return whether a tile is a level crossing.
Definition: road_map.h:85
RoadBits
Enumeration for the road parts on a tile.
Definition: road_type.h:52
@ ROAD_Y
Full road along the y-axis (north-west + south-east)
Definition: road_type.h:59
@ ROAD_X
Full road along the x-axis (south-west + north-east)
Definition: road_type.h:58
RoadTypes
The different roadtypes we support, but then a bitmask of them.
Definition: road_type.h:38
RoadType
The different roadtypes we support.
Definition: road_type.h:25
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:30
@ ROADTYPE_TRAM
Trams.
Definition: road_type.h:28
@ ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:27
@ RVS_ENTERED_STOP
Only set when a vehicle has entered the stop.
Definition: roadveh.h:43
@ RVSB_IN_ROAD_STOP
The vehicle is in a road stop.
Definition: roadveh.h:49
@ RVS_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition: roadveh.h:46
@ RVS_IN_ROAD_STOP
The vehicle is in a road stop.
Definition: roadveh.h:45
@ RVSB_IN_DEPOT
The vehicle is in a depot.
Definition: roadveh.h:38
@ RVSB_WORMHOLE
The vehicle is in a tunnel and/or bridge.
Definition: roadveh.h:39
@ RVS_DRIVE_SIDE
Only used when retrieving move data.
Definition: roadveh.h:44
const uint8_t _road_stop_stop_frame[]
Table of road stop stop frames, when to stop at a road stop.
void SlError(StringID string, const std::string &extra_msg)
Error handler.
Definition: saveload.cpp:321
void SetSaveLoadError(StringID str)
Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friend...
Definition: saveload.cpp:2799
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition: saveload.cpp:351
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition: saveload.cpp:60
bool IsSavegameVersionBefore(SaveLoadVersion major, uint8_t minor=0)
Checks whether the savegame is below major.
Definition: saveload.h:1239
@ SLV_AI_START_DATE
309 PR#10653 Removal of individual AI start dates and added a generic one.
Definition: saveload.h:350
@ SLV_190
190 26547 Separate order travel and wait times
Definition: saveload.h:271
@ SLV_91
91 12347
Definition: saveload.h:152
@ SLV_49
49 8969
Definition: saveload.h:101
@ SLV_90
90 12293
Definition: saveload.h:151
@ SLV_64
64 10006
Definition: saveload.h:119
@ SLV_69
69 10319
Definition: saveload.h:125
@ SLV_ECONOMY_MODE_TIMEKEEPING_UNITS
327 PR#11341 Mode to display economy measurements in wallclock units.
Definition: saveload.h:372
@ SLV_172
172 23947
Definition: saveload.h:249
@ SLV_182
182 25115 FS#5492, r25259, r25296 Goal status
Definition: saveload.h:261
@ SLV_186
186 25833 Objects storage
Definition: saveload.h:266
@ SLV_175
175 24136
Definition: saveload.h:253
@ SLV_16
16.0 2817 16.1 3155
Definition: saveload.h:60
@ SLV_87
87 12129
Definition: saveload.h:147
@ SLV_SERVE_NEUTRAL_INDUSTRIES
210 PR#7234 Company stations can serve industries with attached neutral stations.
Definition: saveload.h:296
@ SLV_147
147 20621
Definition: saveload.h:219
@ SLV_188
188 26169 v1.4 FS#5831 Unify RV travel time
Definition: saveload.h:268
@ SLV_61
61 9892
Definition: saveload.h:116
@ SLV_84
84 11822
Definition: saveload.h:143
@ SLV_25
25 4259
Definition: saveload.h:73
@ SLV_15
15.0 2499
Definition: saveload.h:59
@ SLV_198
198 PR#6763 Switch town growth rate and counter to actual game ticks
Definition: saveload.h:281
@ SLV_36
36 6624
Definition: saveload.h:86
@ SLV_26
26 4466
Definition: saveload.h:74
@ SLV_96
96 13226
Definition: saveload.h:158
@ SLV_EXTEND_RAILTYPES
200 PR#6805 Extend railtypes to 64, adding uint16_t to map array.
Definition: saveload.h:284
@ SLV_17
17.0 3212 17.1 3218
Definition: saveload.h:62
@ SLV_42
42 7573
Definition: saveload.h:93
@ SLV_177
177 24619
Definition: saveload.h:255
@ SLV_EXTEND_INDUSTRY_CARGO_SLOTS
202 PR#6867 Increase industry cargo slots to 16 in, 16 out
Definition: saveload.h:286
@ SLV_103
103 14598
Definition: saveload.h:166
@ SLV_100
100 13952
Definition: saveload.h:163
@ SLV_GROUP_REPLACE_WAGON_REMOVAL
291 PR#7441 Per-group wagon removal flag.
Definition: saveload.h:329
@ SLV_VELOCITY_NAUTICAL
305 PR#10594 Separation of land and nautical velocity (knots!)
Definition: saveload.h:346
@ SLV_VEHICLE_ECONOMY_AGE
334 PR#12141 v14.0 Add vehicle age in economy year, for profit stats minimum age
Definition: saveload.h:380
@ SLV_4
4.0 1 4.1 122 0.3.3, 0.3.4 4.2 1222 0.3.5 4.3 1417 4.4 1426
Definition: saveload.h:37
@ SLV_TOWN_CARGOGEN
208 PR#6965 New algorithms for town building cargo generation.
Definition: saveload.h:293
@ SLV_149
149 20832
Definition: saveload.h:221
@ SLV_83
83 11589
Definition: saveload.h:142
@ SLV_6
6.0 1721 6.1 1768
Definition: saveload.h:46
@ SLV_34
34 6455
Definition: saveload.h:83
@ SLV_LINKGRAPH_SECONDS
308 PR#10610 Store linkgraph update intervals in seconds instead of days.
Definition: saveload.h:349
@ SLV_114
114 15601
Definition: saveload.h:179
@ SLV_137
137 18912
Definition: saveload.h:207
@ SLV_SAVEGAME_ID
313 PR#10719 Add an unique ID to every savegame (used to deduplicate surveys).
Definition: saveload.h:355
@ SLV_131
131 18481
Definition: saveload.h:200
@ SLV_11
11.0 2033 11.1 2041
Definition: saveload.h:53
@ SLV_120
120 16439
Definition: saveload.h:187
@ SLV_99
99 13838
Definition: saveload.h:161
@ SLV_123
123 16909
Definition: saveload.h:190
@ SLV_46
46 8705
Definition: saveload.h:98
@ SLV_122
122 16855
Definition: saveload.h:189
@ SLV_ENDING_YEAR
218 PR#7747 v1.10 Configurable ending year.
Definition: saveload.h:305
@ SLV_141
141 19799
Definition: saveload.h:212
@ SLV_112
112 15290
Definition: saveload.h:177
@ SLV_125
125 17113
Definition: saveload.h:193
@ SLV_166
166 23415
Definition: saveload.h:242
@ SLV_98
98 13375
Definition: saveload.h:160
@ SLV_WATER_TILE_TYPE
342 PR#13030 Simplify water tile type.
Definition: saveload.h:390
@ SLV_117
117 16037
Definition: saveload.h:183
@ SLV_140
140 19382
Definition: saveload.h:211
@ SLV_126
126 17433
Definition: saveload.h:194
@ SLV_138
138 18942 1.0.x
Definition: saveload.h:208
@ SLV_MULTITILE_DOCKS
216 PR#7380 Multiple docks per station.
Definition: saveload.h:303
@ SLV_86
86 12042
Definition: saveload.h:146
@ SLV_ROAD_TYPES
214 PR#6811 NewGRF road types.
Definition: saveload.h:300
@ SLV_1
1.0 0.1.x, 0.2.x
Definition: saveload.h:33
@ SLV_GS_INDUSTRY_CONTROL
287 PR#7912 and PR#8115 GS industry control.
Definition: saveload.h:324
@ SLV_164
164 23290
Definition: saveload.h:239
@ SLV_160
160 21974 1.1.x
Definition: saveload.h:235
@ SLV_38
38 7195
Definition: saveload.h:88
@ SLV_145
145 20376
Definition: saveload.h:217
@ SLV_48
48 8935
Definition: saveload.h:100
@ SLV_57
57 9691
Definition: saveload.h:111
@ SLV_104
104 14735
Definition: saveload.h:167
@ SLV_52
52 9066
Definition: saveload.h:105
@ SLV_134
134 18703
Definition: saveload.h:203
@ SLV_165
165 23304
Definition: saveload.h:241
@ SLV_144
144 20334
Definition: saveload.h:215
@ SLV_2
2.0 0.3.0 2.1 0.3.1, 0.3.2
Definition: saveload.h:34
@ SLV_143
143 20048
Definition: saveload.h:214
@ SLV_127
127 17439
Definition: saveload.h:195
@ SLV_152
152 21171
Definition: saveload.h:225
@ SLV_LAST_LOADING_TICK
301 PR#9693 Store tick of last loading for vehicles.
Definition: saveload.h:341
@ SLV_76
76 11139
Definition: saveload.h:134
@ SLV_SCRIPT_RANDOMIZER
333 PR#12063 v14.0-RC1 Save script randomizers.
Definition: saveload.h:379
@ SLV_COMPANY_INAUGURATED_PERIOD
339 PR#12798 Companies show the period inaugurated in wallclock mode.
Definition: saveload.h:386
@ SLV_78
78 11176
Definition: saveload.h:136
@ SLV_106
106 14919
Definition: saveload.h:170
@ SLV_DEPOT_UNBUNCHING
331 PR#11945 Allow unbunching shared order vehicles at a depot.
Definition: saveload.h:377
@ SLV_119
119 16242
Definition: saveload.h:185
@ SLV_139
139 19346
Definition: saveload.h:209
@ SLV_SHIP_ACCELERATION
329 PR#10734 Start using Vehicle's acceleration field for ships too.
Definition: saveload.h:374
@ SLV_135
135 18719
Definition: saveload.h:205
@ SLV_MULTITRACK_LEVEL_CROSSINGS
302 PR#9931 v13.0 Multi-track level crossings.
Definition: saveload.h:342
@ SLV_121
121 16694
Definition: saveload.h:188
@ SLV_192
192 26700 FS#6066 Fix saving of order backups
Definition: saveload.h:274
@ SLV_58
58 9762
Definition: saveload.h:112
@ SLV_94
94 12816
Definition: saveload.h:155
@ SLV_153
153 21263
Definition: saveload.h:226
@ SLV_101
101 14233
Definition: saveload.h:164
@ SLV_95
95 12924
Definition: saveload.h:157
@ SLV_158
158 21933
Definition: saveload.h:232
@ SLV_133
133 18674
Definition: saveload.h:202
@ SLV_93
93 12648
Definition: saveload.h:154
@ SLV_81
81 11244
Definition: saveload.h:140
@ SLV_72
72 10601
Definition: saveload.h:129
@ SLV_43
43 7642
Definition: saveload.h:94
@ SLV_113
113 15340
Definition: saveload.h:178
@ SLV_ECONOMY_DATE
326 PR#10700 Split calendar and economy timers and dates.
Definition: saveload.h:371
@ SLV_45
45 8501
Definition: saveload.h:97
@ SLV_128
128 18281
Definition: saveload.h:196
@ SLV_GROUP_NUMBERS
336 PR#12297 Add per-company group numbers.
Definition: saveload.h:383
@ SLV_NEWGRF_LAST_SERVICE
317 PR#11124 Added stable date_of_last_service to avoid NewGRF trouble.
Definition: saveload.h:360
@ SLV_53
53 9316
Definition: saveload.h:106
@ SLV_161
161 22567
Definition: saveload.h:236
@ SLV_74
74 11030
Definition: saveload.h:131
@ SLV_184
184 25508 Unit localisation split
Definition: saveload.h:263
@ SLV_INCREASE_STATION_TYPE_FIELD_SIZE
337 PR#12572 Increase size of StationType field in map array
Definition: saveload.h:384
@ SLV_88
88 12134
Definition: saveload.h:148
@ SLV_156
156 21728
Definition: saveload.h:230
@ SLV_NONFLOODING_WATER_TILES
345 PR#13013 Store water tile non-flooding state.
Definition: saveload.h:394
@ SLV_62
62 9905
Definition: saveload.h:117
@ SLV_59
59 9779
Definition: saveload.h:113
@ SLV_82
82 11410
Definition: saveload.h:141
@ SLV_194
194 26881 v1.5
Definition: saveload.h:276
@ SLV_TREES_WATER_CLASS
213 PR#7405 WaterClass update for tree tiles.
Definition: saveload.h:299
@ SLV_124
124 16993
Definition: saveload.h:191
@ SLV_159
159 21962
Definition: saveload.h:233
@ SLV_32
32 6001
Definition: saveload.h:81
@ SLV_56
56 9667
Definition: saveload.h:110
@ SLV_SHIPS_STOP_IN_LOCKS
206 PR#7150 Ship/lock movement changes.
Definition: saveload.h:291
@ SLV_111
111 15190
Definition: saveload.h:176
@ SLV_70
70 10541
Definition: saveload.h:127
@ SLV_183
183 25363 Cargodist
Definition: saveload.h:262
@ SLV_31
31 5999
Definition: saveload.h:80
@ SLV_148
148 20659
Definition: saveload.h:220
@ SLV_50
50 8973
Definition: saveload.h:103
@ SLV_REPAIR_OBJECT_DOCKING_TILES
299 PR#9594 v12.0 Fixing issue with docking tiles overlapping objects.
Definition: saveload.h:338
@ SLV_CONSISTENT_PARTIAL_Z
306 PR#10570 Conversion from an inconsistent partial Z calculation for slopes, to one that is (more) ...
Definition: saveload.h:347
@ SLV_142
142 20003
Definition: saveload.h:213
@ SLV_21
21 3472 0.4.x
Definition: saveload.h:68
@ SLV_136
136 18764
Definition: saveload.h:206
@ SLV_146
146 20446
Definition: saveload.h:218
@ SLV_MAX_LOAN_FOR_COMPANY
330 PR#11224 Separate max loan for each company.
Definition: saveload.h:376
@ SLV_24
24 4150
Definition: saveload.h:71
@ SLV_9
9.0 1909
Definition: saveload.h:50
bool IsSavegameVersionBeforeOrAt(SaveLoadVersion major)
Checks whether the savegame is below or at major.
Definition: saveload.h:1253
Declaration of functions used in more save/load files.
void AfterLoadVehiclesPhase1(bool part_of_load)
Called after load for phase 1 of vehicle initialisation.
Definition: vehicle_sl.cpp:256
void ResetOldNames()
Free the memory of the old names array.
Definition: strings_sl.cpp:102
void FixupTrainLengths()
Fixup old train spacing.
Definition: vehicle_sl.cpp:549
void MoveBuoysToWaypoints()
Perform all steps to upgrade from the old station buoys to the new version that uses waypoints.
Definition: station_sl.cpp:45
void UpdateOldAircraft()
need to be called to load aircraft from old version
Definition: vehicle_sl.cpp:165
void ConvertOldMultiheadToNew()
Converts all trains to the new subtype format introduced in savegame 16.2 It also links multiheaded e...
Definition: vehicle_sl.cpp:113
void ConnectMultiheadedTrains()
Link front and rear multiheaded engines to each other This is done when loading a savegame.
Definition: vehicle_sl.cpp:35
void AfterLoadRoadStops()
(Re)building of road stop caches after loading a savegame.
Definition: station_sl.cpp:138
void MoveWaypointsToBaseStations()
Perform all steps to upgrade from the old waypoints to the new version that uses station.
Definition: waypoint_sl.cpp:67
void AfterLoadVehiclesPhase2(bool part_of_load)
Called after load for phase 2 of vehicle initialisation.
Definition: vehicle_sl.cpp:415
void UpdateHousesAndTowns()
Check and update town and house values.
Definition: town_sl.cpp:64
std::string CopyFromOldName(StringID id)
Copy and convert old custom names to UTF-8.
Definition: strings_sl.cpp:61
void AfterLoadStoryBook()
Called after load to trash broken pages.
Definition: story_sl.cpp:20
void ShowScriptDebugWindowIfScriptError()
Open the AI debug window if one of the AI scripts has crashed.
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
Definition: settings.cpp:59
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:57
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition: settings.cpp:58
ClientSettings _settings_client
The current settings for this game.
Definition: settings.cpp:56
@ SIGTYPE_COMBO
presignal inter-block
Definition: signal_type.h:27
@ SIG_SEMAPHORE
Old-fashioned semaphore signal.
Definition: signal_type.h:18
@ SIG_ELECTRIC
Light signal.
Definition: signal_type.h:17
void UpdateAllSignVirtCoords()
Update the coordinates of all signs.
Definition: signs.cpp:59
DiagDirection GetInclinedSlopeDirection(Slope s)
Returns the direction of an inclined slope.
Definition: slope_func.h:239
void BuildOwnerLegend()
Completes the array for the owned property legend.
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
void UpdateStationAcceptance(Station *st, bool show_msg)
Update the acceptance for a station.
void SetRailStationTileFlags(TileIndex tile, const StationSpec *statspec)
Set rail station tile flags for the given tile.
StationType GetStationType(Tile t)
Get the station type of this tile.
Definition: station_map.h:44
StationGfx GetStationGfx(Tile t)
Get the station graphics of this tile.
Definition: station_map.h:68
void SetStationGfx(Tile t, StationGfx gfx)
Set the station graphics of this tile.
Definition: station_map.h:80
bool IsAirportTile(Tile t)
Is this tile a station tile and an airport tile?
Definition: station_map.h:167
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
Definition: station_map.h:266
bool IsBuoy(Tile t)
Is tile t a buoy tile?
Definition: station_map.h:400
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
Definition: station_map.h:276
bool HasStationTileRail(Tile t)
Has this station tile a rail? In other words, is this station tile a rail station or rail waypoint?
Definition: station_map.h:146
void SetRailStationReservation(Tile t, bool b)
Set the reservation state of the rail station.
Definition: station_map.h:571
bool IsAnyRoadStop(Tile t)
Is the station at t a road station?
Definition: station_map.h:245
bool IsStationTileBlocked(Tile t)
Is tile t a blocked tile?
Definition: station_map.h:431
bool IsTruckStop(Tile t)
Is the station at t a truck stop?
Definition: station_map.h:180
bool IsStationRoadStop(Tile t)
Is the station at t a road station?
Definition: station_map.h:223
bool HasStationRail(Tile t)
Has this station tile a rail? In other words, is this station tile a rail station or rail waypoint?
Definition: station_map.h:135
static const int GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET
The offset for the drive through parts.
Definition: station_map.h:36
bool IsOilRig(Tile t)
Is tile t part of an oilrig?
Definition: station_map.h:368
bool IsBuoyTile(Tile t)
Is tile t a buoy tile?
Definition: station_map.h:410
bool IsDock(Tile t)
Is tile t a dock tile?
Definition: station_map.h:379
@ FACIL_DOCK
Station with a dock.
Definition: station_type.h:58
@ FACIL_AIRPORT
Station with an airport.
Definition: station_type.h:57
@ FACIL_TRAIN
Station with train station.
Definition: station_type.h:54
StationType
Station types.
Definition: station_type.h:31
#define MAX_UVALUE(type)
The largest value that can be entered in a variable.
Definition: stdafx.h:343
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition: string.cpp:81
static const StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames)
Definition: strings_type.h:17
Information about a aircraft vehicle.
Definition: engine_type.h:100
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition: aircraft.h:72
uint8_t type
Type of this airport,.
Definition: station_base.h:294
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:21
void Restore()
Restore the variable.
Base class for all station-ish types.
TileArea train_station
Tile area the train 'station' part covers.
Owner owner
The owner of this station.
StationRect rect
NOSAVE: Station spread out rectangle maintained by StationRect::xxx() functions.
Town * town
The town this station is associated with.
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
VehicleType type
Type of vehicle.
Definition: vehicle_type.h:51
static void AfterLoad()
Savegame conversion for cargopackets.
Helper class to perform the cargo payment.
Definition: economy_base.h:24
Specification of a cargo type.
Definition: cargotype.h:71
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:134
TownAcceptanceEffect town_acceptance_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition: cargotype.h:83
CompanySettings company
default values for per-company settings
Structure to return information about the closest depot location, and whether it could be found.
Definition: vehicle_base.h:230
CompanySettings settings
settings specific for each company
Definition: company_base.h:122
static bool IsValidAiID(size_t index)
Is this company a valid company, controlled by the computer (a NoAI program)?
Definition: company_base.h:159
bool freeform_edges
allow terraforming the tiles at the map edges
uint16_t max_bridge_length
maximum length of bridges
uint16_t terraform_frame_burst
how many tile heights may, over a short period, be terraformed?
uint16_t max_tunnel_length
maximum length of tunnels
uint16_t tree_frame_burst
how many trees may, over a short period, be planted?
uint8_t map_height_limit
the maximum allowed heightlevel
uint16_t clear_frame_burst
how many tiles may, over a short period, be cleared?
uint8_t number_towns
the amount of towns
uint32_t max_loan
the maximum initial loan
uint16_t competitors_interval
the interval (in minutes) between adding competitors
uint8_t industry_density
The industry density.
Disasters, like submarines, skyrangers and their shadows, belong to this class.
TownLayout town_layout
select town layout,
TimekeepingUnits timekeeping_units
time units to use for the game economy, either calendar or wallclock
bool allow_town_level_crossings
towns are allowed to build level crossings
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
bool station_noise_level
build new airports when the town noise level is still within accepted limits
bool infrastructure_maintenance
enable monthly maintenance fee for owner infrastructure
uint8_t feeder_payment_share
percentage of leg payment to virtually pay in feeder systems
TownCargoGenMode town_cargogen_mode
algorithm for generating cargo from houses,
uint8_t larger_towns
the number of cities to build. These start off larger and grow twice as fast
uint64_t inflation_payment
Cumulated inflation of cargo payment since game start; 16 bit fractional part.
Definition: economy_type.h:52
uint64_t inflation_prices
Cumulated inflation of prices since game start; 16 bit fractional part.
Definition: economy_type.h:51
Money old_max_loan_unround
Old: Unrounded max loan.
Definition: economy_type.h:55
uint16_t old_max_loan_unround_fract
Old: Fraction of the unrounded max loan.
Definition: economy_type.h:56
uint8_t misc_flags
Miscellaneous flags.
Definition: engine_type.h:155
AbstractFileType abstract_ftype
Abstract type of file (scenario, heightmap, etc).
Definition: saveload.h:411
Information about GRF, used in the game and (part of it) in savegames.
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Basic data to distinguish a GRF.
Definition: newgrf_config.h:82
MD5Hash md5sum
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF)
Definition: newgrf_config.h:84
TimerGameCalendar::Year ending_year
scoring end date
uint8_t snow_line_height
the configured snow line height (deduced from "snow_coverage")
uint8_t landscape
the landscape we're currently in
uint8_t town_name
the town name generator used for town names
TimerGameCalendar::Year starting_year
starting date
LocaleSettings locale
settings related to used currency/unit system in the current game
PathfinderSettings pf
settings for all pathfinders
EconomySettings economy
settings to change the economy
ConstructionSettings construction
construction of things in-game
DifficultySettings difficulty
settings related to the difficulty
GameCreationSettings game_creation
settings used during the creation of a game (map)
StationSettings station
settings related to station management
VehicleSettings vehicle
options for vehicles
LinkGraphSettings linkgraph
settings for link graph calculations
Stores station stats for a single cargo.
Definition: station_base.h:166
@ GES_RATING
This indicates whether a cargo has a rating at the station.
Definition: station_base.h:183
uint8_t last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
Definition: station_base.h:237
StationCargoList cargo
The cargo packets of cargo waiting in this station.
Definition: station_base.h:210
uint8_t status
Status of this cargo, see GoodsEntryStatus.
Definition: station_base.h:217
static void UpdateAfterLoad()
Update all caches after loading a game, changing NewGRF, etc.
Definition: group_cmd.cpp:101
Group data.
Definition: group.h:72
void Reset()
Completely reset the industry build data.
Defines the data structure for constructing industry.
Definition: industrytype.h:101
std::array< CargoID, INDUSTRY_NUM_INPUTS > accepts_cargo
16 accepted cargoes.
Definition: industrytype.h:115
IndustryBehaviour behaviour
How this industry will behave, and how others entities can use it.
Definition: industrytype.h:119
Defines the internal data of a functional industry.
Definition: industry.h:66
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition: industry.h:238
uint16_t recalc_time
time (in days) for recalculating each link graph component.
DistributionType distribution_mail
distribution type for mail
DistributionType distribution_default
distribution type for all other goods
DistributionType distribution_pax
distribution type for passengers
DistributionType distribution_armoured
distribution type for armoured cargo class
uint16_t recalc_interval
time (in days) between subsequent checks for link graphs to be calculated.
uint8_t units_velocity_nautical
unit system for velocity of ships and aircraft
uint8_t currency
currency we currently use
uint8_t units_velocity
unit system for velocity of trains and road vehicles
uint8_t units_power
unit system for power
uint8_t units_height
unit system for height
uint8_t units_force
unit system for force
uint8_t units_volume
unit system for volume
uint8_t units_weight
unit system for weight
static uint SizeY()
Get the size of the map along the Y.
Definition: map_func.h:279
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
Definition: map_func.h:363
static debug_inline uint SizeX()
Get the size of the map along the X.
Definition: map_func.h:270
static uint MaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
Definition: map_func.h:306
static debug_inline uint MaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
Definition: map_func.h:297
An object, such as transmitter, on the map.
Definition: object_base.h:23
ObjectType type
Type of the object.
Definition: object_base.h:24
Town * town
Town the object is built in.
Definition: object_base.h:25
static void IncTypeCount(ObjectType type)
Increment the count of objects for this type.
Definition: object_base.h:43
TimerGameCalendar::Date build_date
Date of construction.
Definition: object_base.h:27
TileArea location
Location of the object.
Definition: object_base.h:26
Data for backing up an order of a vehicle so it can be restored after a vehicle is rebuilt in the sam...
Definition: order_backup.h:33
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition: order_base.h:259
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:70
uint16_t w
The width of the area.
Definition: tilearea_type.h:20
void Add(TileIndex to_add)
Add a single tile to a tile area; enlarge if needed.
Definition: tilearea.cpp:43
TileIndex tile
The base tile of the area.
Definition: tilearea_type.h:19
uint16_t h
The height of the area.
Definition: tilearea_type.h:21
uint8_t wait_for_pbs_path
how long to wait for a path reservation.
uint8_t wait_oneway_signal
waitingtime in days before a oneway signal
bool reverse_at_signals
whether to reverse at signals at all
bool forbid_90_deg
forbid trains to make 90 deg turns
uint8_t wait_twoway_signal
waitingtime in days before a twoway signal
Tindex index
Index of this pool item.
Definition: pool_type.hpp:238
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:339
static size_t GetNumItems()
Returns number of valid items in the pool.
Definition: pool_type.hpp:369
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:328
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:309
static Titem * GetIfValid(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:350
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:388
static constexpr size_t MAX_SIZE
Make template parameter accessible from outside.
Definition: pool_type.hpp:84
RailType railtype
Railtype, mangled if elrail is disabled.
Definition: engine_type.h:46
A Stop for a Road Vehicle.
Definition: roadstop_base.h:22
Buses, trucks and trams belong to this class.
Definition: roadveh.h:98
uint8_t state
Definition: roadveh.h:100
RoadType roadtype
NOSAVE: Roadtype of this vehicle.
Definition: roadveh.h:108
uint8_t acceleration
Acceleration (1 unit = 1/3.2 mph per tick = 0.5 km-ish/h per tick)
Definition: engine_type.h:70
All ships have this type.
Definition: ship.h:32
static Station * GetIfValid(size_t index)
Returns station if the index is a valid index for this station type.
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
Returns an iterable ensemble of all valid stations of type T.
static bool IsExpected(const BaseStation *st)
Helper for checking whether the given station is of this type.
static Station * Get(size_t index)
Gets station with given index.
static Station * GetByTile(TileIndex tile)
Get the station belonging to a specific tile.
static Station * From(BaseStation *st)
Converts a BaseStation to SpecializedStation with type checking.
static T * From(Vehicle *v)
Converts a Vehicle to SpecializedVehicle with type checking.
T * Next() const
Get next vehicle in the chain.
static Pool::IterateWrapper< T > Iterate(size_t from=0)
Returns an iterable ensemble of all valid vehicles of type T.
bool modified_catchment
different-size catchment areas
bool serve_neutral_industries
company stations can serve industries with attached neutral stations
Station data structure.
Definition: station_base.h:439
RoadStop * bus_stops
All the road stops.
Definition: station_base.h:448
TileArea ship_station
Tile area the ship 'station' part covers.
Definition: station_base.h:454
static void RecomputeCatchmentForAll()
Recomputes catchment of all stations.
Definition: station.cpp:530
Airport airport
Tile area the airport covers.
Definition: station_base.h:453
RoadStop * truck_stops
All the truck stops.
Definition: station_base.h:450
Struct about subsidies, offered and awarded.
Definition: subsidy_base.h:22
Town data structure.
Definition: town.h:54
'Train' is either a loco or a wagon.
Definition: train.h:89
Default settings for vehicles.
uint8_t plane_crashes
number of plane crashes, 0 = none, 1 = reduced, 2 = normal
uint8_t roadveh_acceleration_model
realistic acceleration for road vehicles
uint8_t roadveh_slope_steepness
Steepness of hills for road vehicles when using realistic acceleration.
uint8_t train_acceleration_model
realistic acceleration for trains
uint8_t train_slope_steepness
Steepness of hills for trains when using realistic acceleration.
uint8_t road_side
the side of the road vehicles drive on
bool dynamic_engines
enable dynamic allocation of engine data
uint8_t max_train_length
maximum length for trains
uint8_t plane_speed
divisor for speed of aircraft
bool disable_elrails
when true, the elrails are disabled
Vehicle data structure.
Definition: vehicle_base.h:244
CargoPayment * cargo_payment
The cargo payment we're currently in.
Definition: vehicle_base.h:277
Direction direction
facing
Definition: vehicle_base.h:307
Order current_order
The current order (+ status, like: loading)
Definition: vehicle_base.h:356
int32_t y_pos
y coordinate.
Definition: vehicle_base.h:305
int32_t x_pos
x coordinate.
Definition: vehicle_base.h:304
uint8_t vehstatus
Status.
Definition: vehicle_base.h:354
TileIndex tile
Current tile index.
Definition: vehicle_base.h:264
Owner owner
Which company owns the vehicle?
Definition: vehicle_base.h:309
Representation of a waypoint.
Definition: waypoint_base.h:23
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
Definition: subsidy.cpp:134
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition: tile_map.cpp:95
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition: tile_map.cpp:136
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition: tile_map.cpp:116
uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition: tile_map.h:324
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition: tile_map.h:214
void SetTileType(Tile tile, TileType type)
Set the type of a tile.
Definition: tile_map.h:131
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition: tile_map.h:178
void SetTileOwner(Tile tile, Owner owner)
Sets the owner of a tile.
Definition: tile_map.h:198
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition: tile_map.h:312
static debug_inline TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition: tile_map.h:96
void SetAnimationFrame(Tile t, uint8_t frame)
Set a new animation frame.
Definition: tile_map.h:262
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
Definition: tile_map.h:279
void SetTropicZone(Tile tile, TropicZone type)
Set the tropic zone.
Definition: tile_map.h:225
static debug_inline uint TileHeight(Tile tile)
Returns the height of a tile.
Definition: tile_map.h:29
@ TROPICZONE_NORMAL
Normal tropiczone.
Definition: tile_type.h:77
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in #ZOOM_BASE.
Definition: tile_type.h:18
static const uint MIN_SNOWLINE_HEIGHT
Minimum snowline height.
Definition: tile_type.h:32
static const uint TILE_SIZE
Tile size in world coordinates.
Definition: tile_type.h:15
static const uint TILE_UNIT_MASK
For masking in/out the inner-tile world coordinate units.
Definition: tile_type.h:16
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition: tile_type.h:95
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition: tile_type.h:87
@ MP_TREES
Tile got trees.
Definition: tile_type.h:52
@ MP_ROAD
A tile with road (or tram tracks)
Definition: tile_type.h:50
@ MP_STATION
A tile of a station.
Definition: tile_type.h:53
@ MP_TUNNELBRIDGE
Tunnel entry/exit and bridge heads.
Definition: tile_type.h:57
@ MP_CLEAR
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition: tile_type.h:48
@ MP_HOUSE
A house by a town.
Definition: tile_type.h:51
@ MP_WATER
Water tile.
Definition: tile_type.h:54
@ MP_RAILWAY
A railway.
Definition: tile_type.h:49
@ MP_INDUSTRY
Part of an industry.
Definition: tile_type.h:56
@ MP_VOID
Invisible tiles at the SW and SE border.
Definition: tile_type.h:55
@ MP_OBJECT
Contains objects such as transmitters and owned land.
Definition: tile_type.h:58
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount)
Definition: town.h:33
const CargoSpec * FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect)
Determines the first cargo with a certain town effect.
Definition: town_cmd.cpp:3026
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount)
Definition: town.h:34
@ TOWN_CUSTOM_GROWTH
Growth rate is controlled by GS.
Definition: town.h:199
void UpdateTownMaxPass(Town *t)
Update the maximum amount of montly passengers and mail for a town, based on its population.
Definition: town_cmd.cpp:1966
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
Definition: town_cmd.cpp:3852
void ClearAllTownCachedNames()
Clear the cached_name of all towns.
Definition: town_cmd.cpp:435
static const uint16_t TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition: town.h:35
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition: town_cmd.cpp:3870
void MakeDefaultName(T *obj)
Set the default name for a depot/waypoint.
Definition: town.h:253
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition: town_cmd.cpp:427
HouseID GetHouseType(Tile t)
Get the type of this house, which is an index into the house spec array.
Definition: town_map.h:60
void SetLiftPosition(Tile t, uint8_t pos)
Set the position of the lift on this animated house.
Definition: town_map.h:136
void SetHouseCompleted(Tile t, bool status)
Mark this house as been completed.
Definition: town_map.h:157
void SetTownIndex(Tile t, TownID index)
Set the town index for a road or house tile.
Definition: town_map.h:35
bool IsHouseCompleted(Tile t)
Get the completion of this house.
Definition: town_map.h:146
static constexpr int RATING_INITIAL
initial rating
Definition: town_type.h:43
@ TCGM_ORIGINAL
Original algorithm (quadratic cargo by population)
Definition: town_type.h:104
TownLayout
Town Layouts.
Definition: town_type.h:79
@ TL_RANDOM
Random town layout.
Definition: town_type.h:86
@ TL_BETTER_ROADS
Extended original algorithm (min. 2 distance between roads)
Definition: town_type.h:82
TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track bits incidating with that diagdir.
Definition: track_func.h:524
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
Definition: track_func.h:537
TrackBits TrackStatusToTrackBits(TrackStatus ts)
Returns the present-track-information of a TrackStatus.
Definition: track_func.h:363
TrackBits
Allow incrementing of Track variables.
Definition: track_type.h:35
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels)
Definition: track_type.h:52
@ TRACK_BIT_Y
Y-axis track.
Definition: track_type.h:38
@ TRACK_BIT_NONE
No track.
Definition: track_type.h:36
@ TRACK_BIT_X
X-axis track.
Definition: track_type.h:37
@ INVALID_TRACK
Flag for an invalid track.
Definition: track_type.h:28
@ TRACK_LOWER
Track in the lower corner of the tile (south)
Definition: track_type.h:24
@ TRACK_UPPER
Track in the upper corner of the tile (north)
Definition: track_type.h:23
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition: train_cmd.cpp:76
@ TFP_NONE
Normal operation.
Definition: train.h:38
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
Definition: train.h:39
TransportType
Available types of transport.
@ TRANSPORT_RAIL
Transport by train.
@ TRANSPORT_ROAD
Transport by road vehicle.
TreeGround GetTreeGround(Tile t)
Returns the groundtype for tree tiles.
Definition: tree_map.h:102
TreeGround
Enumeration for ground types of tiles with trees.
Definition: tree_map.h:52
@ TREE_GROUND_SHORE
shore
Definition: tree_map.h:56
@ TREE_GROUND_SNOW_DESERT
a desert or snow tile, depend on landscape
Definition: tree_map.h:55
bool IsTunnelTile(Tile t)
Is this a tunnel (entrance)?
Definition: tunnel_map.h:34
const uint8_t _tunnel_visibility_frame[DIAGDIR_END]
Frame when a vehicle should be hidden in a tunnel with a certain direction.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TransportType GetTunnelBridgeTransportType(Tile t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
void SetTunnelBridgeReservation(Tile t, bool b)
Set the reservation state of the rail tunnel/bridge.
@ VF_PATHFINDER_LOST
Vehicle's pathfinder is lost.
Definition: vehicle_base.h:52
@ VF_LOADING_FINISHED
Vehicle has finished loading.
Definition: vehicle_base.h:45
@ VS_STOPPED
Vehicle is stopped by the player.
Definition: vehicle_base.h:34
@ VS_HIDDEN
Vehicle is not visible.
Definition: vehicle_base.h:33
@ VS_CRASHED
Vehicle is crashed.
Definition: vehicle_base.h:40
@ VEH_INVALID
Non-existing type of vehicle.
Definition: vehicle_type.h:35
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
void MakeVoid(Tile t)
Make a nice void tile ;)
Definition: void_map.h:19
void MakeShore(Tile t)
Helper function to make a coast tile.
Definition: water_map.h:381
void SetWaterClass(Tile t, WaterClass wc)
Set the water class at a tile.
Definition: water_map.h:124
bool IsShipDepot(Tile t)
Is it a water tile with a ship depot on it?
Definition: water_map.h:222
WaterClass
classes of water (for WATER_TILE_CLEAR water tile type).
Definition: water_map.h:39
@ WATER_CLASS_SEA
Sea.
Definition: water_map.h:40
@ WATER_CLASS_CANAL
Canal.
Definition: water_map.h:41
@ WATER_CLASS_INVALID
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition: water_map.h:43
@ WATER_CLASS_RIVER
River.
Definition: water_map.h:42
bool IsShipDepotTile(Tile t)
Is it a ship depot tile?
Definition: water_map.h:232
bool IsCoast(Tile t)
Is it a coast tile?
Definition: water_map.h:201
WaterTileType GetWaterTileType(Tile t)
Get the water tile type of a tile.
Definition: water_map.h:78
void SetNonFloodingWaterTile(Tile t, bool b)
Set the non-flooding water tile state of a tile.
Definition: water_map.h:524
void SetWaterTileType(Tile t, WaterTileType type)
Set the water tile type of a tile.
Definition: water_map.h:89
@ WATER_TILE_COAST
Coast.
Definition: water_map.h:33
@ WATER_TILE_LOCK
Water lock.
Definition: water_map.h:34
@ WATER_TILE_DEPOT
Water Depot.
Definition: water_map.h:35
@ WATER_TILE_CLEAR
Plain water.
Definition: water_map.h:32
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition: water_map.h:112
void MakeCanal(Tile t, Owner o, uint8_t random_bits)
Make a canal tile.
Definition: water_map.h:443
uint8_t GetLockPart(Tile t)
Get the part of a lock.
Definition: water_map.h:326
TileIndex GetOtherShipDepotTile(Tile t)
Get the other tile of the ship depot.
Definition: water_map.h:278
void SetDockingTile(Tile t, bool b)
Set the docking tile state of a tile.
Definition: water_map.h:361
bool IsWater(Tile t)
Is it a plain water tile?
Definition: water_map.h:147
bool IsLock(Tile t)
Is there a lock on a given water tile?
Definition: water_map.h:303
void MakeSea(Tile t)
Make a sea tile.
Definition: water_map.h:422
@ LOCK_PART_MIDDLE
Middle part of a lock.
Definition: water_map.h:66
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition: window.cpp:1818
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:3211
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:3228
Window functions not directly related to making/drawing windows.
@ WC_COMPANY_INFRASTRUCTURE
Company infrastructure overview; Window numbers:
Definition: window_type.h:587
@ WC_COMPANY_COLOUR
Company colour selection; Window numbers:
Definition: window_type.h:230
@ WC_BUILD_TOOLBAR
Build toolbar; Window numbers:
Definition: window_type.h:73
void YapfNotifyTrackLayoutChange(TileIndex tile, Track track)
Use this function to notify YAPF that track layout (or signal configuration) has change.
Definition: yapf_rail.cpp:635
ZoomLevel
All zoom levels we know.
Definition: zoom_type.h:16