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

Generated on Mon May 9 05:18:59 2011 for OpenTTD by  doxygen 1.6.1