Relax validation for conditional order travel time in old savegame load
[openttd-joker.git] / src / saveload / afterload.cpp
blob37efe80923d741fa4f5ed2a1e35501b5ff232262
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file afterload.cpp Code updating data after game load */
12 #include "../stdafx.h"
13 #include "../void_map.h"
14 #include "../signs_base.h"
15 #include "../depot_base.h"
16 #include "../tunnel_base.h"
17 #include "../fios.h"
18 #include "../gamelog_internal.h"
19 #include "../network/network.h"
20 #include "../network/network_func.h"
21 #include "../gfxinit.h"
22 #include "../viewport_func.h"
23 #include "../industry.h"
24 #include "../clear_map.h"
25 #include "../vehicle_func.h"
26 #include "../string_func.h"
27 #include "../date_func.h"
28 #include "../roadveh.h"
29 #include "../train.h"
30 #include "../station_base.h"
31 #include "../waypoint_base.h"
32 #include "../roadstop_base.h"
33 #include "../dock_base.h"
34 #include "../tunnelbridge_map.h"
35 #include "../pathfinder/yapf/yapf_cache.h"
36 #include "../elrail_func.h"
37 #include "../signs_func.h"
38 #include "../aircraft.h"
39 #include "../object_map.h"
40 #include "../object_base.h"
41 #include "../tree_map.h"
42 #include "../company_func.h"
43 #include "../road_cmd.h"
44 #include "../ai/ai.hpp"
45 #include "../ai/ai_gui.hpp"
46 #include "../town.h"
47 #include "../economy_base.h"
48 #include "../animated_tile_func.h"
49 #include "../subsidy_base.h"
50 #include "../subsidy_func.h"
51 #include "../newgrf.h"
52 #include "../engine_func.h"
53 #include "../rail_gui.h"
54 #include "../core/backup_type.hpp"
55 #include "../smallmap_gui.h"
56 #include "../news_func.h"
57 #include "../order_backup.h"
58 #include "../error.h"
59 #include "../disaster_vehicle.h"
60 #include "../tunnel_map.h"
63 #include "saveload_internal.h"
65 #include <signal.h>
66 #include <algorithm>
68 #include "../safeguards.h"
70 extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = INVALID_COMPANY);
72 /**
73 * Makes a tile canal or water depending on the surroundings.
75 * Must only be used for converting old savegames. Use WaterClass now.
77 * This as for example docks and shipdepots do not store
78 * whether the tile used to be canal or 'normal' water.
79 * @param t the tile to change.
80 * @param include_invalid_water_class Also consider WATER_CLASS_INVALID, i.e. industry tiles on land
82 void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
84 /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
85 * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
86 if (!IsTileFlat(t)) {
87 if (include_invalid_water_class) {
88 SetWaterClass(t, WATER_CLASS_INVALID);
89 return;
90 } else {
91 SlErrorCorrupt("Invalid water class for dry tile");
95 /* Mark tile dirty in all cases */
96 MarkTileDirtyByTile(t);
98 if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
99 /* tiles at map borders are always WATER_CLASS_SEA */
100 SetWaterClass(t, WATER_CLASS_SEA);
101 return;
104 bool has_water = false;
105 bool has_canal = false;
106 bool has_river = false;
108 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
109 TileIndex neighbour = TileAddByDiagDir(t, dir);
110 switch (GetTileType(neighbour)) {
111 case MP_WATER:
112 /* clear water and shipdepots have already a WaterClass associated */
113 if (IsCoast(neighbour)) {
114 has_water = true;
115 } else if (!IsLock(neighbour)) {
116 switch (GetWaterClass(neighbour)) {
117 case WATER_CLASS_SEA: has_water = true; break;
118 case WATER_CLASS_CANAL: has_canal = true; break;
119 case WATER_CLASS_RIVER: has_river = true; break;
120 default: SlErrorCorrupt("Invalid water class for tile");
123 break;
125 case MP_RAILWAY:
126 /* Shore or flooded halftile */
127 has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
128 break;
130 case MP_TREES:
131 /* trees on shore */
132 has_water |= (GB(_m[neighbour].m2, 4, 2) == TREE_GROUND_SHORE);
133 break;
135 default: break;
139 if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
140 SetWaterClass(t, WATER_CLASS_INVALID);
141 return;
144 if (has_river && !has_canal) {
145 SetWaterClass(t, WATER_CLASS_RIVER);
146 } else if (has_canal || !has_water) {
147 SetWaterClass(t, WATER_CLASS_CANAL);
148 } else {
149 SetWaterClass(t, WATER_CLASS_SEA);
153 static void ConvertTownOwner()
155 for (TileIndex tile = 0; tile != MapSize(); tile++) {
156 switch (GetTileType(tile)) {
157 case MP_ROAD:
158 if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
159 _m[tile].m3 = OWNER_TOWN;
161 FALLTHROUGH;
163 case MP_TUNNELBRIDGE:
164 if (_m[tile].m1 & 0x80) SetTileOwner(tile, OWNER_TOWN);
165 break;
167 default: break;
172 /* since savegame version 4.1, exclusive transport rights are stored at towns */
173 static void UpdateExclusiveRights()
175 Town *t;
177 FOR_ALL_TOWNS(t) {
178 t->exclusivity = INVALID_COMPANY;
181 /* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
182 * could be implemented this way:
183 * 1.) Go through all stations
184 * Build an array town_blocked[ town_id ][ company_id ]
185 * that stores if at least one station in that town is blocked for a company
186 * 2.) Go through that array, if you find a town that is not blocked for
187 * one company, but for all others, then give him exclusivity.
191 static const byte convert_currency[] = {
192 0, 1, 12, 8, 3,
193 10, 14, 19, 4, 5,
194 9, 11, 13, 6, 17,
195 16, 22, 21, 7, 15,
196 18, 2, 20,
199 /* since savegame version 4.2 the currencies are arranged differently */
200 static void UpdateCurrencies()
202 _settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
205 /* Up to revision 1413 the invisible tiles at the southern border have not been
206 * MP_VOID, even though they should have. This is fixed by this function
208 static void UpdateVoidTiles()
210 uint i;
212 for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
213 for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
216 static inline RailType UpdateRailType(RailType rt, RailType min)
218 return rt >= min ? (RailType)(rt + 1): rt;
222 * Update the viewport coordinates of all signs.
224 void UpdateAllVirtCoords()
226 UpdateAllStationVirtCoords();
227 UpdateAllSignVirtCoords();
228 UpdateAllTownVirtCoords();
232 * Initialization of the windows and several kinds of caches.
233 * This is not done directly in AfterLoadGame because these
234 * functions require that all saveload conversions have been
235 * done. As people tend to add savegame conversion stuff after
236 * the intialization of the windows and caches quite some bugs
237 * had been made.
238 * Moving this out of there is both cleaner and less bug-prone.
240 static void InitializeWindowsAndCaches()
242 /* Initialize windows */
243 ResetWindowSystem();
244 SetupColoursAndInitialWindow();
246 /* Update coordinates of the signs. */
247 UpdateAllVirtCoords();
248 ResetViewportAfterLoadGame();
250 Company *c;
251 FOR_ALL_COMPANIES(c) {
252 /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
253 * accordingly if it is not the case. No need to set it on companies that are not been used already,
254 * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
255 if (_file_to_saveload.abstract_ftype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
256 c->inaugurated_year = _cur_year;
260 /* Count number of objects per type */
261 Object *o;
262 FOR_ALL_OBJECTS(o) {
263 Object::IncTypeCount(o->type);
266 /* Identify owners of persistent storage arrays */
267 Industry *i;
268 FOR_ALL_INDUSTRIES(i) {
269 if (i->psa != NULL) {
270 i->psa->feature = GSF_INDUSTRIES;
271 i->psa->tile = i->location.tile;
274 Station *s;
275 FOR_ALL_STATIONS(s) {
276 if (s->airport.psa != NULL) {
277 s->airport.psa->feature = GSF_AIRPORTS;
278 s->airport.psa->tile = s->airport.tile;
281 Town *t;
282 FOR_ALL_TOWNS(t) {
283 for (std::list<PersistentStorage *>::iterator it = t->psa_list.begin(); it != t->psa_list.end(); ++it) {
284 (*it)->feature = GSF_FAKE_TOWNS;
285 (*it)->tile = t->xy;
289 RecomputePrices();
291 GroupStatistics::UpdateAfterLoad();
293 Station::RecomputeIndustriesNearForAll();
294 RebuildSubsidisedSourceAndDestinationCache();
296 /* Towns have a noise controlled number of airports system
297 * So each airport's noise value must be added to the town->noise_reached value
298 * Reset each town's noise_reached value to '0' before. */
299 UpdateAirportsNoise();
301 CheckTrainsLengths();
302 ShowNewGRFError();
303 ShowAIDebugWindowIfAIError();
305 /* Rebuild the smallmap list of owners. */
306 BuildOwnerLegend();
309 typedef void (CDECL *SignalHandlerPointer)(int);
310 static SignalHandlerPointer _prev_segfault = NULL;
311 static SignalHandlerPointer _prev_abort = NULL;
312 static SignalHandlerPointer _prev_fpe = NULL;
314 static void CDECL HandleSavegameLoadCrash(int signum);
317 * Replaces signal handlers of SIGSEGV and SIGABRT
318 * and stores pointers to original handlers in memory.
320 static void SetSignalHandlers()
322 _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
323 _prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
324 _prev_fpe = signal(SIGFPE, HandleSavegameLoadCrash);
328 * Resets signal handlers back to original handlers.
330 static void ResetSignalHandlers()
332 signal(SIGSEGV, _prev_segfault);
333 signal(SIGABRT, _prev_abort);
334 signal(SIGFPE, _prev_fpe);
338 * Try to find the overridden GRF identifier of the given GRF.
339 * @param c the GRF to get the 'previous' version of.
340 * @return the GRF identifier or \a c if none could be found.
342 static const GRFIdentifier *GetOverriddenIdentifier(const GRFConfig *c)
344 const LoggedAction *la = &_gamelog_action[_gamelog_actions - 1];
345 if (la->at != GLAT_LOAD) return &c->ident;
347 const LoggedChange *lcend = &la->change[la->changes];
348 for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
349 if (lc->ct == GLCT_GRFCOMPAT && lc->grfcompat.grfid == c->ident.grfid) return &lc->grfcompat;
352 return &c->ident;
355 /** Was the saveload crash because of missing NewGRFs? */
356 static bool _saveload_crash_with_missing_newgrfs = false;
359 * Did loading the savegame cause a crash? If so,
360 * were NewGRFs missing?
361 * @return when the saveload crashed due to missing NewGRFs.
363 bool SaveloadCrashWithMissingNewGRFs()
365 return _saveload_crash_with_missing_newgrfs;
369 * Signal handler used to give a user a more useful report for crashes during
370 * the savegame loading process; especially when there's problems with the
371 * NewGRFs that are required by the savegame.
372 * @param signum received signal
374 static void CDECL HandleSavegameLoadCrash(int signum)
376 ResetSignalHandlers();
378 char buffer[8192];
379 char *p = buffer;
380 p += seprintf(p, lastof(buffer), "Loading your savegame caused OpenTTD to crash.\n");
382 for (const GRFConfig *c = _grfconfig; !_saveload_crash_with_missing_newgrfs && c != NULL; c = c->next) {
383 _saveload_crash_with_missing_newgrfs = HasBit(c->flags, GCF_COMPATIBLE) || c->status == GCS_NOT_FOUND;
386 if (_saveload_crash_with_missing_newgrfs) {
387 p += seprintf(p, lastof(buffer),
388 "This is most likely caused by a missing NewGRF or a NewGRF that\n"
389 "has been loaded as replacement for a missing NewGRF. OpenTTD\n"
390 "cannot easily determine whether a replacement NewGRF is of a newer\n"
391 "or older version.\n"
392 "It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
393 "This means that if the author makes incompatible NewGRFs with the\n"
394 "same GRF ID OpenTTD cannot magically do the right thing. In most\n"
395 "cases OpenTTD will load the savegame and not crash, but this is an\n"
396 "exception.\n"
397 "Please load the savegame with the appropriate NewGRFs installed.\n"
398 "The missing/compatible NewGRFs are:\n");
400 for (const GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
401 if (HasBit(c->flags, GCF_COMPATIBLE)) {
402 const GRFIdentifier *replaced = GetOverriddenIdentifier(c);
403 char buf[40];
404 md5sumToString(buf, lastof(buf), replaced->md5sum);
405 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);
407 if (c->status == GCS_NOT_FOUND) {
408 char buf[40];
409 md5sumToString(buf, lastof(buf), c->ident.md5sum);
410 p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s.\n", BSWAP32(c->ident.grfid), c->filename, buf);
413 } else {
414 p += seprintf(p, lastof(buffer),
415 "This is probably caused by a corruption in the savegame.\n"
416 "Please file a bug report and attach this savegame.\n");
419 ShowInfo(buffer);
421 SignalHandlerPointer call = NULL;
422 switch (signum) {
423 case SIGSEGV: call = _prev_segfault; break;
424 case SIGABRT: call = _prev_abort; break;
425 case SIGFPE: call = _prev_fpe; break;
426 default: NOT_REACHED();
428 if (call != NULL) call(signum);
432 * Tries to change owner of this rail tile to a valid owner. In very old versions it could happen that
433 * a rail track had an invalid owner. When conversion isn't possible, track is removed.
434 * @param t tile to update
436 static void FixOwnerOfRailTrack(TileIndex t)
438 assert(!Company::IsValidID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
440 /* remove leftover rail piece from crossing (from very old savegames) */
441 Train *v = NULL, *w;
442 FOR_ALL_TRAINS(w) {
443 if (w->tile == t) {
444 v = w;
445 break;
449 if (v != NULL) {
450 /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
451 SetTileOwner(t, v->owner);
452 return;
455 /* try to find any connected rail */
456 for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
457 TileIndex tt = t + TileOffsByDiagDir(dd);
458 if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
459 GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
460 Company::IsValidID(GetTileOwner(tt))) {
461 SetTileOwner(t, GetTileOwner(tt));
462 return;
466 if (IsLevelCrossingTile(t)) {
467 /* else change the crossing to normal road (road vehicles won't care) */
468 MakeRoadNormal(t, GetCrossingRoadBits(t), GetRoadTypes(t), GetTownIndex(t),
469 GetRoadOwner(t, ROADTYPE_ROAD), GetRoadOwner(t, ROADTYPE_TRAM));
470 return;
473 /* if it's not a crossing, make it clean land */
474 MakeClear(t, CLEAR_GRASS, 0);
478 * Fixes inclination of a vehicle. Older OpenTTD versions didn't update the bits correctly.
479 * @param v vehicle
480 * @param dir vehicle's direction, or # INVALID_DIR if it can be ignored
481 * @return inclination bits to set
483 static uint FixVehicleInclination(Vehicle *v, Direction dir)
485 /* Compute place where this vehicle entered the tile */
486 int entry_x = v->x_pos;
487 int entry_y = v->y_pos;
488 switch (dir) {
489 case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
490 case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
491 case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
492 case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
493 case INVALID_DIR: break;
494 default: NOT_REACHED();
496 byte entry_z = GetSlopePixelZ(entry_x, entry_y);
498 /* Compute middle of the tile. */
499 int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
500 int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
501 byte middle_z = GetSlopePixelZ(middle_x, middle_y);
503 /* middle_z == entry_z, no height change. */
504 if (middle_z == entry_z) return 0;
506 /* middle_z < entry_z, we are going downwards. */
507 if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
509 /* middle_z > entry_z, we are going upwards. */
510 return 1U << GVF_GOINGUP_BIT;
514 * Checks for the possibility that a bridge may be on this tile
515 * These are in fact all the tile types on which a bridge can be found
516 * @param t The tile to analyze
517 * @return True if a bridge might have been present prior to savegame 194 or to patch pack savegame SL_PATCH_PACK_1_9.
519 static inline bool MayHaveBridgeAbove(TileIndex t)
521 return IsTileType(t, MP_CLEAR) || IsTileType(t, MP_RAILWAY) || IsTileType(t, MP_ROAD) ||
522 IsTileType(t, MP_WATER) || IsTileType(t, MP_TUNNELBRIDGE) || IsTileType(t, MP_OBJECT);
525 TileIndex GetOtherTunnelBridgeEndOld(TileIndex tile)
527 DiagDirection dir = GetTunnelBridgeDirection(tile);
528 TileIndexDiff delta = TileOffsByDiagDir(dir);
529 int z = GetTileZ(tile);
531 dir = ReverseDiagDir(dir);
532 do {
533 tile += delta;
534 } while (
535 !IsTunnelTile(tile) ||
536 GetTunnelBridgeDirection(tile) != dir ||
537 GetTileZ(tile) != z
540 return tile;
544 * Perform a (large) amount of savegame conversion *magic* in order to
545 * load older savegames and to fill the caches for various purposes.
546 * @return True iff conversion went without a problem.
548 bool AfterLoadGame()
550 SetSignalHandlers();
552 TileIndex map_size = MapSize();
554 extern TileIndex _cur_tileloop_tile; // From landscape.cpp.
555 /* The LFSR used in RunTileLoop iteration cannot have a zeroed state, make it non-zeroed. */
556 if (_cur_tileloop_tile == 0) _cur_tileloop_tile = 1;
558 if (IsSavegameVersionBefore(98)) GamelogOldver();
560 GamelogTestRevision();
561 GamelogTestMode();
563 if (IsSavegameVersionBefore(98)) GamelogGRFAddList(_grfconfig);
565 if (IsSavegameVersionBefore(119)) {
566 _pause_mode = (_pause_mode == 2) ? PM_PAUSED_NORMAL : PM_UNPAUSED;
567 } else if (_network_dedicated && (_pause_mode & PM_PAUSED_ERROR) != 0) {
568 DEBUG(net, 0, "The loading savegame was paused due to an error state.");
569 DEBUG(net, 0, " The savegame cannot be used for multiplayer!");
570 /* Restore the signals */
571 ResetSignalHandlers();
572 return false;
573 } else if (!_networking || _network_server) {
574 /* If we are in single player, i.e. not networking, and loading the
575 * savegame or we are loading the savegame as network server we do
576 * not want to be bothered by being paused because of the automatic
577 * reason of a network server, e.g. joining clients or too few
578 * active clients. Note that resetting these values for a network
579 * client are very bad because then the client is going to execute
580 * the game loop when the server is not, i.e. it desyncs. */
581 _pause_mode &= ~PMB_PAUSED_NETWORK;
584 /* In very old versions, size of train stations was stored differently.
585 * They had swapped width and height if station was built along the Y axis.
586 * TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
587 * Because the data stored by TTDPatch are unusable for rail stations > 7x7,
588 * recompute the width and height. Doing this unconditionally for all old
589 * savegames simplifies the code. */
590 if (IsSavegameVersionBefore(2)) {
591 Station *st;
592 FOR_ALL_STATIONS(st) {
593 st->train_station.w = st->train_station.h = 0;
595 for (TileIndex t = 0; t < map_size; t++) {
596 if (!IsTileType(t, MP_STATION)) continue;
597 if (_m[t].m5 > 7) continue; // is it a rail station tile?
598 st = Station::Get(_m[t].m2);
599 assert(st->train_station.tile != 0);
600 int dx = TileX(t) - TileX(st->train_station.tile);
601 int dy = TileY(t) - TileY(st->train_station.tile);
602 assert(dx >= 0 && dy >= 0);
603 st->train_station.w = max<uint>(st->train_station.w, dx + 1);
604 st->train_station.h = max<uint>(st->train_station.h, dy + 1);
608 if (IsSavegameVersionBefore(194) || IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_9)) {
609 _settings_game.construction.max_heightlevel = 15;
611 /* In old savegame versions, the heightlevel was coded in bits 0..3 of the type field */
612 for (TileIndex t = 0; t < map_size; t++) {
613 _m[t].height = GB(_m[t].type, 0, 4);
614 SB(_m[t].type, 0, 2, GB(_me[t].m6, 0, 2));
615 SB(_me[t].m6, 0, 2, 0);
616 if (MayHaveBridgeAbove(t)) {
617 SB(_m[t].type, 2, 2, GB(_me[t].m6, 6, 2));
618 SB(_me[t].m6, 6, 2, 0);
619 } else {
620 SB(_m[t].type, 2, 2, 0);
625 /* in version 2.1 of the savegame, town owner was unified. */
626 if (IsSavegameVersionBefore(2, 1)) ConvertTownOwner();
628 /* from version 4.1 of the savegame, exclusive rights are stored at towns */
629 if (IsSavegameVersionBefore(4, 1)) UpdateExclusiveRights();
631 /* from version 4.2 of the savegame, currencies are in a different order */
632 if (IsSavegameVersionBefore(4, 2)) UpdateCurrencies();
634 /* In old version there seems to be a problem that water is owned by
635 * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
636 * (4.3) version, so I just check when versions are older, and then
637 * walk through the whole map.. */
638 if (IsSavegameVersionBefore(4, 3)) {
639 for (TileIndex t = 0; t < map_size; t++) {
640 if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
641 SetTileOwner(t, OWNER_WATER);
646 if (IsSavegameVersionBefore(84)) {
647 Company *c;
648 FOR_ALL_COMPANIES(c) {
649 c->name = CopyFromOldName(c->name_1);
650 if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
651 c->president_name = CopyFromOldName(c->president_name_1);
652 if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
655 Station *st;
656 FOR_ALL_STATIONS(st) {
657 st->name = CopyFromOldName(st->string_id);
658 /* generating new name would be too much work for little effect, use the station name fallback */
659 if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
662 Town *t;
663 FOR_ALL_TOWNS(t) {
664 t->name = CopyFromOldName(t->townnametype);
665 if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
669 /* From this point the old names array is cleared. */
670 ResetOldNames();
672 if (IsSavegameVersionBefore(106)) {
673 /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
674 Station *st;
675 FOR_ALL_STATIONS(st) {
676 if (st->airport.tile == 0) st->airport.tile = INVALID_TILE;
677 if (st->dock_station.tile == 0) st->dock_station.tile = INVALID_TILE;
678 if (st->train_station.tile == 0) st->train_station.tile = INVALID_TILE;
681 /* the same applies to Company::location_of_HQ */
682 Company *c;
683 FOR_ALL_COMPANIES(c) {
684 if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(4) && c->location_of_HQ == 0xFFFF)) {
685 c->location_of_HQ = INVALID_TILE;
690 /* convert road side to my format. */
691 if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
693 /* Check if all NewGRFs are present, we are very strict in MP mode */
694 GRFListCompatibility gcf_res = IsGoodGRFConfigList(_grfconfig);
695 for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
696 if (c->status == GCS_NOT_FOUND) {
697 GamelogGRFRemove(c->ident.grfid);
698 } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
699 GamelogGRFCompatible(&c->ident);
703 if (_networking && gcf_res != GLC_ALL_GOOD) {
704 SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
705 /* Restore the signals */
706 ResetSignalHandlers();
707 return false;
710 switch (gcf_res) {
711 case GLC_COMPATIBLE: ShowErrorMessage(STR_NEWGRF_COMPATIBLE_LOAD_WARNING, INVALID_STRING_ID, WL_CRITICAL); break;
712 case GLC_NOT_FOUND: ShowErrorMessage(STR_NEWGRF_DISABLED_WARNING, INVALID_STRING_ID, WL_CRITICAL); _pause_mode = PM_PAUSED_ERROR; break;
713 default: break;
716 /* The value of _date_fract got divided, so make sure that old games are converted correctly. */
717 if (IsSavegameVersionBefore(11, 1) || (IsSavegameVersionBefore(147) && _date_fract > DAY_TICKS)) _date_fract /= 885;
719 if (IsSavegameVersionBefore(SL_PATCH_PACK_DAYLENGTH))
721 if (!IsPatchPackSavegameVersionBefore(SL_PATCH_PACK))
722 _settings_game.economy.daylength = 4;
723 else
724 _settings_game.economy.daylength = 1;
727 /* Update current year
728 * must be done before loading sprites as some newgrfs check it */
729 SetDate(_date, _date_fract);
732 * Force the old behaviour for compatibility reasons with old savegames. As new
733 * settings can only be loaded from new savegames loading old savegames with new
734 * versions of OpenTTD will normally initialize settings newer than the savegame
735 * version with "new game" defaults which the player can define to their liking.
736 * For some settings we override that to keep the behaviour the same as when the
737 * game was saved.
739 * Note that there is no non-stop in here. This is because the setting could have
740 * either value in TTDPatch. To convert it properly the user has to make sure the
741 * right value has been chosen in the settings. Otherwise we will be converting
742 * it incorrectly in half of the times without a means to correct that.
744 if (IsSavegameVersionBefore(4, 2)) _settings_game.station.modified_catchment = false;
745 if (IsSavegameVersionBefore(6, 1)) _settings_game.pf.forbid_90_deg = false;
746 if (IsSavegameVersionBefore(21)) _settings_game.vehicle.train_acceleration_model = 0;
747 if (IsSavegameVersionBefore(90)) _settings_game.vehicle.plane_speed = 4;
748 if (IsSavegameVersionBefore(95)) _settings_game.vehicle.dynamic_engines = 0;
749 if (IsSavegameVersionBefore(96)) _settings_game.economy.station_noise_level = false;
750 if (IsSavegameVersionBefore(133)) {
751 _settings_game.vehicle.train_slope_steepness = 3;
753 if (IsSavegameVersionBefore(134)) _settings_game.economy.feeder_payment_share = 75;
754 if (IsSavegameVersionBefore(138)) _settings_game.vehicle.plane_crashes = 2;
755 if (IsSavegameVersionBefore(139)) {
756 _settings_game.vehicle.roadveh_acceleration_model = 0;
757 _settings_game.vehicle.roadveh_slope_steepness = 7;
759 if (IsSavegameVersionBefore(143)) _settings_game.economy.allow_town_level_crossings = true;
760 if (IsSavegameVersionBefore(159)) {
761 _settings_game.vehicle.max_train_length = 50;
762 _settings_game.construction.max_bridge_length = 64;
763 _settings_game.construction.max_tunnel_length = 64;
765 if (IsSavegameVersionBefore(166)) _settings_game.economy.infrastructure_maintenance = false;
766 if (IsSavegameVersionBefore(183)) {
767 _settings_game.linkgraph.distribution_pax = DT_MANUAL;
768 _settings_game.linkgraph.distribution_mail = DT_MANUAL;
769 _settings_game.linkgraph.distribution_armoured = DT_MANUAL;
770 _settings_game.linkgraph.distribution_default = DT_MANUAL;
773 /* Load the sprites */
774 GfxLoadSprites();
775 LoadStringWidthTable();
777 /* Copy temporary data to Engine pool */
778 CopyTempEngineData();
780 /* Connect front and rear engines of multiheaded trains and converts
781 * subtype to the new format */
782 if (IsSavegameVersionBefore(17, 1)) ConvertOldMultiheadToNew();
784 /* Connect front and rear engines of multiheaded trains */
785 ConnectMultiheadedTrains();
787 /* Fix the CargoPackets *and* fix the caches of CargoLists.
788 * If this isn't done before Stations and especially Vehicles are
789 * running their AfterLoad we might get in trouble. In the case of
790 * vehicles we could give the wrong (cached) count of items in a
791 * vehicle which causes different results when getting their caches
792 * filled; and that could eventually lead to desyncs. */
793 CargoPacket::AfterLoad();
795 /* Oilrig was moved from id 15 to 9. We have to do this conversion
796 * here as AfterLoadVehicles can check it indirectly via the newgrf
797 * code. */
798 if (IsSavegameVersionBefore(139)) {
799 Station *st;
800 FOR_ALL_STATIONS(st) {
801 if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
802 st->airport.type = AT_OILRIG;
807 /* Update all vehicles */
808 AfterLoadVehicles(true);
810 /* Update old version of trip history */
811 AfterLoadTripHistory();
813 /* Update template vehicles */
814 AfterLoadTemplateVehicles();
816 /* Make sure there is an AI attached to an AI company */
818 Company *c;
819 FOR_ALL_COMPANIES(c) {
820 if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
824 /* make sure there is a town in the game */
825 if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
826 SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
827 /* Restore the signals */
828 ResetSignalHandlers();
829 return false;
832 /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
833 * This problem appears in savegame version 21 too, see r3455. But after loading the
834 * savegame and saving again, the buggy map array could be converted to new savegame
835 * version. It didn't show up before r12070. */
836 if (IsSavegameVersionBefore(87)) UpdateVoidTiles();
838 /* If Load Scenario / New (Scenario) Game is used,
839 * a company does not exist yet. So create one here.
840 * 1 exception: network-games. Those can have 0 companies
841 * But this exception is not true for non-dedicated network servers! */
842 if (!Company::IsValidID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated))) {
843 DoStartupNewCompany(false);
844 Company *c = Company::Get(COMPANY_FIRST);
845 c->settings = _settings_client.company;
848 /* Fix the cache for cargo payments. */
849 CargoPayment *cp;
850 FOR_ALL_CARGO_PAYMENTS(cp) {
851 cp->front->cargo_payment = cp;
852 cp->current_station = cp->front->last_station_visited;
855 if (IsSavegameVersionBefore(72)) {
856 /* Locks in very old savegames had OWNER_WATER as owner */
857 for (TileIndex t = 0; t < MapSize(); t++) {
858 switch (GetTileType(t)) {
859 default: break;
861 case MP_WATER:
862 if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
863 break;
865 case MP_STATION: {
866 if (HasBit(_me[t].m6, 3)) SetBit(_me[t].m6, 2);
867 StationGfx gfx = GetStationGfx(t);
868 StationType st;
869 if ( IsInsideMM(gfx, 0, 8)) { // Rail station
870 st = STATION_RAIL;
871 SetStationGfx(t, gfx - 0);
872 } else if (IsInsideMM(gfx, 8, 67)) { // Airport
873 st = STATION_AIRPORT;
874 SetStationGfx(t, gfx - 8);
875 } else if (IsInsideMM(gfx, 67, 71)) { // Truck
876 st = STATION_TRUCK;
877 SetStationGfx(t, gfx - 67);
878 } else if (IsInsideMM(gfx, 71, 75)) { // Bus
879 st = STATION_BUS;
880 SetStationGfx(t, gfx - 71);
881 } else if (gfx == 75) { // Oil rig
882 st = STATION_OILRIG;
883 SetStationGfx(t, gfx - 75);
884 } else if (IsInsideMM(gfx, 76, 82)) { // Dock
885 st = STATION_DOCK;
886 SetStationGfx(t, gfx - 76);
887 } else if (gfx == 82) { // Buoy
888 st = STATION_BUOY;
889 SetStationGfx(t, gfx - 82);
890 } else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
891 st = STATION_AIRPORT;
892 SetStationGfx(t, gfx - 83 + 67 - 8);
893 } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
894 st = STATION_TRUCK;
895 SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
896 } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
897 st = STATION_BUS;
898 SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
899 } else {
900 /* Restore the signals */
901 ResetSignalHandlers();
902 return false;
904 SB(_me[t].m6, 3, 3, st);
905 break;
911 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_18)) {
912 /* Dock type has changed. */
913 Station *st;
914 FOR_ALL_STATIONS(st) {
915 if (st->dock_station.tile == INVALID_TILE) continue;
916 assert(Dock::CanAllocateItem());
917 if (IsOilRig(st->dock_station.tile)) {
918 /* Set dock station tile to dest tile instead of station. */
919 st->docks = new Dock(st->dock_station.tile, st->dock_station.tile + ToTileIndexDiff({ 1, 0 }));
920 } else if (IsDock(st->dock_station.tile)) {
921 /* A normal two-tiles dock. */
922 st->docks = new Dock(st->dock_station.tile, TileAddByDiagDir(st->dock_station.tile, GetDockDirection(st->dock_station.tile)));
923 } else if (IsBuoy(st->dock_station.tile)) {
924 /* A buoy. */
925 } else {
926 NOT_REACHED();
931 for (TileIndex t = 0; t < map_size; t++) {
932 switch (GetTileType(t)) {
933 case MP_STATION: {
934 BaseStation *bst = BaseStation::GetByTile(t);
936 /* Set up station spread */
937 bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
939 /* Waypoints don't have road stops/oil rigs in the old format */
940 if (!Station::IsExpected(bst)) break;
941 Station *st = Station::From(bst);
943 /* Set up station catchment */
944 st->catchment.BeforeAddTile(t, st->GetCatchmentRadius());
946 switch (GetStationType(t)) {
947 case STATION_TRUCK:
948 case STATION_BUS:
949 if (IsSavegameVersionBefore(6)) {
950 /* Before version 5 you could not have more than 250 stations.
951 * Version 6 adds large maps, so you could only place 253*253
952 * road stops on a map (no freeform edges) = 64009. So, yes
953 * someone could in theory create such a full map to trigger
954 * this assertion, it's safe to assume that's only something
955 * theoretical and does not happen in normal games. */
956 assert(RoadStop::CanAllocateItem());
958 /* From this version on there can be multiple road stops of the
959 * same type per station. Convert the existing stops to the new
960 * internal data structure. */
961 RoadStop *rs = new RoadStop(t);
963 RoadStop **head =
964 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
965 *head = rs;
967 break;
969 case STATION_OILRIG: {
970 /* Very old savegames sometimes have phantom oil rigs, i.e.
971 * an oil rig which got shut down, but not completely removed from
972 * the map
974 TileIndex t1 = TILE_ADDXY(t, 0, 1);
975 if (IsTileType(t1, MP_INDUSTRY) &&
976 GetIndustryGfx(t1) == GFX_OILRIG_1) {
977 /* The internal encoding of oil rigs was changed twice.
978 * It was 3 (till 2.2) and later 5 (till 5.1).
979 * Setting it unconditionally does not hurt.
981 Station::GetByTile(t)->airport.type = AT_OILRIG;
982 } else {
983 DeleteOilRig(t);
985 break;
988 default: break;
990 break;
993 default: break;
997 /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
998 * This has to be called after the oilrig airport_type update above ^^^ ! */
999 if (IsSavegameVersionBefore(2, 2)) UpdateOldAircraft();
1001 /* In version 6.1 we put the town index in the map-array. To do this, we need
1002 * to use m2 (16bit big), so we need to clean m2, and that is where this is
1003 * all about ;) */
1004 if (IsSavegameVersionBefore(6, 1)) {
1005 for (TileIndex t = 0; t < map_size; t++) {
1006 switch (GetTileType(t)) {
1007 case MP_HOUSE:
1008 _m[t].m4 = _m[t].m2;
1009 SetTownIndex(t, CalcClosestTownFromTile(t)->index);
1010 break;
1012 case MP_ROAD:
1013 _m[t].m4 |= (_m[t].m2 << 4);
1014 if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
1015 SetTownIndex(t, CalcClosestTownFromTile(t)->index);
1016 } else {
1017 SetTownIndex(t, 0);
1019 break;
1021 default: break;
1026 /* Force the freeform edges to false for old savegames. */
1027 if (IsSavegameVersionBefore(111)) {
1028 _settings_game.construction.freeform_edges = false;
1031 /* From version 9.0, we update the max passengers of a town (was sometimes negative
1032 * before that. */
1033 if (IsSavegameVersionBefore(9)) {
1034 Town *t;
1035 FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
1038 /* From version 16.0, we included autorenew on engines, which are now saved, but
1039 * of course, we do need to initialize them for older savegames. */
1040 if (IsSavegameVersionBefore(16)) {
1041 Company *c;
1042 FOR_ALL_COMPANIES(c) {
1043 c->engine_renew_list = NULL;
1044 c->settings.engine_renew = false;
1045 c->settings.engine_renew_months = 6;
1046 c->settings.engine_renew_money = 100000;
1049 /* When loading a game, _local_company is not yet set to the correct value.
1050 * However, in a dedicated server we are a spectator, so nothing needs to
1051 * happen. In case we are not a dedicated server, the local company always
1052 * becomes company 0, unless we are in the scenario editor where all the
1053 * companies are 'invalid'.
1055 c = Company::GetIfValid(COMPANY_FIRST);
1056 if (!_network_dedicated && c != NULL) {
1057 c->settings = _settings_client.company;
1061 if (IsSavegameVersionBefore(48)) {
1062 for (TileIndex t = 0; t < map_size; t++) {
1063 switch (GetTileType(t)) {
1064 case MP_RAILWAY:
1065 if (IsPlainRail(t)) {
1066 /* Swap ground type and signal type for plain rail tiles, so the
1067 * ground type uses the same bits as for depots and waypoints. */
1068 uint tmp = GB(_m[t].m4, 0, 4);
1069 SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
1070 SB(_m[t].m2, 0, 4, tmp);
1071 } else if (HasBit(_m[t].m5, 2)) {
1072 /* Split waypoint and depot rail type and remove the subtype. */
1073 ClrBit(_m[t].m5, 2);
1074 ClrBit(_m[t].m5, 6);
1076 break;
1078 case MP_ROAD:
1079 /* Swap m3 and m4, so the track type for rail crossings is the
1080 * same as for normal rail. */
1081 Swap(_m[t].m3, _m[t].m4);
1082 break;
1084 default: break;
1089 if (IsSavegameVersionBefore(61)) {
1090 /* Added the RoadType */
1091 bool old_bridge = IsSavegameVersionBefore(42);
1092 for (TileIndex t = 0; t < map_size; t++) {
1093 switch (GetTileType(t)) {
1094 case MP_ROAD:
1095 SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
1096 switch (GetRoadTileType(t)) {
1097 default: SlErrorCorrupt("Invalid road tile type");
1098 case ROAD_TILE_NORMAL:
1099 SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
1100 SB(_m[t].m4, 4, 4, 0);
1101 SB(_me[t].m6, 2, 4, 0);
1102 break;
1103 case ROAD_TILE_CROSSING:
1104 SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
1105 break;
1106 case ROAD_TILE_DEPOT: break;
1108 SetRoadTypes(t, ROADTYPES_ROAD);
1109 break;
1111 case MP_STATION:
1112 if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
1113 break;
1115 case MP_TUNNELBRIDGE:
1116 /* Middle part of "old" bridges */
1117 if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
1118 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1119 SetRoadTypes(t, ROADTYPES_ROAD);
1121 break;
1123 default: break;
1128 if (IsSavegameVersionBefore(114)) {
1129 bool fix_roadtypes = !IsSavegameVersionBefore(61);
1130 bool old_bridge = IsSavegameVersionBefore(42);
1132 for (TileIndex t = 0; t < map_size; t++) {
1133 switch (GetTileType(t)) {
1134 case MP_ROAD:
1135 if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
1136 SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
1137 switch (GetRoadTileType(t)) {
1138 default: SlErrorCorrupt("Invalid road tile type");
1139 case ROAD_TILE_NORMAL:
1140 SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
1141 SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
1142 SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4)); // tram bits
1143 SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
1144 SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4)); // road bits
1145 break;
1147 case ROAD_TILE_CROSSING:
1148 SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
1149 SB(_me[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
1150 SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
1151 SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1)); // road axis
1152 SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1)); // crossing state
1153 break;
1155 case ROAD_TILE_DEPOT:
1156 break;
1158 if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1159 const Town *town = CalcClosestTownFromTile(t);
1160 if (town != NULL) SetTownIndex(t, town->index);
1162 _m[t].m4 = 0;
1163 break;
1165 case MP_STATION:
1166 if (!IsRoadStop(t)) break;
1168 if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
1169 SB(_me[t].m7, 0, 5, HasBit(_me[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
1170 SB(_m[t].m3, 4, 4, _m[t].m1);
1171 _m[t].m4 = 0;
1172 break;
1174 case MP_TUNNELBRIDGE:
1175 if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
1176 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1177 if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
1179 Owner o = GetTileOwner(t);
1180 SB(_me[t].m7, 0, 5, o); // road owner
1181 SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
1183 SB(_me[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
1184 SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
1186 _m[t].m2 = 0;
1187 _m[t].m4 = 0;
1188 break;
1190 default: break;
1195 if (IsSavegameVersionBefore(42)) {
1196 Vehicle *v;
1198 for (TileIndex t = 0; t < map_size; t++) {
1199 if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
1200 if (IsBridgeTile(t)) {
1201 if (HasBit(_m[t].m5, 6)) { // middle part
1202 Axis axis = (Axis)GB(_m[t].m5, 0, 1);
1204 if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
1205 if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
1206 MakeRailNormal(
1208 GetTileOwner(t),
1209 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
1210 GetRailType(t)
1212 } else {
1213 TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
1215 MakeRoadNormal(
1217 axis == AXIS_X ? ROAD_Y : ROAD_X,
1218 ROADTYPES_ROAD,
1219 town,
1220 GetTileOwner(t), OWNER_NONE
1223 } else {
1224 if (GB(_m[t].m5, 3, 2) == 0) {
1225 MakeClear(t, CLEAR_GRASS, 3);
1226 } else {
1227 if (!IsTileFlat(t)) {
1228 MakeShore(t);
1229 } else {
1230 if (GetTileOwner(t) == OWNER_WATER) {
1231 MakeSea(t);
1232 } else {
1233 MakeCanal(t, GetTileOwner(t), Random());
1238 SetBridgeMiddle(t, axis);
1239 } else { // ramp
1240 Axis axis = (Axis)GB(_m[t].m5, 0, 1);
1241 uint north_south = GB(_m[t].m5, 5, 1);
1242 DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
1243 TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
1245 _m[t].m5 = 1 << 7 | type << 2 | dir;
1250 FOR_ALL_VEHICLES(v) {
1251 if (!v->IsGroundVehicle()) continue;
1252 if (IsBridgeTile(v->tile)) {
1253 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
1255 if (dir != DirToDiagDir(v->direction)) continue;
1256 switch (dir) {
1257 default: SlErrorCorrupt("Invalid vehicle direction");
1258 case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
1259 case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
1260 case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
1261 case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
1263 } else if (v->z_pos > GetSlopePixelZ(v->x_pos, v->y_pos)) {
1264 v->tile = GetNorthernBridgeEnd(v->tile);
1265 } else {
1266 continue;
1268 if (v->type == VEH_TRAIN) {
1269 Train::From(v)->track = TRACK_BIT_WORMHOLE;
1270 } else {
1271 RoadVehicle::From(v)->state = RVSB_WORMHOLE;
1276 /* Elrails got added in rev 24 */
1277 if (IsSavegameVersionBefore(24)) {
1278 RailType min_rail = RAILTYPE_ELECTRIC;
1280 Train *v;
1281 FOR_ALL_TRAINS(v) {
1282 RailType rt = RailVehInfo(v->engine_type)->railtype;
1284 v->railtype = rt;
1285 if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
1288 /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
1289 for (TileIndex t = 0; t < map_size; t++) {
1290 switch (GetTileType(t)) {
1291 case MP_RAILWAY:
1292 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1293 break;
1295 case MP_ROAD:
1296 if (IsLevelCrossing(t)) {
1297 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1299 break;
1301 case MP_STATION:
1302 if (HasStationRail(t)) {
1303 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1305 break;
1307 case MP_TUNNELBRIDGE:
1308 if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
1309 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1311 break;
1313 default:
1314 break;
1318 FOR_ALL_TRAINS(v) {
1319 if (v->IsFrontEngine() || v->IsFreeWagon()) v->ConsistChanged(CCF_TRACK);
1324 /* In version 16.1 of the savegame a company can decide if trains, which get
1325 * replaced, shall keep their old length. In all prior versions, just default
1326 * to false */
1327 if (IsSavegameVersionBefore(16, 1)) {
1328 Company *c;
1329 FOR_ALL_COMPANIES(c) c->settings.renew_keep_length = false;
1332 if (IsSavegameVersionBefore(123)) {
1333 /* Waypoints became subclasses of stations ... */
1334 MoveWaypointsToBaseStations();
1335 /* ... and buoys were moved to waypoints. */
1336 MoveBuoysToWaypoints();
1339 /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
1340 * room for PBS. Now in version 21 move it back :P. */
1341 if (IsSavegameVersionBefore(21) && !IsSavegameVersionBefore(15)) {
1342 for (TileIndex t = 0; t < map_size; t++) {
1343 switch (GetTileType(t)) {
1344 case MP_RAILWAY:
1345 if (HasSignals(t)) {
1346 /* Original signal type/variant was stored in m4 but since saveload
1347 * version 48 they are in m2. The bits has been already moved to m2
1348 * (see the code somewhere above) so don't use m4, use m2 instead. */
1350 /* convert PBS signals to combo-signals */
1351 if (HasBit(_m[t].m2, 2)) SB(_m[t].m2, 0, 2, SIGTYPE_COMBO);
1353 /* move the signal variant back */
1354 SB(_m[t].m2, 2, 1, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1355 ClrBit(_m[t].m2, 3);
1358 /* Clear PBS reservation on track */
1359 if (!IsRailDepotTile(t)) {
1360 SB(_m[t].m4, 4, 4, 0);
1361 } else {
1362 ClrBit(_m[t].m3, 6);
1364 break;
1366 case MP_STATION: // Clear PBS reservation on station
1367 ClrBit(_m[t].m3, 6);
1368 break;
1370 default: break;
1375 if (IsSavegameVersionBefore(25)) {
1376 RoadVehicle *rv;
1377 FOR_ALL_ROADVEHICLES(rv) {
1378 rv->vehstatus &= ~0x40;
1382 if (IsSavegameVersionBefore(26)) {
1383 Station *st;
1384 FOR_ALL_STATIONS(st) {
1385 st->last_vehicle_type = VEH_INVALID;
1389 YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
1391 if (IsSavegameVersionBefore(34)) {
1392 Company *c;
1393 FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
1396 Company *c;
1397 FOR_ALL_COMPANIES(c) {
1398 c->avail_railtypes = GetCompanyRailtypes(c->index);
1399 c->avail_roadtypes = GetCompanyRoadtypes(c->index);
1402 if (!IsSavegameVersionBefore(27)) AfterLoadStations();
1404 /* Time starts at 0 instead of 1920.
1405 * Account for this in older games by adding an offset */
1406 if (IsSavegameVersionBefore(31)) {
1407 Station *st;
1408 Waypoint *wp;
1409 Engine *e;
1410 Industry *i;
1411 Vehicle *v;
1413 _date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1414 _cur_year += ORIGINAL_BASE_YEAR;
1416 FOR_ALL_STATIONS(st) st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1417 FOR_ALL_WAYPOINTS(wp) wp->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1418 FOR_ALL_ENGINES(e) e->intro_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
1419 FOR_ALL_COMPANIES(c) c->inaugurated_year += ORIGINAL_BASE_YEAR;
1420 FOR_ALL_INDUSTRIES(i) i->last_prod_year += ORIGINAL_BASE_YEAR;
1422 FOR_ALL_VEHICLES(v) {
1423 v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
1424 v->build_year += ORIGINAL_BASE_YEAR;
1428 /* From 32 on we save the industry who made the farmland.
1429 * To give this prettiness to old savegames, we remove all farmfields and
1430 * plant new ones. */
1431 if (IsSavegameVersionBefore(32)) {
1432 Industry *i;
1434 for (TileIndex t = 0; t < map_size; t++) {
1435 if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
1436 /* remove fields */
1437 MakeClear(t, CLEAR_GRASS, 3);
1441 FOR_ALL_INDUSTRIES(i) {
1442 uint j;
1444 if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
1445 for (j = 0; j != 50; j++) PlantRandomFarmField(i);
1450 /* Setting no refit flags to all orders in savegames from before refit in orders were added */
1451 if (IsSavegameVersionBefore(36)) {
1452 Order *order;
1453 Vehicle *v;
1455 FOR_ALL_ORDERS(order) {
1456 order->SetRefit(CT_NO_REFIT);
1459 FOR_ALL_VEHICLES(v) {
1460 v->current_order.SetRefit(CT_NO_REFIT);
1464 /* from version 38 we have optional elrails, since we cannot know the
1465 * preference of a user, let elrails enabled; it can be disabled manually */
1466 if (IsSavegameVersionBefore(38)) _settings_game.vehicle.disable_elrails = false;
1467 /* do the same as when elrails were enabled/disabled manually just now */
1468 SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
1469 InitializeRailGUI();
1471 /* From version 53, the map array was changed for house tiles to allow
1472 * space for newhouses grf features. A new byte, m7, was also added. */
1473 if (IsSavegameVersionBefore(53)) {
1474 for (TileIndex t = 0; t < map_size; t++) {
1475 if (IsTileType(t, MP_HOUSE)) {
1476 if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
1477 /* Move the construction stage from m3[7..6] to m5[5..4].
1478 * The construction counter does not have to move. */
1479 SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
1480 SB(_m[t].m3, 6, 2, 0);
1482 /* The "house is completed" bit is now in m6[2]. */
1483 SetHouseCompleted(t, false);
1484 } else {
1485 /* The "lift has destination" bit has been moved from
1486 * m5[7] to m7[0]. */
1487 SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
1488 ClrBit(_m[t].m5, 7);
1490 /* The "lift is moving" bit has been removed, as it does
1491 * the same job as the "lift has destination" bit. */
1492 ClrBit(_m[t].m1, 7);
1494 /* The position of the lift goes from m1[7..0] to m6[7..2],
1495 * making m1 totally free, now. The lift position does not
1496 * have to be a full byte since the maximum value is 36. */
1497 SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
1499 _m[t].m1 = 0;
1500 _m[t].m3 = 0;
1501 SetHouseCompleted(t, true);
1507 /* Check and update house and town values */
1508 UpdateHousesAndTowns();
1510 if (IsSavegameVersionBefore(43)) {
1511 for (TileIndex t = 0; t < map_size; t++) {
1512 if (IsTileType(t, MP_INDUSTRY)) {
1513 switch (GetIndustryGfx(t)) {
1514 case GFX_POWERPLANT_SPARKS:
1515 _m[t].m3 = GB(_m[t].m1, 2, 5);
1516 break;
1518 case GFX_OILWELL_ANIMATED_1:
1519 case GFX_OILWELL_ANIMATED_2:
1520 case GFX_OILWELL_ANIMATED_3:
1521 _m[t].m3 = GB(_m[t].m1, 0, 2);
1522 break;
1524 case GFX_COAL_MINE_TOWER_ANIMATED:
1525 case GFX_COPPER_MINE_TOWER_ANIMATED:
1526 case GFX_GOLD_MINE_TOWER_ANIMATED:
1527 _m[t].m3 = _m[t].m1;
1528 break;
1530 default: // No animation states to change
1531 break;
1537 if (IsSavegameVersionBefore(45)) {
1538 Vehicle *v;
1539 /* Originally just the fact that some cargo had been paid for was
1540 * stored to stop people cheating and cashing in several times. This
1541 * wasn't enough though as it was cleared when the vehicle started
1542 * loading again, even if it didn't actually load anything, so now the
1543 * amount that has been paid is stored. */
1544 FOR_ALL_VEHICLES(v) {
1545 ClrBit(v->vehicle_flags, 2);
1549 /* Buoys do now store the owner of the previous water tile, which can never
1550 * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
1551 if (IsSavegameVersionBefore(46)) {
1552 Waypoint *wp;
1553 FOR_ALL_WAYPOINTS(wp) {
1554 if ((wp->facilities & FACIL_DOCK) != 0 && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
1558 if (IsSavegameVersionBefore(50)) {
1559 Aircraft *v;
1560 /* Aircraft units changed from 8 mph to 1 km-ish/h */
1561 FOR_ALL_AIRCRAFT(v) {
1562 if (v->subtype <= AIR_AIRCRAFT) {
1563 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
1564 v->cur_speed *= 128;
1565 v->cur_speed /= 10;
1566 v->acceleration = avi->acceleration;
1571 if (IsSavegameVersionBefore(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
1573 if (IsSavegameVersionBefore(52)) {
1574 for (TileIndex t = 0; t < map_size; t++) {
1575 if (IsTileType(t, MP_OBJECT) && _m[t].m5 == OBJECT_STATUE) {
1576 _m[t].m2 = CalcClosestTownFromTile(t)->index;
1581 /* A setting containing the proportion of towns that grow twice as
1582 * fast was added in version 54. From version 56 this is now saved in the
1583 * town as cities can be built specifically in the scenario editor. */
1584 if (IsSavegameVersionBefore(56)) {
1585 Town *t;
1587 FOR_ALL_TOWNS(t) {
1588 if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
1589 t->larger_town = true;
1594 if (IsSavegameVersionBefore(57)) {
1595 Vehicle *v;
1596 /* Added a FIFO queue of vehicles loading at stations */
1597 FOR_ALL_VEHICLES(v) {
1598 if ((v->type != VEH_TRAIN || Train::From(v)->IsFrontEngine()) && // for all locs
1599 !(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
1600 v->current_order.IsType(OT_LOADING)) { // loading
1601 Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
1603 /* The loading finished flag is *only* set when actually completely
1604 * finished. Because the vehicle is loading, it is not finished. */
1605 ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
1608 } else if (IsSavegameVersionBefore(59)) {
1609 /* For some reason non-loading vehicles could be in the station's loading vehicle list */
1611 Station *st;
1612 FOR_ALL_STATIONS(st) {
1613 st->loading_vehicles.erase(std::remove_if(st->loading_vehicles.begin(), st->loading_vehicles.end(),
1614 [](Vehicle *v) {
1615 return !v->current_order.IsType(OT_LOADING);
1616 }), st->loading_vehicles.end());
1620 if (IsSavegameVersionBefore(58)) {
1621 /* Setting difficulty industry_density other than zero get bumped to +1
1622 * since a new option (very low at position 1) has been added */
1623 if (_settings_game.difficulty.industry_density > 0) {
1624 _settings_game.difficulty.industry_density++;
1627 /* Same goes for number of towns, although no test is needed, just an increment */
1628 _settings_game.difficulty.number_towns++;
1631 if (IsSavegameVersionBefore(64)) {
1632 /* Since now we allow different signal types and variants on a single tile.
1633 * Move signal states to m4 to make room and clone the signal type/variant. */
1634 for (TileIndex t = 0; t < map_size; t++) {
1635 if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
1636 /* move signal states */
1637 SetSignalStates(t, GB(_m[t].m2, 4, 4));
1638 SB(_m[t].m2, 4, 4, 0);
1639 /* clone signal type and variant */
1640 SB(_m[t].m2, 4, 3, GB(_m[t].m2, 0, 3));
1645 if (IsSavegameVersionBefore(69)) {
1646 /* In some old savegames a bit was cleared when it should not be cleared */
1647 RoadVehicle *rv;
1648 FOR_ALL_ROADVEHICLES(rv) {
1649 if (rv->state == 250 || rv->state == 251) {
1650 SetBit(rv->state, 2);
1655 if (IsSavegameVersionBefore(70)) {
1656 /* Added variables to support newindustries */
1657 Industry *i;
1658 FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
1661 /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
1662 Replace the owner for those by OWNER_NONE. */
1663 if (IsSavegameVersionBefore(82)) {
1664 for (TileIndex t = 0; t < map_size; t++) {
1665 if (IsTileType(t, MP_WATER) &&
1666 GetWaterTileType(t) == WATER_TILE_CLEAR &&
1667 GetTileOwner(t) == OWNER_WATER &&
1668 TileHeight(t) != 0) {
1669 SetTileOwner(t, OWNER_NONE);
1675 * Add the 'previous' owner to the ship depots so we can reset it with
1676 * the correct values when it gets destroyed. This prevents that
1677 * someone can remove canals owned by somebody else and it prevents
1678 * making floods using the removal of ship depots.
1680 if (IsSavegameVersionBefore(83)) {
1681 for (TileIndex t = 0; t < map_size; t++) {
1682 if (IsShipDepotTile(t)) {
1683 _m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
1688 if (IsSavegameVersionBefore(74)) {
1689 Station *st;
1690 FOR_ALL_STATIONS(st) {
1691 for (CargoID c = 0; c < NUM_CARGO; c++) {
1692 st->goods[c].last_speed = 0;
1693 if (st->goods[c].cargo.AvailableCount() != 0) SetBit(st->goods[c].status, GoodsEntry::GES_RATING);
1698 if (IsSavegameVersionBefore(78)) {
1699 Industry *i;
1700 uint j;
1701 FOR_ALL_INDUSTRIES(i) {
1702 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1703 for (j = 0; j < lengthof(i->produced_cargo); j++) {
1704 i->produced_cargo[j] = indsp->produced_cargo[j];
1706 for (j = 0; j < lengthof(i->accepts_cargo); j++) {
1707 i->accepts_cargo[j] = indsp->accepts_cargo[j];
1712 /* Before version 81, the density of grass was always stored as zero, and
1713 * grassy trees were always drawn fully grassy. Furthermore, trees on rough
1714 * land used to have zero density, now they have full density. Therefore,
1715 * make all grassy/rough land trees have a density of 3. */
1716 if (IsSavegameVersionBefore(81)) {
1717 for (TileIndex t = 0; t < map_size; t++) {
1718 if (GetTileType(t) == MP_TREES) {
1719 TreeGround groundType = (TreeGround)GB(_m[t].m2, 4, 2);
1720 if (groundType != TREE_GROUND_SNOW_DESERT) SB(_m[t].m2, 6, 2, 3);
1726 if (IsSavegameVersionBefore(93)) {
1727 /* Rework of orders. */
1728 Order *order;
1729 FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
1731 Vehicle *v;
1732 FOR_ALL_VEHICLES(v) {
1733 if (v->HasOrdersList() && v->GetFirstOrder() != nullptr && v->GetFirstOrder()->IsType(OT_NOTHING)) {
1734 v->FreeOrderChain();
1737 v->current_order.ConvertFromOldSavegame();
1738 if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
1739 FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
1742 } else if (IsSavegameVersionBefore(94)) {
1743 /* Unload and transfer are now mutual exclusive. */
1744 Order *order;
1745 FOR_ALL_ORDERS(order) {
1746 if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1747 order->SetUnloadType(OUFB_TRANSFER);
1748 order->SetLoadType(OLFB_NO_LOAD);
1752 Vehicle *v;
1753 FOR_ALL_VEHICLES(v) {
1754 if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
1755 v->current_order.SetUnloadType(OUFB_TRANSFER);
1756 v->current_order.SetLoadType(OLFB_NO_LOAD);
1761 if (IsSavegameVersionBefore(84)) {
1762 /* Set all share owners to INVALID_COMPANY for
1763 * 1) all inactive companies
1764 * (when inactive companies were stored in the savegame - TTD, TTDP and some
1765 * *really* old revisions of OTTD; else it is already set in InitializeCompanies())
1766 * 2) shares that are owned by inactive companies or self
1767 * (caused by cheating clients in earlier revisions) */
1768 FOR_ALL_COMPANIES(c) {
1769 for (uint i = 0; i < 4; i++) {
1770 CompanyID company = c->share_owners[i];
1771 if (company == INVALID_COMPANY) continue;
1772 if (!Company::IsValidID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
1777 /* The water class was moved/unified. */
1778 if (IsSavegameVersionBefore(146)) {
1779 for (TileIndex t = 0; t < map_size; t++) {
1780 switch (GetTileType(t)) {
1781 case MP_STATION:
1782 switch (GetStationType(t)) {
1783 case STATION_OILRIG:
1784 case STATION_DOCK:
1785 case STATION_BUOY:
1786 SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
1787 SB(_m[t].m3, 0, 2, 0);
1788 break;
1790 default:
1791 SetWaterClass(t, WATER_CLASS_INVALID);
1792 break;
1794 break;
1796 case MP_WATER:
1797 SetWaterClass(t, (WaterClass)GB(_m[t].m3, 0, 2));
1798 SB(_m[t].m3, 0, 2, 0);
1799 break;
1801 case MP_OBJECT:
1802 SetWaterClass(t, WATER_CLASS_INVALID);
1803 break;
1805 default:
1806 /* No water class. */
1807 break;
1812 if (IsSavegameVersionBefore(86)) {
1813 for (TileIndex t = 0; t < map_size; t++) {
1814 /* Move river flag and update canals to use water class */
1815 if (IsTileType(t, MP_WATER)) {
1816 if (GetWaterClass(t) != WATER_CLASS_RIVER) {
1817 if (IsWater(t)) {
1818 Owner o = GetTileOwner(t);
1819 if (o == OWNER_WATER) {
1820 MakeSea(t);
1821 } else {
1822 MakeCanal(t, o, Random());
1824 } else if (IsShipDepot(t)) {
1825 Owner o = (Owner)_m[t].m4; // Original water owner
1826 SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
1832 /* Update locks, depots, docks and buoys to have a water class based
1833 * on its neighbouring tiles. Done after river and canal updates to
1834 * ensure neighbours are correct. */
1835 for (TileIndex t = 0; t < map_size; t++) {
1836 if (!IsTileFlat(t)) continue;
1838 if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
1839 if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
1843 if (IsSavegameVersionBefore(87)) {
1844 for (TileIndex t = 0; t < map_size; t++) {
1845 /* skip oil rigs at borders! */
1846 if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
1847 (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
1848 /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
1849 * This conversion has to be done before buoys with invalid owner are removed. */
1850 SetWaterClass(t, WATER_CLASS_SEA);
1853 if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
1854 Owner o = GetTileOwner(t);
1855 if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
1856 Backup<CompanyByte> cur_company(_current_company, o, FILE_LINE);
1857 ChangeTileOwner(t, o, INVALID_OWNER);
1858 cur_company.Restore();
1860 if (IsBuoyTile(t)) {
1861 /* reset buoy owner to OWNER_NONE in the station struct
1862 * (even if it is owned by active company) */
1863 Waypoint::GetByTile(t)->owner = OWNER_NONE;
1865 } else if (IsTileType(t, MP_ROAD)) {
1866 /* works for all RoadTileType */
1867 for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
1868 /* update even non-existing road types to update tile owner too */
1869 Owner o = GetRoadOwner(t, rt);
1870 if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rt, OWNER_NONE);
1872 if (IsLevelCrossing(t)) {
1873 if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
1875 } else if (IsPlainRailTile(t)) {
1876 if (!Company::IsValidID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
1880 /* Convert old PF settings to new */
1881 if (_settings_game.pf.yapf.rail_use_yapf || IsSavegameVersionBefore(28)) {
1882 _settings_game.pf.pathfinder_for_trains = VPF_YAPF;
1883 } else {
1884 _settings_game.pf.pathfinder_for_trains = VPF_NPF;
1887 if (_settings_game.pf.yapf.road_use_yapf || IsSavegameVersionBefore(28)) {
1888 _settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
1889 } else {
1890 _settings_game.pf.pathfinder_for_roadvehs = VPF_NPF;
1893 if (_settings_game.pf.yapf.ship_use_yapf) {
1894 _settings_game.pf.pathfinder_for_ships = VPF_YAPF;
1895 } else {
1896 _settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
1900 if (IsSavegameVersionBefore(88)) {
1901 /* Profits are now with 8 bit fract */
1902 Vehicle *v;
1903 FOR_ALL_VEHICLES(v) {
1904 v->profit_this_year <<= 8;
1905 v->profit_last_year <<= 8;
1906 v->running_ticks = 0;
1910 if (IsSavegameVersionBefore(91)) {
1911 /* Increase HouseAnimationFrame from 5 to 7 bits */
1912 for (TileIndex t = 0; t < map_size; t++) {
1913 if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
1914 SB(_me[t].m6, 2, 6, GB(_me[t].m6, 3, 5));
1915 SB(_m[t].m3, 5, 1, 0);
1920 if (IsSavegameVersionBefore(62)) {
1921 /* Remove all trams from savegames without tram support.
1922 * There would be trams without tram track under causing crashes sooner or later. */
1923 RoadVehicle *v;
1924 FOR_ALL_ROADVEHICLES(v) {
1925 if (v->First() == v && HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
1926 ShowErrorMessage(STR_WARNING_LOADGAME_REMOVED_TRAMS, INVALID_STRING_ID, WL_CRITICAL);
1927 delete v;
1932 if (IsSavegameVersionBefore(99)) {
1933 for (TileIndex t = 0; t < map_size; t++) {
1934 /* Set newly introduced WaterClass of industry tiles */
1935 if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
1936 SetWaterClassDependingOnSurroundings(t, true);
1938 if (IsTileType(t, MP_INDUSTRY)) {
1939 if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
1940 SetWaterClassDependingOnSurroundings(t, true);
1941 } else {
1942 SetWaterClass(t, WATER_CLASS_INVALID);
1946 /* Replace "house construction year" with "house age" */
1947 if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
1948 _m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
1953 /* Tunnel pool has to be initiated before reservations. */
1954 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_19)) {
1955 for (TileIndex t = 0; t < map_size; t++) {
1956 if (IsTunnelTile(t)) {
1957 DiagDirection dir = GetTunnelBridgeDirection(t);
1958 if (dir == DIAGDIR_SE || dir == DIAGDIR_SW) {
1959 TileIndex start_tile = t;
1960 TileIndex end_tile = GetOtherTunnelBridgeEndOld(start_tile);
1962 if (!Tunnel::CanAllocateItem()) {
1963 SetSaveLoadError(STR_ERROR_TUNNEL_TOO_MANY);
1964 /* Restore the signals */
1965 ResetSignalHandlers();
1966 return false;
1969 const Tunnel *t = new Tunnel(start_tile, end_tile, TileHeight(start_tile), false);
1971 SetTunnelIndex(start_tile, t->index);
1972 SetTunnelIndex(end_tile, t->index);
1978 /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
1979 * format here, as an old layout wouldn't work properly anyway. To be safe, we
1980 * clear any possible PBS reservations as well. */
1981 if (IsSavegameVersionBefore(100)) {
1982 for (TileIndex t = 0; t < map_size; t++) {
1983 switch (GetTileType(t)) {
1984 case MP_RAILWAY:
1985 if (HasSignals(t)) {
1986 /* move the signal variant */
1987 SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1988 SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1989 ClrBit(_m[t].m2, 2);
1990 ClrBit(_m[t].m2, 6);
1993 /* Clear PBS reservation on track */
1994 if (IsRailDepot(t)) {
1995 SetDepotReservation(t, false);
1996 } else {
1997 SetTrackReservation(t, TRACK_BIT_NONE);
1999 break;
2001 case MP_ROAD: // Clear PBS reservation on crossing
2002 if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
2003 break;
2005 case MP_STATION: // Clear PBS reservation on station
2006 if (HasStationRail(t)) SetRailStationReservation(t, false);
2007 break;
2009 case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/bridges
2010 if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
2011 break;
2013 default: break;
2018 /* Reserve all tracks trains are currently on. */
2019 if (IsSavegameVersionBefore(101)) {
2020 const Train *t;
2021 FOR_ALL_TRAINS(t) {
2022 if (t->First() == t) t->ReserveTrackUnderConsist();
2026 if (IsSavegameVersionBefore(102)) {
2027 for (TileIndex t = 0; t < map_size; t++) {
2028 /* Now all crossings should be in correct state */
2029 if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
2033 if (IsSavegameVersionBefore(103)) {
2034 /* Non-town-owned roads now store the closest town */
2035 UpdateNearestTownForRoadTiles(false);
2037 /* signs with invalid owner left from older savegames */
2038 Sign *si;
2039 FOR_ALL_SIGNS(si) {
2040 if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
2043 /* Station can get named based on an industry type, but the current ones
2044 * are not, so mark them as if they are not named by an industry. */
2045 Station *st;
2046 FOR_ALL_STATIONS(st) {
2047 st->indtype = IT_INVALID;
2051 if (IsSavegameVersionBefore(104)) {
2052 Aircraft *a;
2053 FOR_ALL_AIRCRAFT(a) {
2054 /* Set engine_type of shadow and rotor */
2055 if (!a->IsNormalAircraft()) {
2056 a->engine_type = a->First()->engine_type;
2060 /* More companies ... */
2061 Company *c;
2062 FOR_ALL_COMPANIES(c) {
2063 if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
2066 Engine *e;
2067 FOR_ALL_ENGINES(e) {
2068 if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
2071 Town *t;
2072 FOR_ALL_TOWNS(t) {
2073 if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
2074 for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
2078 if (IsSavegameVersionBefore(112)) {
2079 for (TileIndex t = 0; t < map_size; t++) {
2080 /* Check for HQ bit being set, instead of using map accessor,
2081 * since we've already changed it code-wise */
2082 if (IsTileType(t, MP_OBJECT) && HasBit(_m[t].m5, 7)) {
2083 /* Move size and part identification of HQ out of the m5 attribute,
2084 * on new locations */
2085 _m[t].m3 = GB(_m[t].m5, 0, 5);
2086 _m[t].m5 = OBJECT_HQ;
2090 if (IsSavegameVersionBefore(144)) {
2091 for (TileIndex t = 0; t < map_size; t++) {
2092 if (!IsTileType(t, MP_OBJECT)) continue;
2094 /* Reordering/generalisation of the object bits. */
2095 ObjectType type = _m[t].m5;
2096 SB(_me[t].m6, 2, 4, type == OBJECT_HQ ? GB(_m[t].m3, 2, 3) : 0);
2097 _m[t].m3 = type == OBJECT_HQ ? GB(_m[t].m3, 1, 1) | GB(_m[t].m3, 0, 1) << 4 : 0;
2099 /* Make sure those bits are clear as well! */
2100 _m[t].m4 = 0;
2101 _me[t].m7 = 0;
2105 if (IsSavegameVersionBefore(147) && Object::GetNumItems() == 0) {
2106 /* Make real objects for object tiles. */
2107 for (TileIndex t = 0; t < map_size; t++) {
2108 if (!IsTileType(t, MP_OBJECT)) continue;
2110 if (Town::GetNumItems() == 0) {
2111 /* No towns, so remove all objects! */
2112 DoClearSquare(t);
2113 } else {
2114 uint offset = _m[t].m3;
2116 /* Also move the animation state. */
2117 _m[t].m3 = GB(_me[t].m6, 2, 4);
2118 SB(_me[t].m6, 2, 4, 0);
2120 if (offset == 0) {
2121 /* No offset, so make the object. */
2122 ObjectType type = _m[t].m5;
2123 int size = type == OBJECT_HQ ? 2 : 1;
2125 if (!Object::CanAllocateItem()) {
2126 /* Nice... you managed to place 64k lighthouses and
2127 * antennae on the map... boohoo. */
2128 SlError(STR_ERROR_TOO_MANY_OBJECTS);
2131 Object *o = new Object();
2132 o->location.tile = t;
2133 o->location.w = size;
2134 o->location.h = size;
2135 o->build_date = _date;
2136 o->town = type == OBJECT_STATUE ? Town::Get(_m[t].m2) : CalcClosestTownFromTile(t, UINT_MAX);
2137 _m[t].m2 = o->index;
2138 Object::IncTypeCount(type);
2139 } else {
2140 /* We're at an offset, so get the ID from our "root". */
2141 TileIndex northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
2142 assert(IsTileType(northern_tile, MP_OBJECT));
2143 _m[t].m2 = _m[northern_tile].m2;
2149 if (IsSavegameVersionBefore(113)) {
2150 /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
2151 if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
2152 _settings_game.economy.allow_town_roads = false;
2153 _settings_game.economy.town_layout = TL_BETTER_ROADS;
2154 } else {
2155 _settings_game.economy.allow_town_roads = true;
2156 _settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
2159 /* Initialize layout of all towns. Older versions were using different
2160 * generator for random town layout, use it if needed. */
2161 Town *t;
2162 FOR_ALL_TOWNS(t) {
2163 if (_settings_game.economy.town_layout != TL_RANDOM) {
2164 t->layout = _settings_game.economy.town_layout;
2165 continue;
2168 /* Use old layout randomizer code */
2169 byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
2170 switch (layout) {
2171 default: break;
2172 case 5: layout = 1; break;
2173 case 0: layout = 2; break;
2175 t->layout = layout - 1;
2179 if (IsSavegameVersionBefore(114)) {
2180 /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
2181 * The conversion affects oil rigs and buoys too, but it doesn't matter as
2182 * they have st->owner == OWNER_NONE already. */
2183 Station *st;
2184 FOR_ALL_STATIONS(st) {
2185 if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
2189 /* Trains could now stop in a specific location. */
2190 if (IsSavegameVersionBefore(117)) {
2191 Order *o;
2192 FOR_ALL_ORDERS(o) {
2193 if (o->IsType(OT_GOTO_STATION)) o->SetStopLocation(OSL_PLATFORM_FAR_END);
2197 if (IsSavegameVersionBefore(120)) {
2198 extern VehicleDefaultSettings _old_vds;
2199 Company *c;
2200 FOR_ALL_COMPANIES(c) {
2201 c->settings.vehicle = _old_vds;
2205 if (IsSavegameVersionBefore(121)) {
2206 /* Delete small ufos heading for non-existing vehicles */
2207 Vehicle *v;
2208 FOR_ALL_DISASTERVEHICLES(v) {
2209 if (v->subtype == 2 /* ST_SMALL_UFO */ && v->current_order.GetDestination() != 0) {
2210 const Vehicle *u = Vehicle::GetIfValid(v->dest_tile);
2211 if (u == NULL || u->type != VEH_ROAD || !RoadVehicle::From(u)->IsFrontEngine()) {
2212 delete v;
2217 /* We didn't store cargo payment yet, so make them for vehicles that are
2218 * currently at a station and loading/unloading. If they don't get any
2219 * payment anymore they just removed in the next load/unload cycle.
2220 * However, some 0.7 versions might have cargo payment. For those we just
2221 * add cargopayment for the vehicles that don't have it.
2223 Station *st;
2224 FOR_ALL_STATIONS(st) {
2225 for (Vehicle *v : st->loading_vehicles) {
2226 /* There are always as many CargoPayments as Vehicles. We need to make the
2227 * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
2228 assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE);
2229 assert(CargoPayment::CanAllocateItem());
2230 if (v->cargo_payment == NULL) v->cargo_payment = new CargoPayment(v);
2235 if (IsSavegameVersionBefore(122)) {
2236 /* Animated tiles would sometimes not be actually animated or
2237 * in case of old savegames duplicate. */
2239 extern TileIndex *_animated_tile_list;
2240 extern uint _animated_tile_count;
2242 for (uint i = 0; i < _animated_tile_count; /* Nothing */) {
2243 /* Remove if tile is not animated */
2244 bool remove = _tile_type_procs[GetTileType(_animated_tile_list[i])]->animate_tile_proc == NULL;
2246 /* and remove if duplicate */
2247 for (uint j = 0; !remove && j < i; j++) {
2248 remove = _animated_tile_list[i] == _animated_tile_list[j];
2251 if (remove) {
2252 DeleteAnimatedTile(_animated_tile_list[i]);
2253 } else {
2254 i++;
2259 if (IsSavegameVersionBefore(124) && !IsSavegameVersionBefore(1)) {
2260 /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
2261 Waypoint *wp;
2262 FOR_ALL_WAYPOINTS(wp) {
2263 if (wp->facilities & FACIL_TRAIN) {
2264 wp->train_station.tile = wp->xy;
2265 wp->train_station.w = 1;
2266 wp->train_station.h = 1;
2267 } else {
2268 wp->train_station.tile = INVALID_TILE;
2269 wp->train_station.w = 0;
2270 wp->train_station.h = 0;
2275 if (IsSavegameVersionBefore(125)) {
2276 /* Convert old subsidies */
2277 Subsidy *s;
2278 FOR_ALL_SUBSIDIES(s) {
2279 if (s->remaining < 12) {
2280 /* Converting nonawarded subsidy */
2281 s->remaining = 12 - s->remaining; // convert "age" to "remaining"
2282 s->awarded = INVALID_COMPANY; // not awarded to anyone
2283 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2284 switch (cs->town_effect) {
2285 case TE_PASSENGERS:
2286 case TE_MAIL:
2287 /* Town -> Town */
2288 s->src_type = s->dst_type = ST_TOWN;
2289 if (Town::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2290 break;
2291 case TE_GOODS:
2292 case TE_FOOD:
2293 /* Industry -> Town */
2294 s->src_type = ST_INDUSTRY;
2295 s->dst_type = ST_TOWN;
2296 if (Industry::IsValidID(s->src) && Town::IsValidID(s->dst)) continue;
2297 break;
2298 default:
2299 /* Industry -> Industry */
2300 s->src_type = s->dst_type = ST_INDUSTRY;
2301 if (Industry::IsValidID(s->src) && Industry::IsValidID(s->dst)) continue;
2302 break;
2304 } else {
2305 /* Do our best for awarded subsidies. The original source or destination industry
2306 * can't be determined anymore for awarded subsidies, so invalidate them.
2307 * Town -> Town subsidies are converted using simple heuristic */
2308 s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
2309 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2310 switch (cs->town_effect) {
2311 case TE_PASSENGERS:
2312 case TE_MAIL: {
2313 /* Town -> Town */
2314 const Station *ss = Station::GetIfValid(s->src);
2315 const Station *sd = Station::GetIfValid(s->dst);
2316 if (ss != NULL && sd != NULL && ss->owner == sd->owner &&
2317 Company::IsValidID(ss->owner)) {
2318 s->src_type = s->dst_type = ST_TOWN;
2319 s->src = ss->town->index;
2320 s->dst = sd->town->index;
2321 s->awarded = ss->owner;
2322 continue;
2324 break;
2326 default:
2327 break;
2330 /* Awarded non-town subsidy or invalid source/destination, invalidate */
2331 delete s;
2335 if (IsSavegameVersionBefore(126)) {
2336 /* Recompute inflation based on old unround loan limit
2337 * Note: Max loan is 500000. With an inflation of 4% across 170 years
2338 * that results in a max loan of about 0.7 * 2^31.
2339 * So taking the 16 bit fractional part into account there are plenty of bits left
2340 * for unmodified savegames ...
2342 uint64 aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
2344 /* ... well, just clamp it then. */
2345 if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
2347 /* Simulate the inflation, so we also get the payment inflation */
2348 while (_economy.inflation_prices < aimed_inflation) {
2349 if (AddInflation(false)) break;
2353 if (IsSavegameVersionBefore(128)) {
2354 const Depot *d;
2355 FOR_ALL_DEPOTS(d) {
2356 _m[d->xy].m2 = d->index;
2357 if (IsTileType(d->xy, MP_WATER)) _m[GetOtherShipDepotTile(d->xy)].m2 = d->index;
2361 /* The behaviour of force_proceed has been changed. Now
2362 * it counts signals instead of some random time out. */
2363 if (IsSavegameVersionBefore(131)) {
2364 Train *t;
2365 FOR_ALL_TRAINS(t) {
2366 if (t->force_proceed != TFP_NONE) {
2367 t->force_proceed = TFP_STUCK;
2372 /* The bits for the tree ground and tree density have
2373 * been swapped (m2 bits 7..6 and 5..4. */
2374 if (IsSavegameVersionBefore(135)) {
2375 for (TileIndex t = 0; t < map_size; t++) {
2376 if (IsTileType(t, MP_CLEAR)) {
2377 if (GetRawClearGround(t) == CLEAR_SNOW) {
2378 SetClearGroundDensity(t, CLEAR_GRASS, GetClearDensity(t));
2379 SetBit(_m[t].m3, 4);
2380 } else {
2381 ClrBit(_m[t].m3, 4);
2384 if (IsTileType(t, MP_TREES)) {
2385 uint density = GB(_m[t].m2, 6, 2);
2386 uint ground = GB(_m[t].m2, 4, 2);
2387 uint counter = GB(_m[t].m2, 0, 4);
2388 _m[t].m2 = ground << 6 | density << 4 | counter;
2393 /* Wait counter and load/unload ticks got split. */
2394 if (IsSavegameVersionBefore(136)) {
2395 Aircraft *a;
2396 FOR_ALL_AIRCRAFT(a) {
2397 a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
2400 Train *t;
2401 FOR_ALL_TRAINS(t) {
2402 t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
2406 /* Airport tile animation uses animation frame instead of other graphics id */
2407 if (IsSavegameVersionBefore(137)) {
2408 struct AirportTileConversion {
2409 byte old_start;
2410 byte num_frames;
2412 static const AirportTileConversion atc[] = {
2413 {31, 12}, // APT_RADAR_GRASS_FENCE_SW
2414 {50, 4}, // APT_GRASS_FENCE_NE_FLAG
2415 {62, 2}, // 1 unused tile
2416 {66, 12}, // APT_RADAR_FENCE_SW
2417 {78, 12}, // APT_RADAR_FENCE_NE
2418 {101, 10}, // 9 unused tiles
2419 {111, 8}, // 7 unused tiles
2420 {119, 15}, // 14 unused tiles (radar)
2421 {140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
2423 for (TileIndex t = 0; t < map_size; t++) {
2424 if (IsAirportTile(t)) {
2425 StationGfx old_gfx = GetStationGfx(t);
2426 byte offset = 0;
2427 for (uint i = 0; i < lengthof(atc); i++) {
2428 if (old_gfx < atc[i].old_start) {
2429 SetStationGfx(t, old_gfx - offset);
2430 break;
2432 if (old_gfx < atc[i].old_start + atc[i].num_frames) {
2433 SetAnimationFrame(t, old_gfx - atc[i].old_start);
2434 SetStationGfx(t, atc[i].old_start - offset);
2435 break;
2437 offset += atc[i].num_frames - 1;
2443 if (IsSavegameVersionBefore(140)) {
2444 Station *st;
2445 FOR_ALL_STATIONS(st) {
2446 if (st->airport.tile != INVALID_TILE) {
2447 st->airport.w = st->airport.GetSpec()->size_x;
2448 st->airport.h = st->airport.GetSpec()->size_y;
2453 if (IsSavegameVersionBefore(141)) {
2454 for (TileIndex t = 0; t < map_size; t++) {
2455 /* Reset tropic zone for VOID tiles, they shall not have any. */
2456 if (IsTileType(t, MP_VOID)) SetTropicZone(t, TROPICZONE_NORMAL);
2459 /* We need to properly number/name the depots.
2460 * The first step is making sure none of the depots uses the
2461 * 'default' names, after that we can assign the names. */
2462 Depot *d;
2463 FOR_ALL_DEPOTS(d) d->town_cn = UINT16_MAX;
2465 FOR_ALL_DEPOTS(d) MakeDefaultName(d);
2468 if (IsSavegameVersionBefore(142)) {
2469 Depot *d;
2470 FOR_ALL_DEPOTS(d) d->build_date = _date;
2473 /* In old versions it was possible to remove an airport while a plane was
2474 * taking off or landing. This gives all kind of problems when building
2475 * another airport in the same station so we don't allow that anymore.
2476 * For old savegames with such aircraft we just throw them in the air and
2477 * treat the aircraft like they were flying already. */
2478 if (IsSavegameVersionBefore(146)) {
2479 Aircraft *v;
2480 FOR_ALL_AIRCRAFT(v) {
2481 if (!v->IsNormalAircraft()) continue;
2482 Station *st = GetTargetAirportIfValid(v);
2483 if (st == NULL && v->state != FLYING) {
2484 v->state = FLYING;
2485 UpdateAircraftCache(v);
2486 AircraftNextAirportPos_and_Order(v);
2487 /* get aircraft back on running altitude */
2488 if ((v->vehstatus & VS_CRASHED) == 0) {
2489 GetAircraftFlightLevelBounds(v, &v->z_pos, NULL);
2490 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
2496 /* Move the animation frame to the same location (m7) for all objects. */
2497 if (IsSavegameVersionBefore(147)) {
2498 for (TileIndex t = 0; t < map_size; t++) {
2499 switch (GetTileType(t)) {
2500 case MP_HOUSE:
2501 if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
2502 uint per_proc = _me[t].m7;
2503 _me[t].m7 = GB(_me[t].m6, 2, 6) | (GB(_m[t].m3, 5, 1) << 6);
2504 SB(_m[t].m3, 5, 1, 0);
2505 SB(_me[t].m6, 2, 6, min(per_proc, 63));
2507 break;
2509 case MP_INDUSTRY: {
2510 uint rand = _me[t].m7;
2511 _me[t].m7 = _m[t].m3;
2512 _m[t].m3 = rand;
2513 break;
2516 case MP_OBJECT:
2517 _me[t].m7 = _m[t].m3;
2518 _m[t].m3 = 0;
2519 break;
2521 default:
2522 /* For stations/airports it's already at m7 */
2523 break;
2528 /* Add (random) colour to all objects. */
2529 if (IsSavegameVersionBefore(148)) {
2530 Object *o;
2531 FOR_ALL_OBJECTS(o) {
2532 Owner owner = GetTileOwner(o->location.tile);
2533 o->colour = (owner == OWNER_NONE) ? Random() & 0xF : Company::Get(owner)->livery->colour1;
2537 if (IsSavegameVersionBefore(149)) {
2538 for (TileIndex t = 0; t < map_size; t++) {
2539 if (!IsTileType(t, MP_STATION)) continue;
2540 if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && IsTileFlat(t))) {
2541 SetWaterClass(t, WATER_CLASS_INVALID);
2545 /* Waypoints with custom name may have a non-unique town_cn,
2546 * renumber those. First set all affected waypoints to the
2547 * highest possible number to get them numbered in the
2548 * order they have in the pool. */
2549 Waypoint *wp;
2550 FOR_ALL_WAYPOINTS(wp) {
2551 if (wp->name != NULL) wp->town_cn = UINT16_MAX;
2554 FOR_ALL_WAYPOINTS(wp) {
2555 if (wp->name != NULL) MakeDefaultName(wp);
2559 if (IsSavegameVersionBefore(152)) {
2560 _industry_builder.Reset(); // Initialize industry build data.
2562 /* The moment vehicles go from hidden to visible changed. This means
2563 * that vehicles don't always get visible anymore causing things to
2564 * get messed up just after loading the savegame. This fixes that. */
2565 Vehicle *v;
2566 FOR_ALL_VEHICLES(v) {
2567 /* Not all vehicle types can be inside a tunnel. Furthermore,
2568 * testing IsTunnelTile() for invalid tiles causes a crash. */
2569 if (!v->IsGroundVehicle()) continue;
2571 /* Is the vehicle in a tunnel? */
2572 if (!IsTunnelTile(v->tile)) continue;
2574 /* Is the vehicle actually at a tunnel entrance/exit? */
2575 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
2576 if (!IsTunnelTile(vtile)) continue;
2578 /* Are we actually in this tunnel? Or maybe a lower tunnel? */
2579 if (GetSlopePixelZ(v->x_pos, v->y_pos) != v->z_pos) continue;
2581 /* What way are we going? */
2582 const DiagDirection dir = GetTunnelBridgeDirection(vtile);
2583 const DiagDirection vdir = DirToDiagDir(v->direction);
2585 /* Have we passed the visibility "switch" state already? */
2586 byte pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
2587 byte frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2588 extern const byte _tunnel_visibility_frame[DIAGDIR_END];
2590 /* Should the vehicle be hidden or not? */
2591 bool hidden;
2592 if (dir == vdir) { // Entering tunnel
2593 hidden = frame >= _tunnel_visibility_frame[dir];
2594 v->tile = vtile;
2595 } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
2596 hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
2597 /* v->tile changes at the moment when the vehicle leaves the tunnel. */
2598 v->tile = hidden ? GetOtherTunnelBridgeEndOld(vtile) : vtile;
2599 } else {
2600 /* We could get here in two cases:
2601 * - for road vehicles, it is reversing at the end of the tunnel
2602 * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
2603 * Whatever case it is, do not change anything and use the old values.
2604 * Especially changing RV's state would break its reversing in the middle. */
2605 continue;
2608 if (hidden) {
2609 v->vehstatus |= VS_HIDDEN;
2611 switch (v->type) {
2612 case VEH_TRAIN: Train::From(v)->track = TRACK_BIT_WORMHOLE; break;
2613 case VEH_ROAD: RoadVehicle::From(v)->state = RVSB_WORMHOLE; break;
2614 default: NOT_REACHED();
2616 } else {
2617 v->vehstatus &= ~VS_HIDDEN;
2619 switch (v->type) {
2620 case VEH_TRAIN: Train::From(v)->track = DiagDirToDiagTrackBits(vdir); break;
2621 case VEH_ROAD: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
2622 default: NOT_REACHED();
2628 if (IsSavegameVersionBefore(153)) {
2629 RoadVehicle *rv;
2630 FOR_ALL_ROADVEHICLES(rv) {
2631 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
2633 bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
2634 if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
2635 extern const byte _road_stop_stop_frame[];
2636 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)]);
2637 } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
2638 SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
2643 if (IsSavegameVersionBefore(156)) {
2644 /* The train's pathfinder lost flag got moved. */
2645 Train *t;
2646 FOR_ALL_TRAINS(t) {
2647 if (!HasBit(t->flags, 5)) continue;
2649 ClrBit(t->flags, 5);
2650 SetBit(t->vehicle_flags, VF_PATHFINDER_LOST);
2653 /* Introduced terraform/clear limits. */
2654 Company *c;
2655 FOR_ALL_COMPANIES(c) {
2656 c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
2657 c->clear_limit = _settings_game.construction.clear_frame_burst << 16;
2661 if (IsSavegameVersionBefore(158)) {
2662 Vehicle *v;
2663 FOR_ALL_VEHICLES(v) {
2664 switch (v->type) {
2665 case VEH_TRAIN: {
2666 Train *t = Train::From(v);
2668 /* Clear old GOINGUP / GOINGDOWN flags.
2669 * It was changed in savegame version 139, but savegame
2670 * version 158 doesn't use these bits, so it doesn't hurt
2671 * to clear them unconditionally. */
2672 ClrBit(t->flags, 1);
2673 ClrBit(t->flags, 2);
2675 /* Clear both bits first. */
2676 ClrBit(t->gv_flags, GVF_GOINGUP_BIT);
2677 ClrBit(t->gv_flags, GVF_GOINGDOWN_BIT);
2679 /* Crashed vehicles can't be going up/down. */
2680 if (t->vehstatus & VS_CRASHED) break;
2682 /* Only X/Y tracks can be sloped. */
2683 if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
2685 t->gv_flags |= FixVehicleInclination(t, t->direction);
2686 break;
2688 case VEH_ROAD: {
2689 RoadVehicle *rv = RoadVehicle::From(v);
2690 ClrBit(rv->gv_flags, GVF_GOINGUP_BIT);
2691 ClrBit(rv->gv_flags, GVF_GOINGDOWN_BIT);
2693 /* Crashed vehicles can't be going up/down. */
2694 if (rv->vehstatus & VS_CRASHED) break;
2696 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
2698 TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, rv->compatible_roadtypes);
2699 TrackBits trackbits = TrackStatusToTrackBits(ts);
2701 /* Only X/Y tracks can be sloped. */
2702 if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
2704 Direction dir = rv->direction;
2706 /* Test if we are reversing. */
2707 Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
2708 if (AxisToDirection(a) != dir &&
2709 AxisToDirection(a) != ReverseDir(dir)) {
2710 /* When reversing, the road vehicle is on the edge of the tile,
2711 * so it can be safely compared to the middle of the tile. */
2712 dir = INVALID_DIR;
2715 rv->gv_flags |= FixVehicleInclination(rv, dir);
2716 break;
2718 case VEH_SHIP:
2719 break;
2721 default:
2722 continue;
2725 if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2726 /* In old versions, z_pos was 1 unit lower on bridge heads.
2727 * However, this invalid state could be converted to new savegames
2728 * by loading and saving the game in a new version. */
2729 v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos);
2730 DiagDirection dir = GetTunnelBridgeDirection(v->tile);
2731 if (v->type == VEH_TRAIN && !(v->vehstatus & VS_CRASHED) &&
2732 v->direction != DiagDirToDir(dir)) {
2733 /* If the train has left the bridge, it shouldn't have
2734 * track == TRACK_BIT_WORMHOLE - this could happen
2735 * when the train was reversed while on the last "tick"
2736 * on the ramp before leaving the ramp to the bridge. */
2737 Train::From(v)->track = DiagDirToDiagTrackBits(dir);
2741 /* If the vehicle is really above v->tile (not in a wormhole),
2742 * it should have set v->z_pos correctly. */
2743 assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos));
2746 /* Fill Vehicle::cur_real_order_index */
2747 FOR_ALL_VEHICLES(v) {
2748 if (!v->IsPrimaryVehicle()) continue;
2750 /* Older versions are less strict with indices being in range and fix them on the fly */
2751 if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
2753 v->cur_real_order_index = v->cur_implicit_order_index;
2754 v->UpdateRealOrderIndex();
2758 if (IsSavegameVersionBefore(159)) {
2759 /* If the savegame is old (before version 100), then the value of 255
2760 * for these settings did not mean "disabled". As such everything
2761 * before then did reverse.
2762 * To simplify stuff we disable all turning around or we do not
2763 * disable anything at all. So, if some reversing was disabled we
2764 * will keep reversing disabled, otherwise it'll be turned on. */
2765 _settings_game.pf.reverse_at_signals = IsSavegameVersionBefore(100) || (_settings_game.pf.wait_oneway_signal != 255 && _settings_game.pf.wait_twoway_signal != 255 && _settings_game.pf.wait_for_pbs_path != 255);
2767 Train *t;
2768 FOR_ALL_TRAINS(t) {
2769 _settings_game.vehicle.max_train_length = max<uint8>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
2773 if (IsSavegameVersionBefore(160)) {
2774 /* Setting difficulty industry_density other than zero get bumped to +1
2775 * since a new option (minimal at position 1) has been added */
2776 if (_settings_game.difficulty.industry_density > 0) {
2777 _settings_game.difficulty.industry_density++;
2781 if (IsSavegameVersionBefore(161)) {
2782 /* Before savegame version 161, persistent storages were not stored in a pool. */
2784 if (!IsSavegameVersionBefore(76)) {
2785 Industry *ind;
2786 FOR_ALL_INDUSTRIES(ind) {
2787 assert(ind->psa != NULL);
2789 /* Check if the old storage was empty. */
2790 bool is_empty = true;
2791 for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
2792 if (ind->psa->GetValue(i) != 0) {
2793 is_empty = false;
2794 break;
2798 if (!is_empty) {
2799 ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
2800 } else {
2801 delete ind->psa;
2802 ind->psa = NULL;
2807 if (!IsSavegameVersionBefore(145)) {
2808 Station *st;
2809 FOR_ALL_STATIONS(st) {
2810 if (!(st->facilities & FACIL_AIRPORT)) continue;
2811 assert(st->airport.psa != NULL);
2813 /* Check if the old storage was empty. */
2814 bool is_empty = true;
2815 for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
2816 if (st->airport.psa->GetValue(i) != 0) {
2817 is_empty = false;
2818 break;
2822 if (!is_empty) {
2823 st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
2824 } else {
2825 delete st->airport.psa;
2826 st->airport.psa = NULL;
2833 /* This triggers only when old snow_lines were copied into the snow_line_height. */
2834 if (IsSavegameVersionBefore(164) && _settings_game.game_creation.snow_line_height >= MIN_SNOWLINE_HEIGHT * TILE_HEIGHT) {
2835 _settings_game.game_creation.snow_line_height /= TILE_HEIGHT;
2838 if (IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_18_6)) {
2839 _settings_game.game_creation.tree_line_height = _settings_game.game_creation.snow_line_height;
2842 if (IsSavegameVersionBefore(164) && !IsSavegameVersionBefore(32)) {
2843 /* We store 4 fences in the field tiles instead of only SE and SW. */
2844 for (TileIndex t = 0; t < map_size; t++) {
2845 if (!IsTileType(t, MP_CLEAR) && !IsTileType(t, MP_TREES)) continue;
2846 if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) continue;
2847 uint fence = GB(_m[t].m4, 5, 3);
2848 if (fence != 0 && IsTileType(TILE_ADDXY(t, 1, 0), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 1, 0), CLEAR_FIELDS)) {
2849 SetFence(TILE_ADDXY(t, 1, 0), DIAGDIR_NE, fence);
2851 fence = GB(_m[t].m4, 2, 3);
2852 if (fence != 0 && IsTileType(TILE_ADDXY(t, 0, 1), MP_CLEAR) && IsClearGround(TILE_ADDXY(t, 0, 1), CLEAR_FIELDS)) {
2853 SetFence(TILE_ADDXY(t, 0, 1), DIAGDIR_NW, fence);
2855 SB(_m[t].m4, 2, 3, 0);
2856 SB(_m[t].m4, 5, 3, 0);
2860 /* The center of train vehicles was changed, fix up spacing. */
2861 if (IsSavegameVersionBefore(164)) FixupTrainLengths();
2863 if (IsSavegameVersionBefore(165)) {
2864 Town *t;
2866 FOR_ALL_TOWNS(t) {
2867 /* Set the default cargo requirement for town growth */
2868 switch (_settings_game.game_creation.landscape) {
2869 case LT_ARCTIC:
2870 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_WINTER;
2871 break;
2873 case LT_TROPIC:
2874 if (FindFirstCargoWithTownEffect(TE_FOOD) != NULL) t->goal[TE_FOOD] = TOWN_GROWTH_DESERT;
2875 if (FindFirstCargoWithTownEffect(TE_WATER) != NULL) t->goal[TE_WATER] = TOWN_GROWTH_DESERT;
2876 break;
2881 if (IsSavegameVersionBefore(165)) {
2882 /* Adjust zoom level to account for new levels */
2883 _saved_scrollpos_zoom = _saved_scrollpos_zoom + ZOOM_LVL_SHIFT;
2884 _saved_scrollpos_x *= ZOOM_LVL_BASE;
2885 _saved_scrollpos_y *= ZOOM_LVL_BASE;
2888 /* When any NewGRF has been changed the availability of some vehicles might
2889 * have been changed too. e->company_avail must be set to 0 in that case
2890 * which is done by StartupEngines(). */
2891 if (gcf_res != GLC_ALL_GOOD) StartupEngines();
2893 if (IsSavegameVersionBefore(166)) {
2894 /* Update cargo acceptance map of towns. */
2895 for (TileIndex t = 0; t < map_size; t++) {
2896 if (!IsTileType(t, MP_HOUSE)) continue;
2897 Town::Get(GetTownIndex(t))->cargo_accepted.Add(t);
2900 Town *town;
2901 FOR_ALL_TOWNS(town) {
2902 UpdateTownCargoes(town);
2906 /* The road owner of standard road stops was not properly accounted for. */
2907 if (IsSavegameVersionBefore(172)) {
2908 for (TileIndex t = 0; t < map_size; t++) {
2909 if (!IsStandardRoadStopTile(t)) continue;
2910 Owner o = GetTileOwner(t);
2911 SetRoadOwner(t, ROADTYPE_ROAD, o);
2912 SetRoadOwner(t, ROADTYPE_TRAM, o);
2916 if (IsSavegameVersionBefore(175)) {
2917 /* Introduced tree planting limit. */
2918 Company *c;
2919 FOR_ALL_COMPANIES(c) c->tree_limit = _settings_game.construction.tree_frame_burst << 16;
2922 if (IsSavegameVersionBefore(177)) {
2923 /* Fix too high inflation rates */
2924 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
2925 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
2927 /* We have to convert the quarters of bankruptcy into months of bankruptcy */
2928 FOR_ALL_COMPANIES(c) {
2929 c->months_of_bankruptcy = 3 * c->months_of_bankruptcy;
2933 if (IsSavegameVersionBefore(178)) {
2934 extern uint8 _old_diff_level;
2935 /* Initialise script settings profile */
2936 _settings_game.script.settings_profile = IsInsideMM(_old_diff_level, SP_BEGIN, SP_END) ? _old_diff_level : (uint)SP_MEDIUM;
2939 if (IsSavegameVersionBefore(182)) {
2940 Aircraft *v;
2941 /* Aircraft acceleration variable was bonkers */
2942 FOR_ALL_AIRCRAFT(v) {
2943 if (v->subtype <= AIR_AIRCRAFT) {
2944 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
2945 v->acceleration = avi->acceleration;
2949 /* Blocked tiles could be reserved due to a bug, which causes
2950 * other places to assert upon e.g. station reconstruction. */
2951 for (TileIndex t = 0; t < map_size; t++) {
2952 if (HasStationTileRail(t) && IsStationTileBlocked(t)) {
2953 SetRailStationReservation(t, false);
2958 if (IsSavegameVersionBefore(184)) {
2959 /* The global units configuration is split up in multiple configurations. */
2960 extern uint8 _old_units;
2961 _settings_game.locale.units_velocity = Clamp(_old_units, 0, 2);
2962 _settings_game.locale.units_power = Clamp(_old_units, 0, 2);
2963 _settings_game.locale.units_weight = Clamp(_old_units, 1, 2);
2964 _settings_game.locale.units_volume = Clamp(_old_units, 1, 2);
2965 _settings_game.locale.units_force = 2;
2966 _settings_game.locale.units_height = Clamp(_old_units, 0, 2);
2969 if (IsSavegameVersionBefore(186)) {
2970 /* Move ObjectType from map to pool */
2971 for (TileIndex t = 0; t < map_size; t++) {
2972 if (IsTileType(t, MP_OBJECT)) {
2973 Object *o = Object::Get(_m[t].m2);
2974 o->type = _m[t].m5;
2975 _m[t].m5 = 0; // zero upper bits of (now bigger) ObjectID
2980 if (IsSavegameVersionBefore(188)) {
2981 /* Fix articulated road vehicles.
2982 * Some curves were shorter than other curves.
2983 * Now they have the same length, but that means that trailing articulated parts will
2984 * take longer to go through the curve than the parts in front which already left the courve.
2985 * So, make articulated parts catch up. */
2986 RoadVehicle *v;
2987 bool roadside = _settings_game.vehicle.road_side == 1;
2988 SmallVector<uint, 16> skip_frames;
2989 FOR_ALL_ROADVEHICLES(v) {
2990 if (!v->IsFrontEngine()) continue;
2991 skip_frames.Clear();
2992 TileIndex prev_tile = v->tile;
2993 uint prev_tile_skip = 0;
2994 uint cur_skip = 0;
2995 for (RoadVehicle *u = v; u != NULL; u = u->Next()) {
2996 if (u->tile != prev_tile) {
2997 prev_tile_skip = cur_skip;
2998 prev_tile = u->tile;
2999 } else {
3000 cur_skip = prev_tile_skip;
3003 uint *this_skip = skip_frames.Append();
3004 *this_skip = prev_tile_skip;
3006 /* The following 3 curves now take longer than before */
3007 switch (u->state) {
3008 case 2:
3009 cur_skip++;
3010 if (u->frame <= (roadside ? 9 : 5)) *this_skip = cur_skip;
3011 break;
3013 case 4:
3014 cur_skip++;
3015 if (u->frame <= (roadside ? 5 : 9)) *this_skip = cur_skip;
3016 break;
3018 case 5:
3019 cur_skip++;
3020 if (u->frame <= (roadside ? 4 : 2)) *this_skip = cur_skip;
3021 break;
3023 default:
3024 break;
3027 while (cur_skip > skip_frames[0]) {
3028 RoadVehicle *u = v;
3029 RoadVehicle *prev = NULL;
3030 for (uint *it = skip_frames.Begin(); it != skip_frames.End(); ++it, prev = u, u = u->Next()) {
3031 extern bool IndividualRoadVehicleController(RoadVehicle *v, const RoadVehicle *prev);
3032 if (*it >= cur_skip) IndividualRoadVehicleController(u, prev);
3034 cur_skip--;
3039 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_12)) {
3040 Train *t;
3041 FOR_ALL_TRAINS(t) {
3042 t->reverse_distance = 0;
3047 * Only keep order-backups for network clients (and when replaying).
3048 * If we are a network server or not networking, then we just loaded a previously
3049 * saved-by-server savegame. There are no clients with a backup, so clear it.
3050 * Furthermore before savegame version 192 / SL_PATCH_PACK_1_8 the actual content was always corrupt.
3052 if (!_networking || _network_server || IsSavegameVersionBefore(192) || IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_8)) {
3053 #ifndef DEBUG_DUMP_COMMANDS
3054 /* Note: We cannot use CleanPool since that skips part of the destructor
3055 * and then leaks un-reachable Orders in the order pool. */
3056 OrderBackup *ob;
3057 FOR_ALL_ORDER_BACKUPS(ob) {
3058 delete ob;
3060 #endif
3063 if (IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_16)) {
3064 /* red/green signal state bit for tunnel entrances moved
3065 * to no longer re-use signalled tunnel exit bit
3067 for (TileIndex t = 0; t < map_size; t++) {
3068 if (IsTileType(t, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL && IsTunnelBridgeWithSignalSimulation(t)) {
3069 if (HasBit(_m[t].m5, 5)) {
3070 /* signalled tunnel entrance */
3071 SignalState state = HasBit(_m[t].m5, 6) ? SIGNAL_STATE_RED : SIGNAL_STATE_GREEN;
3072 ClrBit(_m[t].m5, 6);
3073 SetTunnelBridgeSignalState(t, state);
3079 if (IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_19)) {
3080 /* load_unload_ticks --> tunnel_bridge_signal_num */
3081 Train *t;
3082 FOR_ALL_TRAINS(t) {
3083 TileIndex tile = t->tile;
3084 if (IsTileType(tile, MP_TUNNELBRIDGE) && GetTunnelBridgeTransportType(tile) == TRANSPORT_RAIL && IsTunnelBridgeWithSignalSimulation(tile)) {
3085 t->tunnel_bridge_signal_num = t->load_unload_ticks;
3086 t->load_unload_ticks = 0;
3091 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_19)) {
3092 /* ensure that previously unused custom bridge-head bits are cleared */
3093 for (TileIndex t = 0; t < map_size; t++) {
3094 if (IsBridgeTile(t) && GetTunnelBridgeTransportType(t) == TRANSPORT_ROAD) {
3095 SB(_m[t].m2, 0, 8, 0);
3100 /* Station acceptance is some kind of cache */
3101 if (IsSavegameVersionBefore(127)) {
3102 Station *st;
3103 FOR_ALL_STATIONS(st) UpdateStationAcceptance(st, false);
3106 // Before this version we didn't store the 5th bit of the tracktype here.
3107 // So set it to 0 just in case there was garbage in there.
3108 if (IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_14)) {
3109 for (TileIndex t = 0; t < map_size; t++) {
3110 if (GetTileType(t) == MP_RAILWAY ||
3111 IsLevelCrossingTile(t) ||
3112 IsRailStationTile(t) ||
3113 IsRailWaypointTile(t) ||
3114 IsRailTunnelBridgeTile(t)) {
3115 ClrBit(_m[t].m1, 7);
3120 /* Set lifetime vehicle profit to 0 if save game before 195 */
3121 if (IsPatchPackSavegameVersionBefore(SL_PATCH_PACK_1_14)) {
3122 Vehicle *v;
3123 FOR_ALL_VEHICLES(v) {
3124 v->profit_lifetime = v->profit_last_year;
3128 if (IsSavegameVersionBefore(SL_PATCH_PACK_1_24)) {
3129 Vehicle *v;
3130 FOR_ALL_VEHICLES(v) {
3131 v->cur_timetable_order_index = v->GetNumManualOrders() > 0 ? v->cur_real_order_index : INVALID_VEH_ORDER_ID;
3133 OrderBackup *bckup;
3134 FOR_ALL_ORDER_BACKUPS(bckup) {
3135 bckup->cur_timetable_order_index = INVALID_VEH_ORDER_ID;
3137 Order *order;
3138 FOR_ALL_ORDERS(order) {
3139 if (order->IsType(OT_CONDITIONAL)) {
3140 if (order->GetTravelTime() != 0) {
3141 DEBUG(sl, 1, "Fixing: order->GetTravelTime() != 0, %u", order->GetTravelTime());
3142 order->SetTravelTime(0);
3146 OrderList *order_list;
3147 FOR_ALL_ORDER_LISTS(order_list) {
3148 order_list->DebugCheckSanity();
3152 /* Road stops is 'only' updating some caches */
3153 AfterLoadRoadStops();
3154 AfterLoadLabelMaps();
3155 AfterLoadCompanyStats();
3156 AfterLoadStoryBook();
3158 GamelogPrintDebug(1);
3160 InitializeWindowsAndCaches();
3161 /* Restore the signals */
3162 ResetSignalHandlers();
3164 AfterLoadLinkGraphs();
3166 AfterLoadTraceRestrict();
3168 AfterLoadTemplateVehiclesUpdateImage();
3170 return true;
3174 * Reload all NewGRF files during a running game. This is a cut-down
3175 * version of AfterLoadGame().
3176 * XXX - We need to reset the vehicle position hash because with a non-empty
3177 * hash AfterLoadVehicles() will loop infinitely. We need AfterLoadVehicles()
3178 * to recalculate vehicle data as some NewGRF vehicle sets could have been
3179 * removed or added and changed statistics
3181 void ReloadNewGRFData()
3183 RailTypeLabel rail_type_label_map[RAILTYPE_END];
3184 for (RailType rt = RAILTYPE_BEGIN; rt != RAILTYPE_END; rt++) {
3185 rail_type_label_map[rt] = GetRailTypeInfo(rt)->label;
3188 /* reload grf data */
3189 GfxLoadSprites();
3190 LoadStringWidthTable();
3191 RecomputePrices();
3192 /* reload vehicles */
3193 ResetVehicleHash();
3194 AfterLoadVehicles(false);
3195 StartupEngines();
3196 GroupStatistics::UpdateAfterLoad();
3197 /* update station graphics */
3198 AfterLoadStations();
3199 /* Update company statistics. */
3200 AfterLoadCompanyStats();
3201 /* Check and update house and town values */
3202 UpdateHousesAndTowns();
3203 /* Delete news referring to no longer existing entities */
3204 DeleteInvalidEngineNews();
3205 /* Update livery selection windows */
3206 for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i);
3207 /* Update company infrastructure counts. */
3208 InvalidateWindowClassesData(WC_COMPANY_INFRASTRUCTURE);
3209 /* redraw the whole screen */
3210 MarkWholeScreenDirty();
3211 CheckTrainsLengths();
3212 AfterLoadTemplateVehiclesUpdateImage();
3214 RailType rail_type_translate_map[RAILTYPE_END];
3215 for (RailType old_type = RAILTYPE_BEGIN; old_type != RAILTYPE_END; old_type++) {
3216 RailType new_type = GetRailTypeByLabel(rail_type_label_map[old_type]);
3217 rail_type_translate_map[old_type] = (new_type == INVALID_RAILTYPE) ? RAILTYPE_RAIL : new_type;
3220 /* Restore correct railtype for all rail tiles.*/
3221 const TileIndex map_size = MapSize();
3222 for (TileIndex t = 0; t < map_size; t++) {
3223 if (GetTileType(t) == MP_RAILWAY ||
3224 IsLevelCrossingTile(t) ||
3225 IsRailStationTile(t) ||
3226 IsRailWaypointTile(t) ||
3227 IsRailTunnelBridgeTile(t)) {
3228 SetRailType(t, rail_type_translate_map[GetRailType(t)]);