afterload.cpp

Go to the documentation of this file.
00001 /* $Id: afterload.cpp 23526 2011-12-15 21:56:00Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "../stdafx.h"
00013 #include "../void_map.h"
00014 #include "../signs_base.h"
00015 #include "../depot_base.h"
00016 #include "../window_func.h"
00017 #include "../fios.h"
00018 #include "../gamelog_internal.h"
00019 #include "../network/network.h"
00020 #include "../gfxinit.h"
00021 #include "../viewport_func.h"
00022 #include "../industry.h"
00023 #include "../clear_map.h"
00024 #include "../vehicle_func.h"
00025 #include "../string_func.h"
00026 #include "../date_func.h"
00027 #include "../roadveh.h"
00028 #include "../train.h"
00029 #include "../station_base.h"
00030 #include "../waypoint_base.h"
00031 #include "../roadstop_base.h"
00032 #include "../tunnelbridge_map.h"
00033 #include "../pathfinder/yapf/yapf_cache.h"
00034 #include "../elrail_func.h"
00035 #include "../signs_func.h"
00036 #include "../aircraft.h"
00037 #include "../object_map.h"
00038 #include "../object_base.h"
00039 #include "../tree_map.h"
00040 #include "../company_func.h"
00041 #include "../road_cmd.h"
00042 #include "../ai/ai.hpp"
00043 #include "../ai/ai_gui.hpp"
00044 #include "../town.h"
00045 #include "../economy_base.h"
00046 #include "../animated_tile_func.h"
00047 #include "../subsidy_base.h"
00048 #include "../subsidy_func.h"
00049 #include "../newgrf.h"
00050 #include "../engine_func.h"
00051 #include "../rail_gui.h"
00052 #include "../core/backup_type.hpp"
00053 #include "../smallmap_gui.h"
00054 #include "../news_func.h"
00055 #include "../group.h"
00056 #include "../error.h"
00057 
00058 #include "table/strings.h"
00059 
00060 #include "saveload_internal.h"
00061 
00062 #include <signal.h>
00063 
00064 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
00065 
00076 void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
00077 {
00078   /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
00079    * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
00080   if (GetTileSlope(t) != SLOPE_FLAT) {
00081     if (include_invalid_water_class) {
00082       SetWaterClass(t, WATER_CLASS_INVALID);
00083       return;
00084     } else {
00085       SlErrorCorrupt("Invalid water class for dry tile");
00086     }
00087   }
00088 
00089   /* Mark tile dirty in all cases */
00090   MarkTileDirtyByTile(t);
00091 
00092   if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
00093     /* tiles at map borders are always WATER_CLASS_SEA */
00094     SetWaterClass(t, WATER_CLASS_SEA);
00095     return;
00096   }
00097 
00098   bool has_water = false;
00099   bool has_canal = false;
00100   bool has_river = false;
00101 
00102   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
00103     TileIndex neighbour = TileAddByDiagDir(t, dir);
00104     switch (GetTileType(neighbour)) {
00105       case MP_WATER:
00106         /* clear water and shipdepots have already a WaterClass associated */
00107         if (IsCoast(neighbour)) {
00108           has_water = true;
00109         } else if (!IsLock(neighbour)) {
00110           switch (GetWaterClass(neighbour)) {
00111             case WATER_CLASS_SEA:   has_water = true; break;
00112             case WATER_CLASS_CANAL: has_canal = true; break;
00113             case WATER_CLASS_RIVER: has_river = true; break;
00114             default: SlErrorCorrupt("Invalid water class for tile");
00115           }
00116         }
00117         break;
00118 
00119       case MP_RAILWAY:
00120         /* Shore or flooded halftile */
00121         has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
00122         break;
00123 
00124       case MP_TREES:
00125         /* trees on shore */
00126         has_water |= (GB(_m[neighbour].m2, 4, 2) == TREE_GROUND_SHORE);
00127         break;
00128 
00129       default: break;
00130     }
00131   }
00132 
00133   if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
00134     SetWaterClass(t, WATER_CLASS_INVALID);
00135     return;
00136   }
00137 
00138   if (has_river && !has_canal) {
00139     SetWaterClass(t, WATER_CLASS_RIVER);
00140   } else if (has_canal || !has_water) {
00141     SetWaterClass(t, WATER_CLASS_CANAL);
00142   } else {
00143     SetWaterClass(t, WATER_CLASS_SEA);
00144   }
00145 }
00146 
00147 static void ConvertTownOwner()
00148 {
00149   for (TileIndex tile = 0; tile != MapSize(); tile++) {
00150     switch (GetTileType(tile)) {
00151       case MP_ROAD:
00152         if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
00153           _m[tile].m3 = OWNER_TOWN;
00154         }
00155         /* FALL THROUGH */
00156 
00157       case MP_TUNNELBRIDGE:
00158         if (_m[tile].m1 & 0x80) SetTileOwner(tile, OWNER_TOWN);
00159         break;
00160 
00161       default: break;
00162     }
00163   }
00164 }
00165 
00166 /* since savegame version 4.1, exclusive transport rights are stored at towns */
00167 static void UpdateExclusiveRights()
00168 {
00169   Town *t;
00170 
00171   FOR_ALL_TOWNS(t) {
00172     t->exclusivity = INVALID_COMPANY;
00173   }
00174 
00175   /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
00176    *   could be implemented this way:
00177    * 1.) Go through all stations
00178    *     Build an array town_blocked[ town_id ][ company_id ]
00179    *     that stores if at least one station in that town is blocked for a company
00180    * 2.) Go through that array, if you find a town that is not blocked for
00181    *     one company, but for all others, then give him exclusivity.
00182    */
00183 }
00184 
00185 static const byte convert_currency[] = {
00186    0,  1, 12,  8,  3,
00187   10, 14, 19,  4,  5,
00188    9, 11, 13,  6, 17,
00189   16, 22, 21,  7, 15,
00190   18,  2, 20,
00191 };
00192 
00193 /* since savegame version 4.2 the currencies are arranged differently */
00194 static void UpdateCurrencies()
00195 {
00196   _settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
00197 }
00198 
00199 /* Up to revision 1413 the invisible tiles at the southern border have not been
00200  * MP_VOID, even though they should have. This is fixed by this function
00201  */
00202 static void UpdateVoidTiles()
00203 {
00204   uint i;
00205 
00206   for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
00207   for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
00208 }
00209 
00210 static inline RailType UpdateRailType(RailType rt, RailType min)
00211 {
00212   return rt >= min ? (RailType)(rt + 1): rt;
00213 }
00214 
00218 void UpdateAllVirtCoords()
00219 {
00220   UpdateAllStationVirtCoords();
00221   UpdateAllSignVirtCoords();
00222   UpdateAllTownVirtCoords();
00223 }
00224 
00234 static void InitializeWindowsAndCaches()
00235 {
00236   /* Initialize windows */
00237   ResetWindowSystem();
00238   SetupColoursAndInitialWindow();
00239 
00240   /* Update coordinates of the signs. */
00241   UpdateAllVirtCoords();
00242   ResetViewportAfterLoadGame();
00243 
00244   Company *c;
00245   FOR_ALL_COMPANIES(c) {
00246     /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
00247      * accordingly if it is not the case.  No need to set it on companies that are not been used already,
00248      * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
00249     if (_file_to_saveload.filetype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
00250       c->inaugurated_year = _cur_year;
00251     }
00252   }
00253 
00254   RecomputePrices();
00255 
00256   GroupStatistics::UpdateAfterLoad();
00257 
00258   Station::RecomputeIndustriesNearForAll();
00259   RebuildSubsidisedSourceAndDestinationCache();
00260 
00261   /* Towns have a noise controlled number of airports system
00262    * So each airport's noise value must be added to the town->noise_reached value
00263    * Reset each town's noise_reached value to '0' before. */
00264   UpdateAirportsNoise();
00265 
00266   CheckTrainsLengths();
00267   ShowNewGRFError();
00268   ShowAIDebugWindowIfAIError();
00269 
00270   /* Rebuild the smallmap list of owners. */
00271   BuildOwnerLegend();
00272 }
00273 
00274 typedef void (CDECL *SignalHandlerPointer)(int);
00275 static SignalHandlerPointer _prev_segfault = NULL;
00276 static SignalHandlerPointer _prev_abort    = NULL;
00277 static SignalHandlerPointer _prev_fpe      = NULL;
00278 
00279 static void CDECL HandleSavegameLoadCrash(int signum);
00280 
00285 static void SetSignalHandlers()
00286 {
00287   _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
00288   _prev_abort    = signal(SIGABRT, HandleSavegameLoadCrash);
00289   _prev_fpe      = signal(SIGFPE,  HandleSavegameLoadCrash);
00290 }
00291 
00295 static void ResetSignalHandlers()
00296 {
00297   signal(SIGSEGV, _prev_segfault);
00298   signal(SIGABRT, _prev_abort);
00299   signal(SIGFPE,  _prev_fpe);
00300 }
00301 
00307 static const GRFIdentifier *GetOverriddenIdentifier(const GRFConfig *c)
00308 {
00309   const LoggedAction *la = &_gamelog_action[_gamelog_actions - 1];
00310   if (la->at != GLAT_LOAD) return &c->ident;
00311 
00312   const LoggedChange *lcend = &la->change[la->changes];
00313   for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
00314     if (lc->ct == GLCT_GRFCOMPAT && lc->grfcompat.grfid == c->ident.grfid) return &lc->grfcompat;
00315   }
00316 
00317   return &c->ident;
00318 }
00319 
00321 static bool _saveload_crash_with_missing_newgrfs = false;
00322 
00328 bool SaveloadCrashWithMissingNewGRFs()
00329 {
00330   return _saveload_crash_with_missing_newgrfs;
00331 }
00332 
00339 static void CDECL HandleSavegameLoadCrash(int signum)
00340 {
00341   ResetSignalHandlers();
00342 
00343   char buffer[8192];
00344   char *p = buffer;
00345   p += seprintf(p, lastof(buffer), "Loading your savegame caused OpenTTD to crash.\n");
00346 
00347   for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != NULL; c = c->next) {
00348     _saveload_crash_with_missing_newgrfs = HasBit(c->flags, GCF_COMPATIBLE) || c->status == GCS_NOT_FOUND;
00349   }
00350 
00351   if (_saveload_crash_with_missing_newgrfs) {
00352     p += seprintf(p, lastof(buffer),
00353       "This is most likely caused by a missing NewGRF or a NewGRF that\n"
00354       "has been loaded as replacement for a missing NewGRF. OpenTTD\n"
00355       "cannot easily determine whether a replacement NewGRF is of a newer\n"
00356       "or older version.\n"
00357       "It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
00358       "This means that if the author makes incompatible NewGRFs with the\n"
00359       "same GRF ID OpenTTD cannot magically do the right thing. In most\n"
00360       "cases OpenTTD will load the savegame and not crash, but this is an\n"
00361       "exception.\n"
00362       "Please load the savegame with the appropriate NewGRFs installed.\n"
00363       "The missing/compatible NewGRFs are:\n");
00364 
00365     for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
00366       if (HasBit(c->flags, GCF_COMPATIBLE)) {
00367         const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
00368         char buf[40];
00369         md5sumToString(buf, lastof(buf), replaced->md5sum);
00370         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);
00371       }
00372       if (c->status == GCS_NOT_FOUND) {
00373         char buf[40];
00374         md5sumToString(buf, lastof(buf), c->ident.md5sum);
00375         p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s.\n", BSWAP32(c->ident.grfid), c->filename, buf);
00376       }
00377     }
00378   } else {
00379     p += seprintf(p, lastof(buffer),
00380       "This is probably caused by a corruption in the savegame.\n"
00381       "Please file a bug report and attach this savegame.\n");
00382   }
00383 
00384   ShowInfo(buffer);
00385 
00386   SignalHandlerPointer call = NULL;
00387   switch (signum) {
00388     case SIGSEGV: call = _prev_segfault; break;
00389     case SIGABRT: call = _prev_abort; break;
00390     case SIGFPE:  call = _prev_fpe; break;
00391     default: NOT_REACHED();
00392   }
00393   if (call != NULL) call(signum);
00394 }
00395 
00401 static void FixOwnerOfRailTrack(TileIndex t)
00402 {
00403   assert(!Company::IsValidID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
00404 
00405   /* remove leftover rail piece from crossing (from very old savegames) */
00406   Train *v = NULL, *w;
00407   FOR_ALL_TRAINS(w) {
00408     if (w->tile == t) {
00409       v = w;
00410       break;
00411     }
00412   }
00413 
00414   if (v != NULL) {
00415     /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
00416     SetTileOwner(t, v->owner);
00417     return;
00418   }
00419 
00420   /* try to find any connected rail */
00421   for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
00422     TileIndex tt = t + TileOffsByDiagDir(dd);
00423     if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
00424         GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
00425         Company::IsValidID(GetTileOwner(tt))) {
00426       SetTileOwner(t, GetTileOwner(tt));
00427       return;
00428     }
00429   }
00430 
00431   if (IsLevelCrossingTile(t)) {
00432     /* else change the crossing to normal road (road vehicles won't care) */
00433     MakeRoadNormal(t, GetCrossingRoadBits(t), GetRoadTypes(t), GetTownIndex(t),
00434       GetRoadOwner(t, ROADTYPE_ROAD), GetRoadOwner(t, ROADTYPE_TRAM));
00435     return;
00436   }
00437 
00438   /* if it's not a crossing, make it clean land */
00439   MakeClear(t, CLEAR_GRASS, 0);
00440 }
00441 
00448 static uint FixVehicleInclination(Vehicle *v, Direction dir)
00449 {
00450   /* Compute place where this vehicle entered the tile */
00451   int entry_x = v->x_pos;
00452   int entry_y = v->y_pos;
00453   switch (dir) {
00454     case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
00455     case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
00456     case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
00457     case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
00458     case INVALID_DIR: break;
00459     default: NOT_REACHED();
00460   }
00461   byte entry_z = GetSlopePixelZ(entry_x, entry_y);
00462 
00463   /* Compute middle of the tile. */
00464   int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + HALF_TILE_SIZE;
00465   int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + HALF_TILE_SIZE;
00466   byte middle_z = GetSlopePixelZ(middle_x, middle_y);
00467 
00468   /* middle_z == entry_z, no height change. */
00469   if (middle_z == entry_z) return 0;
00470 
00471   /* middle_z < entry_z, we are going downwards. */
00472   if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
00473 
00474   /* middle_z > entry_z, we are going upwards. */
00475   return 1U << GVF_GOINGUP_BIT;
00476 }
00477 
00483 bool AfterLoadGame()
00484 {
00485   SetSignalHandlers();
00486 
00487   TileIndex map_size = MapSize();
00488 
00489   if (IsSavegameVersionBefore(98)) GamelogOldver();
00490 
00491   GamelogTestRevision();
00492   GamelogTestMode();
00493 
00494   if (IsSavegameVersionBefore(98)) GamelogGRFAddList(_grfconfig);
00495 
00496   if (IsSavegameVersionBefore(119)) {
00497     _pause_mode = (_pause_mode == 2) ? PM_PAUSED_NORMAL : PM_UNPAUSED;
00498   } else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
00499     DEBUG(net, 0, "The loading savegame was paused due to an error state.");
00500     DEBUG(net, 0, "  The savegame cannot be used for multiplayer!");
00501     /* Restore the signals */
00502     ResetSignalHandlers();
00503     return false;
00504   } else if (!_networking || _network_server) {
00505     /* If we are in single player, i.e. not networking, and loading the
00506      * savegame or we are loading the savegame as network server we do
00507      * not want to be bothered by being paused because of the automatic
00508      * reason of a network server, e.g. joining clients or too few
00509      * active clients. Note that resetting these values for a network
00510      * client are very bad because then the client is going to execute
00511      * the game loop when the server is not, i.e. it desyncs. */
00512     _pause_mode &= ~PMB_PAUSED_NETWORK;
00513   }
00514 
00515   /* In very old versions, size of train stations was stored differently.
00516    * They had swapped width and height if station was built along the Y axis.
00517    * TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
00518    * Because the data stored by TTDPatch are unusable for rail stations > 7x7,
00519    * recompute the width and height. Doing this unconditionally for all old
00520    * savegames simplifies the code. */
00521   if (IsSavegameVersionBefore(2)) {
00522     Station *st;
00523     FOR_ALL_STATIONS(st) {
00524       st->train_station.w = st->train_station.h = 0;
00525     }
00526     for (TileIndex t = 0; t < map_size; t++) {
00527       if (!IsTileType(t, MP_STATION)) continue;
00528       if (_m[t].m5 > 7) continue; // is it a rail station tile?
00529       st = Station::Get(_m[t].m2);
00530       assert(st->train_station.tile != 0);
00531       int dx = TileX(t) - TileX(st->train_station.tile);
00532       int dy = TileY(t) - TileY(st->train_station.tile);
00533       assert(dx >= 0 && dy >= 0);
00534       st->train_station.w = max<uint>(st->train_station.w, dx + 1);
00535       st->train_station.h = max<uint>(st->train_station.h, dy + 1);
00536     }
00537   }
00538 
00539   /* in version 2.1 of the savegame, town owner was unified. */
00540   if (IsSavegameVersionBefore(2, 1)) ConvertTownOwner();
00541 
00542   /* from version 4.1 of the savegame, exclusive rights are stored at towns */
00543   if (IsSavegameVersionBefore(4, 1)) UpdateExclusiveRights();
00544 
00545   /* from version 4.2 of the savegame, currencies are in a different order */
00546   if (IsSavegameVersionBefore(4, 2)) UpdateCurrencies();
00547 
00548   /* In old version there seems to be a problem that water is owned by
00549    * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
00550    * (4.3) version, so I just check when versions are older, and then
00551    * walk through the whole map.. */
00552   if (IsSavegameVersionBefore(4, 3)) {
00553     for (TileIndex t = 0; t < map_size; t++) {
00554       if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
00555         SetTileOwner(t, OWNER_WATER);
00556       }
00557     }
00558   }
00559 
00560   if (IsSavegameVersionBefore(84)) {
00561     Company *c;
00562     FOR_ALL_COMPANIES(c) {
00563       c->name = CopyFromOldName(c->name_1);
00564       if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
00565       c->president_name = CopyFromOldName(c->president_name_1);
00566       if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
00567     }
00568 
00569     Station *st;
00570     FOR_ALL_STATIONS(st) {
00571       st->name = CopyFromOldName(st->string_id);
00572       /* generating new name would be too much work for little effect, use the station name fallback */
00573       if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
00574     }
00575 
00576     Town *t;
00577     FOR_ALL_TOWNS(t) {
00578       t->name = CopyFromOldName(t->townnametype);
00579       if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
00580     }
00581   }
00582 
00583   /* From this point the old names array is cleared. */
00584   ResetOldNames();
00585 
00586   if (IsSavegameVersionBefore(106)) {
00587     /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
00588     Station *st;
00589     FOR_ALL_STATIONS(st) {
00590       if (st->airport.tile       == 0) st->airport.tile = INVALID_TILE;
00591       if (st->dock_tile          == 0) st->dock_tile    = INVALID_TILE;
00592       if (st->train_station.tile == 0) st->train_station.tile   = INVALID_TILE;
00593     }
00594 
00595     /* the same applies to Company::location_of_HQ */
00596     Company *c;
00597     FOR_ALL_COMPANIES(c) {
00598       if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(4) && c->location_of_HQ == 0xFFFF)) {
00599         c->location_of_HQ = INVALID_TILE;
00600       }
00601     }
00602   }
00603 
00604   /* convert road side to my format. */
00605   if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
00606 
00607   /* Check if all NewGRFs are present, we are very strict in MP mode */
00608   GRFListCompatibility gcf_res = IsGoodGRFConfigList(_grfconfig);
00609   for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
00610     if (c->status == GCS_NOT_FOUND) {
00611       GamelogGRFRemove(c->ident.grfid);
00612     } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
00613       GamelogGRFCompatible(&c->ident);
00614     }
00615   }
00616 
00617   if (_networking && gcf_res != GLC_ALL_GOOD) {
00618     SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
00619     /* Restore the signals */
00620     ResetSignalHandlers();
00621     return false;
00622   }
00623 
00624   switch (gcf_res) {
00625     case GLC_COMPATIBLE: ShowErrorMessage(STR_NEWGRF_COMPATIBLE_LOAD_WARNING, INVALID_STRING_ID, WL_CRITICAL); break;
00626     case GLC_NOT_FOUND:  ShowErrorMessage(STR_NEWGRF_DISABLED_WARNING, INVALID_STRING_ID, WL_CRITICAL); _pause_mode = PM_PAUSED_ERROR; break;
00627     default: break;
00628   }
00629 
00630   /* The value of _date_fract got divided, so make sure that old games are converted correctly. */
00631   if (IsSavegameVersionBefore(11, 1) || (IsSavegameVersionBefore(147) && _date_fract > DAY_TICKS)) _date_fract /= 885;
00632 
00633   /* Update current year
00634    * must be done before loading sprites as some newgrfs check it */
00635   SetDate(_date, _date_fract);
00636 
00637   /* Force dynamic engines off when loading older savegames */
00638   if (IsSavegameVersionBefore(95)) _settings_game.vehicle.dynamic_engines = 0;
00639 
00640   /* Load the sprites */
00641   GfxLoadSprites();
00642   LoadStringWidthTable();
00643 
00644   /* Copy temporary data to Engine pool */
00645   CopyTempEngineData();
00646 
00647   /* Connect front and rear engines of multiheaded trains and converts
00648    * subtype to the new format */
00649   if (IsSavegameVersionBefore(17, 1)) ConvertOldMultiheadToNew();
00650 
00651   /* Connect front and rear engines of multiheaded trains */
00652   ConnectMultiheadedTrains();
00653 
00654   /* Fix the CargoPackets *and* fix the caches of CargoLists.
00655    * If this isn't done before Stations and especially Vehicles are
00656    * running their AfterLoad we might get in trouble. In the case of
00657    * vehicles we could give the wrong (cached) count of items in a
00658    * vehicle which causes different results when getting their caches
00659    * filled; and that could eventually lead to desyncs. */
00660   CargoPacket::AfterLoad();
00661 
00662   /* Oilrig was moved from id 15 to 9. We have to do this conversion
00663    * here as AfterLoadVehicles can check it indirectly via the newgrf
00664    * code. */
00665   if (IsSavegameVersionBefore(139)) {
00666     Station *st;
00667     FOR_ALL_STATIONS(st) {
00668       if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
00669         st->airport.type = AT_OILRIG;
00670       }
00671     }
00672   }
00673 
00674   /* Update all vehicles */
00675   AfterLoadVehicles(true);
00676 
00677   /* Make sure there is an AI attached to an AI company */
00678   {
00679     Company *c;
00680     FOR_ALL_COMPANIES(c) {
00681       if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
00682     }
00683   }
00684 
00685   /* make sure there is a town in the game */
00686   if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
00687     SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
00688     /* Restore the signals */
00689     ResetSignalHandlers();
00690     return false;
00691   }
00692 
00693   /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
00694    * This problem appears in savegame version 21 too, see r3455. But after loading the
00695    * savegame and saving again, the buggy map array could be converted to new savegame
00696    * version. It didn't show up before r12070. */
00697   if (IsSavegameVersionBefore(87)) UpdateVoidTiles();
00698 
00699   /* If Load Scenario / New (Scenario) Game is used,
00700    *  a company does not exist yet. So create one here.
00701    * 1 exeption: network-games. Those can have 0 companies
00702    *   But this exeption is not true for non dedicated network_servers! */
00703   if (!Company::IsValidID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated))) {
00704     DoStartupNewCompany(false);
00705   }
00706 
00707   /* Fix the cache for cargo payments. */
00708   CargoPayment *cp;
00709   FOR_ALL_CARGO_PAYMENTS(cp) {
00710     cp->front->cargo_payment = cp;
00711     cp->current_station = cp->front->last_station_visited;
00712   }
00713 
00714   if (IsSavegameVersionBefore(72)) {
00715     /* Locks in very old savegames had OWNER_WATER as owner */
00716     for (TileIndex t = 0; t < MapSize(); t++) {
00717       switch (GetTileType(t)) {
00718         default: break;
00719 
00720         case MP_WATER:
00721           if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
00722           break;
00723 
00724         case MP_STATION: {
00725           if (HasBit(_m[t].m6, 3)) SetBit(_m[t].m6, 2);
00726           StationGfx gfx = GetStationGfx(t);
00727           StationType st;
00728           if (       IsInsideMM(gfx,   0,   8)) { // Rail station
00729             st = STATION_RAIL;
00730             SetStationGfx(t, gfx - 0);
00731           } else if (IsInsideMM(gfx,   8,  67)) { // Airport
00732             st = STATION_AIRPORT;
00733             SetStationGfx(t, gfx - 8);
00734           } else if (IsInsideMM(gfx,  67,  71)) { // Truck
00735             st = STATION_TRUCK;
00736             SetStationGfx(t, gfx - 67);
00737           } else if (IsInsideMM(gfx,  71,  75)) { // Bus
00738             st = STATION_BUS;
00739             SetStationGfx(t, gfx - 71);
00740           } else if (gfx == 75) {                 // Oil rig
00741             st = STATION_OILRIG;
00742             SetStationGfx(t, gfx - 75);
00743           } else if (IsInsideMM(gfx,  76,  82)) { // Dock
00744             st = STATION_DOCK;
00745             SetStationGfx(t, gfx - 76);
00746           } else if (gfx == 82) {                 // Buoy
00747             st = STATION_BUOY;
00748             SetStationGfx(t, gfx - 82);
00749           } else if (IsInsideMM(gfx,  83, 168)) { // Extended airport
00750             st = STATION_AIRPORT;
00751             SetStationGfx(t, gfx - 83 + 67 - 8);
00752           } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
00753             st = STATION_TRUCK;
00754             SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
00755           } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
00756             st = STATION_BUS;
00757             SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
00758           } else {
00759             /* Restore the signals */
00760             ResetSignalHandlers();
00761             return false;
00762           }
00763           SB(_m[t].m6, 3, 3, st);
00764           break;
00765         }
00766       }
00767     }
00768   }
00769 
00770   for (TileIndex t = 0; t < map_size; t++) {
00771     switch (GetTileType(t)) {
00772       case MP_STATION: {
00773         BaseStation *bst = BaseStation::GetByTile(t);
00774 
00775         /* Set up station spread */
00776         bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
00777 
00778         /* Waypoints don't have road stops/oil rigs in the old format */
00779         if (!Station::IsExpected(bst)) break;
00780         Station *st = Station::From(bst);
00781 
00782         switch (GetStationType(t)) {
00783           case STATION_TRUCK:
00784           case STATION_BUS:
00785             if (IsSavegameVersionBefore(6)) {
00786               /* Before version 5 you could not have more than 250 stations.
00787                * Version 6 adds large maps, so you could only place 253*253
00788                * road stops on a map (no freeform edges) = 64009. So, yes
00789                * someone could in theory create such a full map to trigger
00790                * this assertion, it's safe to assume that's only something
00791                * theoretical and does not happen in normal games. */
00792               assert(RoadStop::CanAllocateItem());
00793 
00794               /* From this version on there can be multiple road stops of the
00795                * same type per station. Convert the existing stops to the new
00796                * internal data structure. */
00797               RoadStop *rs = new RoadStop(t);
00798 
00799               RoadStop **head =
00800                 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
00801               *head = rs;
00802             }
00803             break;
00804 
00805           case STATION_OILRIG: {
00806             /* Very old savegames sometimes have phantom oil rigs, i.e.
00807              * an oil rig which got shut down, but not completly removed from
00808              * the map
00809              */
00810             TileIndex t1 = TILE_ADDXY(t, 0, 1);
00811             if (IsTileType(t1, MP_INDUSTRY) &&
00812                 GetIndustryGfx(t1) == GFX_OILRIG_1) {
00813               /* The internal encoding of oil rigs was changed twice.
00814                * It was 3 (till 2.2) and later 5 (till 5.1).
00815                * Setting it unconditionally does not hurt.
00816                */
00817               Station::GetByTile(t)->airport.type = AT_OILRIG;
00818             } else {
00819               DeleteOilRig(t);
00820             }
00821             break;
00822           }
00823 
00824           default: break;
00825         }
00826         break;
00827       }
00828 
00829       default: break;
00830     }
00831   }
00832 
00833   /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
00834    * This has to be called after the oilrig airport_type update above ^^^ ! */
00835   if (IsSavegameVersionBefore(2, 2)) UpdateOldAircraft();
00836 
00837   /* In version 6.1 we put the town index in the map-array. To do this, we need
00838    *  to use m2 (16bit big), so we need to clean m2, and that is where this is
00839    *  all about ;) */
00840   if (IsSavegameVersionBefore(6, 1)) {
00841     for (TileIndex t = 0; t < map_size; t++) {
00842       switch (GetTileType(t)) {
00843         case MP_HOUSE:
00844           _m[t].m4 = _m[t].m2;
00845           SetTownIndex(t, CalcClosestTownFromTile(t)->index);
00846           break;
00847 
00848         case MP_ROAD:
00849           _m[t].m4 |= (_m[t].m2 << 4);
00850           if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
00851             SetTownIndex(t, CalcClosestTownFromTile(t)->index);
00852           } else {
00853             SetTownIndex(t, 0);
00854           }
00855           break;
00856 
00857         default: break;
00858       }
00859     }
00860   }
00861 
00862   /* Force the freeform edges to false for old savegames. */
00863   if (IsSavegameVersionBefore(111)) {
00864     _settings_game.construction.freeform_edges = false;
00865   }
00866 
00867   /* From version 9.0, we update the max passengers of a town (was sometimes negative
00868    *  before that. */
00869   if (IsSavegameVersionBefore(9)) {
00870     Town *t;
00871     FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
00872   }
00873 
00874   /* From version 16.0, we included autorenew on engines, which are now saved, but
00875    *  of course, we do need to initialize them for older savegames. */
00876   if (IsSavegameVersionBefore(16)) {
00877     Company *c;
00878     FOR_ALL_COMPANIES(c) {
00879       c->engine_renew_list            = NULL;
00880       c->settings.engine_renew        = false;
00881       c->settings.engine_renew_months = 6;
00882       c->settings.engine_renew_money  = 100000;
00883     }
00884 
00885     /* When loading a game, _local_company is not yet set to the correct value.
00886      * However, in a dedicated server we are a spectator, so nothing needs to
00887      * happen. In case we are not a dedicated server, the local company always
00888      * becomes company 0, unless we are in the scenario editor where all the
00889      * companies are 'invalid'.
00890      */
00891     c = Company::GetIfValid(COMPANY_FIRST);
00892     if (!_network_dedicated && c != NULL) {
00893       c->settings = _settings_client.company;
00894     }
00895   }
00896 
00897   if (IsSavegameVersionBefore(48)) {
00898     for (TileIndex t = 0; t < map_size; t++) {
00899       switch (GetTileType(t)) {
00900         case MP_RAILWAY:
00901           if (IsPlainRail(t)) {
00902             /* Swap ground type and signal type for plain rail tiles, so the
00903              * ground type uses the same bits as for depots and waypoints. */
00904             uint tmp = GB(_m[t].m4, 0, 4);
00905             SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
00906             SB(_m[t].m2, 0, 4, tmp);
00907           } else if (HasBit(_m[t].m5, 2)) {
00908             /* Split waypoint and depot rail type and remove the subtype. */
00909             ClrBit(_m[t].m5, 2);
00910             ClrBit(_m[t].m5, 6);
00911           }
00912           break;
00913 
00914         case MP_ROAD:
00915           /* Swap m3 and m4, so the track type for rail crossings is the
00916            * same as for normal rail. */
00917           Swap(_m[t].m3, _m[t].m4);
00918           break;
00919 
00920         default: break;
00921       }
00922     }
00923   }
00924 
00925   if (IsSavegameVersionBefore(61)) {
00926     /* Added the RoadType */
00927     bool old_bridge = IsSavegameVersionBefore(42);
00928     for (TileIndex t = 0; t < map_size; t++) {
00929       switch (GetTileType(t)) {
00930         case MP_ROAD:
00931           SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
00932           switch (GetRoadTileType(t)) {
00933             default: SlErrorCorrupt("Invalid road tile type");
00934             case ROAD_TILE_NORMAL:
00935               SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
00936               SB(_m[t].m4, 4, 4, 0);
00937               SB(_m[t].m6, 2, 4, 0);
00938               break;
00939             case ROAD_TILE_CROSSING:
00940               SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
00941               break;
00942             case ROAD_TILE_DEPOT:    break;
00943           }
00944           SetRoadTypes(t, ROADTYPES_ROAD);
00945           break;
00946 
00947         case MP_STATION:
00948           if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
00949           break;
00950 
00951         case MP_TUNNELBRIDGE:
00952           /* Middle part of "old" bridges */
00953           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
00954           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
00955             SetRoadTypes(t, ROADTYPES_ROAD);
00956           }
00957           break;
00958 
00959         default: break;
00960       }
00961     }
00962   }
00963 
00964   if (IsSavegameVersionBefore(114)) {
00965     bool fix_roadtypes = !IsSavegameVersionBefore(61);
00966     bool old_bridge = IsSavegameVersionBefore(42);
00967 
00968     for (TileIndex t = 0; t < map_size; t++) {
00969       switch (GetTileType(t)) {
00970         case MP_ROAD:
00971           if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
00972           SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
00973           switch (GetRoadTileType(t)) {
00974             default: SlErrorCorrupt("Invalid road tile type");
00975             case ROAD_TILE_NORMAL:
00976               SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
00977               SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3));  // ground
00978               SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4));  // tram bits
00979               SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4));  // tram owner
00980               SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4));  // road bits
00981               break;
00982 
00983             case ROAD_TILE_CROSSING:
00984               SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
00985               SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3));  // ground
00986               SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4));  // tram owner
00987               SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1));  // road axis
00988               SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1));  // crossing state
00989               break;
00990 
00991             case ROAD_TILE_DEPOT:
00992               break;
00993           }
00994           if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
00995             const Town *town = CalcClosestTownFromTile(t);
00996             if (town != NULL) SetTownIndex(t, town->index);
00997           }
00998           _m[t].m4 = 0;
00999           break;
01000 
01001         case MP_STATION:
01002           if (!IsRoadStop(t)) break;
01003 
01004           if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
01005           SB(_me[t].m7, 0, 5, HasBit(_m[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
01006           SB(_m[t].m3, 4, 4, _m[t].m1);
01007           _m[t].m4 = 0;
01008           break;
01009 
01010         case MP_TUNNELBRIDGE:
01011           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
01012           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
01013             if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
01014 
01015             Owner o = GetTileOwner(t);
01016             SB(_me[t].m7, 0, 5, o); // road owner
01017             SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
01018           }
01019           SB(_m[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
01020           SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
01021 
01022           _m[t].m2 = 0;
01023           _m[t].m4 = 0;
01024           break;
01025 
01026         default: break;
01027       }
01028     }
01029   }
01030 
01031   if (IsSavegameVersionBefore(42)) {
01032     Vehicle *v;
01033 
01034     for (TileIndex t = 0; t < map_size; t++) {
01035       if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
01036       if (IsBridgeTile(t)) {
01037         if (HasBit(_m[t].m5, 6)) { // middle part
01038           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
01039 
01040           if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
01041             if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
01042               MakeRailNormal(
01043                 t,
01044                 GetTileOwner(t),
01045                 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
01046                 GetRailType(t)
01047               );
01048             } else {
01049               TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
01050 
01051               MakeRoadNormal(
01052                 t,
01053                 axis == AXIS_X ? ROAD_Y : ROAD_X,
01054                 ROADTYPES_ROAD,
01055                 town,
01056                 GetTileOwner(t), OWNER_NONE
01057               );
01058             }
01059           } else {
01060             if (GB(_m[t].m5, 3, 2) == 0) {
01061               MakeClear(t, CLEAR_GRASS, 3);
01062             } else {
01063               if (GetTileSlope(t) != SLOPE_FLAT) {
01064                 MakeShore(t);
01065               } else {
01066                 if (GetTileOwner(t) == OWNER_WATER) {
01067                   MakeSea(t);
01068                 } else {
01069                   MakeCanal(t, GetTileOwner(t), Random());
01070                 }
01071               }
01072             }
01073           }
01074           SetBridgeMiddle(t, axis);
01075         } else { // ramp
01076           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
01077           uint north_south = GB(_m[t].m5, 5, 1);
01078           DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
01079           TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
01080 
01081           _m[t].m5 = 1 << 7 | type << 2 | dir;
01082         }
01083       }
01084     }
01085 
01086     FOR_ALL_VEHICLES(v) {
01087       if (!v->IsGroundVehicle()) continue;
01088       if (IsBridgeTile(v->tile)) {
01089         DiagDirection dir = GetTunnelBridgeDirection(v->tile);
01090 
01091         if (dir != DirToDiagDir(v->direction)) continue;
01092         switch (dir) {
01093           default: SlErrorCorrupt("Invalid vehicle direction");
01094           case DIAGDIR_NE: if ((v->x_pos & 0xF) !=  0)            continue; break;
01095           case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
01096           case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
01097           case DIAGDIR_NW: if ((v->y_pos & 0xF) !=  0)            continue; break;
01098         }
01099       } else if (v->z_pos > GetSlopePixelZ(v->x_pos, v->y_pos)) {
01100         v->tile = GetNorthernBridgeEnd(v->tile);
01101       } else {
01102         continue;
01103       }
01104       if (v->type == VEH_TRAIN) {
01105         Train::From(v)->track = TRACK_BIT_WORMHOLE;
01106       } else {
01107         RoadVehicle::From(v)->state = RVSB_WORMHOLE;
01108       }
01109     }
01110   }
01111 
01112   /* Elrails got added in rev 24 */
01113   if (IsSavegameVersionBefore(24)) {
01114     RailType min_rail = RAILTYPE_ELECTRIC;
01115 
01116     Train *v;
01117     FOR_ALL_TRAINS(v) {
01118       RailType rt = RailVehInfo(v->engine_type)->railtype;
01119 
01120       v->railtype = rt;
01121       if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
01122     }
01123 
01124     /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
01125     for (TileIndex t = 0; t < map_size; t++) {
01126       switch (GetTileType(t)) {
01127         case MP_RAILWAY:
01128           SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
01129           break;
01130 
01131         case MP_ROAD:
01132           if (IsLevelCrossing(t)) {
01133             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
01134           }
01135           break;
01136 
01137         case MP_STATION:
01138           if (HasStationRail(t)) {
01139             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
01140           }
01141           break;
01142 
01143         case MP_TUNNELBRIDGE:
01144           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
01145             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
01146           }
01147           break;
01148 
01149         default:
01150           break;
01151       }
01152     }
01153 
01154     FOR_ALL_TRAINS(v) {
01155       if (v->IsFrontEngine() || v->IsFreeWagon()) v->ConsistChanged(true);
01156     }
01157 
01158   }
01159 
01160   /* In version 16.1 of the savegame a company can decide if trains, which get
01161    * replaced, shall keep their old length. In all prior versions, just default
01162    * to false */
01163   if (IsSavegameVersionBefore(16, 1)) {
01164     Company *c;
01165     FOR_ALL_COMPANIES(c) c->settings.renew_keep_length = false;
01166   }
01167 
01168   if (IsSavegameVersionBefore(123)) {
01169     /* Waypoints became subclasses of stations ... */
01170     MoveWaypointsToBaseStations();
01171     /* ... and buoys were moved to waypoints. */
01172     MoveBuoysToWaypoints();
01173   }
01174 
01175   /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
01176    *  room for PBS. Now in version 21 move it back :P. */
01177   if (IsSavegameVersionBefore(21) && !IsSavegameVersionBefore(15)) {
01178     for (TileIndex t = 0; t < map_size; t++) {
01179       switch (GetTileType(t)) {
01180         case MP_RAILWAY:
01181           if (HasSignals(t)) {
01182             /* convert PBS signals to combo-signals */
01183             if (HasBit(_m[t].m2, 2)) SetSignalType(t, TRACK_X, SIGTYPE_COMBO);
01184 
01185             /* move the signal variant back */
01186             SetSignalVariant(t, TRACK_X, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
01187             ClrBit(_m[t].m2, 3);
01188           }
01189 
01190           /* Clear PBS reservation on track */
01191           if (!IsRailDepotTile(t)) {
01192             SB(_m[t].m4, 4, 4, 0);
01193           } else {
01194             ClrBit(_m[t].m3, 6);
01195           }
01196           break;
01197 
01198         case MP_STATION: // Clear PBS reservation on station
01199           ClrBit(_m[t].m3, 6);
01200           break;
01201 
01202         default: break;
01203       }
01204     }
01205   }
01206 
01207   if (IsSavegameVersionBefore(25)) {
01208     RoadVehicle *rv;
01209     FOR_ALL_ROADVEHICLES(rv) {
01210       rv->vehstatus &= ~0x40;
01211     }
01212   }
01213 
01214   if (IsSavegameVersionBefore(26)) {
01215     Station *st;
01216     FOR_ALL_STATIONS(st) {
01217       st->last_vehicle_type = VEH_INVALID;
01218     }
01219   }
01220 
01221   YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
01222 
01223   if (IsSavegameVersionBefore(34)) {
01224     Company *c;
01225     FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
01226   }
01227 
01228   Company *c;
01229   FOR_ALL_COMPANIES(c) {
01230     c->avail_railtypes = GetCompanyRailtypes(c->index);
01231     c->avail_roadtypes = GetCompanyRoadtypes(c->index);
01232   }
01233 
01234   if (!IsSavegameVersionBefore(27)) AfterLoadStations();
01235 
01236   /* Time starts at 0 instead of 1920.
01237    * Account for this in older games by adding an offset */
01238   if (IsSavegameVersionBefore(31)) {
01239     Station *st;
01240     Waypoint *wp;
01241     Engine *e;
01242     Industry *i;
01243     Vehicle *v;
01244 
01245     _date += DAYS_TILL_ORIGINAL_BASE_YEAR;
01246     _cur_year += ORIGINAL_BASE_YEAR;
01247 
01248     FOR_ALL_STATIONS(st)  st->build_date      += DAYS_TILL_ORIGINAL_BASE_YEAR;
01249     FOR_ALL_WAYPOINTS(wp) wp->build_date      += DAYS_TILL_ORIGINAL_BASE_YEAR;
01250     FOR_ALL_ENGINES(e)    e->intro_date       += DAYS_TILL_ORIGINAL_BASE_YEAR;
01251     FOR_ALL_COMPANIES(c)  c->inaugurated_year += ORIGINAL_BASE_YEAR;
01252     FOR_ALL_INDUSTRIES(i) i->last_prod_year   += ORIGINAL_BASE_YEAR;
01253 
01254     FOR_ALL_VEHICLES(v) {
01255       v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
01256       v->build_year += ORIGINAL_BASE_YEAR;
01257     }
01258   }
01259 
01260   /* From 32 on we save the industry who made the farmland.
01261    *  To give this prettyness to old savegames, we remove all farmfields and
01262    *  plant new ones. */
01263   if (IsSavegameVersionBefore(32)) {
01264     Industry *i;
01265 
01266     for (TileIndex t = 0; t < map_size; t++) {
01267       if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
01268         /* remove fields */
01269         MakeClear(t, CLEAR_GRASS, 3);
01270       }
01271     }
01272 
01273     FOR_ALL_INDUSTRIES(i) {
01274       uint j;
01275 
01276       if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
01277         for (j = 0; j != 50; j++) PlantRandomFarmField(i);
01278       }
01279     }
01280   }
01281 
01282   /* Setting no refit flags to all orders in savegames from before refit in orders were added */
01283   if (IsSavegameVersionBefore(36)) {
01284     Order *order;
01285     Vehicle *v;
01286 
01287     FOR_ALL_ORDERS(order) {
01288       order->SetRefit(CT_NO_REFIT);
01289     }
01290 
01291     FOR_ALL_VEHICLES(v) {
01292       v->current_order.SetRefit(CT_NO_REFIT);
01293     }
01294   }
01295 
01296   /* from version 38 we have optional elrails, since we cannot know the
01297    * preference of a user, let elrails enabled; it can be disabled manually */
01298   if (IsSavegameVersionBefore(38)) _settings_game.vehicle.disable_elrails = false;
01299   /* do the same as when elrails were enabled/disabled manually just now */
01300   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
01301   InitializeRailGUI();
01302 
01303   /* From version 53, the map array was changed for house tiles to allow
01304    * space for newhouses grf features. A new byte, m7, was also added. */
01305   if (IsSavegameVersionBefore(53)) {
01306     for (TileIndex t = 0; t < map_size; t++) {
01307       if (IsTileType(t, MP_HOUSE)) {
01308         if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
01309           /* Move the construction stage from m3[7..6] to m5[5..4].
01310            * The construction counter does not have to move. */
01311           SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
01312           SB(_m[t].m3, 6, 2, 0);
01313 
01314           /* The "house is completed" bit is now in m6[2]. */
01315           SetHouseCompleted(t, false);
01316         } else {
01317           /* The "lift has destination" bit has been moved from
01318            * m5[7] to m7[0]. */
01319           SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
01320           ClrBit(_m[t].m5, 7);
01321 
01322           /* The "lift is moving" bit has been removed, as it does
01323            * the same job as the "lift has destination" bit. */
01324           ClrBit(_m[t].m1, 7);
01325 
01326           /* The position of the lift goes from m1[7..0] to m6[7..2],
01327            * making m1 totally free, now. The lift position does not
01328            * have to be a full byte since the maximum value is 36. */
01329           SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
01330 
01331           _m[t].m1 = 0;
01332           _m[t].m3 = 0;
01333           SetHouseCompleted(t, true);
01334         }
01335       }
01336     }
01337   }
01338 
01339   /* Check and update house and town values */
01340   UpdateHousesAndTowns();
01341 
01342   if (IsSavegameVersionBefore(43)) {
01343     for (TileIndex t = 0; t < map_size; t++) {
01344       if (IsTileType(t, MP_INDUSTRY)) {
01345         switch (GetIndustryGfx(t)) {
01346           case GFX_POWERPLANT_SPARKS:
01347             _m[t].m3 = GB(_m[t].m1, 2, 5);
01348             break;
01349 
01350           case GFX_OILWELL_ANIMATED_1:
01351           case GFX_OILWELL_ANIMATED_2:
01352           case GFX_OILWELL_ANIMATED_3:
01353             _m[t].m3 = GB(_m[t].m1, 0, 2);
01354             break;
01355 
01356           case GFX_COAL_MINE_TOWER_ANIMATED:
01357           case GFX_COPPER_MINE_TOWER_ANIMATED:
01358           case GFX_GOLD_MINE_TOWER_ANIMATED:
01359              _m[t].m3 = _m[t].m1;
01360              break;
01361 
01362           default: // No animation states to change
01363             break;
01364         }
01365       }
01366     }
01367   }
01368 
01369   if (IsSavegameVersionBefore(45)) {
01370     Vehicle *v;
01371     /* Originally just the fact that some cargo had been paid for was
01372      * stored to stop people cheating and cashing in several times. This
01373      * wasn't enough though as it was cleared when the vehicle started
01374      * loading again, even if it didn't actually load anything, so now the
01375      * amount that has been paid is stored. */
01376     FOR_ALL_VEHICLES(v) {
01377       ClrBit(v->vehicle_flags, 2);
01378     }
01379   }
01380 
01381   /* Buoys do now store the owner of the previous water tile, which can never
01382    * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
01383   if (IsSavegameVersionBefore(46)) {
01384     Waypoint *wp;
01385     FOR_ALL_WAYPOINTS(wp) {
01386       if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
01387     }
01388   }
01389 
01390   if (IsSavegameVersionBefore(50)) {
01391     Aircraft *v;
01392     /* Aircraft units changed from 8 mph to 1 km-ish/h */
01393     FOR_ALL_AIRCRAFT(v) {
01394       if (v->subtype <= AIR_AIRCRAFT) {
01395         const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
01396         v->cur_speed *= 128;
01397         v->cur_speed /= 10;
01398         v->acceleration = avi->acceleration;
01399       }
01400     }
01401   }
01402 
01403   if (IsSavegameVersionBefore(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
01404 
01405   if (IsSavegameVersionBefore(52)) {
01406     for (TileIndex t = 0; t < map_size; t++) {
01407       if (IsStatueTile(t)) {
01408         _m[t].m2 = CalcClosestTownFromTile(t)->index;
01409       }
01410     }
01411   }
01412 
01413   /* A setting containing the proportion of towns that grow twice as
01414    * fast was added in version 54. From version 56 this is now saved in the
01415    * town as cities can be built specifically in the scenario editor. */
01416   if (IsSavegameVersionBefore(56)) {
01417     Town *t;
01418 
01419     FOR_ALL_TOWNS(t) {
01420       if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
01421         t->larger_town = true;
01422       }
01423     }
01424   }
01425 
01426   if (IsSavegameVersionBefore(57)) {
01427     Vehicle *v;
01428     /* Added a FIFO queue of vehicles loading at stations */
01429     FOR_ALL_VEHICLES(v) {
01430       if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) &&  // for all locs
01431           !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
01432           v->current_order.IsType(OT_LOADING)) {         // loading
01433         Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
01434 
01435         /* The loading finished flag is *only* set when actually completely
01436          * finished. Because the vehicle is loading, it is not finished. */
01437         ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
01438       }
01439     }
01440   } else if (IsSavegameVersionBefore(59)) {
01441     /* For some reason non-loading vehicles could be in the station's loading vehicle list */
01442 
01443     Station *st;
01444     FOR_ALL_STATIONS(st) {
01445       std::list<Vehicle *>::iterator iter;
01446       for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
01447         Vehicle *v = *iter;
01448         iter++;
01449         if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
01450       }
01451     }
01452   }
01453 
01454   if (IsSavegameVersionBefore(58)) {
01455     /* Setting difficulty industry_density other than zero get bumped to +1
01456      * since a new option (very low at position 1) has been added */
01457     if (_settings_game.difficulty.industry_density > 0) {
01458       _settings_game.difficulty.industry_density++;
01459     }
01460 
01461     /* Same goes for number of towns, although no test is needed, just an increment */
01462     _settings_game.difficulty.number_towns++;
01463   }
01464 
01465   if (IsSavegameVersionBefore(64)) {
01466     /* copy the signal type/variant and move signal states bits */
01467     for (TileIndex t = 0; t < map_size; t++) {
01468       if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
01469         SetSignalStates(t, GB(_m[t].m2, 4, 4));
01470         SetSignalVariant(t, INVALID_TRACK, GetSignalVariant(t, TRACK_X));
01471         SetSignalType(t, INVALID_TRACK, GetSignalType(t, TRACK_X));
01472         ClrBit(_m[t].m2, 7);
01473       }
01474     }
01475   }
01476 
01477   if (IsSavegameVersionBefore(69)) {
01478     /* In some old savegames a bit was cleared when it should not be cleared */
01479     RoadVehicle *rv;
01480     FOR_ALL_ROADVEHICLES(rv) {
01481       if (rv->state == 250 || rv->state == 251) {
01482         SetBit(rv->state, 2);
01483       }
01484     }
01485   }
01486 
01487   if (IsSavegameVersionBefore(70)) {
01488     /* Added variables to support newindustries */
01489     Industry *i;
01490     FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
01491   }
01492 
01493   /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
01494       Replace the owner for those by OWNER_NONE. */
01495   if (IsSavegameVersionBefore(82)) {
01496     for (TileIndex t = 0; t < map_size; t++) {
01497       if (IsTileType(t, MP_WATER) &&
01498           GetWaterTileType(t) == WATER_TILE_CLEAR &&
01499           GetTileOwner(t) == OWNER_WATER &&
01500           TileHeight(t) != 0) {
01501         SetTileOwner(t, OWNER_NONE);
01502       }
01503     }
01504   }
01505 
01506   /*
01507    * Add the 'previous' owner to the ship depots so we can reset it with
01508    * the correct values when it gets destroyed. This prevents that
01509    * someone can remove canals owned by somebody else and it prevents
01510    * making floods using the removal of ship depots.
01511    */
01512   if (IsSavegameVersionBefore(83)) {
01513     for (TileIndex t = 0; t < map_size; t++) {
01514       if (IsShipDepotTile(t)) {
01515         _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
01516       }
01517     }
01518   }
01519 
01520   if (IsSavegameVersionBefore(74)) {
01521     Station *st;
01522     FOR_ALL_STATIONS(st) {
01523       for (CargoID c = 0; c < NUM_CARGO; c++) {
01524         st->goods[c].last_speed = 0;
01525         if (st->goods[c].cargo.Count() != 0) SetBit(st->goods[c].acceptance_pickup, GoodsEntry::GES_PICKUP);
01526       }
01527     }
01528   }
01529 
01530   if (IsSavegameVersionBefore(78)) {
01531     Industry *i;
01532     uint j;
01533     FOR_ALL_INDUSTRIES(i) {
01534       const IndustrySpec *indsp = GetIndustrySpec(i->type);
01535       for (j = 0; j < lengthof(i->produced_cargo); j++) {
01536         i->produced_cargo[j] = indsp->produced_cargo[j];
01537       }
01538       for (j = 0; j < lengthof(i->accepts_cargo); j++) {
01539         i->accepts_cargo[j] = indsp->accepts_cargo[j];
01540       }
01541     }
01542   }
01543 
01544   /* Before version 81, the density of grass was always stored as zero, and
01545    * grassy trees were always drawn fully grassy. Furthermore, trees on rough
01546    * land used to have zero density, now they have full density. Therefore,
01547    * make all grassy/rough land trees have a density of 3. */
01548   if (IsSavegameVersionBefore(81)) {
01549     for (TileIndex t = 0; t < map_size; t++) {
01550       if (GetTileType(t) == MP_TREES) {
01551         TreeGround groundType = (TreeGround)GB(_m[t].m2, 4, 2);
01552         if (groundType != TREE_GROUND_SNOW_DESERT) SB(_m[t].m2, 6, 2, 3);
01553       }
01554     }
01555   }
01556 
01557 
01558   if (IsSavegameVersionBefore(93)) {
01559     /* Rework of orders. */
01560     Order *order;
01561     FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
01562 
01563     Vehicle *v;
01564     FOR_ALL_VEHICLES(v) {
01565       if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && v->orders.list->GetFirstOrder()->IsType(OT_NOTHING)) {
01566         v->orders.list->FreeChain();
01567         v->orders.list = NULL;
01568       }
01569 
01570       v->current_order.ConvertFromOldSavegame();
01571       if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
01572         FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
01573       }
01574     }
01575   } else if (IsSavegameVersionBefore(94)) {
01576     /* Unload and transfer are now mutual exclusive. */
01577     Order *order;
01578     FOR_ALL_ORDERS(order) {
01579       if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
01580         order->SetUnloadType(OUFB_TRANSFER);
01581         order->SetLoadType(OLFB_NO_LOAD);
01582       }
01583     }
01584 
01585     Vehicle *v;
01586     FOR_ALL_VEHICLES(v) {
01587       if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
01588         v->current_order.SetUnloadType(OUFB_TRANSFER);
01589         v->current_order.SetLoadType(OLFB_NO_LOAD);
01590       }
01591     }
01592   }
01593 
01594   if (IsSavegameVersionBefore(84)) {
01595     /* Set all share owners to INVALID_COMPANY for
01596      * 1) all inactive companies
01597      *     (when inactive companies were stored in the savegame - TTD, TTDP and some
01598      *      *really* old revisions of OTTD; else it is already set in InitializeCompanies())
01599      * 2) shares that are owned by inactive companies or self
01600      *     (caused by cheating clients in earlier revisions) */
01601     FOR_ALL_COMPANIES(c) {
01602       for (uint i = 0; i < 4; i++) {
01603         CompanyID company = c->share_owners[i];
01604         if (company == INVALID_COMPANY) continue;
01605         if (!Company::IsValidID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
01606       }
01607     }
01608   }
01609 
01610   /* The water class was moved/unified. */
01611   if (IsSavegameVersionBefore(146)) {
01612     for (TileIndex t = 0; t < map_size; t++) {
01613       switch (GetTileType(t)) {
01614         case MP_STATION:
01615           switch (GetStationType(t)) {
01616             case STATION_OILRIG:
01617             case STATION_DOCK:
01618             case STATION_BUOY:
01619               SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
01620               SB(_m[t].m3, 0, 2, 0);
01621               break;
01622 
01623             default:
01624               SetWaterClass(t, WATER_CLASS_INVALID);
01625               break;
01626           }
01627           break;
01628 
01629         case MP_WATER:
01630           SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
01631           SB(_m[t].m3, 0, 2, 0);
01632           break;
01633 
01634         case MP_OBJECT:
01635           SetWaterClass(t, WATER_CLASS_INVALID);
01636           break;
01637 
01638         default:
01639           /* No water class. */
01640           break;
01641       }
01642     }
01643   }
01644 
01645   if (IsSavegameVersionBefore(86)) {
01646     for (TileIndex t = 0; t < map_size; t++) {
01647       /* Move river flag and update canals to use water class */
01648       if (IsTileType(t, MP_WATER)) {
01649         if (GetWaterClass(t) != WATER_CLASS_RIVER) {
01650           if (IsWater(t)) {
01651             Owner o = GetTileOwner(t);
01652             if (o == OWNER_WATER) {
01653               MakeSea(t);
01654             } else {
01655               MakeCanal(t, o, Random());
01656             }
01657           } else if (IsShipDepot(t)) {
01658             Owner o = (Owner)_m[t].m4; // Original water owner
01659             SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
01660           }
01661         }
01662       }
01663     }
01664 
01665     /* Update locks, depots, docks and buoys to have a water class based
01666      * on its neighbouring tiles. Done after river and canal updates to
01667      * ensure neighbours are correct. */
01668     for (TileIndex t = 0; t < map_size; t++) {
01669       if (GetTileSlope(t) != SLOPE_FLAT) continue;
01670 
01671       if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
01672       if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
01673     }
01674   }
01675 
01676   if (IsSavegameVersionBefore(87)) {
01677     for (TileIndex t = 0; t < map_size; t++) {
01678       /* skip oil rigs at borders! */
01679       if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
01680           (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
01681         /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
01682          * This conversion has to be done before buoys with invalid owner are removed. */
01683         SetWaterClass(t, WATER_CLASS_SEA);
01684       }
01685 
01686       if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
01687         Owner o = GetTileOwner(t);
01688         if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
01689           Backup<CompanyByte> cur_company(_current_company, o, FILE_LINE);
01690           ChangeTileOwner(t, o, INVALID_OWNER);
01691           cur_company.Restore();
01692         }
01693         if (IsBuoyTile(t)) {
01694           /* reset buoy owner to OWNER_NONE in the station struct
01695            * (even if it is owned by active company) */
01696           Waypoint::GetByTile(t)->owner = OWNER_NONE;
01697         }
01698       } else if (IsTileType(t, MP_ROAD)) {
01699         /* works for all RoadTileType */
01700         for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
01701           /* update even non-existing road types to update tile owner too */
01702           Owner o = GetRoadOwner(t, rt);
01703           if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rt, OWNER_NONE);
01704         }
01705         if (IsLevelCrossing(t)) {
01706           if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
01707         }
01708       } else if (IsPlainRailTile(t)) {
01709         if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
01710       }
01711     }
01712 
01713     /* Convert old PF settings to new */
01714     if (_settings_game.pf.yapf.rail_use_yapf || IsSavegameVersionBefore(28)) {
01715       _settings_game.pf.pathfinder_for_trains = VPF_YAPF;
01716     } else {
01717       _settings_game.pf.pathfinder_for_trains = VPF_NPF;
01718     }
01719 
01720     if (_settings_game.pf.yapf.road_use_yapf || IsSavegameVersionBefore(28)) {
01721       _settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
01722     } else {
01723       _settings_game.pf.pathfinder_for_roadvehs = VPF_NPF;
01724     }
01725 
01726     if (_settings_game.pf.yapf.ship_use_yapf) {
01727       _settings_game.pf.pathfinder_for_ships = VPF_YAPF;
01728     } else {
01729       _settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
01730     }
01731   }
01732 
01733   if (IsSavegameVersionBefore(88)) {
01734     /* Profits are now with 8 bit fract */
01735     Vehicle *v;
01736     FOR_ALL_VEHICLES(v) {
01737       v->profit_this_year <<= 8;
01738       v->profit_last_year <<= 8;
01739       v->running_ticks = 0;
01740     }
01741   }
01742 
01743   if (IsSavegameVersionBefore(91)) {
01744     /* Increase HouseAnimationFrame from 5 to 7 bits */
01745     for (TileIndex t = 0; t < map_size; t++) {
01746       if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
01747         SB(_m[t].m6, 2, 6, GB(_m[t].m6, 3, 5));
01748         SB(_m[t].m3, 5, 1, 0);
01749       }
01750     }
01751   }
01752 
01753   if (IsSavegameVersionBefore(62)) {
01754     /* Remove all trams from savegames without tram support.
01755      * There would be trams without tram track under causing crashes sooner or later. */
01756     RoadVehicle *v;
01757     FOR_ALL_ROADVEHICLES(v) {
01758       if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
01759         ShowErrorMessage(STR_WARNING_LOADGAME_REMOVED_TRAMS, INVALID_STRING_ID, WL_CRITICAL);
01760         delete v;
01761       }
01762     }
01763   }
01764 
01765   if (IsSavegameVersionBefore(99)) {
01766     for (TileIndex t = 0; t < map_size; t++) {
01767       /* Set newly introduced WaterClass of industry tiles */
01768       if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
01769         SetWaterClassDependingOnSurroundings(t, true);
01770       }
01771       if (IsTileType(t, MP_INDUSTRY)) {
01772         if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
01773           SetWaterClassDependingOnSurroundings(t, true);
01774         } else {
01775           SetWaterClass(t, WATER_CLASS_INVALID);
01776         }
01777       }
01778 
01779       /* Replace "house construction year" with "house age" */
01780       if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
01781         _m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
01782       }
01783     }
01784   }
01785 
01786   /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
01787    * format here, as an old layout wouldn't work properly anyway. To be safe, we
01788    * clear any possible PBS reservations as well. */
01789   if (IsSavegameVersionBefore(100)) {
01790     for (TileIndex t = 0; t < map_size; t++) {
01791       switch (GetTileType(t)) {
01792         case MP_RAILWAY:
01793           if (HasSignals(t)) {
01794             /* move the signal variant */
01795             SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
01796             SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
01797             ClrBit(_m[t].m2, 2);
01798             ClrBit(_m[t].m2, 6);
01799           }
01800 
01801           /* Clear PBS reservation on track */
01802           if (IsRailDepot(t)) {
01803             SetDepotReservation(t, false);
01804           } else {
01805             SetTrackReservation(t, TRACK_BIT_NONE);
01806           }
01807           break;
01808 
01809         case MP_ROAD: // Clear PBS reservation on crossing
01810           if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
01811           break;
01812 
01813         case MP_STATION: // Clear PBS reservation on station
01814           if (HasStationRail(t)) SetRailStationReservation(t, false);
01815           break;
01816 
01817         case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/birdges
01818           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
01819           break;
01820 
01821         default: break;
01822       }
01823     }
01824   }
01825 
01826   /* Reserve all tracks trains are currently on. */
01827   if (IsSavegameVersionBefore(101)) {
01828     const Train *t;
01829     FOR_ALL_TRAINS(t) {
01830       if (t->First() == t) t->ReserveTrackUnderConsist();
01831     }
01832   }
01833 
01834   if (IsSavegameVersionBefore(102)) {
01835     for (TileIndex t = 0; t < map_size; t++) {
01836       /* Now all crossings should be in correct state */
01837       if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
01838     }
01839   }
01840 
01841   if (IsSavegameVersionBefore(103)) {
01842     /* Non-town-owned roads now store the closest town */
01843     UpdateNearestTownForRoadTiles(false);
01844 
01845     /* signs with invalid owner left from older savegames */
01846     Sign *si;
01847     FOR_ALL_SIGNS(si) {
01848       if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
01849     }
01850 
01851     /* Station can get named based on an industry type, but the current ones
01852      * are not, so mark them as if they are not named by an industry. */
01853     Station *st;
01854     FOR_ALL_STATIONS(st) {
01855       st->indtype = IT_INVALID;
01856     }
01857   }
01858 
01859   if (IsSavegameVersionBefore(104)) {
01860     Aircraft *a;
01861     FOR_ALL_AIRCRAFT(a) {
01862       /* Set engine_type of shadow and rotor */
01863       if (!a->IsNormalAircraft()) {
01864         a->engine_type = a->First()->engine_type;
01865       }
01866     }
01867 
01868     /* More companies ... */
01869     Company *c;
01870     FOR_ALL_COMPANIES(c) {
01871       if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
01872     }
01873 
01874     Engine *e;
01875     FOR_ALL_ENGINES(e) {
01876       if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
01877     }
01878 
01879     Town *t;
01880     FOR_ALL_TOWNS(t) {
01881       if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
01882       for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
01883     }
01884   }
01885 
01886   if (IsSavegameVersionBefore(112)) {
01887     for (TileIndex t = 0; t < map_size; t++) {
01888       /* Check for HQ bit being set, instead of using map accessor,
01889        * since we've already changed it code-wise */
01890       if (IsTileType(t, MP_OBJECT) && HasBit(_m[t].m5, 7)) {
01891         /* Move size and part identification of HQ out of the m5 attribute,
01892          * on new locations */
01893         _m[t].m3 = GB(_m[t].m5, 0, 5);
01894         _m[t].m5 = OBJECT_HQ;
01895       }
01896     }
01897   }
01898   if (IsSavegameVersionBefore(144)) {
01899     for (TileIndex t = 0; t < map_size; t++) {
01900       if (!IsTileType(t, MP_OBJECT)) continue;
01901 
01902       /* Reordering/generalisation of the object bits. */
01903       ObjectType type = GetObjectType(t);
01904       SB(_m[t].m6, 2, 4, type == OBJECT_HQ ? GB(_m[t].m3, 2, 3) : 0);
01905       _m[t].m3 = type == OBJECT_HQ ? GB(_m[t].m3, 1, 1) | GB(_m[t].m3, 0, 1) << 4 : 0;
01906 
01907       /* Make sure those bits are clear as well! */
01908       _m[t].m4 = 0;
01909       _me[t].m7 = 0;
01910     }
01911   }
01912 
01913   if (IsSavegameVersionBefore(147) && Object::GetNumItems() == 0) {
01914     /* Make real objects for object tiles. */
01915     for (TileIndex t = 0; t < map_size; t++) {
01916       if (!IsTileType(t, MP_OBJECT)) continue;
01917 
01918       if (Town::GetNumItems() == 0) {
01919         /* No towns, so remove all objects! */
01920         DoClearSquare(t);
01921       } else {
01922         uint offset = _m[t].m3;
01923 
01924         /* Also move the animation state. */
01925         _m[t].m3 = GB(_m[t].m6, 2, 4);
01926         SB(_m[t].m6, 2, 4, 0);
01927 
01928         if (offset == 0) {
01929           /* No offset, so make the object. */
01930           ObjectType type = GetObjectType(t);
01931           int size = type == OBJECT_HQ ? 2 : 1;
01932 
01933           if (!Object::CanAllocateItem()) {
01934             /* Nice... you managed to place 64k lighthouses and
01935              * antennae on the map... boohoo. */
01936             SlError(STR_ERROR_TOO_MANY_OBJECTS);
01937           }
01938 
01939           Object *o = new Object();
01940           o->location.tile = t;
01941           o->location.w    = size;
01942           o->location.h    = size;
01943           o->build_date    = _date;
01944           o->town          = type == OBJECT_STATUE ? Town::Get(_m[t].m2) : CalcClosestTownFromTile(t, UINT_MAX);
01945           _m[t].m2 = o->index;
01946           Object::IncTypeCount(type);
01947         } else {
01948           /* We're at an offset, so get the ID from our "root". */
01949           TileIndex northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
01950           assert(IsTileType(northern_tile, MP_OBJECT));
01951           _m[t].m2 = _m[northern_tile].m2;
01952         }
01953       }
01954     }
01955   }
01956 
01957   if (IsSavegameVersionBefore(113)) {
01958     /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
01959     if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
01960       _settings_game.economy.allow_town_roads = false;
01961       _settings_game.economy.town_layout = TL_BETTER_ROADS;
01962     } else {
01963       _settings_game.economy.allow_town_roads = true;
01964       _settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
01965     }
01966 
01967     /* Initialize layout of all towns. Older versions were using different
01968      * generator for random town layout, use it if needed. */
01969     Town *t;
01970     FOR_ALL_TOWNS(t) {
01971       if (_settings_game.economy.town_layout != TL_RANDOM) {
01972         t->layout = _settings_game.economy.town_layout;
01973         continue;
01974       }
01975 
01976       /* Use old layout randomizer code */
01977       byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
01978       switch (layout) {
01979         default: break;
01980         case 5: layout = 1; break;
01981         case 0: layout = 2; break;
01982       }
01983       t->layout = layout - 1;
01984     }
01985   }
01986 
01987   if (IsSavegameVersionBefore(114)) {
01988     /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
01989      * The conversion affects oil rigs and buoys too, but it doesn't matter as
01990      * they have st->owner == OWNER_NONE already. */
01991     Station *st;
01992     FOR_ALL_STATIONS(st) {
01993       if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
01994     }
01995   }
01996 
01997   /* Trains could now stop in a specific location. */
01998   if (IsSavegameVersionBefore(117)) {
01999     Order *o;
02000     FOR_ALL_ORDERS(o) {
02001       if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
02002     }
02003   }
02004 
02005   if (IsSavegameVersionBefore(120)) {
02006     extern VehicleDefaultSettings _old_vds;
02007     Company *c;
02008     FOR_ALL_COMPANIES(c) {
02009       c->settings.vehicle = _old_vds;
02010     }
02011   }
02012 
02013   if (IsSavegameVersionBefore(121)) {
02014     /* Delete small ufos heading for non-existing vehicles */
02015     Vehicle *v;
02016     FOR_ALL_DISASTERVEHICLES(v) {
02017       if (v->subtype == 2/*ST_SMALL_UFO*/ && v->current_order.GetDestination() != 0) {
02018         const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
02019         if (u == NULL || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
02020           delete v;
02021         }
02022       }
02023     }
02024 
02025     /* We didn't store cargo payment yet, so make them for vehicles that are
02026      * currently at a station and loading/unloading. If they don't get any
02027      * payment anymore they just removed in the next load/unload cycle.
02028      * However, some 0.7 versions might have cargo payment. For those we just
02029      * add cargopayment for the vehicles that don't have it.
02030      */
02031     Station *st;
02032     FOR_ALL_STATIONS(st) {
02033       std::list<Vehicle *>::iterator iter;
02034       for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
02035         /* There are always as many CargoPayments as Vehicles. We need to make the
02036          * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
02037         assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
02038         assert(CargoPayment::CanAllocateItem());
02039         Vehicle *v = *iter;
02040         if (v->cargo_payment == NULL) v->cargo_payment = new CargoPayment(v);
02041       }
02042     }
02043   }
02044 
02045   if (IsSavegameVersionBefore(122)) {
02046     /* Animated tiles would sometimes not be actually animated or
02047      * in case of old savegames duplicate. */
02048 
02049     extern TileIndex *_animated_tile_list;
02050     extern uint _animated_tile_count;
02051 
02052     for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
02053       /* Remove if tile is not animated */
02054       bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == NULL;
02055 
02056       /* and remove if duplicate */
02057       for (uint j = 0; !remove && j < i; j++) {
02058         remove = _animated_tile_list[i] == _animated_tile_list[j];
02059       }
02060 
02061       if (remove) {
02062         DeleteAnimatedTile(_animated_tile_list[i]);
02063       } else {
02064         i++;
02065       }
02066     }
02067   }
02068 
02069   if (IsSavegameVersionBefore(124) && !IsSavegameVersionBefore(1)) {
02070     /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
02071     Waypoint *wp;
02072     FOR_ALL_WAYPOINTS(wp) {
02073       if (wp->facilities & FACIL_TRAIN) {
02074         wp->train_station.tile = wp->xy;
02075         wp->train_station.w = 1;
02076         wp->train_station.h = 1;
02077       } else {
02078         wp->train_station.tile = INVALID_TILE;
02079         wp->train_station.w = 0;
02080         wp->train_station.h = 0;
02081       }
02082     }
02083   }
02084 
02085   if (IsSavegameVersionBefore(125)) {
02086     /* Convert old subsidies */
02087     Subsidy *s;
02088     FOR_ALL_SUBSIDIES(s) {
02089       if (s->remaining < 12) {
02090         /* Converting nonawarded subsidy */
02091         s->remaining = 12 - s->remaining; // convert "age" to "remaining"
02092         s->awarded = INVALID_COMPANY; // not awarded to anyone
02093         const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
02094         switch (cs->town_effect) {
02095           case TE_PASSENGERS:
02096           case TE_MAIL:
02097             /* Town -> Town */
02098             s->src_type = s->dst_type = ST_TOWN;
02099             if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
02100             break;
02101           case TE_GOODS:
02102           case TE_FOOD:
02103             /* Industry -> Town */
02104             s->src_type = ST_INDUSTRY;
02105             s->dst_type = ST_TOWN;
02106             if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
02107             break;
02108           default:
02109             /* Industry -> Industry */
02110             s->src_type = s->dst_type = ST_INDUSTRY;
02111             if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
02112             break;
02113         }
02114       } else {
02115         /* Do our best for awarded subsidies. The original source or destination industry
02116          * can't be determined anymore for awarded subsidies, so invalidate them.
02117          * Town -> Town subsidies are converted using simple heuristic */
02118         s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
02119         const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
02120         switch (cs->town_effect) {
02121           case TE_PASSENGERS:
02122           case TE_MAIL: {
02123             /* Town -> Town */
02124             const Station *ss = Station::GetIfValid(s->src);
02125             const Station *sd = Station::GetIfValid(s->dst);
02126             if (ss != NULL && sd != NULL && ss->owner == sd->owner &&
02127                 Company::IsValidID(ss->owner)) {
02128               s->src_type = s->dst_type = ST_TOWN;
02129               s->src = ss->town->index;
02130               s->dst = sd->town->index;
02131               s->awarded = ss->owner;
02132               continue;
02133             }
02134             break;
02135           }
02136           default:
02137             break;
02138         }
02139       }
02140       /* Awarded non-town subsidy or invalid source/destination, invalidate */
02141       delete s;
02142     }
02143   }
02144 
02145   if (IsSavegameVersionBefore(126)) {
02146     /* Recompute inflation based on old unround loan limit
02147      * Note: Max loan is 500000. With an inflation of 4% across 170 years
02148      *       that results in a max loan of about 0.7 * 2^31.
02149      *       So taking the 16 bit fractional part into account there are plenty of bits left
02150      *       for unmodified savegames ...
02151      */
02152     uint64 aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
02153 
02154     /* ... well, just clamp it then. */
02155     if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
02156 
02157     /* Simulate the inflation, so we also get the payment inflation */
02158     while (_economy.inflation_prices < aimed_inflation) {
02159       AddInflation(false);
02160     }
02161   }
02162 
02163   if (IsSavegameVersionBefore(127)) {
02164     Station *st;
02165     FOR_ALL_STATIONS(st) UpdateStationAcceptance(st, false);
02166   }
02167 
02168   if (IsSavegameVersionBefore(128)) {
02169     const Depot *d;
02170     FOR_ALL_DEPOTS(d) {
02171       _m[d->xy].m2 = d->index;
02172       if (IsTileType(d->xy, MP_WATER)) _m[GetOtherShipDepotTile(d->xy)].m2 = d->index;
02173     }
02174   }
02175 
02176   /* The behaviour of force_proceed has been changed. Now
02177    * it counts signals instead of some random time out. */
02178   if (IsSavegameVersionBefore(131)) {
02179     Train *t;
02180     FOR_ALL_TRAINS(t) {
02181       if (t->force_proceed != TFP_NONE) {
02182         t->force_proceed = TFP_STUCK;
02183       }
02184     }
02185   }
02186 
02187   /* The bits for the tree ground and tree density have
02188    * been swapped (m2 bits 7..6 and 5..4. */
02189   if (IsSavegameVersionBefore(135)) {
02190     for (TileIndex t = 0; t < map_size; t++) {
02191       if (IsTileType(t, MP_CLEAR)) {
02192         if (GetRawClearGround(t) == CLEAR_SNOW) {
02193           SetClearGroundDensity(t, CLEAR_GRASS, GetClearDensity(t));
02194           SetBit(_m[t].m3, 4);
02195         } else {
02196           ClrBit(_m[t].m3, 4);
02197         }
02198       }
02199       if (IsTileType(t, MP_TREES)) {
02200         uint density = GB(_m[t].m2, 6, 2);
02201         uint ground = GB(_m[t].m2, 4, 2);
02202         uint counter = GB(_m[t].m2, 0, 4);
02203         _m[t].m2 = ground << 6 | density << 4 | counter;
02204       }
02205     }
02206   }
02207 
02208   /* Wait counter and load/unload ticks got split. */
02209   if (IsSavegameVersionBefore(136)) {
02210     Aircraft *a;
02211     FOR_ALL_AIRCRAFT(a) {
02212       a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
02213     }
02214 
02215     Train *t;
02216     FOR_ALL_TRAINS(t) {
02217       t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
02218     }
02219   }
02220 
02221   /* Airport tile animation uses animation frame instead of other graphics id */
02222   if (IsSavegameVersionBefore(137)) {
02223     struct AirportTileConversion {
02224       byte old_start;
02225       byte num_frames;
02226     };
02227     static const AirportTileConversion atc[] = {
02228       {31,  12}, // APT_RADAR_GRASS_FENCE_SW
02229       {50,   4}, // APT_GRASS_FENCE_NE_FLAG
02230       {62,   2}, // 1 unused tile
02231       {66,  12}, // APT_RADAR_FENCE_SW
02232       {78,  12}, // APT_RADAR_FENCE_NE
02233       {101, 10}, // 9 unused tiles
02234       {111,  8}, // 7 unused tiles
02235       {119, 15}, // 14 unused tiles (radar)
02236       {140,  4}, // APT_GRASS_FENCE_NE_FLAG_2
02237     };
02238     for (TileIndex t = 0; t < map_size; t++) {
02239       if (IsAirportTile(t)) {
02240         StationGfx old_gfx = GetStationGfx(t);
02241         byte offset = 0;
02242         for (uint i = 0; i < lengthof(atc); i++) {
02243           if (old_gfx < atc[i].old_start) {
02244             SetStationGfx(t, old_gfx - offset);
02245             break;
02246           }
02247           if (old_gfx < atc[i].old_start + atc[i].num_frames) {
02248             SetAnimationFrame(t, old_gfx - atc[i].old_start);
02249             SetStationGfx(t, atc[i].old_start - offset);
02250             break;
02251           }
02252           offset += atc[i].num_frames - 1;
02253         }
02254       }
02255     }
02256   }
02257 
02258   if (IsSavegameVersionBefore(140)) {
02259     Station *st;
02260     FOR_ALL_STATIONS(st) {
02261       if (st->airport.tile != INVALID_TILE) {
02262         st->airport.w = st->airport.GetSpec()->size_x;
02263         st->airport.h = st->airport.GetSpec()->size_y;
02264       }
02265     }
02266   }
02267 
02268   if (IsSavegameVersionBefore(141)) {
02269     for (TileIndex t = 0; t < map_size; t++) {
02270       /* Reset tropic zone for VOID tiles, they shall not have any. */
02271       if (IsTileType(t, MP_VOID)) SetTropicZone(t, TROPICZONE_NORMAL);
02272     }
02273 
02274     /* We need to properly number/name the depots.
02275      * The first step is making sure none of the depots uses the
02276      * 'default' names, after that we can assign the names. */
02277     Depot *d;
02278     FOR_ALL_DEPOTS(d) d->town_cn = UINT16_MAX;
02279 
02280     FOR_ALL_DEPOTS(d) MakeDefaultName(d);
02281   }
02282 
02283   if (IsSavegameVersionBefore(142)) {
02284     Depot *d;
02285     FOR_ALL_DEPOTS(d) d->build_date = _date;
02286   }
02287 
02288   /* In old versions it was possible to remove an airport while a plane was
02289    * taking off or landing. This gives all kind of problems when building
02290    * another airport in the same station so we don't allow that anymore.
02291    * For old savegames with such aircraft we just throw them in the air and
02292    * treat the aircraft like they were flying already. */
02293   if (IsSavegameVersionBefore(146)) {
02294     Aircraft *v;
02295     FOR_ALL_AIRCRAFT(v) {
02296       if (!v->IsNormalAircraft()) continue;
02297       Station *st = GetTargetAirportIfValid(v);
02298       if (st == NULL && v->state != FLYING) {
02299         v->state = FLYING;
02300         UpdateAircraftCache(v);
02301         AircraftNextAirportPos_and_Order(v);
02302         /* get aircraft back on running altitude */
02303         if ((v->vehstatus & VS_CRASHED) == 0) SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlyingAltitude(v));
02304       }
02305     }
02306   }
02307 
02308   /* Move the animation frame to the same location (m7) for all objects. */
02309   if (IsSavegameVersionBefore(147)) {
02310     for (TileIndex t = 0; t < map_size; t++) {
02311       switch (GetTileType(t)) {
02312         case MP_HOUSE:
02313           if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
02314             uint per_proc = _me[t].m7;
02315             _me[t].m7 = GB(_m[t].m6, 2, 6) | (GB(_m[t].m3, 5, 1) << 6);
02316             SB(_m[t].m3, 5, 1, 0);
02317             SB(_m[t].m6, 2, 6, min(per_proc, 63));
02318           }
02319           break;
02320 
02321         case MP_INDUSTRY: {
02322           uint rand = _me[t].m7;
02323           _me[t].m7 = _m[t].m3;
02324           _m[t].m3 = rand;
02325           break;
02326         }
02327 
02328         case MP_OBJECT:
02329           _me[t].m7 = _m[t].m3;
02330           _m[t].m3 = 0;
02331           break;
02332 
02333         default:
02334           /* For stations/airports it's already at m7 */
02335           break;
02336       }
02337     }
02338   }
02339 
02340   /* Add (random) colour to all objects. */
02341   if (IsSavegameVersionBefore(148)) {
02342     Object *o;
02343     FOR_ALL_OBJECTS(o) {
02344       Owner owner = GetTileOwner(o->location.tile);
02345       o->colour = (owner == OWNER_NONE) ? Random() & 0xF : Company::Get(owner)->livery->colour1;
02346     }
02347   }
02348 
02349   if (IsSavegameVersionBefore(149)) {
02350     for (TileIndex t = 0; t < map_size; t++) {
02351       if (!IsTileType(t, MP_STATION)) continue;
02352       if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && GetTileSlope(t) == SLOPE_FLAT)) {
02353         SetWaterClass(t, WATER_CLASS_INVALID);
02354       }
02355     }
02356 
02357     /* Waypoints with custom name may have a non-unique town_cn,
02358      * renumber those. First set all affected waypoints to the
02359      * highest possible number to get them numbered in the
02360      * order they have in the pool. */
02361     Waypoint *wp;
02362     FOR_ALL_WAYPOINTS(wp) {
02363       if (wp->name != NULL) wp->town_cn = UINT16_MAX;
02364     }
02365 
02366     FOR_ALL_WAYPOINTS(wp) {
02367       if (wp->name != NULL) MakeDefaultName(wp);
02368     }
02369   }
02370 
02371   if (IsSavegameVersionBefore(152)) {
02372     _industry_builder.Reset(); // Initialize industry build data.
02373 
02374     /* The moment vehicles go from hidden to visible changed. This means
02375      * that vehicles don't always get visible anymore causing things to
02376      * get messed up just after loading the savegame. This fixes that. */
02377     Vehicle *v;
02378     FOR_ALL_VEHICLES(v) {
02379       /* Not all vehicle types can be inside a tunnel. Furthermore,
02380        * testing IsTunnelTile() for invalid tiles causes a crash. */
02381       if (!v->IsGroundVehicle()) continue;
02382 
02383       /* Is the vehicle in a tunnel? */
02384       if (!IsTunnelTile(v->tile)) continue;
02385 
02386       /* Is the vehicle actually at a tunnel entrance/exit? */
02387       TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
02388       if (!IsTunnelTile(vtile)) continue;
02389 
02390       /* Are we actually in this tunnel? Or maybe a lower tunnel? */
02391       if (GetSlopePixelZ(v->x_pos, v->y_pos) != v->z_pos) continue;
02392 
02393       /* What way are we going? */
02394       const DiagDirection dir = GetTunnelBridgeDirection(vtile);
02395       const DiagDirection vdir = DirToDiagDir(v->direction);
02396 
02397       /* Have we passed the visibility "switch" state already? */
02398       byte pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
02399       byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
02400       extern const byte _tunnel_visibility_frame[DIAGDIR_END];
02401 
02402       /* Should the vehicle be hidden or not? */
02403       bool hidden;
02404       if (dir == vdir) { // Entering tunnel
02405         hidden = frame >= _tunnel_visibility_frame[dir];
02406         v->tile = vtile;
02407       } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
02408         hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
02409         /* v->tile changes at the moment when the vehicle leaves the tunnel. */
02410         v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
02411       } else {
02412         /* We could get here in two cases:
02413          * - for road vehicles, it is reversing at the end of the tunnel
02414          * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
02415          * Whatever case it is, do not change anything and use the old values.
02416          * Especially changing RV's state would break its reversing in the middle. */
02417         continue;
02418       }
02419 
02420       if (hidden) {
02421         v->vehstatus |= VS_HIDDEN;
02422 
02423         switch (v->type) {
02424           case VEH_TRAIN: Train::From(v)->track       = TRACK_BIT_WORMHOLE; break;
02425           case VEH_ROAD:  RoadVehicle::From(v)->state = RVSB_WORMHOLE;      break;
02426           default: NOT_REACHED();
02427         }
02428       } else {
02429         v->vehstatus &= ~VS_HIDDEN;
02430 
02431         switch (v->type) {
02432           case VEH_TRAIN: Train::From(v)->track       = DiagDirToDiagTrackBits(vdir); break;
02433           case VEH_ROAD:  RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
02434           default: NOT_REACHED();
02435         }
02436       }
02437     }
02438   }
02439 
02440   if (IsSavegameVersionBefore(153)) {
02441     RoadVehicle *rv;
02442     FOR_ALL_ROADVEHICLES(rv) {
02443       if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
02444 
02445       bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
02446       if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
02447         extern const byte _road_stop_stop_frame[];
02448         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)]);
02449       } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
02450         SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
02451       }
02452     }
02453   }
02454 
02455   if (IsSavegameVersionBefore(156)) {
02456     /* The train's pathfinder lost flag got moved. */
02457     Train *t;
02458     FOR_ALL_TRAINS(t) {
02459       if (!HasBit(t->flags, 5)) continue;
02460 
02461       ClrBit(t->flags, 5);
02462       SetBit(t->vehicle_flags, VF_PATHFINDER_LOST);
02463     }
02464 
02465     /* Introduced terraform/clear limits. */
02466     Company *c;
02467     FOR_ALL_COMPANIES(c) {
02468       c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
02469       c->clear_limit     = _settings_game.construction.clear_frame_burst << 16;
02470     }
02471   }
02472 
02473   if (IsSavegameVersionBefore(158)) {
02474     Vehicle *v;
02475     FOR_ALL_VEHICLES(v) {
02476       switch (v->type) {
02477         case VEH_TRAIN: {
02478           Train *t = Train::From(v);
02479 
02480           /* Clear old GOINGUP / GOINGDOWN flags.
02481            * It was changed in savegame version 139, but savegame
02482            * version 158 doesn't use these bits, so it doesn't hurt
02483            * to clear them unconditionally. */
02484           ClrBit(t->flags, 1);
02485           ClrBit(t->flags, 2);
02486 
02487           /* Clear both bits first. */
02488           ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
02489           ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
02490 
02491           /* Crashed vehicles can't be going up/down. */
02492           if (t->vehstatus & VS_CRASHED) break;
02493 
02494           /* Only X/Y tracks can be sloped. */
02495           if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
02496 
02497           t->gv_flags |= FixVehicleInclination(t, t->direction);
02498           break;
02499         }
02500         case VEH_ROAD: {
02501           RoadVehicle *rv = RoadVehicle::From(v);
02502           ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
02503           ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
02504 
02505           /* Crashed vehicles can't be going up/down. */
02506           if (rv->vehstatus & VS_CRASHED) break;
02507 
02508           if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
02509 
02510           TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, rv->compatible_roadtypes);
02511           TrackBits trackbits = TrackStatusToTrackBits(ts);
02512 
02513           /* Only X/Y tracks can be sloped. */
02514           if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
02515 
02516           Direction dir = rv->direction;
02517 
02518           /* Test if we are reversing. */
02519           Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
02520           if (AxisToDirection(a) != dir &&
02521               AxisToDirection(a) != ReverseDir(dir)) {
02522             /* When reversing, the road vehicle is on the edge of the tile,
02523              * so it can be safely compared to the middle of the tile. */
02524             dir = INVALID_DIR;
02525           }
02526 
02527           rv->gv_flags |= FixVehicleInclination(rv, dir);
02528           break;
02529         }
02530         case VEH_SHIP:
02531           break;
02532 
02533         default:
02534           continue;
02535       }
02536 
02537       if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
02538         /* In old versions, z_pos was 1 unit lower on bridge heads.
02539          * However, this invalid state could be converted to new savegames
02540          * by loading and saving the game in a new version. */
02541         v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos);
02542         DiagDirection dir = GetTunnelBridgeDirection(v->tile);
02543         if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
02544             v->direction != DiagDirToDir(dir)) {
02545           /* If the train has left the bridge, it shouldn't have
02546            * track == TRACK_BIT_WORMHOLE - this could happen
02547            * when the train was reversed while on the last "tick"
02548            * on the ramp before leaving the ramp to the bridge. */
02549           Train::From(v)->track = DiagDirToDiagTrackBits(dir);
02550         }
02551       }
02552 
02553       /* If the vehicle is really above v->tile (not in a wormhole),
02554        * it should have set v->z_pos correctly. */
02555       assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos));
02556     }
02557 
02558     /* Fill Vehicle::cur_real_order_index */
02559     FOR_ALL_VEHICLES(v) {
02560       if (!v->IsPrimaryVehicle()) continue;
02561 
02562       /* Older versions are less strict with indices being in range and fix them on the fly */
02563       if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
02564 
02565       v->cur_real_order_index = v->cur_implicit_order_index;
02566       v->UpdateRealOrderIndex();
02567     }
02568   }
02569 
02570   if (IsSavegameVersionBefore(159)) {
02571     /* If the savegame is old (before version 100), then the value of 255
02572      * for these settings did not mean "disabled". As such everything
02573      * before then did reverse.
02574      * To simplify stuff we disable all turning around or we do not
02575      * disable anything at all. So, if some reversing was disabled we
02576      * will keep reversing disabled, otherwise it'll be turned on. */
02577     _settings_game.pf.reverse_at_signals = IsSavegameVersionBefore(100) || (_settings_game.pf.wait_oneway_signal != 255 && _settings_game.pf.wait_twoway_signal != 255 && _settings_game.pf.wait_for_pbs_path != 255);
02578 
02579     Train *t;
02580     FOR_ALL_TRAINS(t) {
02581       _settings_game.vehicle.max_train_length = max<uint8>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
02582     }
02583   }
02584 
02585   if (IsSavegameVersionBefore(160)) {
02586     /* Setting difficulty industry_density other than zero get bumped to +1
02587      * since a new option (minimal at position 1) has been added */
02588     if (_settings_game.difficulty.industry_density > 0) {
02589       _settings_game.difficulty.industry_density++;
02590     }
02591   }
02592 
02593   if (IsSavegameVersionBefore(161)) {
02594     /* Before savegame version 161, persistent storages were not stored in a pool. */
02595 
02596     if (!IsSavegameVersionBefore(76)) {
02597       Industry *ind;
02598       FOR_ALL_INDUSTRIES(ind) {
02599         assert(ind->psa != NULL);
02600 
02601         /* Check if the old storage was empty. */
02602         bool is_empty = true;
02603         for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
02604           if (ind->psa->GetValue(i) != 0) {
02605             is_empty = false;
02606             break;
02607           }
02608         }
02609 
02610         if (!is_empty) {
02611           ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
02612         } else {
02613           delete ind->psa;
02614           ind->psa = NULL;
02615         }
02616       }
02617     }
02618 
02619     if (!IsSavegameVersionBefore(145)) {
02620       Station *st;
02621       FOR_ALL_STATIONS(st) {
02622         if (!(st->facilities & FACIL_AIRPORT)) continue;
02623         assert(st->airport.psa != NULL);
02624 
02625         /* Check if the old storage was empty. */
02626         bool is_empty = true;
02627         for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
02628           if (st->airport.psa->GetValue(i) != 0) {
02629             is_empty = false;
02630             break;
02631           }
02632         }
02633 
02634         if (!is_empty) {
02635           st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
02636         } else {
02637           delete st->airport.psa;
02638           st->airport.psa = NULL;
02639 
02640         }
02641       }
02642     }
02643   }
02644 
02645   /* This triggers only when old snow_lines were copied into the snow_line_height. */
02646   if (IsSavegameVersionBefore(164) && _settings_game.game_creation.snow_line_height >= MIN_SNOWLINE_HEIGHT * TILE_HEIGHT) {
02647     _settings_game.game_creation.snow_line_height /= TILE_HEIGHT;
02648   }
02649 
02650   if (IsSavegameVersionBefore(164) && !IsSavegameVersionBefore(32)) {
02651     /* We store 4 fences in the field tiles instead of only SE and SW. */
02652     for (TileIndex t = 0; t < map_size; t++) {
02653       if (!IsTileType(t, MP_CLEAR) && !IsTileType(t, MP_TREES)) continue;
02654       if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) continue;
02655       uint fence = GB(_m[t].m4, 5, 3);
02656       if (fence != 0 && IsTileType(TILE_ADDXY(t, 1, 0), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 1, 0), CLEAR_FIELDS)) {
02657         SetFenceNE(TILE_ADDXY(t, 1, 0), fence);
02658       }
02659       fence = GB(_m[t].m4, 2, 3);
02660       if (fence != 0 && IsTileType(TILE_ADDXY(t, 0, 1), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 0, 1), CLEAR_FIELDS)) {
02661         SetFenceNW(TILE_ADDXY(t, 0, 1), fence);
02662       }
02663       SB(_m[t].m4, 2, 3, 0);
02664       SB(_m[t].m4, 5, 3, 0);
02665     }
02666   }
02667 
02668   /* The center of train vehicles was changed, fix up spacing. */
02669   if (IsSavegameVersionBefore(164)) FixupTrainLengths();
02670 
02671   if (IsSavegameVersionBefore(165)) {
02672     Town *t;
02673 
02674     FOR_ALL_TOWNS(t) {
02675       /* Set the default cargo requirement for town growth */
02676       switch (_settings_game.game_creation.landscape) {
02677         case LT_ARCTIC:
02678           if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
02679           break;
02680 
02681         case LT_TROPIC:
02682           if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
02683           if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
02684           break;
02685       }
02686     }
02687   }
02688 
02689   if (IsSavegameVersionBefore(165)) {
02690     /* Adjust zoom level to account for new levels */
02691     _saved_scrollpos_zoom = _saved_scrollpos_zoom + ZOOM_LVL_SHIFT;
02692     _saved_scrollpos_x *= ZOOM_LVL_BASE;
02693     _saved_scrollpos_y *= ZOOM_LVL_BASE;
02694   }
02695 
02696   /* When any NewGRF has been changed the availability of some vehicles might
02697    * have been changed too. e->company_avail must be set to 0 in that case
02698    * which is done by StartupEngines(). */
02699   if (gcf_res != GLC_ALL_GOOD) StartupEngines();
02700 
02701   if (IsSavegameVersionBefore(166)) {
02702     /* Update cargo acceptance map of towns. */
02703     for (TileIndex t = 0; t < map_size; t++) {
02704       if (!IsTileType(t, MP_HOUSE)) continue;
02705       Town::Get(GetTownIndex(t))->cargo_accepted.Add(t);
02706     }
02707 
02708     Town *town;
02709     FOR_ALL_TOWNS(town) {
02710       UpdateTownCargoes(town);
02711     }
02712   }
02713 
02714   /* Road stops is 'only' updating some caches */
02715   AfterLoadRoadStops();
02716   AfterLoadLabelMaps();
02717   AfterLoadCompanyStats();
02718 
02719   GamelogPrintDebug(1);
02720 
02721   InitializeWindowsAndCaches();
02722   /* Restore the signals */
02723   ResetSignalHandlers();
02724   return true;
02725 }
02726 
02735 void ReloadNewGRFData()
02736 {
02737   /* reload grf data */
02738   GfxLoadSprites();
02739   LoadStringWidthTable();
02740   RecomputePrices();
02741   /* reload vehicles */
02742   ResetVehiclePosHash();
02743   AfterLoadVehicles(false);
02744   StartupEngines();
02745   GroupStatistics::UpdateAfterLoad();
02746   /* update station graphics */
02747   AfterLoadStations();
02748   /* Update company statistics. */
02749   AfterLoadCompanyStats();
02750   /* Check and update house and town values */
02751   UpdateHousesAndTowns();
02752   /* Delete news referring to no longer existing entities */
02753   DeleteInvalidEngineNews();
02754   /* Update livery selection windows */
02755   for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i);
02756   /* Update company infrastructure counts. */
02757   InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
02758   /* redraw the whole screen */
02759   MarkWholeScreenDirty();
02760   CheckTrainsLengths();
02761 }