afterload.cpp

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

Generated on Tue Sep 14 17:06:53 2010 for OpenTTD by  doxygen 1.6.1