OpenTTD
afterload.cpp
Go to the documentation of this file.
1 /* $Id: afterload.cpp 27020 2014-10-15 18:31:37Z rubidium $ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #include "../stdafx.h"
13 #include "../void_map.h"
14 #include "../signs_base.h"
15 #include "../depot_base.h"
16 #include "../fios.h"
17 #include "../gamelog_internal.h"
18 #include "../network/network.h"
19 #include "../gfxinit.h"
20 #include "../viewport_func.h"
21 #include "../industry.h"
22 #include "../clear_map.h"
23 #include "../vehicle_func.h"
24 #include "../string_func.h"
25 #include "../date_func.h"
26 #include "../roadveh.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 "../ai/ai_gui.hpp"
43 #include "../town.h"
44 #include "../economy_base.h"
45 #include "../animated_tile_func.h"
46 #include "../subsidy_base.h"
47 #include "../subsidy_func.h"
48 #include "../newgrf.h"
49 #include "../engine_func.h"
50 #include "../rail_gui.h"
51 #include "../core/backup_type.hpp"
52 #include "../smallmap_gui.h"
53 #include "../news_func.h"
54 #include "../order_backup.h"
55 #include "../error.h"
56 #include "../disaster_vehicle.h"
57 
58 
59 #include "saveload_internal.h"
60 
61 #include <signal.h>
62 
63 #include "../safeguards.h"
64 
65 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
66 
77 void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
78 {
79  /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
80  * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
81  if (!IsTileFlat(t)) {
82  if (include_invalid_water_class) {
84  return;
85  } else {
86  SlErrorCorrupt("Invalid water class for dry tile");
87  }
88  }
89 
90  /* Mark tile dirty in all cases */
92 
93  if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
94  /* tiles at map borders are always WATER_CLASS_SEA */
96  return;
97  }
98 
99  bool has_water = false;
100  bool has_canal = false;
101  bool has_river = false;
102 
103  for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
104  TileIndex neighbour = TileAddByDiagDir(t, dir);
105  switch (GetTileType(neighbour)) {
106  case MP_WATER:
107  /* clear water and shipdepots have already a WaterClass associated */
108  if (IsCoast(neighbour)) {
109  has_water = true;
110  } else if (!IsLock(neighbour)) {
111  switch (GetWaterClass(neighbour)) {
112  case WATER_CLASS_SEA: has_water = true; break;
113  case WATER_CLASS_CANAL: has_canal = true; break;
114  case WATER_CLASS_RIVER: has_river = true; break;
115  default: SlErrorCorrupt("Invalid water class for tile");
116  }
117  }
118  break;
119 
120  case MP_RAILWAY:
121  /* Shore or flooded halftile */
122  has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
123  break;
124 
125  case MP_TREES:
126  /* trees on shore */
127  has_water |= (GB(_m[neighbour].m2, 4, 2) == TREE_GROUND_SHORE);
128  break;
129 
130  default: break;
131  }
132  }
133 
134  if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
136  return;
137  }
138 
139  if (has_river && !has_canal) {
141  } else if (has_canal || !has_water) {
143  } else {
145  }
146 }
147 
148 static void ConvertTownOwner()
149 {
150  for (TileIndex tile = 0; tile != MapSize(); tile++) {
151  switch (GetTileType(tile)) {
152  case MP_ROAD:
153  if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
154  _m[tile].m3 = OWNER_TOWN;
155  }
156  /* FALL THROUGH */
157 
158  case MP_TUNNELBRIDGE:
159  if (_m[tile].m1 & 0x80) SetTileOwner(tile, OWNER_TOWN);
160  break;
161 
162  default: break;
163  }
164  }
165 }
166 
167 /* since savegame version 4.1, exclusive transport rights are stored at towns */
168 static void UpdateExclusiveRights()
169 {
170  Town *t;
171 
172  FOR_ALL_TOWNS(t) {
174  }
175 
176  /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
177  * could be implemented this way:
178  * 1.) Go through all stations
179  * Build an array town_blocked[ town_id ][ company_id ]
180  * that stores if at least one station in that town is blocked for a company
181  * 2.) Go through that array, if you find a town that is not blocked for
182  * one company, but for all others, then give him exclusivity.
183  */
184 }
185 
186 static const byte convert_currency[] = {
187  0, 1, 12, 8, 3,
188  10, 14, 19, 4, 5,
189  9, 11, 13, 6, 17,
190  16, 22, 21, 7, 15,
191  18, 2, 20,
192 };
193 
194 /* since savegame version 4.2 the currencies are arranged differently */
195 static void UpdateCurrencies()
196 {
198 }
199 
200 /* Up to revision 1413 the invisible tiles at the southern border have not been
201  * MP_VOID, even though they should have. This is fixed by this function
202  */
203 static void UpdateVoidTiles()
204 {
205  uint i;
206 
207  for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
208  for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
209 }
210 
211 static inline RailType UpdateRailType(RailType rt, RailType min)
212 {
213  return rt >= min ? (RailType)(rt + 1): rt;
214 }
215 
220 {
224 }
225 
236 {
237  /* Initialize windows */
240 
241  /* Update coordinates of the signs. */
243  ResetViewportAfterLoadGame();
244 
245  Company *c;
246  FOR_ALL_COMPANIES(c) {
247  /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
248  * accordingly if it is not the case. No need to set it on companies that are not been used already,
249  * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
250  if (_file_to_saveload.filetype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
252  }
253  }
254 
255  /* Count number of objects per type */
256  Object *o;
257  FOR_ALL_OBJECTS(o) {
259  }
260 
261  /* Identify owners of persistent storage arrays */
262  Industry *i;
263  FOR_ALL_INDUSTRIES(i) {
264  if (i->psa != NULL) {
265  i->psa->feature = GSF_INDUSTRIES;
266  i->psa->tile = i->location.tile;
267  }
268  }
269  Station *s;
270  FOR_ALL_STATIONS(s) {
271  if (s->airport.psa != NULL) {
272  s->airport.psa->feature = GSF_AIRPORTS;
273  s->airport.psa->tile = s->airport.tile;
274  }
275  }
276  Town *t;
277  FOR_ALL_TOWNS(t) {
278  for (std::list<PersistentStorage *>::iterator it = t->psa_list.begin(); it != t->psa_list.end(); ++it) {
279  (*it)->feature = GSF_FAKE_TOWNS;
280  (*it)->tile = t->xy;
281  }
282  }
283 
284  RecomputePrices();
285 
287 
290 
291  /* Towns have a noise controlled number of airports system
292  * So each airport's noise value must be added to the town->noise_reached value
293  * Reset each town's noise_reached value to '0' before. */
295 
297  ShowNewGRFError();
299 
300  /* Rebuild the smallmap list of owners. */
302 }
303 
304 typedef void (CDECL *SignalHandlerPointer)(int);
305 static SignalHandlerPointer _prev_segfault = NULL;
306 static SignalHandlerPointer _prev_abort = NULL;
307 static SignalHandlerPointer _prev_fpe = NULL;
308 
309 static void CDECL HandleSavegameLoadCrash(int signum);
310 
315 static void SetSignalHandlers()
316 {
317  _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
318  _prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
319  _prev_fpe = signal(SIGFPE, HandleSavegameLoadCrash);
320 }
321 
325 static void ResetSignalHandlers()
326 {
327  signal(SIGSEGV, _prev_segfault);
328  signal(SIGABRT, _prev_abort);
329  signal(SIGFPE, _prev_fpe);
330 }
331 
338 {
340  if (la->at != GLAT_LOAD) return &c->ident;
341 
342  const LoggedChange *lcend = &la->change[la->changes];
343  for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
344  if (lc->ct == GLCT_GRFCOMPAT && lc->grfcompat.grfid == c->ident.grfid) return &lc->grfcompat;
345  }
346 
347  return &c->ident;
348 }
349 
352 
359 {
361 }
362 
369 static void CDECL HandleSavegameLoadCrash(int signum)
370 {
372 
373  char buffer[8192];
374  char *p = buffer;
375  p += seprintf(p, lastof(buffer), "Loading your savegame caused OpenTTD to crash.\n");
376 
377  for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != NULL; c = c->next) {
378  _saveload_crash_with_missing_newgrfs = HasBit(c->flags, GCF_COMPATIBLE) || c->status == GCS_NOT_FOUND;
379  }
380 
381  if (_saveload_crash_with_missing_newgrfs) {
382  p += seprintf(p, lastof(buffer),
383  "This is most likely caused by a missing NewGRF or a NewGRF that\n"
384  "has been loaded as replacement for a missing NewGRF. OpenTTD\n"
385  "cannot easily determine whether a replacement NewGRF is of a newer\n"
386  "or older version.\n"
387  "It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
388  "This means that if the author makes incompatible NewGRFs with the\n"
389  "same GRF ID OpenTTD cannot magically do the right thing. In most\n"
390  "cases OpenTTD will load the savegame and not crash, but this is an\n"
391  "exception.\n"
392  "Please load the savegame with the appropriate NewGRFs installed.\n"
393  "The missing/compatible NewGRFs are:\n");
394 
395  for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
396  if (HasBit(c->flags, GCF_COMPATIBLE)) {
397  const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
398  char buf[40];
399  md5sumToString(buf, lastof(buf), replaced->md5sum);
400  p += seprintf(p, lastof(buffer), "NewGRF %08X (checksum %s) not found.\n Loaded NewGRF \"%s\" with same GRF ID instead.\n", BSWAP32(c->ident.grfid), buf, c->filename);
401  }
402  if (c->status == GCS_NOT_FOUND) {
403  char buf[40];
404  md5sumToString(buf, lastof(buf), c->ident.md5sum);
405  p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s.\n", BSWAP32(c->ident.grfid), c->filename, buf);
406  }
407  }
408  } else {
409  p += seprintf(p, lastof(buffer),
410  "This is probably caused by a corruption in the savegame.\n"
411  "Please file a bug report and attach this savegame.\n");
412  }
413 
414  ShowInfo(buffer);
415 
416  SignalHandlerPointer call = NULL;
417  switch (signum) {
418  case SIGSEGV: call = _prev_segfault; break;
419  case SIGABRT: call = _prev_abort; break;
420  case SIGFPE: call = _prev_fpe; break;
421  default: NOT_REACHED();
422  }
423  if (call != NULL) call(signum);
424 }
425 
432 {
434 
435  /* remove leftover rail piece from crossing (from very old savegames) */
436  Train *v = NULL, *w;
437  FOR_ALL_TRAINS(w) {
438  if (w->tile == t) {
439  v = w;
440  break;
441  }
442  }
443 
444  if (v != NULL) {
445  /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
446  SetTileOwner(t, v->owner);
447  return;
448  }
449 
450  /* try to find any connected rail */
451  for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
452  TileIndex tt = t + TileOffsByDiagDir(dd);
453  if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
456  SetTileOwner(t, GetTileOwner(tt));
457  return;
458  }
459  }
460 
461  if (IsLevelCrossingTile(t)) {
462  /* else change the crossing to normal road (road vehicles won't care) */
465  return;
466  }
467 
468  /* if it's not a crossing, make it clean land */
469  MakeClear(t, CLEAR_GRASS, 0);
470 }
471 
479 {
480  /* Compute place where this vehicle entered the tile */
481  int entry_x = v->x_pos;
482  int entry_y = v->y_pos;
483  switch (dir) {
484  case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
485  case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
486  case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
487  case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
488  case INVALID_DIR: break;
489  default: NOT_REACHED();
490  }
491  byte entry_z = GetSlopePixelZ(entry_x, entry_y);
492 
493  /* Compute middle of the tile. */
494  int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
495  int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
496  byte middle_z = GetSlopePixelZ(middle_x, middle_y);
497 
498  /* middle_z == entry_z, no height change. */
499  if (middle_z == entry_z) return 0;
500 
501  /* middle_z < entry_z, we are going downwards. */
502  if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
503 
504  /* middle_z > entry_z, we are going upwards. */
505  return 1U << GVF_GOINGUP_BIT;
506 }
507 
514 static inline bool MayHaveBridgeAbove(TileIndex t)
515 {
516  return IsTileType(t, MP_CLEAR) || IsTileType(t, MP_RAILWAY) || IsTileType(t, MP_ROAD) ||
518 }
519 
526 {
528 
529  TileIndex map_size = MapSize();
530 
531  extern TileIndex _cur_tileloop_tile; // From landscape.cpp.
532  /* The LFSR used in RunTileLoop iteration cannot have a zeroed state, make it non-zeroed. */
533  if (_cur_tileloop_tile == 0) _cur_tileloop_tile = 1;
534 
536 
538  GamelogTestMode();
539 
541 
542  if (IsSavegameVersionBefore(119)) {
544  } else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
545  DEBUG(net, 0, "The loading savegame was paused due to an error state.");
546  DEBUG(net, 0, " The savegame cannot be used for multiplayer!");
547  /* Restore the signals */
549  return false;
550  } else if (!_networking || _network_server) {
551  /* If we are in single player, i.e. not networking, and loading the
552  * savegame or we are loading the savegame as network server we do
553  * not want to be bothered by being paused because of the automatic
554  * reason of a network server, e.g. joining clients or too few
555  * active clients. Note that resetting these values for a network
556  * client are very bad because then the client is going to execute
557  * the game loop when the server is not, i.e. it desyncs. */
559  }
560 
561  /* In very old versions, size of train stations was stored differently.
562  * They had swapped width and height if station was built along the Y axis.
563  * TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
564  * Because the data stored by TTDPatch are unusable for rail stations > 7x7,
565  * recompute the width and height. Doing this unconditionally for all old
566  * savegames simplifies the code. */
567  if (IsSavegameVersionBefore(2)) {
568  Station *st;
569  FOR_ALL_STATIONS(st) {
570  st->train_station.w = st->train_station.h = 0;
571  }
572  for (TileIndex t = 0; t < map_size; t++) {
573  if (!IsTileType(t, MP_STATION)) continue;
574  if (_m[t].m5 > 7) continue; // is it a rail station tile?
575  st = Station::Get(_m[t].m2);
576  assert(st->train_station.tile != 0);
577  int dx = TileX(t) - TileX(st->train_station.tile);
578  int dy = TileY(t) - TileY(st->train_station.tile);
579  assert(dx >= 0 && dy >= 0);
580  st->train_station.w = max<uint>(st->train_station.w, dx + 1);
581  st->train_station.h = max<uint>(st->train_station.h, dy + 1);
582  }
583  }
584 
585  if (IsSavegameVersionBefore(194)) {
587 
588  /* In old savegame versions, the heightlevel was coded in bits 0..3 of the type field */
589  for (TileIndex t = 0; t < map_size; t++) {
590  _m[t].height = GB(_m[t].type, 0, 4);
591  SB(_m[t].type, 0, 2, GB(_me[t].m6, 0, 2));
592  SB(_me[t].m6, 0, 2, 0);
593  if (MayHaveBridgeAbove(t)) {
594  SB(_m[t].type, 2, 2, GB(_me[t].m6, 6, 2));
595  SB(_me[t].m6, 6, 2, 0);
596  } else {
597  SB(_m[t].type, 2, 2, 0);
598  }
599  }
600  }
601 
602  /* in version 2.1 of the savegame, town owner was unified. */
603  if (IsSavegameVersionBefore(2, 1)) ConvertTownOwner();
604 
605  /* from version 4.1 of the savegame, exclusive rights are stored at towns */
606  if (IsSavegameVersionBefore(4, 1)) UpdateExclusiveRights();
607 
608  /* from version 4.2 of the savegame, currencies are in a different order */
609  if (IsSavegameVersionBefore(4, 2)) UpdateCurrencies();
610 
611  /* In old version there seems to be a problem that water is owned by
612  * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
613  * (4.3) version, so I just check when versions are older, and then
614  * walk through the whole map.. */
615  if (IsSavegameVersionBefore(4, 3)) {
616  for (TileIndex t = 0; t < map_size; t++) {
617  if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
619  }
620  }
621  }
622 
623  if (IsSavegameVersionBefore(84)) {
624  Company *c;
625  FOR_ALL_COMPANIES(c) {
626  c->name = CopyFromOldName(c->name_1);
627  if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
629  if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
630  }
631 
632  Station *st;
633  FOR_ALL_STATIONS(st) {
634  st->name = CopyFromOldName(st->string_id);
635  /* generating new name would be too much work for little effect, use the station name fallback */
636  if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
637  }
638 
639  Town *t;
640  FOR_ALL_TOWNS(t) {
641  t->name = CopyFromOldName(t->townnametype);
642  if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
643  }
644  }
645 
646  /* From this point the old names array is cleared. */
647  ResetOldNames();
648 
649  if (IsSavegameVersionBefore(106)) {
650  /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
651  Station *st;
652  FOR_ALL_STATIONS(st) {
653  if (st->airport.tile == 0) st->airport.tile = INVALID_TILE;
654  if (st->dock_tile == 0) st->dock_tile = INVALID_TILE;
655  if (st->train_station.tile == 0) st->train_station.tile = INVALID_TILE;
656  }
657 
658  /* the same applies to Company::location_of_HQ */
659  Company *c;
660  FOR_ALL_COMPANIES(c) {
661  if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(4) && c->location_of_HQ == 0xFFFF)) {
663  }
664  }
665  }
666 
667  /* convert road side to my format. */
669 
670  /* Check if all NewGRFs are present, we are very strict in MP mode */
672  for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
673  if (c->status == GCS_NOT_FOUND) {
674  GamelogGRFRemove(c->ident.grfid);
675  } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
676  GamelogGRFCompatible(&c->ident);
677  }
678  }
679 
680  if (_networking && gcf_res != GLC_ALL_GOOD) {
681  SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
682  /* Restore the signals */
684  return false;
685  }
686 
687  switch (gcf_res) {
688  case GLC_COMPATIBLE: ShowErrorMessage(STR_NEWGRF_COMPATIBLE_LOAD_WARNING, INVALID_STRING_ID, WL_CRITICAL); break;
689  case GLC_NOT_FOUND: ShowErrorMessage(STR_NEWGRF_DISABLED_WARNING, INVALID_STRING_ID, WL_CRITICAL); _pause_mode = PM_PAUSED_ERROR; break;
690  default: break;
691  }
692 
693  /* The value of _date_fract got divided, so make sure that old games are converted correctly. */
695 
696  /* Update current year
697  * must be done before loading sprites as some newgrfs check it */
699 
700  /*
701  * Force the old behaviour for compatibility reasons with old savegames. As new
702  * settings can only be loaded from new savegames loading old savegames with new
703  * versions of OpenTTD will normally initialize settings newer than the savegame
704  * version with "new game" defaults which the player can define to their liking.
705  * For some settings we override that to keep the behaviour the same as when the
706  * game was saved.
707  *
708  * Note that there is no non-stop in here. This is because the setting could have
709  * either value in TTDPatch. To convert it properly the user has to make sure the
710  * right value has been chosen in the settings. Otherwise we will be converting
711  * it incorrectly in half of the times without a means to correct that.
712  */
719  if (IsSavegameVersionBefore(133)) {
722  }
727  if (IsSavegameVersionBefore(159)) {
731  }
733  if (IsSavegameVersionBefore(183)) {
738  }
739 
740  /* Load the sprites */
741  GfxLoadSprites();
743 
744  /* Copy temporary data to Engine pool */
746 
747  /* Connect front and rear engines of multiheaded trains and converts
748  * subtype to the new format */
750 
751  /* Connect front and rear engines of multiheaded trains */
753 
754  /* Fix the CargoPackets *and* fix the caches of CargoLists.
755  * If this isn't done before Stations and especially Vehicles are
756  * running their AfterLoad we might get in trouble. In the case of
757  * vehicles we could give the wrong (cached) count of items in a
758  * vehicle which causes different results when getting their caches
759  * filled; and that could eventually lead to desyncs. */
761 
762  /* Oilrig was moved from id 15 to 9. We have to do this conversion
763  * here as AfterLoadVehicles can check it indirectly via the newgrf
764  * code. */
765  if (IsSavegameVersionBefore(139)) {
766  Station *st;
767  FOR_ALL_STATIONS(st) {
768  if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
769  st->airport.type = AT_OILRIG;
770  }
771  }
772  }
773 
774  /* Update all vehicles */
775  AfterLoadVehicles(true);
776 
777  /* Make sure there is an AI attached to an AI company */
778  {
779  Company *c;
780  FOR_ALL_COMPANIES(c) {
781  if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
782  }
783  }
784 
785  /* make sure there is a town in the game */
786  if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
787  SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
788  /* Restore the signals */
790  return false;
791  }
792 
793  /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
794  * This problem appears in savegame version 21 too, see r3455. But after loading the
795  * savegame and saving again, the buggy map array could be converted to new savegame
796  * version. It didn't show up before r12070. */
797  if (IsSavegameVersionBefore(87)) UpdateVoidTiles();
798 
799  /* If Load Scenario / New (Scenario) Game is used,
800  * a company does not exist yet. So create one here.
801  * 1 exception: network-games. Those can have 0 companies
802  * But this exception is not true for non-dedicated network servers! */
804  DoStartupNewCompany(false);
807  }
808 
809  /* Fix the cache for cargo payments. */
810  CargoPayment *cp;
812  cp->front->cargo_payment = cp;
814  }
815 
816  if (IsSavegameVersionBefore(72)) {
817  /* Locks in very old savegames had OWNER_WATER as owner */
818  for (TileIndex t = 0; t < MapSize(); t++) {
819  switch (GetTileType(t)) {
820  default: break;
821 
822  case MP_WATER:
824  break;
825 
826  case MP_STATION: {
827  if (HasBit(_me[t].m6, 3)) SetBit(_me[t].m6, 2);
828  StationGfx gfx = GetStationGfx(t);
829  StationType st;
830  if ( IsInsideMM(gfx, 0, 8)) { // Rail station
831  st = STATION_RAIL;
832  SetStationGfx(t, gfx - 0);
833  } else if (IsInsideMM(gfx, 8, 67)) { // Airport
834  st = STATION_AIRPORT;
835  SetStationGfx(t, gfx - 8);
836  } else if (IsInsideMM(gfx, 67, 71)) { // Truck
837  st = STATION_TRUCK;
838  SetStationGfx(t, gfx - 67);
839  } else if (IsInsideMM(gfx, 71, 75)) { // Bus
840  st = STATION_BUS;
841  SetStationGfx(t, gfx - 71);
842  } else if (gfx == 75) { // Oil rig
843  st = STATION_OILRIG;
844  SetStationGfx(t, gfx - 75);
845  } else if (IsInsideMM(gfx, 76, 82)) { // Dock
846  st = STATION_DOCK;
847  SetStationGfx(t, gfx - 76);
848  } else if (gfx == 82) { // Buoy
849  st = STATION_BUOY;
850  SetStationGfx(t, gfx - 82);
851  } else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
852  st = STATION_AIRPORT;
853  SetStationGfx(t, gfx - 83 + 67 - 8);
854  } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
855  st = STATION_TRUCK;
857  } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
858  st = STATION_BUS;
860  } else {
861  /* Restore the signals */
863  return false;
864  }
865  SB(_me[t].m6, 3, 3, st);
866  break;
867  }
868  }
869  }
870  }
871 
872  for (TileIndex t = 0; t < map_size; t++) {
873  switch (GetTileType(t)) {
874  case MP_STATION: {
876 
877  /* Set up station spread */
878  bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
879 
880  /* Waypoints don't have road stops/oil rigs in the old format */
881  if (!Station::IsExpected(bst)) break;
882  Station *st = Station::From(bst);
883 
884  switch (GetStationType(t)) {
885  case STATION_TRUCK:
886  case STATION_BUS:
887  if (IsSavegameVersionBefore(6)) {
888  /* Before version 5 you could not have more than 250 stations.
889  * Version 6 adds large maps, so you could only place 253*253
890  * road stops on a map (no freeform edges) = 64009. So, yes
891  * someone could in theory create such a full map to trigger
892  * this assertion, it's safe to assume that's only something
893  * theoretical and does not happen in normal games. */
894  assert(RoadStop::CanAllocateItem());
895 
896  /* From this version on there can be multiple road stops of the
897  * same type per station. Convert the existing stops to the new
898  * internal data structure. */
899  RoadStop *rs = new RoadStop(t);
900 
901  RoadStop **head =
902  IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
903  *head = rs;
904  }
905  break;
906 
907  case STATION_OILRIG: {
908  /* Very old savegames sometimes have phantom oil rigs, i.e.
909  * an oil rig which got shut down, but not completely removed from
910  * the map
911  */
912  TileIndex t1 = TILE_ADDXY(t, 0, 1);
913  if (IsTileType(t1, MP_INDUSTRY) &&
914  GetIndustryGfx(t1) == GFX_OILRIG_1) {
915  /* The internal encoding of oil rigs was changed twice.
916  * It was 3 (till 2.2) and later 5 (till 5.1).
917  * Setting it unconditionally does not hurt.
918  */
920  } else {
921  DeleteOilRig(t);
922  }
923  break;
924  }
925 
926  default: break;
927  }
928  break;
929  }
930 
931  default: break;
932  }
933  }
934 
935  /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
936  * This has to be called after the oilrig airport_type update above ^^^ ! */
938 
939  /* In version 6.1 we put the town index in the map-array. To do this, we need
940  * to use m2 (16bit big), so we need to clean m2, and that is where this is
941  * all about ;) */
942  if (IsSavegameVersionBefore(6, 1)) {
943  for (TileIndex t = 0; t < map_size; t++) {
944  switch (GetTileType(t)) {
945  case MP_HOUSE:
946  _m[t].m4 = _m[t].m2;
948  break;
949 
950  case MP_ROAD:
951  _m[t].m4 |= (_m[t].m2 << 4);
952  if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
954  } else {
955  SetTownIndex(t, 0);
956  }
957  break;
958 
959  default: break;
960  }
961  }
962  }
963 
964  /* Force the freeform edges to false for old savegames. */
965  if (IsSavegameVersionBefore(111)) {
967  }
968 
969  /* From version 9.0, we update the max passengers of a town (was sometimes negative
970  * before that. */
971  if (IsSavegameVersionBefore(9)) {
972  Town *t;
973  FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
974  }
975 
976  /* From version 16.0, we included autorenew on engines, which are now saved, but
977  * of course, we do need to initialize them for older savegames. */
978  if (IsSavegameVersionBefore(16)) {
979  Company *c;
980  FOR_ALL_COMPANIES(c) {
981  c->engine_renew_list = NULL;
982  c->settings.engine_renew = false;
984  c->settings.engine_renew_money = 100000;
985  }
986 
987  /* When loading a game, _local_company is not yet set to the correct value.
988  * However, in a dedicated server we are a spectator, so nothing needs to
989  * happen. In case we are not a dedicated server, the local company always
990  * becomes company 0, unless we are in the scenario editor where all the
991  * companies are 'invalid'.
992  */
994  if (!_network_dedicated && c != NULL) {
996  }
997  }
998 
999  if (IsSavegameVersionBefore(48)) {
1000  for (TileIndex t = 0; t < map_size; t++) {
1001  switch (GetTileType(t)) {
1002  case MP_RAILWAY:
1003  if (IsPlainRail(t)) {
1004  /* Swap ground type and signal type for plain rail tiles, so the
1005  * ground type uses the same bits as for depots and waypoints. */
1006  uint tmp = GB(_m[t].m4, 0, 4);
1007  SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
1008  SB(_m[t].m2, 0, 4, tmp);
1009  } else if (HasBit(_m[t].m5, 2)) {
1010  /* Split waypoint and depot rail type and remove the subtype. */
1011  ClrBit(_m[t].m5, 2);
1012  ClrBit(_m[t].m5, 6);
1013  }
1014  break;
1015 
1016  case MP_ROAD:
1017  /* Swap m3 and m4, so the track type for rail crossings is the
1018  * same as for normal rail. */
1019  Swap(_m[t].m3, _m[t].m4);
1020  break;
1021 
1022  default: break;
1023  }
1024  }
1025  }
1026 
1027  if (IsSavegameVersionBefore(61)) {
1028  /* Added the RoadType */
1029  bool old_bridge = IsSavegameVersionBefore(42);
1030  for (TileIndex t = 0; t < map_size; t++) {
1031  switch (GetTileType(t)) {
1032  case MP_ROAD:
1033  SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
1034  switch (GetRoadTileType(t)) {
1035  default: SlErrorCorrupt("Invalid road tile type");
1036  case ROAD_TILE_NORMAL:
1037  SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
1038  SB(_m[t].m4, 4, 4, 0);
1039  SB(_me[t].m6, 2, 4, 0);
1040  break;
1041  case ROAD_TILE_CROSSING:
1042  SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
1043  break;
1044  case ROAD_TILE_DEPOT: break;
1045  }
1047  break;
1048 
1049  case MP_STATION:
1051  break;
1052 
1053  case MP_TUNNELBRIDGE:
1054  /* Middle part of "old" bridges */
1055  if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
1056  if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1058  }
1059  break;
1060 
1061  default: break;
1062  }
1063  }
1064  }
1065 
1066  if (IsSavegameVersionBefore(114)) {
1067  bool fix_roadtypes = !IsSavegameVersionBefore(61);
1068  bool old_bridge = IsSavegameVersionBefore(42);
1069 
1070  for (TileIndex t = 0; t < map_size; t++) {
1071  switch (GetTileType(t)) {
1072  case MP_ROAD:
1073  if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
1074  SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
1075  switch (GetRoadTileType(t)) {
1076  default: SlErrorCorrupt("Invalid road tile type");
1077  case ROAD_TILE_NORMAL:
1078  SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
1079  SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
1080  SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4)); // tram bits
1081  SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
1082  SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4)); // road bits
1083  break;
1084 
1085  case ROAD_TILE_CROSSING:
1086  SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
1087  SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
1088  SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
1089  SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1)); // road axis
1090  SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1)); // crossing state
1091  break;
1092 
1093  case ROAD_TILE_DEPOT:
1094  break;
1095  }
1096  if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1097  const Town *town = CalcClosestTownFromTile(t);
1098  if (town != NULL) SetTownIndex(t, town->index);
1099  }
1100  _m[t].m4 = 0;
1101  break;
1102 
1103  case MP_STATION:
1104  if (!IsRoadStop(t)) break;
1105 
1106  if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
1107  SB(_me[t].m7, 0, 5, HasBit(_me[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
1108  SB(_m[t].m3, 4, 4, _m[t].m1);
1109  _m[t].m4 = 0;
1110  break;
1111 
1112  case MP_TUNNELBRIDGE:
1113  if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
1114  if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1115  if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
1116 
1117  Owner o = GetTileOwner(t);
1118  SB(_me[t].m7, 0, 5, o); // road owner
1119  SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
1120  }
1121  SB(_me[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
1122  SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
1123 
1124  _m[t].m2 = 0;
1125  _m[t].m4 = 0;
1126  break;
1127 
1128  default: break;
1129  }
1130  }
1131  }
1132 
1133  if (IsSavegameVersionBefore(42)) {
1134  Vehicle *v;
1135 
1136  for (TileIndex t = 0; t < map_size; t++) {
1138  if (IsBridgeTile(t)) {
1139  if (HasBit(_m[t].m5, 6)) { // middle part
1140  Axis axis = (Axis)GB(_m[t].m5, 0, 1);
1141 
1142  if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
1143  if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
1144  MakeRailNormal(
1145  t,
1146  GetTileOwner(t),
1147  axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
1148  GetRailType(t)
1149  );
1150  } else {
1151  TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
1152 
1154  t,
1155  axis == AXIS_X ? ROAD_Y : ROAD_X,
1157  town,
1159  );
1160  }
1161  } else {
1162  if (GB(_m[t].m5, 3, 2) == 0) {
1163  MakeClear(t, CLEAR_GRASS, 3);
1164  } else {
1165  if (!IsTileFlat(t)) {
1166  MakeShore(t);
1167  } else {
1168  if (GetTileOwner(t) == OWNER_WATER) {
1169  MakeSea(t);
1170  } else {
1171  MakeCanal(t, GetTileOwner(t), Random());
1172  }
1173  }
1174  }
1175  }
1176  SetBridgeMiddle(t, axis);
1177  } else { // ramp
1178  Axis axis = (Axis)GB(_m[t].m5, 0, 1);
1179  uint north_south = GB(_m[t].m5, 5, 1);
1180  DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
1181  TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
1182 
1183  _m[t].m5 = 1 << 7 | type << 2 | dir;
1184  }
1185  }
1186  }
1187 
1188  FOR_ALL_VEHICLES(v) {
1189  if (!v->IsGroundVehicle()) continue;
1190  if (IsBridgeTile(v->tile)) {
1192 
1193  if (dir != DirToDiagDir(v->direction)) continue;
1194  switch (dir) {
1195  default: SlErrorCorrupt("Invalid vehicle direction");
1196  case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
1197  case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
1198  case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
1199  case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
1200  }
1201  } else if (v->z_pos > GetSlopePixelZ(v->x_pos, v->y_pos)) {
1202  v->tile = GetNorthernBridgeEnd(v->tile);
1203  } else {
1204  continue;
1205  }
1206  if (v->type == VEH_TRAIN) {
1207  Train::From(v)->track = TRACK_BIT_WORMHOLE;
1208  } else {
1210  }
1211  }
1212  }
1213 
1214  /* Elrails got added in rev 24 */
1215  if (IsSavegameVersionBefore(24)) {
1216  RailType min_rail = RAILTYPE_ELECTRIC;
1217 
1218  Train *v;
1219  FOR_ALL_TRAINS(v) {
1220  RailType rt = RailVehInfo(v->engine_type)->railtype;
1221 
1222  v->railtype = rt;
1223  if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
1224  }
1225 
1226  /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
1227  for (TileIndex t = 0; t < map_size; t++) {
1228  switch (GetTileType(t)) {
1229  case MP_RAILWAY:
1230  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1231  break;
1232 
1233  case MP_ROAD:
1234  if (IsLevelCrossing(t)) {
1235  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1236  }
1237  break;
1238 
1239  case MP_STATION:
1240  if (HasStationRail(t)) {
1241  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1242  }
1243  break;
1244 
1245  case MP_TUNNELBRIDGE:
1247  SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1248  }
1249  break;
1250 
1251  default:
1252  break;
1253  }
1254  }
1255 
1256  FOR_ALL_TRAINS(v) {
1257  if (v->IsFrontEngine() || v->IsFreeWagon()) v->ConsistChanged(CCF_TRACK);
1258  }
1259 
1260  }
1261 
1262  /* In version 16.1 of the savegame a company can decide if trains, which get
1263  * replaced, shall keep their old length. In all prior versions, just default
1264  * to false */
1265  if (IsSavegameVersionBefore(16, 1)) {
1266  Company *c;
1267  FOR_ALL_COMPANIES(c) c->settings.renew_keep_length = false;
1268  }
1269 
1270  if (IsSavegameVersionBefore(123)) {
1271  /* Waypoints became subclasses of stations ... */
1273  /* ... and buoys were moved to waypoints. */
1275  }
1276 
1277  /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
1278  * room for PBS. Now in version 21 move it back :P. */
1280  for (TileIndex t = 0; t < map_size; t++) {
1281  switch (GetTileType(t)) {
1282  case MP_RAILWAY:
1283  if (HasSignals(t)) {
1284  /* Original signal type/variant was stored in m4 but since saveload
1285  * version 48 they are in m2. The bits has been already moved to m2
1286  * (see the code somewhere above) so don't use m4, use m2 instead. */
1287 
1288  /* convert PBS signals to combo-signals */
1289  if (HasBit(_m[t].m2, 2)) SB(_m[t].m2, 0, 2, SIGTYPE_COMBO);
1290 
1291  /* move the signal variant back */
1292  SB(_m[t].m2, 2, 1, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1293  ClrBit(_m[t].m2, 3);
1294  }
1295 
1296  /* Clear PBS reservation on track */
1297  if (!IsRailDepotTile(t)) {
1298  SB(_m[t].m4, 4, 4, 0);
1299  } else {
1300  ClrBit(_m[t].m3, 6);
1301  }
1302  break;
1303 
1304  case MP_STATION: // Clear PBS reservation on station
1305  ClrBit(_m[t].m3, 6);
1306  break;
1307 
1308  default: break;
1309  }
1310  }
1311  }
1312 
1313  if (IsSavegameVersionBefore(25)) {
1314  RoadVehicle *rv;
1315  FOR_ALL_ROADVEHICLES(rv) {
1316  rv->vehstatus &= ~0x40;
1317  }
1318  }
1319 
1320  if (IsSavegameVersionBefore(26)) {
1321  Station *st;
1322  FOR_ALL_STATIONS(st) {
1323  st->last_vehicle_type = VEH_INVALID;
1324  }
1325  }
1326 
1328 
1329  if (IsSavegameVersionBefore(34)) {
1330  Company *c;
1331  FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
1332  }
1333 
1334  Company *c;
1335  FOR_ALL_COMPANIES(c) {
1338  }
1339 
1340  if (!IsSavegameVersionBefore(27)) AfterLoadStations();
1341 
1342  /* Time starts at 0 instead of 1920.
1343  * Account for this in older games by adding an offset */
1344  if (IsSavegameVersionBefore(31)) {
1345  Station *st;
1346  Waypoint *wp;
1347  Engine *e;
1348  Industry *i;
1349  Vehicle *v;
1350 
1353 
1354  FOR_ALL_STATIONS(st) st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1356  FOR_ALL_ENGINES(e) e->intro_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1357  FOR_ALL_COMPANIES(c) c->inaugurated_year += ORIGINAL_BASE_YEAR;
1358  FOR_ALL_INDUSTRIES(i) i->last_prod_year += ORIGINAL_BASE_YEAR;
1359 
1360  FOR_ALL_VEHICLES(v) {
1363  }
1364  }
1365 
1366  /* From 32 on we save the industry who made the farmland.
1367  * To give this prettiness to old savegames, we remove all farmfields and
1368  * plant new ones. */
1369  if (IsSavegameVersionBefore(32)) {
1370  Industry *i;
1371 
1372  for (TileIndex t = 0; t < map_size; t++) {
1373  if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
1374  /* remove fields */
1375  MakeClear(t, CLEAR_GRASS, 3);
1376  }
1377  }
1378 
1379  FOR_ALL_INDUSTRIES(i) {
1380  uint j;
1381 
1383  for (j = 0; j != 50; j++) PlantRandomFarmField(i);
1384  }
1385  }
1386  }
1387 
1388  /* Setting no refit flags to all orders in savegames from before refit in orders were added */
1389  if (IsSavegameVersionBefore(36)) {
1390  Order *order;
1391  Vehicle *v;
1392 
1393  FOR_ALL_ORDERS(order) {
1394  order->SetRefit(CT_NO_REFIT);
1395  }
1396 
1397  FOR_ALL_VEHICLES(v) {
1399  }
1400  }
1401 
1402  /* from version 38 we have optional elrails, since we cannot know the
1403  * preference of a user, let elrails enabled; it can be disabled manually */
1405  /* do the same as when elrails were enabled/disabled manually just now */
1408 
1409  /* From version 53, the map array was changed for house tiles to allow
1410  * space for newhouses grf features. A new byte, m7, was also added. */
1411  if (IsSavegameVersionBefore(53)) {
1412  for (TileIndex t = 0; t < map_size; t++) {
1413  if (IsTileType(t, MP_HOUSE)) {
1414  if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
1415  /* Move the construction stage from m3[7..6] to m5[5..4].
1416  * The construction counter does not have to move. */
1417  SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
1418  SB(_m[t].m3, 6, 2, 0);
1419 
1420  /* The "house is completed" bit is now in m6[2]. */
1421  SetHouseCompleted(t, false);
1422  } else {
1423  /* The "lift has destination" bit has been moved from
1424  * m5[7] to m7[0]. */
1425  SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
1426  ClrBit(_m[t].m5, 7);
1427 
1428  /* The "lift is moving" bit has been removed, as it does
1429  * the same job as the "lift has destination" bit. */
1430  ClrBit(_m[t].m1, 7);
1431 
1432  /* The position of the lift goes from m1[7..0] to m6[7..2],
1433  * making m1 totally free, now. The lift position does not
1434  * have to be a full byte since the maximum value is 36. */
1435  SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
1436 
1437  _m[t].m1 = 0;
1438  _m[t].m3 = 0;
1439  SetHouseCompleted(t, true);
1440  }
1441  }
1442  }
1443  }
1444 
1445  /* Check and update house and town values */
1447 
1448  if (IsSavegameVersionBefore(43)) {
1449  for (TileIndex t = 0; t < map_size; t++) {
1450  if (IsTileType(t, MP_INDUSTRY)) {
1451  switch (GetIndustryGfx(t)) {
1452  case GFX_POWERPLANT_SPARKS:
1453  _m[t].m3 = GB(_m[t].m1, 2, 5);
1454  break;
1455 
1456  case GFX_OILWELL_ANIMATED_1:
1457  case GFX_OILWELL_ANIMATED_2:
1458  case GFX_OILWELL_ANIMATED_3:
1459  _m[t].m3 = GB(_m[t].m1, 0, 2);
1460  break;
1461 
1462  case GFX_COAL_MINE_TOWER_ANIMATED:
1463  case GFX_COPPER_MINE_TOWER_ANIMATED:
1464  case GFX_GOLD_MINE_TOWER_ANIMATED:
1465  _m[t].m3 = _m[t].m1;
1466  break;
1467 
1468  default: // No animation states to change
1469  break;
1470  }
1471  }
1472  }
1473  }
1474 
1475  if (IsSavegameVersionBefore(45)) {
1476  Vehicle *v;
1477  /* Originally just the fact that some cargo had been paid for was
1478  * stored to stop people cheating and cashing in several times. This
1479  * wasn't enough though as it was cleared when the vehicle started
1480  * loading again, even if it didn't actually load anything, so now the
1481  * amount that has been paid is stored. */
1482  FOR_ALL_VEHICLES(v) {
1483  ClrBit(v->vehicle_flags, 2);
1484  }
1485  }
1486 
1487  /* Buoys do now store the owner of the previous water tile, which can never
1488  * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
1489  if (IsSavegameVersionBefore(46)) {
1490  Waypoint *wp;
1491  FOR_ALL_WAYPOINTS(wp) {
1492  if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
1493  }
1494  }
1495 
1496  if (IsSavegameVersionBefore(50)) {
1497  Aircraft *v;
1498  /* Aircraft units changed from 8 mph to 1 km-ish/h */
1499  FOR_ALL_AIRCRAFT(v) {
1500  if (v->subtype <= AIR_AIRCRAFT) {
1501  const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
1502  v->cur_speed *= 128;
1503  v->cur_speed /= 10;
1504  v->acceleration = avi->acceleration;
1505  }
1506  }
1507  }
1508 
1509  if (IsSavegameVersionBefore(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
1510 
1511  if (IsSavegameVersionBefore(52)) {
1512  for (TileIndex t = 0; t < map_size; t++) {
1513  if (IsTileType(t, MP_OBJECT) && _m[t].m5 == OBJECT_STATUE) {
1515  }
1516  }
1517  }
1518 
1519  /* A setting containing the proportion of towns that grow twice as
1520  * fast was added in version 54. From version 56 this is now saved in the
1521  * town as cities can be built specifically in the scenario editor. */
1522  if (IsSavegameVersionBefore(56)) {
1523  Town *t;
1524 
1525  FOR_ALL_TOWNS(t) {
1527  t->larger_town = true;
1528  }
1529  }
1530  }
1531 
1532  if (IsSavegameVersionBefore(57)) {
1533  Vehicle *v;
1534  /* Added a FIFO queue of vehicles loading at stations */
1535  FOR_ALL_VEHICLES(v) {
1536  if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) && // for all locs
1537  !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
1538  v->current_order.IsType(OT_LOADING)) { // loading
1539  Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
1540 
1541  /* The loading finished flag is *only* set when actually completely
1542  * finished. Because the vehicle is loading, it is not finished. */
1544  }
1545  }
1546  } else if (IsSavegameVersionBefore(59)) {
1547  /* For some reason non-loading vehicles could be in the station's loading vehicle list */
1548 
1549  Station *st;
1550  FOR_ALL_STATIONS(st) {
1551  std::list<Vehicle *>::iterator iter;
1552  for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
1553  Vehicle *v = *iter;
1554  iter++;
1555  if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
1556  }
1557  }
1558  }
1559 
1560  if (IsSavegameVersionBefore(58)) {
1561  /* Setting difficulty industry_density other than zero get bumped to +1
1562  * since a new option (very low at position 1) has been added */
1565  }
1566 
1567  /* Same goes for number of towns, although no test is needed, just an increment */
1569  }
1570 
1571  if (IsSavegameVersionBefore(64)) {
1572  /* Since now we allow different signal types and variants on a single tile.
1573  * Move signal states to m4 to make room and clone the signal type/variant. */
1574  for (TileIndex t = 0; t < map_size; t++) {
1575  if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
1576  /* move signal states */
1577  SetSignalStates(t, GB(_m[t].m2, 4, 4));
1578  SB(_m[t].m2, 4, 4, 0);
1579  /* clone signal type and variant */
1580  SB(_m[t].m2, 4, 3, GB(_m[t].m2, 0, 3));
1581  }
1582  }
1583  }
1584 
1585  if (IsSavegameVersionBefore(69)) {
1586  /* In some old savegames a bit was cleared when it should not be cleared */
1587  RoadVehicle *rv;
1588  FOR_ALL_ROADVEHICLES(rv) {
1589  if (rv->state == 250 || rv->state == 251) {
1590  SetBit(rv->state, 2);
1591  }
1592  }
1593  }
1594 
1595  if (IsSavegameVersionBefore(70)) {
1596  /* Added variables to support newindustries */
1597  Industry *i;
1598  FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
1599  }
1600 
1601  /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
1602  Replace the owner for those by OWNER_NONE. */
1603  if (IsSavegameVersionBefore(82)) {
1604  for (TileIndex t = 0; t < map_size; t++) {
1605  if (IsTileType(t, MP_WATER) &&
1607  GetTileOwner(t) == OWNER_WATER &&
1608  TileHeight(t) != 0) {
1610  }
1611  }
1612  }
1613 
1614  /*
1615  * Add the 'previous' owner to the ship depots so we can reset it with
1616  * the correct values when it gets destroyed. This prevents that
1617  * someone can remove canals owned by somebody else and it prevents
1618  * making floods using the removal of ship depots.
1619  */
1620  if (IsSavegameVersionBefore(83)) {
1621  for (TileIndex t = 0; t < map_size; t++) {
1622  if (IsShipDepotTile(t)) {
1623  _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
1624  }
1625  }
1626  }
1627 
1628  if (IsSavegameVersionBefore(74)) {
1629  Station *st;
1630  FOR_ALL_STATIONS(st) {
1631  for (CargoID c = 0; c < NUM_CARGO; c++) {
1632  st->goods[c].last_speed = 0;
1633  if (st->goods[c].cargo.AvailableCount() != 0) SetBit(st->goods[c].status, GoodsEntry::GES_RATING);
1634  }
1635  }
1636  }
1637 
1638  if (IsSavegameVersionBefore(78)) {
1639  Industry *i;
1640  uint j;
1641  FOR_ALL_INDUSTRIES(i) {
1642  const IndustrySpec *indsp = GetIndustrySpec(i->type);
1643  for (j = 0; j < lengthof(i->produced_cargo); j++) {
1644  i->produced_cargo[j] = indsp->produced_cargo[j];
1645  }
1646  for (j = 0; j < lengthof(i->accepts_cargo); j++) {
1647  i->accepts_cargo[j] = indsp->accepts_cargo[j];
1648  }
1649  }
1650  }
1651 
1652  /* Before version 81, the density of grass was always stored as zero, and
1653  * grassy trees were always drawn fully grassy. Furthermore, trees on rough
1654  * land used to have zero density, now they have full density. Therefore,
1655  * make all grassy/rough land trees have a density of 3. */
1656  if (IsSavegameVersionBefore(81)) {
1657  for (TileIndex t = 0; t < map_size; t++) {
1658  if (GetTileType(t) == MP_TREES) {
1659  TreeGround groundType = (TreeGround)GB(_m[t].m2, 4, 2);
1660  if (groundType != TREE_GROUND_SNOW_DESERT) SB(_m[t].m2, 6, 2, 3);
1661  }
1662  }
1663  }
1664 
1665 
1666  if (IsSavegameVersionBefore(93)) {
1667  /* Rework of orders. */
1668  Order *order;
1669  FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
1670 
1671  Vehicle *v;
1672  FOR_ALL_VEHICLES(v) {
1673  if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && v->orders.list->GetFirstOrder()->IsType(OT_NOTHING)) {
1674  v->orders.list->FreeChain();
1675  v->orders.list = NULL;
1676  }
1677 
1679  if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
1680  FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
1681  }
1682  }
1683  } else if (IsSavegameVersionBefore(94)) {
1684  /* Unload and transfer are now mutual exclusive. */
1685  Order *order;
1686  FOR_ALL_ORDERS(order) {
1687  if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1688  order->SetUnloadType(OUFB_TRANSFER);
1689  order->SetLoadType(OLFB_NO_LOAD);
1690  }
1691  }
1692 
1693  Vehicle *v;
1694  FOR_ALL_VEHICLES(v) {
1698  }
1699  }
1700  }
1701 
1702  if (IsSavegameVersionBefore(84)) {
1703  /* Set all share owners to INVALID_COMPANY for
1704  * 1) all inactive companies
1705  * (when inactive companies were stored in the savegame - TTD, TTDP and some
1706  * *really* old revisions of OTTD; else it is already set in InitializeCompanies())
1707  * 2) shares that are owned by inactive companies or self
1708  * (caused by cheating clients in earlier revisions) */
1709  FOR_ALL_COMPANIES(c) {
1710  for (uint i = 0; i < 4; i++) {
1711  CompanyID company = c->share_owners[i];
1712  if (company == INVALID_COMPANY) continue;
1713  if (!Company::IsValidID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
1714  }
1715  }
1716  }
1717 
1718  /* The water class was moved/unified. */
1719  if (IsSavegameVersionBefore(146)) {
1720  for (TileIndex t = 0; t < map_size; t++) {
1721  switch (GetTileType(t)) {
1722  case MP_STATION:
1723  switch (GetStationType(t)) {
1724  case STATION_OILRIG:
1725  case STATION_DOCK:
1726  case STATION_BUOY:
1727  SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
1728  SB(_m[t].m3, 0, 2, 0);
1729  break;
1730 
1731  default:
1733  break;
1734  }
1735  break;
1736 
1737  case MP_WATER:
1738  SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
1739  SB(_m[t].m3, 0, 2, 0);
1740  break;
1741 
1742  case MP_OBJECT:
1744  break;
1745 
1746  default:
1747  /* No water class. */
1748  break;
1749  }
1750  }
1751  }
1752 
1753  if (IsSavegameVersionBefore(86)) {
1754  for (TileIndex t = 0; t < map_size; t++) {
1755  /* Move river flag and update canals to use water class */
1756  if (IsTileType(t, MP_WATER)) {
1757  if (GetWaterClass(t) != WATER_CLASS_RIVER) {
1758  if (IsWater(t)) {
1759  Owner o = GetTileOwner(t);
1760  if (o == OWNER_WATER) {
1761  MakeSea(t);
1762  } else {
1763  MakeCanal(t, o, Random());
1764  }
1765  } else if (IsShipDepot(t)) {
1766  Owner o = (Owner)_m[t].m4; // Original water owner
1768  }
1769  }
1770  }
1771  }
1772 
1773  /* Update locks, depots, docks and buoys to have a water class based
1774  * on its neighbouring tiles. Done after river and canal updates to
1775  * ensure neighbours are correct. */
1776  for (TileIndex t = 0; t < map_size; t++) {
1777  if (!IsTileFlat(t)) continue;
1778 
1780  if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
1781  }
1782  }
1783 
1784  if (IsSavegameVersionBefore(87)) {
1785  for (TileIndex t = 0; t < map_size; t++) {
1786  /* skip oil rigs at borders! */
1787  if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
1788  (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
1789  /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
1790  * This conversion has to be done before buoys with invalid owner are removed. */
1792  }
1793 
1794  if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
1795  Owner o = GetTileOwner(t);
1796  if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
1797  Backup<CompanyByte> cur_company(_current_company, o, FILE_LINE);
1799  cur_company.Restore();
1800  }
1801  if (IsBuoyTile(t)) {
1802  /* reset buoy owner to OWNER_NONE in the station struct
1803  * (even if it is owned by active company) */
1805  }
1806  } else if (IsTileType(t, MP_ROAD)) {
1807  /* works for all RoadTileType */
1808  for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
1809  /* update even non-existing road types to update tile owner too */
1810  Owner o = GetRoadOwner(t, rt);
1811  if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rt, OWNER_NONE);
1812  }
1813  if (IsLevelCrossing(t)) {
1815  }
1816  } else if (IsPlainRailTile(t)) {
1818  }
1819  }
1820 
1821  /* Convert old PF settings to new */
1824  } else {
1826  }
1827 
1830  } else {
1832  }
1833 
1836  } else {
1838  }
1839  }
1840 
1841  if (IsSavegameVersionBefore(88)) {
1842  /* Profits are now with 8 bit fract */
1843  Vehicle *v;
1844  FOR_ALL_VEHICLES(v) {
1845  v->profit_this_year <<= 8;
1846  v->profit_last_year <<= 8;
1847  v->running_ticks = 0;
1848  }
1849  }
1850 
1851  if (IsSavegameVersionBefore(91)) {
1852  /* Increase HouseAnimationFrame from 5 to 7 bits */
1853  for (TileIndex t = 0; t < map_size; t++) {
1854  if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
1855  SB(_me[t].m6, 2, 6, GB(_me[t].m6, 3, 5));
1856  SB(_m[t].m3, 5, 1, 0);
1857  }
1858  }
1859  }
1860 
1861  if (IsSavegameVersionBefore(62)) {
1862  /* Remove all trams from savegames without tram support.
1863  * There would be trams without tram track under causing crashes sooner or later. */
1864  RoadVehicle *v;
1865  FOR_ALL_ROADVEHICLES(v) {
1866  if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
1867  ShowErrorMessage(STR_WARNING_LOADGAME_REMOVED_TRAMS, INVALID_STRING_ID, WL_CRITICAL);
1868  delete v;
1869  }
1870  }
1871  }
1872 
1873  if (IsSavegameVersionBefore(99)) {
1874  for (TileIndex t = 0; t < map_size; t++) {
1875  /* Set newly introduced WaterClass of industry tiles */
1876  if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
1878  }
1879  if (IsTileType(t, MP_INDUSTRY)) {
1880  if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
1882  } else {
1884  }
1885  }
1886 
1887  /* Replace "house construction year" with "house age" */
1888  if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
1889  _m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
1890  }
1891  }
1892  }
1893 
1894  /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
1895  * format here, as an old layout wouldn't work properly anyway. To be safe, we
1896  * clear any possible PBS reservations as well. */
1897  if (IsSavegameVersionBefore(100)) {
1898  for (TileIndex t = 0; t < map_size; t++) {
1899  switch (GetTileType(t)) {
1900  case MP_RAILWAY:
1901  if (HasSignals(t)) {
1902  /* move the signal variant */
1903  SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1904  SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1905  ClrBit(_m[t].m2, 2);
1906  ClrBit(_m[t].m2, 6);
1907  }
1908 
1909  /* Clear PBS reservation on track */
1910  if (IsRailDepot(t)) {
1911  SetDepotReservation(t, false);
1912  } else {
1914  }
1915  break;
1916 
1917  case MP_ROAD: // Clear PBS reservation on crossing
1918  if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
1919  break;
1920 
1921  case MP_STATION: // Clear PBS reservation on station
1922  if (HasStationRail(t)) SetRailStationReservation(t, false);
1923  break;
1924 
1925  case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/bridges
1927  break;
1928 
1929  default: break;
1930  }
1931  }
1932  }
1933 
1934  /* Reserve all tracks trains are currently on. */
1935  if (IsSavegameVersionBefore(101)) {
1936  const Train *t;
1937  FOR_ALL_TRAINS(t) {
1938  if (t->First() == t) t->ReserveTrackUnderConsist();
1939  }
1940  }
1941 
1942  if (IsSavegameVersionBefore(102)) {
1943  for (TileIndex t = 0; t < map_size; t++) {
1944  /* Now all crossings should be in correct state */
1945  if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
1946  }
1947  }
1948 
1949  if (IsSavegameVersionBefore(103)) {
1950  /* Non-town-owned roads now store the closest town */
1952 
1953  /* signs with invalid owner left from older savegames */
1954  Sign *si;
1955  FOR_ALL_SIGNS(si) {
1956  if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
1957  }
1958 
1959  /* Station can get named based on an industry type, but the current ones
1960  * are not, so mark them as if they are not named by an industry. */
1961  Station *st;
1962  FOR_ALL_STATIONS(st) {
1963  st->indtype = IT_INVALID;
1964  }
1965  }
1966 
1967  if (IsSavegameVersionBefore(104)) {
1968  Aircraft *a;
1969  FOR_ALL_AIRCRAFT(a) {
1970  /* Set engine_type of shadow and rotor */
1971  if (!a->IsNormalAircraft()) {
1972  a->engine_type = a->First()->engine_type;
1973  }
1974  }
1975 
1976  /* More companies ... */
1977  Company *c;
1978  FOR_ALL_COMPANIES(c) {
1979  if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
1980  }
1981 
1982  Engine *e;
1983  FOR_ALL_ENGINES(e) {
1984  if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
1985  }
1986 
1987  Town *t;
1988  FOR_ALL_TOWNS(t) {
1989  if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
1990  for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
1991  }
1992  }
1993 
1994  if (IsSavegameVersionBefore(112)) {
1995  for (TileIndex t = 0; t < map_size; t++) {
1996  /* Check for HQ bit being set, instead of using map accessor,
1997  * since we've already changed it code-wise */
1998  if (IsTileType(t, MP_OBJECT) && HasBit(_m[t].m5, 7)) {
1999  /* Move size and part identification of HQ out of the m5 attribute,
2000  * on new locations */
2001  _m[t].m3 = GB(_m[t].m5, 0, 5);
2002  _m[t].m5 = OBJECT_HQ;
2003  }
2004  }
2005  }
2006  if (IsSavegameVersionBefore(144)) {
2007  for (TileIndex t = 0; t < map_size; t++) {
2008  if (!IsTileType(t, MP_OBJECT)) continue;
2009 
2010  /* Reordering/generalisation of the object bits. */
2011  ObjectType type = _m[t].m5;
2012  SB(_me[t].m6, 2, 4, type == OBJECT_HQ ? GB(_m[t].m3, 2, 3) : 0);
2013  _m[t].m3 = type == OBJECT_HQ ? GB(_m[t].m3, 1, 1) | GB(_m[t].m3, 0, 1) << 4 : 0;
2014 
2015  /* Make sure those bits are clear as well! */
2016  _m[t].m4 = 0;
2017  _me[t].m7 = 0;
2018  }
2019  }
2020 
2021  if (IsSavegameVersionBefore(147) && Object::GetNumItems() == 0) {
2022  /* Make real objects for object tiles. */
2023  for (TileIndex t = 0; t < map_size; t++) {
2024  if (!IsTileType(t, MP_OBJECT)) continue;
2025 
2026  if (Town::GetNumItems() == 0) {
2027  /* No towns, so remove all objects! */
2028  DoClearSquare(t);
2029  } else {
2030  uint offset = _m[t].m3;
2031 
2032  /* Also move the animation state. */
2033  _m[t].m3 = GB(_me[t].m6, 2, 4);
2034  SB(_me[t].m6, 2, 4, 0);
2035 
2036  if (offset == 0) {
2037  /* No offset, so make the object. */
2038  ObjectType type = _m[t].m5;
2039  int size = type == OBJECT_HQ ? 2 : 1;
2040 
2041  if (!Object::CanAllocateItem()) {
2042  /* Nice... you managed to place 64k lighthouses and
2043  * antennae on the map... boohoo. */
2044  SlError(STR_ERROR_TOO_MANY_OBJECTS);
2045  }
2046 
2047  Object *o = new Object();
2048  o->location.tile = t;
2049  o->location.w = size;
2050  o->location.h = size;
2051  o->build_date = _date;
2052  o->town = type == OBJECT_STATUE ? Town::Get(_m[t].m2) : CalcClosestTownFromTile(t, UINT_MAX);
2053  _m[t].m2 = o->index;
2054  Object::IncTypeCount(type);
2055  } else {
2056  /* We're at an offset, so get the ID from our "root". */
2057  TileIndex northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
2058  assert(IsTileType(northern_tile, MP_OBJECT));
2059  _m[t].m2 = _m[northern_tile].m2;
2060  }
2061  }
2062  }
2063  }
2064 
2065  if (IsSavegameVersionBefore(113)) {
2066  /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
2067  if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
2070  } else {
2073  }
2074 
2075  /* Initialize layout of all towns. Older versions were using different
2076  * generator for random town layout, use it if needed. */
2077  Town *t;
2078  FOR_ALL_TOWNS(t) {
2081  continue;
2082  }
2083 
2084  /* Use old layout randomizer code */
2085  byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
2086  switch (layout) {
2087  default: break;
2088  case 5: layout = 1; break;
2089  case 0: layout = 2; break;
2090  }
2091  t->layout = layout - 1;
2092  }
2093  }
2094 
2095  if (IsSavegameVersionBefore(114)) {
2096  /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
2097  * The conversion affects oil rigs and buoys too, but it doesn't matter as
2098  * they have st->owner == OWNER_NONE already. */
2099  Station *st;
2100  FOR_ALL_STATIONS(st) {
2101  if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
2102  }
2103  }
2104 
2105  /* Trains could now stop in a specific location. */
2106  if (IsSavegameVersionBefore(117)) {
2107  Order *o;
2108  FOR_ALL_ORDERS(o) {
2109  if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
2110  }
2111  }
2112 
2113  if (IsSavegameVersionBefore(120)) {
2115  Company *c;
2116  FOR_ALL_COMPANIES(c) {
2117  c->settings.vehicle = _old_vds;
2118  }
2119  }
2120 
2121  if (IsSavegameVersionBefore(121)) {
2122  /* Delete small ufos heading for non-existing vehicles */
2123  Vehicle *v;
2125  if (v->subtype == 2 /* ST_SMALL_UFO */ && v->current_order.GetDestination() != 0) {
2126  const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
2127  if (u == NULL || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
2128  delete v;
2129  }
2130  }
2131  }
2132 
2133  /* We didn't store cargo payment yet, so make them for vehicles that are
2134  * currently at a station and loading/unloading. If they don't get any
2135  * payment anymore they just removed in the next load/unload cycle.
2136  * However, some 0.7 versions might have cargo payment. For those we just
2137  * add cargopayment for the vehicles that don't have it.
2138  */
2139  Station *st;
2140  FOR_ALL_STATIONS(st) {
2141  std::list<Vehicle *>::iterator iter;
2142  for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
2143  /* There are always as many CargoPayments as Vehicles. We need to make the
2144  * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
2147  Vehicle *v = *iter;
2148  if (v->cargo_payment == NULL) v->cargo_payment = new CargoPayment(v);
2149  }
2150  }
2151  }
2152 
2153  if (IsSavegameVersionBefore(122)) {
2154  /* Animated tiles would sometimes not be actually animated or
2155  * in case of old savegames duplicate. */
2156 
2158  extern uint _animated_tile_count;
2159 
2160  for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
2161  /* Remove if tile is not animated */
2162  bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == NULL;
2163 
2164  /* and remove if duplicate */
2165  for (uint j = 0; !remove && j < i; j++) {
2166  remove = _animated_tile_list[i] == _animated_tile_list[j];
2167  }
2168 
2169  if (remove) {
2170  DeleteAnimatedTile(_animated_tile_list[i]);
2171  } else {
2172  i++;
2173  }
2174  }
2175  }
2176 
2178  /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
2179  Waypoint *wp;
2180  FOR_ALL_WAYPOINTS(wp) {
2181  if (wp->facilities & FACIL_TRAIN) {
2182  wp->train_station.tile = wp->xy;
2183  wp->train_station.w = 1;
2184  wp->train_station.h = 1;
2185  } else {
2187  wp->train_station.w = 0;
2188  wp->train_station.h = 0;
2189  }
2190  }
2191  }
2192 
2193  if (IsSavegameVersionBefore(125)) {
2194  /* Convert old subsidies */
2195  Subsidy *s;
2196  FOR_ALL_SUBSIDIES(s) {
2197  if (s->remaining < 12) {
2198  /* Converting nonawarded subsidy */
2199  s->remaining = 12 - s->remaining; // convert "age" to "remaining"
2200  s->awarded = INVALID_COMPANY; // not awarded to anyone
2201  const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2202  switch (cs->town_effect) {
2203  case TE_PASSENGERS:
2204  case TE_MAIL:
2205  /* Town -> Town */
2206  s->src_type = s->dst_type = ST_TOWN;
2207  if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2208  break;
2209  case TE_GOODS:
2210  case TE_FOOD:
2211  /* Industry -> Town */
2212  s->src_type = ST_INDUSTRY;
2213  s->dst_type = ST_TOWN;
2214  if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2215  break;
2216  default:
2217  /* Industry -> Industry */
2218  s->src_type = s->dst_type = ST_INDUSTRY;
2219  if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
2220  break;
2221  }
2222  } else {
2223  /* Do our best for awarded subsidies. The original source or destination industry
2224  * can't be determined anymore for awarded subsidies, so invalidate them.
2225  * Town -> Town subsidies are converted using simple heuristic */
2226  s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
2227  const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2228  switch (cs->town_effect) {
2229  case TE_PASSENGERS:
2230  case TE_MAIL: {
2231  /* Town -> Town */
2232  const Station *ss = Station::GetIfValid(s->src);
2233  const Station *sd = Station::GetIfValid(s->dst);
2234  if (ss != NULL && sd != NULL && ss->owner == sd->owner &&
2235  Company::IsValidID(ss->owner)) {
2236  s->src_type = s->dst_type = ST_TOWN;
2237  s->src = ss->town->index;
2238  s->dst = sd->town->index;
2239  s->awarded = ss->owner;
2240  continue;
2241  }
2242  break;
2243  }
2244  default:
2245  break;
2246  }
2247  }
2248  /* Awarded non-town subsidy or invalid source/destination, invalidate */
2249  delete s;
2250  }
2251  }
2252 
2253  if (IsSavegameVersionBefore(126)) {
2254  /* Recompute inflation based on old unround loan limit
2255  * Note: Max loan is 500000. With an inflation of 4% across 170 years
2256  * that results in a max loan of about 0.7 * 2^31.
2257  * So taking the 16 bit fractional part into account there are plenty of bits left
2258  * for unmodified savegames ...
2259  */
2260  uint64 aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
2261 
2262  /* ... well, just clamp it then. */
2263  if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
2264 
2265  /* Simulate the inflation, so we also get the payment inflation */
2266  while (_economy.inflation_prices < aimed_inflation) {
2267  if (AddInflation(false)) break;
2268  }
2269  }
2270 
2271  if (IsSavegameVersionBefore(128)) {
2272  const Depot *d;
2273  FOR_ALL_DEPOTS(d) {
2274  _m[d->xy].m2 = d->index;
2275  if (IsTileType(d->xy, MP_WATER)) _m[GetOtherShipDepotTile(d->xy)].m2 = d->index;
2276  }
2277  }
2278 
2279  /* The behaviour of force_proceed has been changed. Now
2280  * it counts signals instead of some random time out. */
2281  if (IsSavegameVersionBefore(131)) {
2282  Train *t;
2283  FOR_ALL_TRAINS(t) {
2284  if (t->force_proceed != TFP_NONE) {
2285  t->force_proceed = TFP_STUCK;
2286  }
2287  }
2288  }
2289 
2290  /* The bits for the tree ground and tree density have
2291  * been swapped (m2 bits 7..6 and 5..4. */
2292  if (IsSavegameVersionBefore(135)) {
2293  for (TileIndex t = 0; t < map_size; t++) {
2294  if (IsTileType(t, MP_CLEAR)) {
2295  if (GetRawClearGround(t) == CLEAR_SNOW) {
2297  SetBit(_m[t].m3, 4);
2298  } else {
2299  ClrBit(_m[t].m3, 4);
2300  }
2301  }
2302  if (IsTileType(t, MP_TREES)) {
2303  uint density = GB(_m[t].m2, 6, 2);
2304  uint ground = GB(_m[t].m2, 4, 2);
2305  uint counter = GB(_m[t].m2, 0, 4);
2306  _m[t].m2 = ground << 6 | density << 4 | counter;
2307  }
2308  }
2309  }
2310 
2311  /* Wait counter and load/unload ticks got split. */
2312  if (IsSavegameVersionBefore(136)) {
2313  Aircraft *a;
2314  FOR_ALL_AIRCRAFT(a) {
2315  a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
2316  }
2317 
2318  Train *t;
2319  FOR_ALL_TRAINS(t) {
2320  t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
2321  }
2322  }
2323 
2324  /* Airport tile animation uses animation frame instead of other graphics id */
2325  if (IsSavegameVersionBefore(137)) {
2326  struct AirportTileConversion {
2327  byte old_start;
2328  byte num_frames;
2329  };
2330  static const AirportTileConversion atc[] = {
2331  {31, 12}, // APT_RADAR_GRASS_FENCE_SW
2332  {50, 4}, // APT_GRASS_FENCE_NE_FLAG
2333  {62, 2}, // 1 unused tile
2334  {66, 12}, // APT_RADAR_FENCE_SW
2335  {78, 12}, // APT_RADAR_FENCE_NE
2336  {101, 10}, // 9 unused tiles
2337  {111, 8}, // 7 unused tiles
2338  {119, 15}, // 14 unused tiles (radar)
2339  {140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
2340  };
2341  for (TileIndex t = 0; t < map_size; t++) {
2342  if (IsAirportTile(t)) {
2343  StationGfx old_gfx = GetStationGfx(t);
2344  byte offset = 0;
2345  for (uint i = 0; i < lengthof(atc); i++) {
2346  if (old_gfx < atc[i].old_start) {
2347  SetStationGfx(t, old_gfx - offset);
2348  break;
2349  }
2350  if (old_gfx < atc[i].old_start + atc[i].num_frames) {
2351  SetAnimationFrame(t, old_gfx - atc[i].old_start);
2352  SetStationGfx(t, atc[i].old_start - offset);
2353  break;
2354  }
2355  offset += atc[i].num_frames - 1;
2356  }
2357  }
2358  }
2359  }
2360 
2361  if (IsSavegameVersionBefore(140)) {
2362  Station *st;
2363  FOR_ALL_STATIONS(st) {
2364  if (st->airport.tile != INVALID_TILE) {
2365  st->airport.w = st->airport.GetSpec()->size_x;
2366  st->airport.h = st->airport.GetSpec()->size_y;
2367  }
2368  }
2369  }
2370 
2371  if (IsSavegameVersionBefore(141)) {
2372  for (TileIndex t = 0; t < map_size; t++) {
2373  /* Reset tropic zone for VOID tiles, they shall not have any. */
2375  }
2376 
2377  /* We need to properly number/name the depots.
2378  * The first step is making sure none of the depots uses the
2379  * 'default' names, after that we can assign the names. */
2380  Depot *d;
2381  FOR_ALL_DEPOTS(d) d->town_cn = UINT16_MAX;
2382 
2383  FOR_ALL_DEPOTS(d) MakeDefaultName(d);
2384  }
2385 
2386  if (IsSavegameVersionBefore(142)) {
2387  Depot *d;
2388  FOR_ALL_DEPOTS(d) d->build_date = _date;
2389  }
2390 
2391  /* In old versions it was possible to remove an airport while a plane was
2392  * taking off or landing. This gives all kind of problems when building
2393  * another airport in the same station so we don't allow that anymore.
2394  * For old savegames with such aircraft we just throw them in the air and
2395  * treat the aircraft like they were flying already. */
2396  if (IsSavegameVersionBefore(146)) {
2397  Aircraft *v;
2398  FOR_ALL_AIRCRAFT(v) {
2399  if (!v->IsNormalAircraft()) continue;
2401  if (st == NULL && v->state != FLYING) {
2402  v->state = FLYING;
2405  /* get aircraft back on running altitude */
2406  if ((v->vehstatus & VS_CRASHED) == 0) {
2407  GetAircraftFlightLevelBounds(v, &v->z_pos, NULL);
2408  SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
2409  }
2410  }
2411  }
2412  }
2413 
2414  /* Move the animation frame to the same location (m7) for all objects. */
2415  if (IsSavegameVersionBefore(147)) {
2416  for (TileIndex t = 0; t < map_size; t++) {
2417  switch (GetTileType(t)) {
2418  case MP_HOUSE:
2419  if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
2420  uint per_proc = _me[t].m7;
2421  _me[t].m7 = GB(_me[t].m6, 2, 6) | (GB(_m[t].m3, 5, 1) << 6);
2422  SB(_m[t].m3, 5, 1, 0);
2423  SB(_me[t].m6, 2, 6, min(per_proc, 63));
2424  }
2425  break;
2426 
2427  case MP_INDUSTRY: {
2428  uint rand = _me[t].m7;
2429  _me[t].m7 = _m[t].m3;
2430  _m[t].m3 = rand;
2431  break;
2432  }
2433 
2434  case MP_OBJECT:
2435  _me[t].m7 = _m[t].m3;
2436  _m[t].m3 = 0;
2437  break;
2438 
2439  default:
2440  /* For stations/airports it's already at m7 */
2441  break;
2442  }
2443  }
2444  }
2445 
2446  /* Add (random) colour to all objects. */
2447  if (IsSavegameVersionBefore(148)) {
2448  Object *o;
2449  FOR_ALL_OBJECTS(o) {
2450  Owner owner = GetTileOwner(o->location.tile);
2451  o->colour = (owner == OWNER_NONE) ? Random() & 0xF : Company::Get(owner)->livery->colour1;
2452  }
2453  }
2454 
2455  if (IsSavegameVersionBefore(149)) {
2456  for (TileIndex t = 0; t < map_size; t++) {
2457  if (!IsTileType(t, MP_STATION)) continue;
2458  if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && IsTileFlat(t))) {
2460  }
2461  }
2462 
2463  /* Waypoints with custom name may have a non-unique town_cn,
2464  * renumber those. First set all affected waypoints to the
2465  * highest possible number to get them numbered in the
2466  * order they have in the pool. */
2467  Waypoint *wp;
2468  FOR_ALL_WAYPOINTS(wp) {
2469  if (wp->name != NULL) wp->town_cn = UINT16_MAX;
2470  }
2471 
2472  FOR_ALL_WAYPOINTS(wp) {
2473  if (wp->name != NULL) MakeDefaultName(wp);
2474  }
2475  }
2476 
2477  if (IsSavegameVersionBefore(152)) {
2478  _industry_builder.Reset(); // Initialize industry build data.
2479 
2480  /* The moment vehicles go from hidden to visible changed. This means
2481  * that vehicles don't always get visible anymore causing things to
2482  * get messed up just after loading the savegame. This fixes that. */
2483  Vehicle *v;
2484  FOR_ALL_VEHICLES(v) {
2485  /* Not all vehicle types can be inside a tunnel. Furthermore,
2486  * testing IsTunnelTile() for invalid tiles causes a crash. */
2487  if (!v->IsGroundVehicle()) continue;
2488 
2489  /* Is the vehicle in a tunnel? */
2490  if (!IsTunnelTile(v->tile)) continue;
2491 
2492  /* Is the vehicle actually at a tunnel entrance/exit? */
2493  TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
2494  if (!IsTunnelTile(vtile)) continue;
2495 
2496  /* Are we actually in this tunnel? Or maybe a lower tunnel? */
2497  if (GetSlopePixelZ(v->x_pos, v->y_pos) != v->z_pos) continue;
2498 
2499  /* What way are we going? */
2500  const DiagDirection dir = GetTunnelBridgeDirection(vtile);
2501  const DiagDirection vdir = DirToDiagDir(v->direction);
2502 
2503  /* Have we passed the visibility "switch" state already? */
2504  byte pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
2505  byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2506  extern const byte _tunnel_visibility_frame[DIAGDIR_END];
2507 
2508  /* Should the vehicle be hidden or not? */
2509  bool hidden;
2510  if (dir == vdir) { // Entering tunnel
2511  hidden = frame >= _tunnel_visibility_frame[dir];
2512  v->tile = vtile;
2513  } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
2514  hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
2515  /* v->tile changes at the moment when the vehicle leaves the tunnel. */
2516  v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
2517  } else {
2518  /* We could get here in two cases:
2519  * - for road vehicles, it is reversing at the end of the tunnel
2520  * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
2521  * Whatever case it is, do not change anything and use the old values.
2522  * Especially changing RV's state would break its reversing in the middle. */
2523  continue;
2524  }
2525 
2526  if (hidden) {
2527  v->vehstatus |= VS_HIDDEN;
2528 
2529  switch (v->type) {
2530  case VEH_TRAIN: Train::From(v)->track = TRACK_BIT_WORMHOLE; break;
2531  case VEH_ROAD: RoadVehicle::From(v)->state = RVSB_WORMHOLE; break;
2532  default: NOT_REACHED();
2533  }
2534  } else {
2535  v->vehstatus &= ~VS_HIDDEN;
2536 
2537  switch (v->type) {
2538  case VEH_TRAIN: Train::From(v)->track = DiagDirToDiagTrackBits(vdir); break;
2539  case VEH_ROAD: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
2540  default: NOT_REACHED();
2541  }
2542  }
2543  }
2544  }
2545 
2546  if (IsSavegameVersionBefore(153)) {
2547  RoadVehicle *rv;
2548  FOR_ALL_ROADVEHICLES(rv) {
2549  if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
2550 
2551  bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
2552  if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
2553  extern const byte _road_stop_stop_frame[];
2554  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)]);
2555  } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
2556  SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
2557  }
2558  }
2559  }
2560 
2561  if (IsSavegameVersionBefore(156)) {
2562  /* The train's pathfinder lost flag got moved. */
2563  Train *t;
2564  FOR_ALL_TRAINS(t) {
2565  if (!HasBit(t->flags, 5)) continue;
2566 
2567  ClrBit(t->flags, 5);
2569  }
2570 
2571  /* Introduced terraform/clear limits. */
2572  Company *c;
2573  FOR_ALL_COMPANIES(c) {
2576  }
2577  }
2578 
2579  if (IsSavegameVersionBefore(158)) {
2580  Vehicle *v;
2581  FOR_ALL_VEHICLES(v) {
2582  switch (v->type) {
2583  case VEH_TRAIN: {
2584  Train *t = Train::From(v);
2585 
2586  /* Clear old GOINGUP / GOINGDOWN flags.
2587  * It was changed in savegame version 139, but savegame
2588  * version 158 doesn't use these bits, so it doesn't hurt
2589  * to clear them unconditionally. */
2590  ClrBit(t->flags, 1);
2591  ClrBit(t->flags, 2);
2592 
2593  /* Clear both bits first. */
2596 
2597  /* Crashed vehicles can't be going up/down. */
2598  if (t->vehstatus & VS_CRASHED) break;
2599 
2600  /* Only X/Y tracks can be sloped. */
2601  if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
2602 
2604  break;
2605  }
2606  case VEH_ROAD: {
2607  RoadVehicle *rv = RoadVehicle::From(v);
2610 
2611  /* Crashed vehicles can't be going up/down. */
2612  if (rv->vehstatus & VS_CRASHED) break;
2613 
2614  if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
2615 
2616  TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, rv->compatible_roadtypes);
2617  TrackBits trackbits = TrackStatusToTrackBits(ts);
2618 
2619  /* Only X/Y tracks can be sloped. */
2620  if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
2621 
2622  Direction dir = rv->direction;
2623 
2624  /* Test if we are reversing. */
2625  Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
2626  if (AxisToDirection(a) != dir &&
2627  AxisToDirection(a) != ReverseDir(dir)) {
2628  /* When reversing, the road vehicle is on the edge of the tile,
2629  * so it can be safely compared to the middle of the tile. */
2630  dir = INVALID_DIR;
2631  }
2632 
2633  rv->gv_flags |= FixVehicleInclination(rv, dir);
2634  break;
2635  }
2636  case VEH_SHIP:
2637  break;
2638 
2639  default:
2640  continue;
2641  }
2642 
2643  if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2644  /* In old versions, z_pos was 1 unit lower on bridge heads.
2645  * However, this invalid state could be converted to new savegames
2646  * by loading and saving the game in a new version. */
2647  v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos);
2649  if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
2650  v->direction != DiagDirToDir(dir)) {
2651  /* If the train has left the bridge, it shouldn't have
2652  * track == TRACK_BIT_WORMHOLE - this could happen
2653  * when the train was reversed while on the last "tick"
2654  * on the ramp before leaving the ramp to the bridge. */
2655  Train::From(v)->track = DiagDirToDiagTrackBits(dir);
2656  }
2657  }
2658 
2659  /* If the vehicle is really above v->tile (not in a wormhole),
2660  * it should have set v->z_pos correctly. */
2661  assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos));
2662  }
2663 
2664  /* Fill Vehicle::cur_real_order_index */
2665  FOR_ALL_VEHICLES(v) {
2666  if (!v->IsPrimaryVehicle()) continue;
2667 
2668  /* Older versions are less strict with indices being in range and fix them on the fly */
2670 
2672  v->UpdateRealOrderIndex();
2673  }
2674  }
2675 
2676  if (IsSavegameVersionBefore(159)) {
2677  /* If the savegame is old (before version 100), then the value of 255
2678  * for these settings did not mean "disabled". As such everything
2679  * before then did reverse.
2680  * To simplify stuff we disable all turning around or we do not
2681  * disable anything at all. So, if some reversing was disabled we
2682  * will keep reversing disabled, otherwise it'll be turned on. */
2684 
2685  Train *t;
2686  FOR_ALL_TRAINS(t) {
2688  }
2689  }
2690 
2691  if (IsSavegameVersionBefore(160)) {
2692  /* Setting difficulty industry_density other than zero get bumped to +1
2693  * since a new option (minimal at position 1) has been added */
2696  }
2697  }
2698 
2699  if (IsSavegameVersionBefore(161)) {
2700  /* Before savegame version 161, persistent storages were not stored in a pool. */
2701 
2702  if (!IsSavegameVersionBefore(76)) {
2703  Industry *ind;
2704  FOR_ALL_INDUSTRIES(ind) {
2705  assert(ind->psa != NULL);
2706 
2707  /* Check if the old storage was empty. */
2708  bool is_empty = true;
2709  for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
2710  if (ind->psa->GetValue(i) != 0) {
2711  is_empty = false;
2712  break;
2713  }
2714  }
2715 
2716  if (!is_empty) {
2717  ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
2718  } else {
2719  delete ind->psa;
2720  ind->psa = NULL;
2721  }
2722  }
2723  }
2724 
2725  if (!IsSavegameVersionBefore(145)) {
2726  Station *st;
2727  FOR_ALL_STATIONS(st) {
2728  if (!(st->facilities & FACIL_AIRPORT)) continue;
2729  assert(st->airport.psa != NULL);
2730 
2731  /* Check if the old storage was empty. */
2732  bool is_empty = true;
2733  for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
2734  if (st->airport.psa->GetValue(i) != 0) {
2735  is_empty = false;
2736  break;
2737  }
2738  }
2739 
2740  if (!is_empty) {
2741  st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
2742  } else {
2743  delete st->airport.psa;
2744  st->airport.psa = NULL;
2745 
2746  }
2747  }
2748  }
2749  }
2750 
2751  /* This triggers only when old snow_lines were copied into the snow_line_height. */
2754  }
2755 
2757  /* We store 4 fences in the field tiles instead of only SE and SW. */
2758  for (TileIndex t = 0; t < map_size; t++) {
2759  if (!IsTileType(t, MP_CLEAR) && !IsTileType(t, MP_TREES)) continue;
2760  if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) continue;
2761  uint fence = GB(_m[t].m4, 5, 3);
2762  if (fence != 0 && IsTileType(TILE_ADDXY(t, 1, 0), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 1, 0), CLEAR_FIELDS)) {
2763  SetFence(TILE_ADDXY(t, 1, 0), DIAGDIR_NE, fence);
2764  }
2765  fence = GB(_m[t].m4, 2, 3);
2766  if (fence != 0 && IsTileType(TILE_ADDXY(t, 0, 1), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 0, 1), CLEAR_FIELDS)) {
2767  SetFence(TILE_ADDXY(t, 0, 1), DIAGDIR_NW, fence);
2768  }
2769  SB(_m[t].m4, 2, 3, 0);
2770  SB(_m[t].m4, 5, 3, 0);
2771  }
2772  }
2773 
2774  /* The center of train vehicles was changed, fix up spacing. */
2776 
2777  if (IsSavegameVersionBefore(165)) {
2778  Town *t;
2779 
2780  FOR_ALL_TOWNS(t) {
2781  /* Set the default cargo requirement for town growth */
2783  case LT_ARCTIC:
2785  break;
2786 
2787  case LT_TROPIC:
2790  break;
2791  }
2792  }
2793  }
2794 
2795  if (IsSavegameVersionBefore(165)) {
2796  /* Adjust zoom level to account for new levels */
2797  _saved_scrollpos_zoom = _saved_scrollpos_zoom + ZOOM_LVL_SHIFT;
2798  _saved_scrollpos_x *= ZOOM_LVL_BASE;
2799  _saved_scrollpos_y *= ZOOM_LVL_BASE;
2800  }
2801 
2802  /* When any NewGRF has been changed the availability of some vehicles might
2803  * have been changed too. e->company_avail must be set to 0 in that case
2804  * which is done by StartupEngines(). */
2805  if (gcf_res != GLC_ALL_GOOD) StartupEngines();
2806 
2807  if (IsSavegameVersionBefore(166)) {
2808  /* Update cargo acceptance map of towns. */
2809  for (TileIndex t = 0; t < map_size; t++) {
2810  if (!IsTileType(t, MP_HOUSE)) continue;
2811  Town::Get(GetTownIndex(t))->cargo_accepted.Add(t);
2812  }
2813 
2814  Town *town;
2815  FOR_ALL_TOWNS(town) {
2816  UpdateTownCargoes(town);
2817  }
2818  }
2819 
2820  /* The road owner of standard road stops was not properly accounted for. */
2821  if (IsSavegameVersionBefore(172)) {
2822  for (TileIndex t = 0; t < map_size; t++) {
2823  if (!IsStandardRoadStopTile(t)) continue;
2824  Owner o = GetTileOwner(t);
2825  SetRoadOwner(t, ROADTYPE_ROAD, o);
2826  SetRoadOwner(t, ROADTYPE_TRAM, o);
2827  }
2828  }
2829 
2830  if (IsSavegameVersionBefore(175)) {
2831  /* Introduced tree planting limit. */
2832  Company *c;
2833  FOR_ALL_COMPANIES(c) c->tree_limit = _settings_game.construction.tree_frame_burst << 16;
2834  }
2835 
2836  if (IsSavegameVersionBefore(177)) {
2837  /* Fix too high inflation rates */
2838  if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
2840 
2841  /* We have to convert the quarters of bankruptcy into months of bankruptcy */
2842  FOR_ALL_COMPANIES(c) {
2844  }
2845  }
2846 
2847  if (IsSavegameVersionBefore(178)) {
2848  extern uint8 _old_diff_level;
2849  /* Initialise script settings profile */
2850  _settings_game.script.settings_profile = IsInsideMM(_old_diff_level, SP_BEGIN, SP_END) ? _old_diff_level : (uint)SP_MEDIUM;
2851  }
2852 
2853  if (IsSavegameVersionBefore(182)) {
2854  Aircraft *v;
2855  /* Aircraft acceleration variable was bonkers */
2856  FOR_ALL_AIRCRAFT(v) {
2857  if (v->subtype <= AIR_AIRCRAFT) {
2858  const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
2859  v->acceleration = avi->acceleration;
2860  }
2861  }
2862 
2863  /* Blocked tiles could be reserved due to a bug, which causes
2864  * other places to assert upon e.g. station reconstruction. */
2865  for (TileIndex t = 0; t < map_size; t++) {
2867  SetRailStationReservation(t, false);
2868  }
2869  }
2870  }
2871 
2872  if (IsSavegameVersionBefore(184)) {
2873  /* The global units configuration is split up in multiple configurations. */
2874  extern uint8 _old_units;
2875  _settings_game.locale.units_velocity = Clamp(_old_units, 0, 2);
2876  _settings_game.locale.units_power = Clamp(_old_units, 0, 2);
2877  _settings_game.locale.units_weight = Clamp(_old_units, 1, 2);
2878  _settings_game.locale.units_volume = Clamp(_old_units, 1, 2);
2880  _settings_game.locale.units_height = Clamp(_old_units, 0, 2);
2881  }
2882 
2883  if (IsSavegameVersionBefore(186)) {
2884  /* Move ObjectType from map to pool */
2885  for (TileIndex t = 0; t < map_size; t++) {
2886  if (IsTileType(t, MP_OBJECT)) {
2887  Object *o = Object::Get(_m[t].m2);
2888  o->type = _m[t].m5;
2889  _m[t].m5 = 0; // zero upper bits of (now bigger) ObjectID
2890  }
2891  }
2892  }
2893 
2894  if (IsSavegameVersionBefore(188)) {
2895  /* Fix articulated road vehicles.
2896  * Some curves were shorter than other curves.
2897  * Now they have the same length, but that means that trailing articulated parts will
2898  * take longer to go through the curve than the parts in front which already left the courve.
2899  * So, make articulated parts catch up. */
2900  RoadVehicle *v;
2901  bool roadside = _settings_game.vehicle.road_side == 1;
2902  SmallVector<uint, 16> skip_frames;
2903  FOR_ALL_ROADVEHICLES(v) {
2904  if (!v->IsFrontEngine()) continue;
2905  skip_frames.Clear();
2906  TileIndex prev_tile = v->tile;
2907  uint prev_tile_skip = 0;
2908  uint cur_skip = 0;
2909  for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
2910  if (u->tile != prev_tile) {
2911  prev_tile_skip = cur_skip;
2912  prev_tile = u->tile;
2913  } else {
2914  cur_skip = prev_tile_skip;
2915  }
2916 
2917  uint *this_skip = skip_frames.Append();
2918  *this_skip = prev_tile_skip;
2919 
2920  /* The following 3 curves now take longer than before */
2921  switch (u->state) {
2922  case 2:
2923  cur_skip++;
2924  if (u->frame <= (roadside ? 9 : 5)) *this_skip = cur_skip;
2925  break;
2926 
2927  case 4:
2928  cur_skip++;
2929  if (u->frame <= (roadside ? 5 : 9)) *this_skip = cur_skip;
2930  break;
2931 
2932  case 5:
2933  cur_skip++;
2934  if (u->frame <= (roadside ? 4 : 2)) *this_skip = cur_skip;
2935  break;
2936 
2937  default:
2938  break;
2939  }
2940  }
2941  while (cur_skip > skip_frames[0]) {
2942  RoadVehicle *u = v;
2943  RoadVehicle *prev = NULL;
2944  for (uint *it = skip_frames.Begin(); it != skip_frames.End(); ++it, prev = u, u = u->Next()) {
2945  extern bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev);
2946  if (*it >= cur_skip) IndividualRoadVehicleController(u, prev);
2947  }
2948  cur_skip--;
2949  }
2950  }
2951  }
2952 
2953  /*
2954  * Only keep order-backups for network clients.
2955  * If we are a network server or not networking, then we just loaded a previously
2956  * saved-by-server savegame. There are no clients with a backup, so clear it.
2957  * Furthermore before savegame version 192 the actual content was always corrupt.
2958  */
2960  /* Note: We cannot use CleanPool since that skips part of the destructor
2961  * and then leaks un-reachable Orders in the order pool. */
2962  OrderBackup *ob;
2963  FOR_ALL_ORDER_BACKUPS(ob) {
2964  delete ob;
2965  }
2966  }
2967 
2968 
2969  /* Station acceptance is some kind of cache */
2970  if (IsSavegameVersionBefore(127)) {
2971  Station *st;
2972  FOR_ALL_STATIONS(st) UpdateStationAcceptance(st, false);
2973  }
2974 
2975  /* Road stops is 'only' updating some caches */
2977  AfterLoadLabelMaps();
2980 
2981  GamelogPrintDebug(1);
2982 
2984  /* Restore the signals */
2986 
2988  return true;
2989 }
2990 
3000 {
3001  /* reload grf data */
3002  GfxLoadSprites();
3004  RecomputePrices();
3005  /* reload vehicles */
3006  ResetVehicleHash();
3007  AfterLoadVehicles(false);
3008  StartupEngines();
3010  /* update station graphics */
3011  AfterLoadStations();
3012  /* Update company statistics. */
3014  /* Check and update house and town values */
3016  /* Delete news referring to no longer existing entities */
3018  /* Update livery selection windows */
3020  /* Update company infrastructure counts. */
3022  /* redraw the whole screen */
3025 }