# afterload.cpp

Go to the documentation of this file.

    00001 /* $Id: afterload.cpp 18515 2009-12-16 16:23:44Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
    00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
    00008  */
    00009
    00012 #include "../stdafx.h"
    00013 #include "../void_map.h"
    00014 #include "../signs_base.h"
    00015 #include "../depot_base.h"
    00016 #include "../window_func.h"
    00017 #include "../fios.h"
    00018 #include "../gamelog.h"
    00019 #include "../gamelog_internal.h"
    00020 #include "../network/network.h"
    00021 #include "../gfxinit.h"
    00022 #include "../functions.h"
    00023 #include "../industry.h"
    00024 #include "../clear_map.h"
    00025 #include "../vehicle_func.h"
    00026 #include "../newgrf_station.h"
    00027 #include "../openttd.h"
    00028 #include "../debug.h"
    00029 #include "../string_func.h"
    00030 #include "../date_func.h"
    00031 #include "../roadveh.h"
    00032 #include "../train.h"
    00033 #include "../station_base.h"
    00034 #include "../waypoint_base.h"
    00035 #include "../roadstop_base.h"
    00036 #include "../tunnelbridge_map.h"
    00037 #include "../landscape.h"
    00038 #include "../pathfinder/yapf/yapf_cache.h"
    00039 #include "../elrail_func.h"
    00040 #include "../signs_func.h"
    00041 #include "../aircraft.h"
    00042 #include "../unmovable_map.h"
    00043 #include "../tree_map.h"
    00044 #include "../company_func.h"
    00045 #include "../road_cmd.h"
    00046 #include "../ai/ai.hpp"
    00047 #include "../town.h"
    00048 #include "../economy_base.h"
    00049 #include "../animated_tile_func.h"
    00050 #include "../subsidy_base.h"
    00051 #include "../subsidy_func.h"
    00052
    00053 #include "table/strings.h"
    00054
    00055 #include "saveload_internal.h"
    00056
    00057 #include <signal.h>
    00058
    00059 extern StringID _switch_mode_errorstr;
    00060 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
    00061 extern void InitializeRailGUI();
    00062
    00073 void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
    00074 {
    00075   /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
    00076    * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
    00077   if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
    00078     if (include_invalid_water_class) {
    00079       SetWaterClass(t, WATER_CLASS_INVALID);
    00080       return;
    00081     } else {
    00082       NOT_REACHED();
    00083     }
    00084   }
    00085
    00086   /* Mark tile dirty in all cases */
    00087   MarkTileDirtyByTile(t);
    00088
    00089   if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
    00090     /* tiles at map borders are always WATER_CLASS_SEA */
    00091     SetWaterClass(t, WATER_CLASS_SEA);
    00092     return;
    00093   }
    00094
    00095   bool has_water = false;
    00096   bool has_canal = false;
    00097   bool has_river = false;
    00098
    00099   for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
    00100     TileIndex neighbour = TileAddByDiagDir(t, dir);
    00101     switch (GetTileType(neighbour)) {
    00102       case MP_WATER:
    00103         /* clear water and shipdepots have already a WaterClass associated */
    00104         if (IsCoast(neighbour)) {
    00105           has_water = true;
    00106         } else if (!IsLock(neighbour)) {
    00107           switch (GetWaterClass(neighbour)) {
    00108             case WATER_CLASS_SEA:   has_water = true; break;
    00109             case WATER_CLASS_CANAL: has_canal = true; break;
    00110             case WATER_CLASS_RIVER: has_river = true; break;
    00111             default: NOT_REACHED();
    00112           }
    00113         }
    00114         break;
    00115
    00116       case MP_RAILWAY:
    00117         /* Shore or flooded halftile */
    00118         has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
    00119         break;
    00120
    00121       case MP_TREES:
    00122         /* trees on shore */
    00123         has_water |= (GetTreeGround(neighbour) == TREE_GROUND_SHORE);
    00124         break;
    00125
    00126       default: break;
    00127     }
    00128   }
    00129
    00130   if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
    00131     SetWaterClass(t, WATER_CLASS_INVALID);
    00132     return;
    00133   }
    00134
    00135   if (has_river && !has_canal) {
    00136     SetWaterClass(t, WATER_CLASS_RIVER);
    00137   } else if (has_canal || !has_water) {
    00138     SetWaterClass(t, WATER_CLASS_CANAL);
    00139   } else {
    00140     SetWaterClass(t, WATER_CLASS_SEA);
    00141   }
    00142 }
    00143
    00144 static void ConvertTownOwner()
    00145 {
    00146   for (TileIndex tile = 0; tile != MapSize(); tile++) {
    00147     switch (GetTileType(tile)) {
    00148       case MP_ROAD:
    00149         if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
    00150           _m[tile].m3 = OWNER_TOWN;
    00151         }
    00152         /* FALLTHROUGH */
    00153
    00154       case MP_TUNNELBRIDGE:
    00155         if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN);
    00156         break;
    00157
    00158       default: break;
    00159     }
    00160   }
    00161 }
    00162
    00163 /* since savegame version 4.1, exclusive transport rights are stored at towns */
    00164 static void UpdateExclusiveRights()
    00165 {
    00166   Town *t;
    00167
    00168   FOR_ALL_TOWNS(t) {
    00169     t->exclusivity = INVALID_COMPANY;
    00170   }
    00171
    00172   /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
    00173    *   could be implemented this way:
    00174    * 1.) Go through all stations
    00175    *     Build an array town_blocked[ town_id ][ company_id ]
    00176    *     that stores if at least one station in that town is blocked for a company
    00177    * 2.) Go through that array, if you find a town that is not blocked for
    00178    *     one company, but for all others, then give him exclusivity.
    00179    */
    00180 }
    00181
    00182 static const byte convert_currency[] = {
    00183    0,  1, 12,  8,  3,
    00184   10, 14, 19,  4,  5,
    00185    9, 11, 13,  6, 17,
    00186   16, 22, 21,  7, 15,
    00187   18,  2, 20,
    00188 };
    00189
    00190 /* since savegame version 4.2 the currencies are arranged differently */
    00191 static void UpdateCurrencies()
    00192 {
    00193   _settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
    00194 }
    00195
    00196 /* Up to revision 1413 the invisible tiles at the southern border have not been
    00197  * MP_VOID, even though they should have. This is fixed by this function
    00198  */
    00199 static void UpdateVoidTiles()
    00200 {
    00201   uint i;
    00202
    00203   for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
    00204   for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
    00205 }
    00206
    00207 static inline RailType UpdateRailType(RailType rt, RailType min)
    00208 {
    00209   return rt >= min ? (RailType)(rt + 1): rt;
    00210 }
    00211
    00215 void UpdateAllVirtCoords()
    00216 {
    00217   UpdateAllStationVirtCoords();
    00218   UpdateAllSignVirtCoords();
    00219   UpdateAllTownVirtCoords();
    00220 }
    00221
    00231 static void InitializeWindowsAndCaches()
    00232 {
    00233   /* Initialize windows */
    00234   ResetWindowSystem();
    00235   SetupColoursAndInitialWindow();
    00236
    00237   /* Update coordinates of the signs. */
    00238   UpdateAllVirtCoords();
    00239   ResetViewportAfterLoadGame();
    00240
    00241   Company *c;
    00242   FOR_ALL_COMPANIES(c) {
    00243     /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
    00244      * accordingly if it is not the case.  No need to set it on companies that are not been used already,
    00245      * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
    00246     if (_file_to_saveload.filetype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
    00247       c->inaugurated_year = _cur_year;
    00248     }
    00249   }
    00250
    00251   RecomputePrices();
    00252
    00253   SetCachedEngineCounts();
    00254
    00255   Station::RecomputeIndustriesNearForAll();
    00256   RebuildSubsidisedSourceAndDestinationCache();
    00257
    00258   /* Towns have a noise controlled number of airports system
    00259    * So each airport's noise value must be added to the town->noise_reached value
    00260    * Reset each town's noise_reached value to '0' before. */
    00261   UpdateAirportsNoise();
    00262
    00263   CheckTrainsLengths();
    00264   ShowNewGRFError();
    00265 }
    00266
    00267 typedef void (CDECL *SignalHandlerPointer)(int);
    00268 static SignalHandlerPointer _prev_segfault = NULL;
    00269 static SignalHandlerPointer _prev_abort    = NULL;
    00270 static SignalHandlerPointer _prev_fpe      = NULL;
    00271
    00272 static void CDECL HandleSavegameLoadCrash(int signum);
    00273
    00278 static void SetSignalHandlers()
    00279 {
    00280   _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
    00281   _prev_abort    = signal(SIGABRT, HandleSavegameLoadCrash);
    00282   _prev_fpe      = signal(SIGFPE,  HandleSavegameLoadCrash);
    00283 }
    00284
    00288 static void ResetSignalHandlers()
    00289 {
    00290   signal(SIGSEGV, _prev_segfault);
    00291   signal(SIGABRT, _prev_abort);
    00292   signal(SIGFPE,  _prev_fpe);
    00293 }
    00294
    00300 static const GRFIdentifier *GetOverriddenIdentifier(const GRFConfig *c)
    00301 {
    00302   const LoggedAction *la = &_gamelog_action[_gamelog_actions - 1];
    00303   if (la->at != GLAT_LOAD) return c;
    00304
    00305   const LoggedChange *lcend = &la->change[la->changes];
    00306   for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
    00307     if (lc->ct == GLCT_GRFCOMPAT && lc->grfcompat.grfid == c->grfid) return &lc->grfcompat;
    00308   }
    00309
    00310   return c;
    00311 }
    00312
    00319 static void CDECL HandleSavegameLoadCrash(int signum)
    00320 {
    00321   ResetSignalHandlers();
    00322
    00323   char buffer[8192];
    00324   char *p = buffer;
    00325   p += seprintf(p, lastof(buffer),
    00326       "Loading your savegame caused OpenTTD to crash.\n"
    00327       "This is most likely caused by a missing NewGRF or a NewGRF that has been\n"
    00328       "loaded as replacement for a missing NewGRF. OpenTTD cannot easily\n"
    00329       "determine whether a replacement NewGRF is of a newer or older version.\n"
    00330       "It will load a NewGRF with the same GRF ID as the missing NewGRF. This\n"
    00331       "means that if the author makes incompatible NewGRFs with the same GRF ID\n"
    00332       "OpenTTD cannot magically do the right thing. In most cases OpenTTD will\n"
    00333       "load the savegame and not crash, but this is an exception.\n"
    00334       "Please load the savegame with the appropriate NewGRFs. When loading a\n"
    00335       "savegame still crashes when all NewGRFs are found you should file a\n"
    00336       "bug report. The missing NewGRFs are:\n");
    00337
    00338   for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
    00339     if (HasBit(c->flags, GCF_COMPATIBLE)) {
    00340       const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
    00341       char buf[40];
    00342       md5sumToString(buf, lastof(buf), replaced->md5sum);
    00343       p += seprintf(p, lastof(buffer), "NewGRF %08X (checksum %s) not found.\n  Loaded NewGRF \"%s\" with same GRF ID instead.\n", BSWAP32(c->grfid), buf, c->filename);
    00344     }
    00345     if (c->status == GCS_NOT_FOUND) {
    00346       char buf[40];
    00347       md5sumToString(buf, lastof(buf), c->md5sum);
    00348       p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s.\n", BSWAP32(c->grfid), c->filename, buf);
    00349     }
    00350   }
    00351
    00352   ShowInfo(buffer);
    00353
    00354   SignalHandlerPointer call = NULL;
    00355   switch (signum) {
    00356     case SIGSEGV: call = _prev_segfault; break;
    00357     case SIGABRT: call = _prev_abort; break;
    00358     case SIGFPE:  call = _prev_fpe; break;
    00359     default: NOT_REACHED();
    00360   }
    00361   if (call != NULL) call(signum);
    00362 }
    00363
    00369 static void FixOwnerOfRailTrack(TileIndex t)
    00370 {
    00371   assert(!Company::IsValidID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
    00372
    00373   /* remove leftover rail piece from crossing (from very old savegames) */
    00374   Train *v = NULL, *w;
    00375   FOR_ALL_TRAINS(w) {
    00376     if (w->tile == t) {
    00377       v = w;
    00378       break;
    00379     }
    00380   }
    00381
    00382   if (v != NULL) {
    00383     /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
    00384     SetTileOwner(t, v->owner);
    00385     return;
    00386   }
    00387
    00388   /* try to find any connected rail */
    00389   for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
    00390     TileIndex tt = t + TileOffsByDiagDir(dd);
    00391     if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
    00392         GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
    00393         Company::IsValidID(GetTileOwner(tt))) {
    00394       SetTileOwner(t, GetTileOwner(tt));
    00395       return;
    00396     }
    00397   }
    00398
    00399   if (IsLevelCrossingTile(t)) {
    00400     /* else change the crossing to normal road (road vehicles won't care) */
    00401     MakeRoadNormal(t, GetCrossingRoadBits(t), GetRoadTypes(t), GetTownIndex(t),
    00402       GetRoadOwner(t, ROADTYPE_ROAD), GetRoadOwner(t, ROADTYPE_TRAM));
    00403     return;
    00404   }
    00405
    00406   /* if it's not a crossing, make it clean land */
    00407   MakeClear(t, CLEAR_GRASS, 0);
    00408 }
    00409
    00410 bool AfterLoadGame()
    00411 {
    00412   SetSignalHandlers();
    00413
    00414   TileIndex map_size = MapSize();
    00415   Company *c;
    00416
    00417   if (CheckSavegameVersion(98)) GamelogOldver();
    00418
    00419   GamelogTestRevision();
    00420   GamelogTestMode();
    00421
    00422   if (CheckSavegameVersion(98)) GamelogGRFAddList(_grfconfig);
    00423
    00424   if (CheckSavegameVersion(119)) {
    00425     _pause_mode = (_pause_mode == 2) ? PM_PAUSED_NORMAL : PM_UNPAUSED;
    00426   } else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
    00427     DEBUG(net, 0, "The loading savegame was paused due to an error state.");
    00428     DEBUG(net, 0, "  The savegame cannot be used for multiplayer!");
    00429     /* Restore the signals */
    00430     ResetSignalHandlers();
    00431     return false;
    00432   } else if (!_networking || _network_server) {
    00433     /* If we are in single player, i.e. not networking, and loading the
    00434      * savegame or we are loading the savegame as network server we do
    00435      * not want to be bothered by being paused because of the automatic
    00436      * reason of a network server, e.g. joining clients or too few
    00437      * active clients. Note that resetting these values for a network
    00438      * client are very bad because then the client is going to execute
    00439      * the game loop when the server is not, i.e. it desyncs. */
    00440     _pause_mode &= ~PMB_PAUSED_NETWORK;
    00441   }
    00442
    00443   /* in very old versions, size of train stations was stored differently */
    00444   if (CheckSavegameVersion(2)) {
    00445     Station *st;
    00446     FOR_ALL_STATIONS(st) {
    00447       if (st->train_station.tile != 0 && st->train_station.h == 0) {
    00448         uint n = _savegame_type == SGT_OTTD ? 4 : 3; // OTTD uses 4 bits per dimensions, TTD 3 bits
    00449         uint w = GB(st->train_station.w, n, n);
    00450         uint h = GB(st->train_station.w, 0, n);
    00451
    00452         if (GetRailStationAxis(st->train_station.tile) != AXIS_X) Swap(w, h);
    00453
    00454         st->train_station.w = w;
    00455         st->train_station.h = h;
    00456
    00457         assert(GetStationIndex(st->train_station.tile + TileDiffXY(w - 1, h - 1)) == st->index);
    00458       }
    00459     }
    00460   }
    00461
    00462   /* in version 2.1 of the savegame, town owner was unified. */
    00463   if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
    00464
    00465   /* from version 4.1 of the savegame, exclusive rights are stored at towns */
    00466   if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
    00467
    00468   /* from version 4.2 of the savegame, currencies are in a different order */
    00469   if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
    00470
    00471   /* In old version there seems to be a problem that water is owned by
    00472    * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
    00473    * (4.3) version, so I just check when versions are older, and then
    00474    * walk through the whole map.. */
    00475   if (CheckSavegameVersionOldStyle(4, 3)) {
    00476     for (TileIndex t = 0; t < map_size; t++) {
    00477       if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
    00478         SetTileOwner(t, OWNER_WATER);
    00479       }
    00480     }
    00481   }
    00482
    00483   if (CheckSavegameVersion(84)) {
    00484     FOR_ALL_COMPANIES(c) {
    00485       c->name = CopyFromOldName(c->name_1);
    00486       if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
    00487       c->president_name = CopyFromOldName(c->president_name_1);
    00488       if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
    00489     }
    00490
    00491     Station *st;
    00492     FOR_ALL_STATIONS(st) {
    00493       st->name = CopyFromOldName(st->string_id);
    00494       /* generating new name would be too much work for little effect, use the station name fallback */
    00495       if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
    00496     }
    00497
    00498     Town *t;
    00499     FOR_ALL_TOWNS(t) {
    00500       t->name = CopyFromOldName(t->townnametype);
    00501       if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
    00502     }
    00503   }
    00504
    00505   /* From this point the old names array is cleared. */
    00506   ResetOldNames();
    00507
    00508   if (CheckSavegameVersion(106)) {
    00509     /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
    00510     Station *st;
    00511     FOR_ALL_STATIONS(st) {
    00512       if (st->airport_tile       == 0) st->airport_tile = INVALID_TILE;
    00513       if (st->dock_tile          == 0) st->dock_tile    = INVALID_TILE;
    00514       if (st->train_station.tile == 0) st->train_station.tile   = INVALID_TILE;
    00515     }
    00516
    00517     /* the same applies to Company::location_of_HQ */
    00518     Company *c;
    00519     FOR_ALL_COMPANIES(c) {
    00520       if (c->location_of_HQ == 0 || (CheckSavegameVersion(4) && c->location_of_HQ == 0xFFFF)) {
    00521         c->location_of_HQ = INVALID_TILE;
    00522       }
    00523     }
    00524   }
    00525
    00526   /* convert road side to my format. */
    00527   if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
    00528
    00529   /* Check if all NewGRFs are present, we are very strict in MP mode */
    00530   GRFListCompatibility gcf_res = IsGoodGRFConfigList();
    00531   if (_networking && gcf_res != GLC_ALL_GOOD) {
    00532     SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
    00533     /* Restore the signals */
    00534     ResetSignalHandlers();
    00535     return false;
    00536   }
    00537
    00538   switch (gcf_res) {
    00539     case GLC_COMPATIBLE: _switch_mode_errorstr = STR_NEWGRF_COMPATIBLE_LOAD_WARNING; break;
    00540     case GLC_NOT_FOUND:  _switch_mode_errorstr = STR_NEWGRF_DISABLED_WARNING; _pause_mode = PM_PAUSED_ERROR; break;
    00541     default: break;
    00542   }
    00543
    00544   /* Update current year
    00545    * must be done before loading sprites as some newgrfs check it */
    00546   SetDate(_date);
    00547
    00548   /* Force dynamic engines off when loading older savegames */
    00549   if (CheckSavegameVersion(95)) _settings_game.vehicle.dynamic_engines = 0;
    00550
    00551   /* Load the sprites */
    00552   GfxLoadSprites();
    00553   LoadStringWidthTable();
    00554
    00555   /* Copy temporary data to Engine pool */
    00556   CopyTempEngineData();
    00557
    00558   /* Connect front and rear engines of multiheaded trains and converts
    00559    * subtype to the new format */
    00560   if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
    00561
    00562   /* Connect front and rear engines of multiheaded trains */
    00563   ConnectMultiheadedTrains();
    00564
    00565   /* Fix the CargoPackets *and* fix the caches of CargoLists.
    00566    * If this isn't done before Stations and especially Vehicles are
    00567    * running their AfterLoad we might get in trouble. In the case of
    00568    * vehicles we could give the wrong (cached) count of items in a
    00569    * vehicle which causes different results when getting their caches
    00570    * filled; and that could eventually lead to desyncs. */
    00571   CargoPacket::AfterLoad();
    00572
    00573   /* Update all vehicles */
    00574   AfterLoadVehicles(true);
    00575
    00576   /* Make sure there is an AI attached to an AI company */
    00577   {
    00578     Company *c;
    00579     FOR_ALL_COMPANIES(c) {
    00580       if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
    00581     }
    00582   }
    00583
    00584   /* make sure there is a town in the game */
    00585   if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, UINT_MAX)) {
    00586     SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
    00587     /* Restore the signals */
    00588     ResetSignalHandlers();
    00589     return false;
    00590   }
    00591
    00592   /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
    00593    * This problem appears in savegame version 21 too, see r3455. But after loading the
    00594    * savegame and saving again, the buggy map array could be converted to new savegame
    00595    * version. It didn't show up before r12070. */
    00596   if (CheckSavegameVersion(87)) UpdateVoidTiles();
    00597
    00598   /* If Load Scenario / New (Scenario) Game is used,
    00599    *  a company does not exist yet. So create one here.
    00600    * 1 exeption: network-games. Those can have 0 companies
    00601    *   But this exeption is not true for non dedicated network_servers! */
    00602   if (!Company::IsValidID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated)))
    00603     DoStartupNewCompany(false);
    00604
    00605   /* Fix the cache for cargo payments. */
    00606   CargoPayment *cp;
    00607   FOR_ALL_CARGO_PAYMENTS(cp) {
    00608     cp->front->cargo_payment = cp;
    00609     cp->current_station = cp->front->last_station_visited;
    00610   }
    00611
    00612   if (CheckSavegameVersion(72)) {
    00613     /* Locks/shiplifts in very old savegames had OWNER_WATER as owner */
    00614     for (TileIndex t = 0; t < MapSize(); t++) {
    00615       switch (GetTileType(t)) {
    00616         default: break;
    00617
    00618         case MP_WATER:
    00619           if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
    00620           break;
    00621
    00622         case MP_STATION: {
    00623           if (HasBit(_m[t].m6, 3)) SetBit(_m[t].m6, 2);
    00624           StationGfx gfx = GetStationGfx(t);
    00625           StationType st;
    00626           if (       IsInsideMM(gfx,   0,   8)) { // Rail station
    00627             st = STATION_RAIL;
    00628             SetStationGfx(t, gfx - 0);
    00629           } else if (IsInsideMM(gfx,   8,  67)) { // Airport
    00630             st = STATION_AIRPORT;
    00631             SetStationGfx(t, gfx - 8);
    00632           } else if (IsInsideMM(gfx,  67,  71)) { // Truck
    00633             st = STATION_TRUCK;
    00634             SetStationGfx(t, gfx - 67);
    00635           } else if (IsInsideMM(gfx,  71,  75)) { // Bus
    00636             st = STATION_BUS;
    00637             SetStationGfx(t, gfx - 71);
    00638           } else if (gfx == 75) {                 // Oil rig
    00639             st = STATION_OILRIG;
    00640             SetStationGfx(t, gfx - 75);
    00641           } else if (IsInsideMM(gfx,  76,  82)) { // Dock
    00642             st = STATION_DOCK;
    00643             SetStationGfx(t, gfx - 76);
    00644           } else if (gfx == 82) {                 // Buoy
    00645             st = STATION_BUOY;
    00646             SetStationGfx(t, gfx - 82);
    00647           } else if (IsInsideMM(gfx,  83, 168)) { // Extended airport
    00648             st = STATION_AIRPORT;
    00649             SetStationGfx(t, gfx - 83 + 67 - 8);
    00650           } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
    00651             st = STATION_TRUCK;
    00652             SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
    00653           } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
    00654             st = STATION_BUS;
    00655             SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
    00656           } else {
    00657             /* Restore the signals */
    00658             ResetSignalHandlers();
    00659             return false;
    00660           }
    00661           SB(_m[t].m6, 3, 3, st);
    00662         } break;
    00663       }
    00664     }
    00665   }
    00666
    00667   for (TileIndex t = 0; t < map_size; t++) {
    00668     switch (GetTileType(t)) {
    00669       case MP_STATION: {
    00670         BaseStation *bst = BaseStation::GetByTile(t);
    00671
    00672         /* Set up station spread */
    00673         bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
    00674
    00675         /* Waypoints don't have road stops/oil rigs in the old format */
    00676         if (!Station::IsExpected(bst)) break;
    00677         Station *st = Station::From(bst);
    00678
    00679         switch (GetStationType(t)) {
    00680           case STATION_TRUCK:
    00681           case STATION_BUS:
    00682             if (CheckSavegameVersion(6)) {
    00683               /* From this version on there can be multiple road stops of the
    00684                * same type per station. Convert the existing stops to the new
    00685                * internal data structure. */
    00686               RoadStop *rs = new RoadStop(t);
    00687               if (rs == NULL) error("Too many road stops in savegame");
    00688
    00689               RoadStop **head =
    00690                 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
    00691               *head = rs;
    00692             }
    00693             break;
    00694
    00695           case STATION_OILRIG: {
    00696             /* Very old savegames sometimes have phantom oil rigs, i.e.
    00697              * an oil rig which got shut down, but not completly removed from
    00698              * the map
    00699              */
    00700             TileIndex t1 = TILE_ADDXY(t, 0, 1);
    00701             if (IsTileType(t1, MP_INDUSTRY) &&
    00702                 GetIndustryGfx(t1) == GFX_OILRIG_1) {
    00703               /* The internal encoding of oil rigs was changed twice.
    00704                * It was 3 (till 2.2) and later 5 (till 5.1).
    00705                * Setting it unconditionally does not hurt.
    00706                */
    00707               Station::GetByTile(t)->airport_type = AT_OILRIG;
    00708             } else {
    00709               DeleteOilRig(t);
    00710             }
    00711             break;
    00712           }
    00713
    00714           default: break;
    00715         }
    00716         break;
    00717       }
    00718
    00719       default: break;
    00720     }
    00721   }
    00722
    00723   /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
    00724    * This has to be called after the oilrig airport_type update above ^^^ ! */
    00725   if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
    00726
    00727   /* In version 6.1 we put the town index in the map-array. To do this, we need
    00728    *  to use m2 (16bit big), so we need to clean m2, and that is where this is
    00729    *  all about ;) */
    00730   if (CheckSavegameVersionOldStyle(6, 1)) {
    00731     for (TileIndex t = 0; t < map_size; t++) {
    00732       switch (GetTileType(t)) {
    00733         case MP_HOUSE:
    00734           _m[t].m4 = _m[t].m2;
    00735           SetTownIndex(t, CalcClosestTownFromTile(t)->index);
    00736           break;
    00737
    00738         case MP_ROAD:
    00739           _m[t].m4 |= (_m[t].m2 << 4);
    00740           if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
    00741             SetTownIndex(t, CalcClosestTownFromTile(t)->index);
    00742           } else {
    00743             SetTownIndex(t, 0);
    00744           }
    00745           break;
    00746
    00747         default: break;
    00748       }
    00749     }
    00750   }
    00751
    00752   /* Force the freeform edges to false for old savegames. */
    00753   if (CheckSavegameVersion(111)) {
    00754     _settings_game.construction.freeform_edges = false;
    00755   }
    00756
    00757   /* From version 9.0, we update the max passengers of a town (was sometimes negative
    00758    *  before that. */
    00759   if (CheckSavegameVersion(9)) {
    00760     Town *t;
    00761     FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
    00762   }
    00763
    00764   /* From version 16.0, we included autorenew on engines, which are now saved, but
    00765    *  of course, we do need to initialize them for older savegames. */
    00766   if (CheckSavegameVersion(16)) {
    00767     FOR_ALL_COMPANIES(c) {
    00768       c->engine_renew_list            = NULL;
    00769       c->settings.engine_renew        = false;
    00770       c->settings.engine_renew_months = 6;
    00771       c->settings.engine_renew_money  = 100000;
    00772     }
    00773
    00774     /* When loading a game, _local_company is not yet set to the correct value.
    00775      * However, in a dedicated server we are a spectator, so nothing needs to
    00776      * happen. In case we are not a dedicated server, the local company always
    00777      * becomes company 0, unless we are in the scenario editor where all the
    00778      * companies are 'invalid'.
    00779      */
    00780     c = Company::GetIfValid(COMPANY_FIRST);
    00781     if (!_network_dedicated && c != NULL) {
    00782       c->settings = _settings_client.company;
    00783     }
    00784   }
    00785
    00786   if (CheckSavegameVersion(48)) {
    00787     for (TileIndex t = 0; t < map_size; t++) {
    00788       switch (GetTileType(t)) {
    00789         case MP_RAILWAY:
    00790           if (IsPlainRail(t)) {
    00791             /* Swap ground type and signal type for plain rail tiles, so the
    00792              * ground type uses the same bits as for depots and waypoints. */
    00793             uint tmp = GB(_m[t].m4, 0, 4);
    00794             SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
    00795             SB(_m[t].m2, 0, 4, tmp);
    00796           } else if (HasBit(_m[t].m5, 2)) {
    00797             /* Split waypoint and depot rail type and remove the subtype. */
    00798             ClrBit(_m[t].m5, 2);
    00799             ClrBit(_m[t].m5, 6);
    00800           }
    00801           break;
    00802
    00803         case MP_ROAD:
    00804           /* Swap m3 and m4, so the track type for rail crossings is the
    00805            * same as for normal rail. */
    00806           Swap(_m[t].m3, _m[t].m4);
    00807           break;
    00808
    00809         default: break;
    00810       }
    00811     }
    00812   }
    00813
    00814   if (CheckSavegameVersion(61)) {
    00815     /* Added the RoadType */
    00816     bool old_bridge = CheckSavegameVersion(42);
    00817     for (TileIndex t = 0; t < map_size; t++) {
    00818       switch (GetTileType(t)) {
    00819         case MP_ROAD:
    00820           SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
    00821           switch (GetRoadTileType(t)) {
    00822             default: NOT_REACHED();
    00823             case ROAD_TILE_NORMAL:
    00824               SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
    00825               SB(_m[t].m4, 4, 4, 0);
    00826               SB(_m[t].m6, 2, 4, 0);
    00827               break;
    00828             case ROAD_TILE_CROSSING:
    00829               SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
    00830               break;
    00831             case ROAD_TILE_DEPOT:    break;
    00832           }
    00833           SetRoadTypes(t, ROADTYPES_ROAD);
    00834           break;
    00835
    00836         case MP_STATION:
    00837           if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
    00838           break;
    00839
    00840         case MP_TUNNELBRIDGE:
    00841           /* Middle part of "old" bridges */
    00842           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
    00843           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
    00844             SetRoadTypes(t, ROADTYPES_ROAD);
    00845           }
    00846           break;
    00847
    00848         default: break;
    00849       }
    00850     }
    00851   }
    00852
    00853   if (CheckSavegameVersion(114)) {
    00854     bool fix_roadtypes = !CheckSavegameVersion(61);
    00855     bool old_bridge = CheckSavegameVersion(42);
    00856
    00857     for (TileIndex t = 0; t < map_size; t++) {
    00858       switch (GetTileType(t)) {
    00859         case MP_ROAD:
    00860           if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
    00861           SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
    00862           switch (GetRoadTileType(t)) {
    00863             default: NOT_REACHED();
    00864             case ROAD_TILE_NORMAL:
    00865               SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
    00866               SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3));  // ground
    00867               SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4));  // tram bits
    00868               SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4));  // tram owner
    00869               SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4));  // road bits
    00870               break;
    00871
    00872             case ROAD_TILE_CROSSING:
    00873               SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
    00874               SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3));  // ground
    00875               SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4));  // tram owner
    00876               SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1));  // road axis
    00877               SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1));  // crossing state
    00878               break;
    00879
    00880             case ROAD_TILE_DEPOT:
    00881               break;
    00882           }
    00883           if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
    00884             const Town *town = CalcClosestTownFromTile(t);
    00885             if (town != NULL) SetTownIndex(t, town->index);
    00886           }
    00887           _m[t].m4 = 0;
    00888           break;
    00889
    00890         case MP_STATION:
    00891           if (!IsRoadStop(t)) break;
    00892
    00893           if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
    00894           SB(_me[t].m7, 0, 5, HasBit(_m[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
    00895           SB(_m[t].m3, 4, 4, _m[t].m1);
    00896           _m[t].m4 = 0;
    00897           break;
    00898
    00899         case MP_TUNNELBRIDGE:
    00900           if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
    00901           if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
    00902             if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
    00903
    00904             Owner o = GetTileOwner(t);
    00905             SB(_me[t].m7, 0, 5, o); // road owner
    00906             SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
    00907           }
    00908           SB(_m[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
    00909           SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
    00910
    00911           _m[t].m2 = 0;
    00912           _m[t].m4 = 0;
    00913           break;
    00914
    00915         default: break;
    00916       }
    00917     }
    00918   }
    00919
    00920   if (CheckSavegameVersion(42)) {
    00921     Vehicle *v;
    00922
    00923     for (TileIndex t = 0; t < map_size; t++) {
    00924       if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
    00925       if (IsBridgeTile(t)) {
    00926         if (HasBit(_m[t].m5, 6)) { // middle part
    00927           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
    00928
    00929           if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
    00930             if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
    00931               MakeRailNormal(
    00932                 t,
    00933                 GetTileOwner(t),
    00934                 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
    00935                 GetRailType(t)
    00936               );
    00937             } else {
    00938               TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
    00939
    00940               MakeRoadNormal(
    00941                 t,
    00942                 axis == AXIS_X ? ROAD_Y : ROAD_X,
    00943                 ROADTYPES_ROAD,
    00944                 town,
    00945                 GetTileOwner(t), OWNER_NONE
    00946               );
    00947             }
    00948           } else {
    00949             if (GB(_m[t].m5, 3, 2) == 0) {
    00950               MakeClear(t, CLEAR_GRASS, 3);
    00951             } else {
    00952               if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
    00953                 MakeShore(t);
    00954               } else {
    00955                 if (GetTileOwner(t) == OWNER_WATER) {
    00956                   MakeSea(t);
    00957                 } else {
    00958                   MakeCanal(t, GetTileOwner(t), Random());
    00959                 }
    00960               }
    00961             }
    00962           }
    00963           SetBridgeMiddle(t, axis);
    00964         } else { // ramp
    00965           Axis axis = (Axis)GB(_m[t].m5, 0, 1);
    00966           uint north_south = GB(_m[t].m5, 5, 1);
    00967           DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
    00968           TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
    00969
    00970           _m[t].m5 = 1 << 7 | type << 2 | dir;
    00971         }
    00972       }
    00973     }
    00974
    00975     FOR_ALL_VEHICLES(v) {
    00976       if (v->type != VEH_TRAIN && v->type != VEH_ROAD) continue;
    00977       if (IsBridgeTile(v->tile)) {
    00978         DiagDirection dir = GetTunnelBridgeDirection(v->tile);
    00979
    00980         if (dir != DirToDiagDir(v->direction)) continue;
    00981         switch (dir) {
    00982           default: NOT_REACHED();
    00983           case DIAGDIR_NE: if ((v->x_pos & 0xF) !=  0)            continue; break;
    00984           case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
    00985           case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
    00986           case DIAGDIR_NW: if ((v->y_pos & 0xF) !=  0)            continue; break;
    00987         }
    00988       } else if (v->z_pos > GetSlopeZ(v->x_pos, v->y_pos)) {
    00989         v->tile = GetNorthernBridgeEnd(v->tile);
    00990       } else {
    00991         continue;
    00992       }
    00993       if (v->type == VEH_TRAIN) {
    00994         Train::From(v)->track = TRACK_BIT_WORMHOLE;
    00995       } else {
    00996         RoadVehicle::From(v)->state = RVSB_WORMHOLE;
    00997       }
    00998     }
    00999   }
    01000
    01001   /* Elrails got added in rev 24 */
    01002   if (CheckSavegameVersion(24)) {
    01003     RailType min_rail = RAILTYPE_ELECTRIC;
    01004
    01005     Train *v;
    01006     FOR_ALL_TRAINS(v) {
    01007       RailType rt = RailVehInfo(v->engine_type)->railtype;
    01008
    01009       v->railtype = rt;
    01010       if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
    01011     }
    01012
    01013     /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
    01014     for (TileIndex t = 0; t < map_size; t++) {
    01015       switch (GetTileType(t)) {
    01016         case MP_RAILWAY:
    01017           SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    01018           break;
    01019
    01020         case MP_ROAD:
    01021           if (IsLevelCrossing(t)) {
    01022             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    01023           }
    01024           break;
    01025
    01026         case MP_STATION:
    01027           if (HasStationRail(t)) {
    01028             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    01029           }
    01030           break;
    01031
    01032         case MP_TUNNELBRIDGE:
    01033           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
    01034             SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
    01035           }
    01036           break;
    01037
    01038         default:
    01039           break;
    01040       }
    01041     }
    01042
    01043     FOR_ALL_TRAINS(v) {
    01044       if (v->IsFrontEngine() || v->IsFreeWagon()) TrainConsistChanged(v, true);
    01045     }
    01046
    01047   }
    01048
    01049   /* In version 16.1 of the savegame a company can decide if trains, which get
    01050    * replaced, shall keep their old length. In all prior versions, just default
    01051    * to false */
    01052   if (CheckSavegameVersionOldStyle(16, 1)) {
    01053     FOR_ALL_COMPANIES(c) c->settings.renew_keep_length = false;
    01054   }
    01055
    01056   if (CheckSavegameVersion(123)) {
    01057     /* Waypoints became subclasses of stations ... */
    01058     MoveWaypointsToBaseStations();
    01059     /* ... and buoys were moved to waypoints. */
    01060     MoveBuoysToWaypoints();
    01061   }
    01062
    01063   /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
    01064    *  room for PBS. Now in version 21 move it back :P. */
    01065   if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
    01066     for (TileIndex t = 0; t < map_size; t++) {
    01067       switch (GetTileType(t)) {
    01068         case MP_RAILWAY:
    01069           if (HasSignals(t)) {
    01070             /* convert PBS signals to combo-signals */
    01071             if (HasBit(_m[t].m2, 2)) SetSignalType(t, TRACK_X, SIGTYPE_COMBO);
    01072
    01073             /* move the signal variant back */
    01074             SetSignalVariant(t, TRACK_X, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
    01075             ClrBit(_m[t].m2, 3);
    01076           }
    01077
    01078           /* Clear PBS reservation on track */
    01079           if (!IsRailDepotTile(t)) {
    01080             SB(_m[t].m4, 4, 4, 0);
    01081           } else {
    01082             ClrBit(_m[t].m3, 6);
    01083           }
    01084           break;
    01085
    01086         case MP_STATION: // Clear PBS reservation on station
    01087           ClrBit(_m[t].m3, 6);
    01088           break;
    01089
    01090         default: break;
    01091       }
    01092     }
    01093   }
    01094
    01095   if (CheckSavegameVersion(25)) {
    01096     RoadVehicle *rv;
    01097     FOR_ALL_ROADVEHICLES(rv) {
    01098       rv->vehstatus &= ~0x40;
    01099     }
    01100   }
    01101
    01102   if (CheckSavegameVersion(26)) {
    01103     Station *st;
    01104     FOR_ALL_STATIONS(st) {
    01105       st->last_vehicle_type = VEH_INVALID;
    01106     }
    01107   }
    01108
    01109   YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
    01110
    01111   if (CheckSavegameVersion(34)) FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
    01112
    01113   FOR_ALL_COMPANIES(c) {
    01114     c->avail_railtypes = GetCompanyRailtypes(c->index);
    01115     c->avail_roadtypes = GetCompanyRoadtypes(c->index);
    01116   }
    01117
    01118   if (!CheckSavegameVersion(27)) AfterLoadStations();
    01119
    01120   /* Time starts at 0 instead of 1920.
    01121    * Account for this in older games by adding an offset */
    01122   if (CheckSavegameVersion(31)) {
    01123     Station *st;
    01124     Waypoint *wp;
    01125     Engine *e;
    01126     Industry *i;
    01127     Vehicle *v;
    01128
    01129     _date += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01130     _cur_year += ORIGINAL_BASE_YEAR;
    01131
    01132     FOR_ALL_STATIONS(st)  st->build_date      += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01133     FOR_ALL_WAYPOINTS(wp) wp->build_date      += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01134     FOR_ALL_ENGINES(e)    e->intro_date       += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01135     FOR_ALL_COMPANIES(c)  c->inaugurated_year += ORIGINAL_BASE_YEAR;
    01136     FOR_ALL_INDUSTRIES(i) i->last_prod_year   += ORIGINAL_BASE_YEAR;
    01137
    01138     FOR_ALL_VEHICLES(v) {
    01139       v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
    01140       v->build_year += ORIGINAL_BASE_YEAR;
    01141     }
    01142   }
    01143
    01144   /* From 32 on we save the industry who made the farmland.
    01145    *  To give this prettyness to old savegames, we remove all farmfields and
    01146    *  plant new ones. */
    01147   if (CheckSavegameVersion(32)) {
    01148     Industry *i;
    01149
    01150     for (TileIndex t = 0; t < map_size; t++) {
    01151       if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
    01152         /* remove fields */
    01153         MakeClear(t, CLEAR_GRASS, 3);
    01154       } else if (IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES)) {
    01155         /* remove fences around fields */
    01156         SetFenceSE(t, 0);
    01157         SetFenceSW(t, 0);
    01158       }
    01159     }
    01160
    01161     FOR_ALL_INDUSTRIES(i) {
    01162       uint j;
    01163
    01164       if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
    01165         for (j = 0; j != 50; j++) PlantRandomFarmField(i);
    01166       }
    01167     }
    01168   }
    01169
    01170   /* Setting no refit flags to all orders in savegames from before refit in orders were added */
    01171   if (CheckSavegameVersion(36)) {
    01172     Order *order;
    01173     Vehicle *v;
    01174
    01175     FOR_ALL_ORDERS(order) {
    01176       order->SetRefit(CT_NO_REFIT);
    01177     }
    01178
    01179     FOR_ALL_VEHICLES(v) {
    01180       v->current_order.SetRefit(CT_NO_REFIT);
    01181     }
    01182   }
    01183
    01184   /* from version 38 we have optional elrails, since we cannot know the
    01185    * preference of a user, let elrails enabled; it can be disabled manually */
    01186   if (CheckSavegameVersion(38)) _settings_game.vehicle.disable_elrails = false;
    01187   /* do the same as when elrails were enabled/disabled manually just now */
    01188   SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
    01189   InitializeRailGUI();
    01190
    01191   /* From version 53, the map array was changed for house tiles to allow
    01192    * space for newhouses grf features. A new byte, m7, was also added. */
    01193   if (CheckSavegameVersion(53)) {
    01194     for (TileIndex t = 0; t < map_size; t++) {
    01195       if (IsTileType(t, MP_HOUSE)) {
    01196         if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
    01197           /* Move the construction stage from m3[7..6] to m5[5..4].
    01198            * The construction counter does not have to move. */
    01199           SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
    01200           SB(_m[t].m3, 6, 2, 0);
    01201
    01202           /* The "house is completed" bit is now in m6[2]. */
    01203           SetHouseCompleted(t, false);
    01204         } else {
    01205           /* The "lift has destination" bit has been moved from
    01206            * m5[7] to m7[0]. */
    01207           SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
    01208           ClrBit(_m[t].m5, 7);
    01209
    01210           /* The "lift is moving" bit has been removed, as it does
    01211            * the same job as the "lift has destination" bit. */
    01212           ClrBit(_m[t].m1, 7);
    01213
    01214           /* The position of the lift goes from m1[7..0] to m6[7..2],
    01215            * making m1 totally free, now. The lift position does not
    01216            * have to be a full byte since the maximum value is 36. */
    01217           SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
    01218
    01219           _m[t].m1 = 0;
    01220           _m[t].m3 = 0;
    01221           SetHouseCompleted(t, true);
    01222         }
    01223       }
    01224     }
    01225   }
    01226
    01227   /* Check and update house and town values */
    01228   UpdateHousesAndTowns();
    01229
    01230   if (CheckSavegameVersion(43)) {
    01231     for (TileIndex t = 0; t < map_size; t++) {
    01232       if (IsTileType(t, MP_INDUSTRY)) {
    01233         switch (GetIndustryGfx(t)) {
    01234           case GFX_POWERPLANT_SPARKS:
    01235             SetIndustryAnimationState(t, GB(_m[t].m1, 2, 5));
    01236             break;
    01237
    01238           case GFX_OILWELL_ANIMATED_1:
    01239           case GFX_OILWELL_ANIMATED_2:
    01240           case GFX_OILWELL_ANIMATED_3:
    01241             SetIndustryAnimationState(t, GB(_m[t].m1, 0, 2));
    01242             break;
    01243
    01244           case GFX_COAL_MINE_TOWER_ANIMATED:
    01245           case GFX_COPPER_MINE_TOWER_ANIMATED:
    01246           case GFX_GOLD_MINE_TOWER_ANIMATED:
    01247              SetIndustryAnimationState(t, _m[t].m1);
    01248              break;
    01249
    01250           default: // No animation states to change
    01251             break;
    01252         }
    01253       }
    01254     }
    01255   }
    01256
    01257   if (CheckSavegameVersion(45)) {
    01258     Vehicle *v;
    01259     /* Originally just the fact that some cargo had been paid for was
    01260      * stored to stop people cheating and cashing in several times. This
    01261      * wasn't enough though as it was cleared when the vehicle started
    01262      * loading again, even if it didn't actually load anything, so now the
    01263      * amount that has been paid is stored. */
    01264     FOR_ALL_VEHICLES(v) {
    01265       ClrBit(v->vehicle_flags, 2);
    01266     }
    01267   }
    01268
    01269   /* Buoys do now store the owner of the previous water tile, which can never
    01270    * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
    01271   if (CheckSavegameVersion(46)) {
    01272     Waypoint *wp;
    01273     FOR_ALL_WAYPOINTS(wp) {
    01274       if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
    01275     }
    01276   }
    01277
    01278   if (CheckSavegameVersion(50)) {
    01279     Aircraft *v;
    01280     /* Aircraft units changed from 8 mph to 1 km/h */
    01281     FOR_ALL_AIRCRAFT(v) {
    01282       if (v->subtype <= AIR_AIRCRAFT) {
    01283         const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
    01284         v->cur_speed *= 129;
    01285         v->cur_speed /= 10;
    01286         v->max_speed = avi->max_speed;
    01287         v->acceleration = avi->acceleration;
    01288       }
    01289     }
    01290   }
    01291
    01292   if (CheckSavegameVersion(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
    01293
    01294   if (CheckSavegameVersion(52)) {
    01295     for (TileIndex t = 0; t < map_size; t++) {
    01296       if (IsStatueTile(t)) {
    01297         _m[t].m2 = CalcClosestTownFromTile(t)->index;
    01298       }
    01299     }
    01300   }
    01301
    01302   /* A setting containing the proportion of towns that grow twice as
    01303    * fast was added in version 54. From version 56 this is now saved in the
    01304    * town as cities can be built specifically in the scenario editor. */
    01305   if (CheckSavegameVersion(56)) {
    01306     Town *t;
    01307
    01308     FOR_ALL_TOWNS(t) {
    01309       if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
    01310         t->larger_town = true;
    01311       }
    01312     }
    01313   }
    01314
    01315   if (CheckSavegameVersion(57)) {
    01316     Vehicle *v;
    01317     /* Added a FIFO queue of vehicles loading at stations */
    01318     FOR_ALL_VEHICLES(v) {
    01319       if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) &&  // for all locs
    01320           !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
    01321           v->current_order.IsType(OT_LOADING)) {         // loading
    01322         Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
    01323
    01324         /* The loading finished flag is *only* set when actually completely
    01325          * finished. Because the vehicle is loading, it is not finished. */
    01326         ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
    01327       }
    01328     }
    01329   } else if (CheckSavegameVersion(59)) {
    01330     /* For some reason non-loading vehicles could be in the station's loading vehicle list */
    01331
    01332     Station *st;
    01333     FOR_ALL_STATIONS(st) {
    01334       std::list<Vehicle *>::iterator iter;
    01335       for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
    01336         Vehicle *v = *iter;
    01337         iter++;
    01338         if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
    01339       }
    01340     }
    01341   }
    01342
    01343   if (CheckSavegameVersion(58)) {
    01344     /* Setting difficulty number_industries other than zero get bumped to +1
    01345      * since a new option (very low at position1) has been added */
    01346     if (_settings_game.difficulty.number_industries > 0) {
    01347       _settings_game.difficulty.number_industries++;
    01348     }
    01349
    01350     /* Same goes for number of towns, although no test is needed, just an increment */
    01351     _settings_game.difficulty.number_towns++;
    01352   }
    01353
    01354   if (CheckSavegameVersion(64)) {
    01355     /* copy the signal type/variant and move signal states bits */
    01356     for (TileIndex t = 0; t < map_size; t++) {
    01357       if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
    01358         SetSignalStates(t, GB(_m[t].m2, 4, 4));
    01359         SetSignalVariant(t, INVALID_TRACK, GetSignalVariant(t, TRACK_X));
    01360         SetSignalType(t, INVALID_TRACK, GetSignalType(t, TRACK_X));
    01361         ClrBit(_m[t].m2, 7);
    01362       }
    01363     }
    01364   }
    01365
    01366   if (CheckSavegameVersion(69)) {
    01367     /* In some old savegames a bit was cleared when it should not be cleared */
    01368     RoadVehicle *rv;
    01369     FOR_ALL_ROADVEHICLES(rv) {
    01370       if (rv->state == 250 || rv->state == 251) {
    01371         SetBit(rv->state, 2);
    01372       }
    01373     }
    01374   }
    01375
    01376   if (CheckSavegameVersion(70)) {
    01377     /* Added variables to support newindustries */
    01378     Industry *i;
    01379     FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
    01380   }
    01381
    01382   /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
    01383       Replace the owner for those by OWNER_NONE. */
    01384   if (CheckSavegameVersion(82)) {
    01385     for (TileIndex t = 0; t < map_size; t++) {
    01386       if (IsTileType(t, MP_WATER) &&
    01387           GetWaterTileType(t) == WATER_TILE_CLEAR &&
    01388           GetTileOwner(t) == OWNER_WATER &&
    01389           TileHeight(t) != 0) {
    01390         SetTileOwner(t, OWNER_NONE);
    01391       }
    01392     }
    01393   }
    01394
    01395   /*
    01396    * Add the 'previous' owner to the ship depots so we can reset it with
    01397    * the correct values when it gets destroyed. This prevents that
    01398    * someone can remove canals owned by somebody else and it prevents
    01399    * making floods using the removal of ship depots.
    01400    */
    01401   if (CheckSavegameVersion(83)) {
    01402     for (TileIndex t = 0; t < map_size; t++) {
    01403       if (IsTileType(t, MP_WATER) && IsShipDepot(t)) {
    01404         _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
    01405       }
    01406     }
    01407   }
    01408
    01409   if (CheckSavegameVersion(74)) {
    01410     Station *st;
    01411     FOR_ALL_STATIONS(st) {
    01412       for (CargoID c = 0; c < NUM_CARGO; c++) {
    01413         st->goods[c].last_speed = 0;
    01414         if (st->goods[c].cargo.Count() != 0) SetBit(st->goods[c].acceptance_pickup, GoodsEntry::PICKUP);
    01415       }
    01416     }
    01417   }
    01418
    01419   if (CheckSavegameVersion(78)) {
    01420     Industry *i;
    01421     uint j;
    01422     FOR_ALL_INDUSTRIES(i) {
    01423       const IndustrySpec *indsp = GetIndustrySpec(i->type);
    01424       for (j = 0; j < lengthof(i->produced_cargo); j++) {
    01425         i->produced_cargo[j] = indsp->produced_cargo[j];
    01426       }
    01427       for (j = 0; j < lengthof(i->accepts_cargo); j++) {
    01428         i->accepts_cargo[j] = indsp->accepts_cargo[j];
    01429       }
    01430     }
    01431   }
    01432
    01433   /* Before version 81, the density of grass was always stored as zero, and
    01434    * grassy trees were always drawn fully grassy. Furthermore, trees on rough
    01435    * land used to have zero density, now they have full density. Therefore,
    01436    * make all grassy/rough land trees have a density of 3. */
    01437   if (CheckSavegameVersion(81)) {
    01438     for (TileIndex t = 0; t < map_size; t++) {
    01439       if (GetTileType(t) == MP_TREES) {
    01440         TreeGround groundType = GetTreeGround(t);
    01441         if (groundType != TREE_GROUND_SNOW_DESERT) SetTreeGroundDensity(t, groundType, 3);
    01442       }
    01443     }
    01444   }
    01445
    01446
    01447   if (CheckSavegameVersion(93)) {
    01448     /* Rework of orders. */
    01449     Order *order;
    01450     FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
    01451
    01452     Vehicle *v;
    01453     FOR_ALL_VEHICLES(v) {
    01454       if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && v->orders.list->GetFirstOrder()->IsType(OT_NOTHING)) {
    01455         v->orders.list->FreeChain();
    01456         v->orders.list = NULL;
    01457       }
    01458
    01459       v->current_order.ConvertFromOldSavegame();
    01460       if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
    01461         FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
    01462       }
    01463     }
    01464   } else if (CheckSavegameVersion(94)) {
    01465     /* Unload and transfer are now mutual exclusive. */
    01466     Order *order;
    01467     FOR_ALL_ORDERS(order) {
    01468       if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
    01469         order->SetUnloadType(OUFB_TRANSFER);
    01470         order->SetLoadType(OLFB_NO_LOAD);
    01471       }
    01472     }
    01473
    01474     Vehicle *v;
    01475     FOR_ALL_VEHICLES(v) {
    01476       if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
    01477         v->current_order.SetUnloadType(OUFB_TRANSFER);
    01478         v->current_order.SetLoadType(OLFB_NO_LOAD);
    01479       }
    01480     }
    01481   }
    01482
    01483   if (CheckSavegameVersion(84)) {
    01484     /* Set all share owners to INVALID_COMPANY for
    01485      * 1) all inactive companies
    01486      *     (when inactive companies were stored in the savegame - TTD, TTDP and some
    01487      *      *really* old revisions of OTTD; else it is already set in InitializeCompanies())
    01488      * 2) shares that are owned by inactive companies or self
    01489      *     (caused by cheating clients in earlier revisions) */
    01490     FOR_ALL_COMPANIES(c) {
    01491       for (uint i = 0; i < 4; i++) {
    01492         CompanyID company = c->share_owners[i];
    01493         if (company == INVALID_COMPANY) continue;
    01494         if (!Company::IsValidID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
    01495       }
    01496     }
    01497   }
    01498
    01499   if (CheckSavegameVersion(86)) {
    01500     for (TileIndex t = 0; t < map_size; t++) {
    01501       /* Move river flag and update canals to use water class */
    01502       if (IsTileType(t, MP_WATER)) {
    01503         if (GetWaterClass(t) != WATER_CLASS_RIVER) {
    01504           if (IsWater(t)) {
    01505             Owner o = GetTileOwner(t);
    01506             if (o == OWNER_WATER) {
    01507               MakeSea(t);
    01508             } else {
    01509               MakeCanal(t, o, Random());
    01510             }
    01511           } else if (IsShipDepot(t)) {
    01512             Owner o = (Owner)_m[t].m4; // Original water owner
    01513             SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
    01514           }
    01515         }
    01516       }
    01517     }
    01518
    01519     /* Update locks, depots, docks and buoys to have a water class based
    01520      * on its neighbouring tiles. Done after river and canal updates to
    01521      * ensure neighbours are correct. */
    01522     for (TileIndex t = 0; t < map_size; t++) {
    01523       if (GetTileSlope(t, NULL) != SLOPE_FLAT) continue;
    01524
    01525       if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
    01526       if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
    01527     }
    01528   }
    01529
    01530   if (CheckSavegameVersion(87)) {
    01531     for (TileIndex t = 0; t < map_size; t++) {
    01532       /* skip oil rigs at borders! */
    01533       if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
    01534           (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
    01535         /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
    01536          * This conversion has to be done before buoys with invalid owner are removed. */
    01537         SetWaterClass(t, WATER_CLASS_SEA);
    01538       }
    01539
    01540       if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
    01541         Owner o = GetTileOwner(t);
    01542         if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
    01543           _current_company = o;
    01544           ChangeTileOwner(t, o, INVALID_OWNER);
    01545         }
    01546         if (IsBuoyTile(t)) {
    01547           /* reset buoy owner to OWNER_NONE in the station struct
    01548            * (even if it is owned by active company) */
    01549           Waypoint::GetByTile(t)->owner = OWNER_NONE;
    01550         }
    01551       } else if (IsTileType(t, MP_ROAD)) {
    01552         /* works for all RoadTileType */
    01553         for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
    01554           /* update even non-existing road types to update tile owner too */
    01555           Owner o = GetRoadOwner(t, rt);
    01556           if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rt, OWNER_NONE);
    01557         }
    01558         if (IsLevelCrossing(t)) {
    01559           if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
    01560         }
    01561       } else if (IsPlainRailTile(t)) {
    01562         if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
    01563       }
    01564     }
    01565
    01566     /* Convert old PF settings to new */
    01567     if (_settings_game.pf.yapf.rail_use_yapf || CheckSavegameVersion(28)) {
    01568       _settings_game.pf.pathfinder_for_trains = VPF_YAPF;
    01569     } else {
    01570       _settings_game.pf.pathfinder_for_trains = VPF_NPF;
    01571     }
    01572
    01573     if (_settings_game.pf.yapf.road_use_yapf || CheckSavegameVersion(28)) {
    01574       _settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
    01575     } else {
    01576       _settings_game.pf.pathfinder_for_roadvehs = VPF_NPF;
    01577     }
    01578
    01579     if (_settings_game.pf.yapf.ship_use_yapf) {
    01580       _settings_game.pf.pathfinder_for_ships = VPF_YAPF;
    01581     } else {
    01582       _settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
    01583     }
    01584   }
    01585
    01586   if (CheckSavegameVersion(88)) {
    01587     /* Profits are now with 8 bit fract */
    01588     Vehicle *v;
    01589     FOR_ALL_VEHICLES(v) {
    01590       v->profit_this_year <<= 8;
    01591       v->profit_last_year <<= 8;
    01592       v->running_ticks = 0;
    01593     }
    01594   }
    01595
    01596   if (CheckSavegameVersion(91)) {
    01597     /* Increase HouseAnimationFrame from 5 to 7 bits */
    01598     for (TileIndex t = 0; t < map_size; t++) {
    01599       if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
    01600         SetHouseAnimationFrame(t, GB(_m[t].m6, 3, 5));
    01601       }
    01602     }
    01603   }
    01604
    01605   if (CheckSavegameVersion(62)) {
    01606     /* Remove all trams from savegames without tram support.
    01607      * There would be trams without tram track under causing crashes sooner or later. */
    01608     RoadVehicle *v;
    01609     FOR_ALL_ROADVEHICLES(v) {
    01610       if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
    01611         if (_switch_mode_errorstr == INVALID_STRING_ID || _switch_mode_errorstr == STR_NEWGRF_COMPATIBLE_LOAD_WARNING) {
    01612           _switch_mode_errorstr = STR_WARNING_LOADGAME_REMOVED_TRAMS;
    01613         }
    01614         delete v;
    01615       }
    01616     }
    01617   }
    01618
    01619   if (CheckSavegameVersion(99)) {
    01620     for (TileIndex t = 0; t < map_size; t++) {
    01621       /* Set newly introduced WaterClass of industry tiles */
    01622       if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
    01623         SetWaterClassDependingOnSurroundings(t, true);
    01624       }
    01625       if (IsTileType(t, MP_INDUSTRY)) {
    01626         if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
    01627           SetWaterClassDependingOnSurroundings(t, true);
    01628         } else {
    01629           SetWaterClass(t, WATER_CLASS_INVALID);
    01630         }
    01631       }
    01632
    01633       /* Replace "house construction year" with "house age" */
    01634       if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
    01635         _m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
    01636       }
    01637     }
    01638   }
    01639
    01640   /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
    01641    * format here, as an old layout wouldn't work properly anyway. To be safe, we
    01642    * clear any possible PBS reservations as well. */
    01643   if (CheckSavegameVersion(100)) {
    01644     for (TileIndex t = 0; t < map_size; t++) {
    01645       switch (GetTileType(t)) {
    01646         case MP_RAILWAY:
    01647           if (HasSignals(t)) {
    01648             /* move the signal variant */
    01649             SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
    01650             SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
    01651             ClrBit(_m[t].m2, 2);
    01652             ClrBit(_m[t].m2, 6);
    01653           }
    01654
    01655           /* Clear PBS reservation on track */
    01656           if (IsRailDepot(t)) {
    01657             SetDepotReservation(t, false);
    01658           } else {
    01659             SetTrackReservation(t, TRACK_BIT_NONE);
    01660           }
    01661           break;
    01662
    01663         case MP_ROAD: // Clear PBS reservation on crossing
    01664           if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
    01665           break;
    01666
    01667         case MP_STATION: // Clear PBS reservation on station
    01668           if (HasStationRail(t)) SetRailStationReservation(t, false);
    01669           break;
    01670
    01671         case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/birdges
    01672           if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
    01673           break;
    01674
    01675         default: break;
    01676       }
    01677     }
    01678   }
    01679
    01680   /* Reserve all tracks trains are currently on. */
    01681   if (CheckSavegameVersion(101)) {
    01682     const Train *t;
    01683     FOR_ALL_TRAINS(t) {
    01684       if (t->First() == t) t->ReserveTrackUnderConsist();
    01685     }
    01686   }
    01687
    01688   if (CheckSavegameVersion(102)) {
    01689     for (TileIndex t = 0; t < map_size; t++) {
    01690       /* Now all crossings should be in correct state */
    01691       if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
    01692     }
    01693   }
    01694
    01695   if (CheckSavegameVersion(103)) {
    01696     /* Non-town-owned roads now store the closest town */
    01697     UpdateNearestTownForRoadTiles(false);
    01698
    01699     /* signs with invalid owner left from older savegames */
    01700     Sign *si;
    01701     FOR_ALL_SIGNS(si) {
    01702       if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
    01703     }
    01704
    01705     /* Station can get named based on an industry type, but the current ones
    01706      * are not, so mark them as if they are not named by an industry. */
    01707     Station *st;
    01708     FOR_ALL_STATIONS(st) {
    01709       st->indtype = IT_INVALID;
    01710     }
    01711   }
    01712
    01713   if (CheckSavegameVersion(104)) {
    01714     Aircraft *a;
    01715     FOR_ALL_AIRCRAFT(a) {
    01716       /* Set engine_type of shadow and rotor */
    01717       if (!a->IsNormalAircraft()) {
    01718         a->engine_type = a->First()->engine_type;
    01719       }
    01720     }
    01721
    01722     /* More companies ... */
    01723     Company *c;
    01724     FOR_ALL_COMPANIES(c) {
    01725       if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
    01726     }
    01727
    01728     Engine *e;
    01729     FOR_ALL_ENGINES(e) {
    01730       if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
    01731     }
    01732
    01733     Town *t;
    01734     FOR_ALL_TOWNS(t) {
    01735       if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
    01736       for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
    01737     }
    01738   }
    01739
    01740   if (CheckSavegameVersion(112)) {
    01741     for (TileIndex t = 0; t < map_size; t++) {
    01742       /* Check for HQ bit being set, instead of using map accessor,
    01743        * since we've already changed it code-wise */
    01744       if (IsTileType(t, MP_UNMOVABLE) && HasBit(_m[t].m5, 7)) {
    01745         /* Move size and part identification of HQ out of the m5 attribute,
    01746          * on new locations */
    01747         uint8 old_m5 = _m[t].m5;
    01748         _m[t].m5 = UNMOVABLE_HQ;
    01749         SetCompanyHQSize(t, GB(old_m5, 2, 3));
    01750         SetCompanyHQSection(t, GB(old_m5, 0, 2));
    01751       }
    01752     }
    01753   }
    01754
    01755   if (CheckSavegameVersion(113)) {
    01756     /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
    01757     if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
    01758       _settings_game.economy.allow_town_roads = false;
    01759       _settings_game.economy.town_layout = TL_BETTER_ROADS;
    01760     } else {
    01761       _settings_game.economy.allow_town_roads = true;
    01762       _settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
    01763     }
    01764
    01765     /* Initialize layout of all towns. Older versions were using different
    01766      * generator for random town layout, use it if needed. */
    01767     Town *t;
    01768     FOR_ALL_TOWNS(t) {
    01769       if (_settings_game.economy.town_layout != TL_RANDOM) {
    01770         t->layout = _settings_game.economy.town_layout;
    01771         continue;
    01772       }
    01773
    01774       /* Use old layout randomizer code */
    01775       byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
    01776       switch (layout) {
    01777         default: break;
    01778         case 5: layout = 1; break;
    01779         case 0: layout = 2; break;
    01780       }
    01781       t->layout = layout - 1;
    01782     }
    01783   }
    01784
    01785   if (CheckSavegameVersion(114)) {
    01786     /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
    01787      * The conversion affects oil rigs and buoys too, but it doesn't matter as
    01788      * they have st->owner == OWNER_NONE already. */
    01789     Station *st;
    01790     FOR_ALL_STATIONS(st) {
    01791       if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
    01792     }
    01793   }
    01794
    01795   /* Trains could now stop in a specific location. */
    01796   if (CheckSavegameVersion(117)) {
    01797     Order *o;
    01798     FOR_ALL_ORDERS(o) {
    01799       if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
    01800     }
    01801   }
    01802
    01803   if (CheckSavegameVersion(120)) {
    01804     extern VehicleDefaultSettings _old_vds;
    01805     Company *c;
    01806     FOR_ALL_COMPANIES(c) {
    01807       c->settings.vehicle = _old_vds;
    01808     }
    01809   }
    01810
    01811   if (CheckSavegameVersion(121)) {
    01812     /* Delete small ufos heading for non-existing vehicles */
    01813     Vehicle *v;
    01814     FOR_ALL_DISASTERVEHICLES(v) {
    01815       if (v->subtype == 2/*ST_SMALL_UFO*/ && v->current_order.GetDestination() != 0) {
    01816         const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
    01817         if (u == NULL || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsRoadVehFront()) {
    01818           delete v;
    01819         }
    01820       }
    01821     }
    01822
    01823     /* We didn't store cargo payment yet, so make them for vehicles that are
    01824      * currently at a station and loading/unloading. If they don't get any
    01825      * payment anymore they just removed in the next load/unload cycle.
    01826      * However, some 0.7 versions might have cargo payment. For those we just
    01827      * add cargopayment for the vehicles that don't have it.
    01828      */
    01829     Station *st;
    01830     FOR_ALL_STATIONS(st) {
    01831       std::list<Vehicle *>::iterator iter;
    01832       for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) {
    01833         Vehicle *v = *iter;
    01834         if (v->cargo_payment == NULL) v->cargo_payment = new CargoPayment(v);
    01835       }
    01836     }
    01837   }
    01838
    01839   if (CheckSavegameVersion(122)) {
    01840     /* Animated tiles would sometimes not be actually animated or
    01841      * in case of old savegames duplicate. */
    01842
    01843     extern TileIndex *_animated_tile_list;
    01844     extern uint _animated_tile_count;
    01845
    01846     for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
    01847       /* Remove if tile is not animated */
    01848       bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == NULL;
    01849
    01850       /* and remove if duplicate */
    01851       for (uint j = 0; !remove && j < i; j++) {
    01852         remove = _animated_tile_list[i] == _animated_tile_list[j];
    01853       }
    01854
    01855       if (remove) {
    01856         DeleteAnimatedTile(_animated_tile_list[i]);
    01857       } else {
    01858         i++;
    01859       }
    01860     }
    01861   }
    01862
    01863   if (CheckSavegameVersion(124)) {
    01864     /* The train station tile area was added */
    01865     Waypoint *wp;
    01866     FOR_ALL_WAYPOINTS(wp) {
    01867       if (wp->facilities & FACIL_TRAIN) {
    01868         wp->train_station.tile = wp->xy;
    01869         wp->train_station.w = 1;
    01870         wp->train_station.h = 1;
    01871       } else {;
    01872         wp->train_station.tile = INVALID_TILE;
    01873         wp->train_station.w = 0;
    01874         wp->train_station.h = 0;
    01875       }
    01876     }
    01877   }
    01878
    01879   if (CheckSavegameVersion(125)) {
    01880     /* Convert old subsidies */
    01881     Subsidy *s;
    01882     FOR_ALL_SUBSIDIES(s) {
    01883       if (s->remaining < 12) {
    01884         /* Converting nonawarded subsidy */
    01885         s->remaining = 12 - s->remaining; // convert "age" to "remaining"
    01886         s->awarded = INVALID_COMPANY; // not awarded to anyone
    01887         const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
    01888         switch (cs->town_effect) {
    01889           case TE_PASSENGERS:
    01890           case TE_MAIL:
    01891             /* Town -> Town */
    01892             s->src_type = s->dst_type = ST_TOWN;
    01893             if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
    01894             break;
    01895           case TE_GOODS:
    01896           case TE_FOOD:
    01897             /* Industry -> Town */
    01898             s->src_type = ST_INDUSTRY;
    01899             s->dst_type = ST_TOWN;
    01900             if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
    01901             break;
    01902           default:
    01903             /* Industry -> Industry */
    01904             s->src_type = s->dst_type = ST_INDUSTRY;
    01905             if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
    01906             break;
    01907         }
    01908       } else {
    01909         /* Do our best for awarded subsidies. The original source or destination industry
    01910          * can't be determined anymore for awarded subsidies, so invalidate them.
    01911          * Town -> Town subsidies are converted using simple heuristic */
    01912         s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
    01913         const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
    01914         switch (cs->town_effect) {
    01915           case TE_PASSENGERS:
    01916           case TE_MAIL: {
    01917             /* Town -> Town */
    01918             const Station *ss = Station::GetIfValid(s->src);
    01919             const Station *sd = Station::GetIfValid(s->dst);
    01920             if (ss != NULL && sd != NULL && ss->owner == sd->owner &&
    01921                 Company::IsValidID(ss->owner)) {
    01922               s->src_type = s->dst_type = ST_TOWN;
    01923               s->src = ss->town->index;
    01924               s->dst = sd->town->index;
    01925               s->awarded = ss->owner;
    01926               continue;
    01927             }
    01928             break;
    01929           }
    01930           default:
    01931             break;
    01932         }
    01933       }
    01934       /* Awarded non-town subsidy or invalid source/destination, invalidate */
    01935       delete s;
    01936     }
    01937   }
    01938
    01939   if (CheckSavegameVersion(126)) {
    01940     /* Recompute inflation based on old unround loan limit
    01941      * Note: Max loan is 500000. With an inflation of 4% across 170 years
    01942      *       that results in a max loan of about 0.7 * 2^31.
    01943      *       So taking the 16 bit fractional part into account there are plenty of bits left
    01944      *       for unmodified savegames ...
    01945      */
    01946     uint64 aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
    01947
    01948     /* ... well, just clamp it then. */
    01949     if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
    01950
    01951     /* Simulate the inflation, so we also get the payment inflation */
    01952     while (_economy.inflation_prices < aimed_inflation) {
    01953       AddInflation(false);
    01954     }
    01955   }
    01956
    01957   if (CheckSavegameVersion(127)) {
    01958     Station *st;
    01959     FOR_ALL_STATIONS(st) UpdateStationAcceptance(st, false);
    01960   }
    01961
    01962   if (CheckSavegameVersion(128)) {
    01963     const Depot *d;
    01964     FOR_ALL_DEPOTS(d) {
    01965       _m[d->xy].m2 = d->index;
    01966       if (IsTileType(d->xy, MP_WATER)) _m[GetOtherShipDepotTile(d->xy)].m2 = d->index;
    01967     }
    01968   }
    01969
    01970   /* The behaviour of force_proceed has been changed. Now
    01971    * it counts signals instead of some random time out. */
    01972   if (CheckSavegameVersion(131)) {
    01973     Train *t;
    01974     FOR_ALL_TRAINS(t) {
    01975       t->force_proceed = min<byte>(t->force_proceed, 1);
    01976     }
    01977   }
    01978
    01979   /* Road stops is 'only' updating some caches */
    01980   AfterLoadRoadStops();
    01981   AfterLoadLabelMaps();
    01982
    01983   GamelogPrintDebug(1);
    01984
    01985   InitializeWindowsAndCaches();
    01986   /* Restore the signals */
    01987   ResetSignalHandlers();
    01988   return true;
    01989 }
    01990
    01997 void ReloadNewGRFData()
    01998 {
    01999   /* reload grf data */
    02000   GfxLoadSprites();
    02001   LoadStringWidthTable();
    02002   RecomputePrices();
    02003   /* reload vehicles */
    02004   ResetVehiclePosHash();
    02005   AfterLoadVehicles(false);
    02006   StartupEngines();
    02007   SetCachedEngineCounts();
    02008   /* update station graphics */
    02009   AfterLoadStations();
    02010   /* Check and update house and town values */
    02011   UpdateHousesAndTowns();
    02012   /* Update livery selection windows */
    02013   for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i);
    02014   /* redraw the whole screen */
    02015   MarkWholeScreenDirty();
    02016   CheckTrainsLengths();
    02017 }