afterload.cpp

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

Generated on Fri Dec 31 17:15:37 2010 for OpenTTD by  doxygen 1.6.1