afterload.cpp

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

Generated on Sun Jan 23 01:49:08 2011 for OpenTTD by  doxygen 1.6.1