afterload.cpp

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