afterload.cpp

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