# afterload.cpp

Go to the documentation of this file.

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