# afterload.cpp

Go to the documentation of this file.

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