OpenTTD Source 20260512-master-g20b387b91f
afterload.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../stdafx.h"
11#include "../void_map.h"
12#include "../signs_base.h"
13#include "../depot_base.h"
14#include "../fios.h"
15#include "../gamelog_internal.h"
16#include "../network/network.h"
18#include "../gfxinit.h"
19#include "../viewport_func.h"
20#include "../viewport_kdtree.h"
21#include "../industry.h"
22#include "../clear_map.h"
23#include "../vehicle_func.h"
24#include "../string_func.h"
25#include "../strings_func.h"
26#include "../window_func.h"
27#include "../roadveh.h"
28#include "../roadveh_cmd.h"
29#include "../train.h"
30#include "../station_base.h"
31#include "../waypoint_base.h"
32#include "../roadstop_base.h"
33#include "../tunnelbridge_map.h"
35#include "../elrail_func.h"
36#include "../signs_func.h"
37#include "../aircraft.h"
38#include "../object_map.h"
39#include "../object_base.h"
40#include "../tree_map.h"
41#include "../company_func.h"
42#include "../road_cmd.h"
43#include "../ai/ai.hpp"
45#include "../game/game.hpp"
46#include "../town.h"
47#include "../economy_base.h"
50#include "../subsidy_base.h"
51#include "../subsidy_func.h"
52#include "../newgrf.h"
53#include "../newgrf_station.h"
54#include "../engine_func.h"
55#include "../rail_gui.h"
57#include "../smallmap_gui.h"
58#include "../news_func.h"
59#include "../order_backup.h"
60#include "../error.h"
61#include "../disaster_vehicle.h"
62#include "../ship.h"
63#include "../water.h"
64#include "../timer/timer.h"
68#include "../picker_func.h"
69
70#include "saveload_internal.h"
71
72#include <signal.h>
73
74#include "table/strings.h"
75
76#include "../safeguards.h"
77
78extern Company *DoStartupNewCompany(bool is_ai, CompanyID company = CompanyID::Invalid());
79extern void ClearOldOrders();
80
91void SetWaterClassDependingOnSurroundings(Tile t, bool include_invalid_water_class)
92{
93 /* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
94 * Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
95 if (!IsTileFlat(t)) {
96 if (include_invalid_water_class) {
98 return;
99 } else {
100 SlErrorCorrupt("Invalid water class for dry tile");
101 }
102 }
103
104 /* Mark tile dirty in all cases */
106
107 if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == Map::MaxX() - 1 || TileY(t) == Map::MaxY() - 1) {
108 /* tiles at map borders are always WaterClass::Sea */
110 return;
111 }
112
113 bool has_water = false;
114 bool has_canal = false;
115 bool has_river = false;
116
117 for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
118 Tile neighbour = TileAddByDiagDir(t, dir);
119 switch (GetTileType(neighbour)) {
120 case TileType::Water:
121 /* clear water and shipdepots have already a WaterClass associated */
122 if (IsCoast(neighbour)) {
123 has_water = true;
124 } else if (!IsLock(neighbour)) {
125 switch (GetWaterClass(neighbour)) {
126 case WaterClass::Sea: has_water = true; break;
127 case WaterClass::Canal: has_canal = true; break;
128 case WaterClass::River: has_river = true; break;
129 default: SlErrorCorrupt("Invalid water class for tile");
130 }
131 }
132 break;
133
135 /* Shore or flooded halftile */
136 has_water |= (GetRailGroundType(neighbour) == RailGroundType::HalfTileWater);
137 break;
138
139 case TileType::Trees:
140 /* trees on shore */
141 has_water |= (static_cast<TreeGround>(GB(neighbour.m2(), 4, 2)) == TreeGround::Shore);
142 break;
143
144 default: break;
145 }
146 }
147
148 if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
150 return;
151 }
152
153 if (has_river && !has_canal) {
155 } else if (has_canal || !has_water) {
157 } else {
159 }
160}
161
162static void ConvertTownOwner()
163{
164 for (auto tile : Map::Iterate()) {
165 switch (GetTileType(tile)) {
166 case TileType::Road:
167 if (GB(tile.m5(), 4, 2) == to_underlying(RoadTileType::Crossing) && HasBit(tile.m3(), 7)) {
168 tile.m3() = OWNER_TOWN.base();
169 }
170 [[fallthrough]];
171
173 if (tile.m1() & 0x80) SetTileOwner(tile, OWNER_TOWN);
174 break;
175
176 default: break;
177 }
178 }
179}
180
183{
184 for (Town *t : Town::Iterate()) {
185 t->exclusivity = CompanyID::Invalid();
186 }
187}
188
189static const uint8_t convert_currency[] = {
190 0, 1, 12, 8, 3,
191 10, 14, 19, 4, 5,
192 9, 11, 13, 6, 17,
193 16, 22, 21, 7, 15,
194 18, 2, 20,
195};
196
198static void UpdateCurrencies()
199{
200 _settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
201}
202
207static void UpdateVoidTiles()
208{
209 for (uint x = 0; x < Map::SizeX(); x++) MakeVoid(TileXY(x, Map::MaxY()));
210 for (uint y = 0; y < Map::SizeY(); y++) MakeVoid(TileXY(Map::MaxX(), y));
211}
212
213static inline RailType UpdateRailType(RailType rt, RailType min)
214{
215 return rt >= min ? (RailType)(rt + 1): rt;
216}
217
222{
226 UpdateAllTextEffectVirtCoords();
227 RebuildViewportKdtree();
228}
229
230void ClearAllCachedNames()
231{
232 ClearAllStationCachedNames();
234 ClearAllIndustryCachedNames();
235}
236
247{
248 /* Initialize windows */
251
252 /* Update coordinates of the signs. */
253 ClearAllCachedNames();
255 ResetViewportAfterLoadGame();
256
257 for (Company *c : Company::Iterate()) {
258 /* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
259 * accordingly if it is not the case. No need to set it on companies that are not been used already,
260 * thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
261 if (_file_to_saveload.ftype.abstract == AbstractFileType::Scenario && c->inaugurated_year != EconomyTime::MIN_YEAR) {
262 c->inaugurated_year = TimerGameEconomy::year;
263 }
264 }
265
266 /* Count number of objects per type */
267 for (Object *o : Object::Iterate()) {
268 Object::IncTypeCount(o->type);
269 }
270
271 /* Identify owners of persistent storage arrays */
272 for (Industry *i : Industry::Iterate()) {
273 if (i->psa != nullptr) {
274 i->psa->feature = GrfSpecFeature::Industries;
275 i->psa->tile = i->location.tile;
276 }
277 }
278 for (Station *s : Station::Iterate()) {
279 if (s->airport.psa != nullptr) {
280 s->airport.psa->feature = GrfSpecFeature::Airports;
281 s->airport.psa->tile = s->airport.tile;
282 }
283 }
284 for (Town *t : Town::Iterate()) {
285 for (auto &it : t->psa_list) {
286 it->feature = GrfSpecFeature::FakeTowns;
287 it->tile = t->xy;
288 }
289 }
290 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
291 if (rv->IsFrontEngine()) {
292 rv->CargoChanged();
293 }
294 }
295
297
299
301
302 /* Towns have a noise controlled number of airports system
303 * So each airport's noise value must be added to the town->noise_reached value
304 * Reset each town's noise_reached value to '0' before. */
306
309
310 /* Rebuild the smallmap list of owners. */
312}
313
314typedef void (CDECL *SignalHandlerPointer)(int);
315static SignalHandlerPointer _prev_segfault = nullptr;
316static SignalHandlerPointer _prev_abort = nullptr;
317static SignalHandlerPointer _prev_fpe = nullptr;
318
319static void CDECL HandleSavegameLoadCrash(int signum);
320
325static void SetSignalHandlers()
326{
327 _prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
328 _prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
329 _prev_fpe = signal(SIGFPE, HandleSavegameLoadCrash);
330}
331
336{
337 signal(SIGSEGV, _prev_segfault);
338 signal(SIGABRT, _prev_abort);
339 signal(SIGFPE, _prev_fpe);
340}
341
344
354
361static void CDECL HandleSavegameLoadCrash(int signum)
362{
364
365 std::string message;
366 message.reserve(1024);
367 message += "Loading your savegame caused OpenTTD to crash.\n";
368
369 _saveload_crash_with_missing_newgrfs = std::ranges::any_of(_grfconfig, [](const auto &c) { return c->flags.Test(GRFConfigFlag::Compatible) || c->status == GRFStatus::NotFound; });
370
372 message +=
373 "This is most likely caused by a missing NewGRF or a NewGRF that\n"
374 "has been loaded as replacement for a missing NewGRF. OpenTTD\n"
375 "cannot easily determine whether a replacement NewGRF is of a newer\n"
376 "or older version.\n"
377 "It will load a NewGRF with the same GRF ID as the missing NewGRF.\n"
378 "This means that if the author makes incompatible NewGRFs with the\n"
379 "same GRF ID, OpenTTD cannot magically do the right thing. In most\n"
380 "cases, OpenTTD will load the savegame and not crash, but this is an\n"
381 "exception.\n"
382 "Please load the savegame with the appropriate NewGRFs installed.\n"
383 "The missing/compatible NewGRFs are:\n";
384
385 for (const auto &c : _grfconfig) {
386 if (c->flags.Test(GRFConfigFlag::Compatible)) {
387 const GRFIdentifier &replaced = _gamelog.GetOverriddenIdentifier(*c);
388 format_append(message, "NewGRF {:08X} (checksum {}) not found.\n Loaded NewGRF \"{}\" (checksum {}) with same GRF ID instead.\n",
389 std::byteswap(c->ident.grfid), FormatArrayAsHex(c->original_md5sum), c->filename, FormatArrayAsHex(replaced.md5sum));
390 }
391 if (c->status == GRFStatus::NotFound) {
392 format_append(message, "NewGRF {:08X} ({}) not found; checksum {}.\n",
393 std::byteswap(c->ident.grfid), c->filename, FormatArrayAsHex(c->ident.md5sum));
394 }
395 }
396 } else {
397 message +=
398 "This is probably caused by a corruption in the savegame.\n"
399 "Please file a bug report and attach this savegame.\n";
400 }
401
402 ShowInfoI(message);
403
404 SignalHandlerPointer call = nullptr;
405 switch (signum) {
406 case SIGSEGV: call = _prev_segfault; break;
407 case SIGABRT: call = _prev_abort; break;
408 case SIGFPE: call = _prev_fpe; break;
409 default: NOT_REACHED();
410 }
411 if (call != nullptr) call(signum);
412}
413
420{
422
423 /* remove leftover rail piece from crossing (from very old savegames) */
424 Train *v = nullptr;
425 for (Train *w : Train::Iterate()) {
426 if (w->tile == TileIndex(t)) {
427 v = w;
428 break;
429 }
430 }
431
432 if (v != nullptr) {
433 /* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
434 SetTileOwner(t, v->owner);
435 return;
436 }
437
438 /* try to find any connected rail */
439 for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
440 TileIndex tt{t + TileOffsByDiagDir(dd)};
445 return;
446 }
447 }
448
449 if (IsLevelCrossingTile(t)) {
450 /* else change the crossing to normal road (road vehicles won't care) */
451 Owner road = GetRoadOwner(t, RoadTramType::Road);
452 Owner tram = GetRoadOwner(t, RoadTramType::Tram);
454 bool hasroad = HasBit(t.m7(), 6);
455 bool hastram = HasBit(t.m7(), 7);
456
457 /* MakeRoadNormal */
459 SetTileOwner(t, road);
460 t.m3() = (hasroad ? bits.base() : 0);
461 t.m5() = (hastram ? bits.base() : 0) | to_underlying(RoadTileType::Normal) << 6;
462 SB(t.m6(), 2, 4, 0);
464 return;
465 }
466
467 /* if it's not a crossing, make it clean land */
469}
470
478{
479 /* Compute place where this vehicle entered the tile */
480 int entry_x = v->x_pos;
481 int entry_y = v->y_pos;
482 switch (dir) {
483 case DIR_NE: entry_x |= TILE_UNIT_MASK; break;
484 case DIR_NW: entry_y |= TILE_UNIT_MASK; break;
485 case DIR_SW: entry_x &= ~TILE_UNIT_MASK; break;
486 case DIR_SE: entry_y &= ~TILE_UNIT_MASK; break;
487 case INVALID_DIR: break;
488 default: NOT_REACHED();
489 }
490 uint8_t entry_z = GetSlopePixelZ(entry_x, entry_y, true);
491
492 /* Compute middle of the tile. */
493 int middle_x = (v->x_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
494 int middle_y = (v->y_pos & ~TILE_UNIT_MASK) + TILE_SIZE / 2;
495 uint8_t middle_z = GetSlopePixelZ(middle_x, middle_y, true);
496
497 /* middle_z == entry_z, no height change. */
498 if (middle_z == entry_z) return 0;
499
500 /* middle_z < entry_z, we are going downwards. */
501 if (middle_z < entry_z) return 1U << GVF_GOINGDOWN_BIT;
502
503 /* middle_z > entry_z, we are going upwards. */
504 return 1U << GVF_GOINGUP_BIT;
505}
506
513{
514 for (Vehicle *v : Vehicle::Iterate()) {
515 if (v->IsGroundVehicle()) {
516 /*
517 * Either the vehicle is not actually on the given tile, i.e. it is
518 * in the wormhole of a bridge or a tunnel, or the Z-coordinate must
519 * be the same as when it would be recalculated right now.
520 */
521 assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos, true));
522 }
523 }
524}
525
537
541static void StartScripts()
542{
543 /* Script debug window requires AIs to be started before trying to start GameScript. */
544
545 /* Start the AIs. */
546 for (const Company *c : Company::Iterate()) {
547 if (Company::IsValidAiID(c->index)) AI::StartNew(c->index);
548 }
549
550 /* Start the GameScript. */
552
554}
555
562{
564
565 extern TileIndex _cur_tileloop_tile; // From landscape.cpp.
566 /* The LFSR used in RunTileLoop iteration cannot have a zeroed state, make it non-zeroed. */
567 if (_cur_tileloop_tile == 0) _cur_tileloop_tile = TileIndex{1};
568
570
571 _gamelog.TestRevision();
572 _gamelog.TestMode();
573
574 RebuildTownKdtree();
575 RebuildStationKdtree();
576 /* This needs to be done even before conversion, because some conversions will destroy objects
577 * that otherwise won't exist in the tree. */
578 RebuildViewportKdtree();
579
580 /* Group hierarchy may be evaluated during conversion, so ensure its correct early on. */
582
584
586 _pause_mode = (_pause_mode.base() == 2) ? PauseMode::Normal : PauseModes{};
587 } else if (_network_dedicated && _pause_mode.Test(PauseMode::Error)) {
588 Debug(net, 0, "The loading savegame was paused due to an error state");
589 Debug(net, 0, " This savegame cannot be used for multiplayer");
590 /* Restore the signals */
592 return false;
593 } else if (!_networking || _network_server) {
594 /* If we are in singleplayer mode, i.e. not networking, and loading the
595 * savegame or we are loading the savegame as network server we do
596 * not want to be bothered by being paused because of the automatic
597 * reason of a network server, e.g. joining clients or too few
598 * active clients. Note that resetting these values for a network
599 * client are very bad because then the client is going to execute
600 * the game loop when the server is not, i.e. it desyncs. */
602 }
603
604 /* In very old versions, size of train stations was stored differently.
605 * They had swapped width and height if station was built along the Y axis.
606 * TTO and TTD used 3 bits for width/height, while OpenTTD used 4.
607 * Because the data stored by TTDPatch are unusable for rail stations > 7x7,
608 * recompute the width and height. Doing this unconditionally for all old
609 * savegames simplifies the code. */
611 for (Station *st : Station::Iterate()) {
612 st->train_station.w = st->train_station.h = 0;
613 }
614 for (auto t : Map::Iterate()) {
615 if (!IsTileType(t, TileType::Station)) continue;
616 if (t.m5() > 7) continue; // is it a rail station tile?
617 Station *st = Station::Get(t.m2());
618 assert(st->train_station.tile != 0);
619 int dx = TileX(t) - TileX(st->train_station.tile);
620 int dy = TileY(t) - TileY(st->train_station.tile);
621 assert(dx >= 0 && dy >= 0);
622 st->train_station.w = std::max<uint>(st->train_station.w, dx + 1);
623 st->train_station.h = std::max<uint>(st->train_station.h, dy + 1);
624 }
625 }
626
628 _settings_game.construction.map_height_limit = 15;
629
630 /* In old savegame versions, the heightlevel was coded in bits 0..3 of the type field */
631 for (auto t : Map::Iterate()) {
632 t.height() = GB(t.type(), 0, 4);
633 SB(t.type(), 0, 2, GB(t.m6(), 0, 2));
634 SB(t.m6(), 0, 2, 0);
635 if (MayHaveBridgeAbove(t)) {
636 SB(t.type(), 2, 2, GB(t.m6(), 6, 2));
637 SB(t.m6(), 6, 2, 0);
638 } else {
639 SB(t.type(), 2, 2, 0);
640 }
641 }
642 }
643
644 /* in version 2.1 of the savegame, town owner was unified. */
645 if (IsSavegameVersionBefore(SLV_2, 1)) ConvertTownOwner();
646
647 /* from version 4.1 of the savegame, exclusive rights are stored at towns */
649
650 /* from version 4.2 of the savegame, currencies are in a different order */
652
653 /* In old version there seems to be a problem that water is owned by
654 * OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
655 * (4.3) version, so I just check when versions are older, and then
656 * walk through the whole map.. */
658 for (const auto t : Map::Iterate()) {
659 if (IsTileType(t, TileType::Water) && GetTileOwner(t) >= MAX_COMPANIES) {
661 }
662 }
663 }
664
666 for (Company *c : Company::Iterate()) {
667 c->name = CopyFromOldName(c->name_1);
668 if (!c->name.empty()) c->name_1 = STR_SV_UNNAMED;
669 c->president_name = CopyFromOldName(c->president_name_1);
670 if (!c->president_name.empty()) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
671 }
672
673 for (Station *st : Station::Iterate()) {
674 st->name = CopyFromOldName(st->string_id);
675 /* generating new name would be too much work for little effect, use the station name fallback */
676 if (!st->name.empty()) st->string_id = STR_SV_STNAME_FALLBACK;
677 }
678
679 for (Town *t : Town::Iterate()) {
680 t->name = CopyFromOldName(t->townnametype);
681 if (!t->name.empty()) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
682 }
683 }
684
685 /* From this point the old names array is cleared. */
687
689 /* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
690 for (Station *st : Station::Iterate()) {
691 if (st->airport.tile == 0) st->airport.tile = INVALID_TILE;
692 if (st->train_station.tile == 0) st->train_station.tile = INVALID_TILE;
693 }
694
695 /* the same applies to Company::location_of_HQ */
696 for (Company *c : Company::Iterate()) {
697 if (c->location_of_HQ == 0 || (IsSavegameVersionBefore(SLV_4) && c->location_of_HQ == 0xFFFF)) {
698 c->location_of_HQ = INVALID_TILE;
699 }
700 }
701 }
702
703 /* convert road side to my format. */
704 if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
705
706 /* Check if all NewGRFs are present, we are very strict in MP mode */
708 for (const auto &c : _grfconfig) {
709 if (c->status == GRFStatus::NotFound) {
710 _gamelog.GRFRemove(c->ident.grfid);
711 } else if (c->flags.Test(GRFConfigFlag::Compatible)) {
712 _gamelog.GRFCompatible(c->ident);
713 }
714 }
715
716 if (_networking && gcf_res != GRFListCompatibility::AllGood) {
717 SetSaveLoadError(STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH);
718 /* Restore the signals */
720 return false;
721 }
722
723 switch (gcf_res) {
724 case GRFListCompatibility::Compatible: ShowErrorMessage(GetEncodedString(STR_NEWGRF_COMPATIBLE_LOAD_WARNING), {}, WL_CRITICAL); break;
726 default: break;
727 }
728
729 /* The value of TimerGameCalendar::date_fract got divided, so make sure that old games are converted correctly. */
731
732 /* Update current year
733 * must be done before loading sprites as some newgrfs check it */
735
736 /* Only new games can use wallclock units. */
737 if (IsSavegameVersionBefore(SLV_ECONOMY_MODE_TIMEKEEPING_UNITS)) _settings_game.economy.timekeeping_units = TimekeepingUnits::Calendar;
738
739 /* Set the correct default for 'minutes per year' if the savegame was created before the setting existed. */
740 if (IsSavegameVersionBefore(SLV_CALENDAR_SUB_DATE_FRACT)) _settings_game.economy.minutes_per_calendar_year = CalendarTime::DEF_MINUTES_PER_YEAR;
741
742 /* Update economy year. If we don't have a separate economy date saved, follow the calendar date. */
745 } else {
747 }
748
749 /*
750 * Force the old behaviour for compatibility reasons with old savegames. As new
751 * settings can only be loaded from new savegames loading old savegames with new
752 * versions of OpenTTD will normally initialize settings newer than the savegame
753 * version with "new game" defaults which the player can define to their liking.
754 * For some settings we override that to keep the behaviour the same as when the
755 * game was saved.
756 *
757 * Note that there is no non-stop in here. This is because the setting could have
758 * either value in TTDPatch. To convert it properly the user has to make sure the
759 * right value has been chosen in the settings. Otherwise we will be converting
760 * it incorrectly in half of the times without a means to correct that.
761 */
762 if (IsSavegameVersionBefore(SLV_4, 2)) _settings_game.station.modified_catchment = false;
763 if (IsSavegameVersionBefore(SLV_6, 1)) _settings_game.pf.forbid_90_deg = false;
764 if (IsSavegameVersionBefore(SLV_21)) _settings_game.vehicle.train_acceleration_model = 0;
765 if (IsSavegameVersionBefore(SLV_90)) _settings_game.vehicle.plane_speed = 4;
766 if (IsSavegameVersionBefore(SLV_95)) _settings_game.vehicle.dynamic_engines = false;
767 if (IsSavegameVersionBefore(SLV_96)) _settings_game.economy.station_noise_level = false;
769 _settings_game.vehicle.train_slope_steepness = 3;
770 }
771 if (IsSavegameVersionBefore(SLV_134)) _settings_game.economy.feeder_payment_share = 75;
772 if (IsSavegameVersionBefore(SLV_138)) _settings_game.vehicle.plane_crashes = 2;
774 _settings_game.vehicle.roadveh_acceleration_model = 0;
775 _settings_game.vehicle.roadveh_slope_steepness = 7;
776 }
777 if (IsSavegameVersionBefore(SLV_143)) _settings_game.economy.allow_town_level_crossings = true;
779 _settings_game.vehicle.max_train_length = 50;
780 _settings_game.construction.max_bridge_length = 64;
781 _settings_game.construction.max_tunnel_length = 64;
782 }
783 if (IsSavegameVersionBefore(SLV_166)) _settings_game.economy.infrastructure_maintenance = false;
785 _settings_game.linkgraph.distribution_pax = DistributionType::Manual;
786 _settings_game.linkgraph.distribution_mail = DistributionType::Manual;
787 _settings_game.linkgraph.distribution_armoured = DistributionType::Manual;
788 _settings_game.linkgraph.distribution_default = DistributionType::Manual;
789 }
790
792 _settings_game.game_creation.ending_year = CalendarTime::DEF_END_YEAR;
793 }
794
795 /* Convert linkgraph update settings from days to seconds. */
797 _settings_game.linkgraph.recalc_interval *= CalendarTime::SECONDS_PER_DAY;
798 _settings_game.linkgraph.recalc_time *= CalendarTime::SECONDS_PER_DAY;
799 }
800
801 /* Load the sprites */
804
805 /* Copy temporary data to Engine pool */
807
808 /* Connect front and rear engines of multiheaded trains and converts
809 * subtype to the new format */
811
812 /* Connect front and rear engines of multiheaded trains */
814
815 /* Fix the CargoPackets *and* fix the caches of CargoLists.
816 * If this isn't done before Stations and especially Vehicles are
817 * running their AfterLoad we might get in trouble. In the case of
818 * vehicles we could give the wrong (cached) count of items in a
819 * vehicle which causes different results when getting their caches
820 * filled; and that could eventually lead to desyncs. */
822
823 /* Update all vehicles: Phase 1 */
825
826 /* Old orders are no longer needed. */
828
829 /* make sure there is a town in the game */
830 if (_game_mode == GM_NORMAL && Town::GetNumItems() == 0) {
831 SetSaveLoadError(STR_ERROR_NO_TOWN_IN_SCENARIO);
832 /* Restore the signals */
834 return false;
835 }
836
837 /* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
838 * This problem appears in savegame version 21 too, see r3455. But after loading the
839 * savegame and saving again, the buggy map array could be converted to new savegame
840 * version. It didn't show up before r12070. */
842
843 /* Fix the cache for cargo payments. */
844 for (CargoPayment *cp : CargoPayment::Iterate()) {
845 cp->front->cargo_payment = cp;
846 cp->current_station = cp->front->last_station_visited;
847 }
848
849
851 /* Prior to SLV_WATER_TILE_TYPE, the water tile type was stored differently from the enumeration. This has to be
852 * converted before SLV_72 and SLV_82 conversions which use GetWaterTileType. */
853 static constexpr uint8_t WBL_COAST_FLAG = 0;
854
855 for (auto t : Map::Iterate()) {
856 if (!IsTileType(t, TileType::Water)) continue;
857
858 switch (GB(t.m5(), 4, 4)) {
859 case 0x0: /* Previously WBL_TYPE_NORMAL, Clear water or coast. */
861 break;
862
863 case 0x1: SetWaterTileType(t, WaterTileType::Lock); break; /* Previously WBL_TYPE_LOCK */
864 case 0x8: SetWaterTileType(t, WaterTileType::Depot); break; /* Previously WBL_TYPE_DEPOT */
865 default: SetWaterTileType(t, WaterTileType::Clear); break; /* Shouldn't happen... */
866 }
867 }
868 }
869
871 /* Locks in very old savegames had OWNER_WATER as owner */
872 for (auto t : Map::Iterate()) {
873 switch (GetTileType(t)) {
874 default: break;
875
876 case TileType::Water:
878 break;
879
880 case TileType::Station: {
881 if (HasBit(t.m6(), 3)) SetBit(t.m6(), 2);
882 StationGfx gfx = GetStationGfx(t);
883 StationType st;
884 if ( IsInsideMM(gfx, 0, 8)) { // Rail station
886 SetStationGfx(t, gfx - 0);
887 } else if (IsInsideMM(gfx, 8, 67)) { // Airport
889 SetStationGfx(t, gfx - 8);
890 } else if (IsInsideMM(gfx, 67, 71)) { // Truck
892 SetStationGfx(t, gfx - 67);
893 } else if (IsInsideMM(gfx, 71, 75)) { // Bus
894 st = StationType::Bus;
895 SetStationGfx(t, gfx - 71);
896 } else if (gfx == 75) { // Oil rig
898 SetStationGfx(t, gfx - 75);
899 } else if (IsInsideMM(gfx, 76, 82)) { // Dock
901 SetStationGfx(t, gfx - 76);
902 } else if (gfx == 82) { // Buoy
904 SetStationGfx(t, gfx - 82);
905 } else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
907 SetStationGfx(t, gfx - 83 + 67 - 8);
908 } else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
911 } else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
912 st = StationType::Bus;
914 } else {
915 /* Restore the signals */
917 return false;
918 }
919 SB(t.m6(), 3, 3, to_underlying(st));
920 break;
921 }
922 }
923 }
924 }
925
927 /* Expansion of station type field in m6 */
928 for (auto t : Map::Iterate()) {
930 ClrBit(t.m6(), 6);
931 }
932 }
933 }
934
935 for (const auto t : Map::Iterate()) {
936 switch (GetTileType(t)) {
937 case TileType::Station: {
939
940 /* Sanity check */
941 if (!IsBuoy(t) && bst->owner != GetTileOwner(t)) SlErrorCorrupt("Wrong owner for station tile");
942
943 /* Set up station spread */
944 bst->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
945
946 /* Waypoints don't have road stops/oil rigs in the old format */
947 if (!Station::IsExpected(bst)) break;
948 Station *st = Station::From(bst);
949
950 switch (GetStationType(t)) {
952 case StationType::Bus:
954 /* Before version 5 you could not have more than 250 stations.
955 * Version 6 adds large maps, so you could only place 253*253
956 * road stops on a map (no freeform edges) = 64009. So, yes
957 * someone could in theory create such a full map to trigger
958 * this assertion, it's safe to assume that's only something
959 * theoretical and does not happen in normal games. */
961
962 /* From this version on there can be multiple road stops of the
963 * same type per station. Convert the existing stops to the new
964 * internal data structure. */
965 RoadStop *rs = RoadStop::Create(t);
966
967 RoadStop **head =
968 IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
969 *head = rs;
970 }
971 break;
972
973 case StationType::Oilrig: {
974 /* The internal encoding of oil rigs was changed twice.
975 * It was 3 (till 2.2) and later 5 (till 5.1).
976 * DeleteOilRig asserts on the correct type, and
977 * setting it unconditionally does not hurt.
978 */
979 Station::GetByTile(t)->airport.type = AT_OILRIG;
980
981 /* Very old savegames sometimes have phantom oil rigs, i.e.
982 * an oil rig which got shut down, but not completely removed from
983 * the map
984 */
985 TileIndex t1 = TileAddXY(t, 0, 1);
986 if (!IsTileType(t1, TileType::Industry) || GetIndustryGfx(t1) != GFX_OILRIG_1) {
987 DeleteOilRig(t);
988 }
989 break;
990 }
991
992 default: break;
993 }
994 break;
995 }
996
997 default: break;
998 }
999 }
1000
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 ;) */
1005 for (auto t : Map::Iterate()) {
1006 switch (GetTileType(t)) {
1007 case TileType::House:
1008 t.m4() = t.m2();
1010 break;
1011
1012 case TileType::Road:
1013 t.m4() |= (t.m2() << 4);
1014 if (GB(t.m5(), 4, 2) == to_underlying(RoadTileType::Depot)) break;
1015 if ((GB(t.m5(), 4, 2) == to_underlying(RoadTileType::Crossing) ? (Owner)t.m3() : GetTileOwner(t)) == OWNER_TOWN) {
1017 } else {
1018 SetTownIndex(t, TownID::Begin());
1019 }
1020 break;
1021
1022 default: break;
1023 }
1024 }
1025 }
1026
1027 /* Force the freeform edges to false for old savegames. */
1029 _settings_game.construction.freeform_edges = false;
1030 }
1031
1032 /* From version 9.0, we update the max passengers of a town (was sometimes negative
1033 * before that. */
1035 for (Town *t : Town::Iterate()) UpdateTownMaxPass(t);
1036 }
1037
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. */
1041 for (Company *c : Company::Iterate()) {
1042 c->engine_renew_list = nullptr;
1043 c->settings.engine_renew = false;
1044 c->settings.engine_renew_months = 6;
1045 c->settings.engine_renew_money = 100000;
1046 }
1047
1048 /* When loading a game, _local_company is not yet set to the correct value.
1049 * However, in a dedicated server we are a spectator, so nothing needs to
1050 * happen. In case we are not a dedicated server, the local company always
1051 * becomes the first available company, unless we are in the scenario editor
1052 * where all the companies are 'invalid'.
1053 */
1055 if (!_network_dedicated && c != nullptr) {
1056 c->settings = _settings_client.company;
1057 }
1058 }
1059
1061 for (auto t : Map::Iterate()) {
1062 switch (GetTileType(t)) {
1063 case TileType::Railway:
1064 if (IsPlainRail(t)) {
1065 /* Swap ground type and signal type for plain rail tiles, so the
1066 * ground type uses the same bits as for depots and waypoints. */
1067 uint tmp = GB(t.m4(), 0, 4);
1068 SB(t.m4(), 0, 4, GB(t.m2(), 0, 4));
1069 SB(t.m2(), 0, 4, tmp);
1070 } else if (HasBit(t.m5(), 2)) {
1071 /* Split waypoint and depot rail type and remove the subtype. */
1072 ClrBit(t.m5(), 2);
1073 ClrBit(t.m5(), 6);
1074 }
1075 break;
1076
1077 case TileType::Road:
1078 /* Swap m3 and m4, so the track type for rail crossings is the
1079 * same as for normal rail. */
1080 std::swap(t.m3(), t.m4());
1081 break;
1082
1083 default: break;
1084 }
1085 }
1086 }
1087
1089 /* Added the RoadType */
1090 bool old_bridge = IsSavegameVersionBefore(SLV_42);
1091 for (auto t : Map::Iterate()) {
1092 switch (GetTileType(t)) {
1093 case TileType::Road:
1094 SB(t.m5(), 6, 2, GB(t.m5(), 4, 2));
1095 switch (GetRoadTileType(t)) {
1096 default: SlErrorCorrupt("Invalid road tile type");
1098 SB(t.m4(), 0, 4, GB(t.m5(), 0, 4));
1099 SB(t.m4(), 4, 4, 0);
1100 SB(t.m6(), 2, 4, 0);
1101 break;
1103 SB(t.m4(), 5, 2, GB(t.m5(), 2, 2));
1104 break;
1105 case RoadTileType::Depot: break;
1106 }
1107 SB(t.m7(), 6, 2, 1); // Set pre-NRT road type bits for conversion later.
1108 break;
1109
1110 case TileType::Station:
1111 if (IsStationRoadStop(t)) SB(t.m7(), 6, 2, 1);
1112 break;
1113
1115 /* Middle part of "old" bridges */
1116 if (old_bridge && IsBridge(t) && HasBit(t.m5(), 6)) break;
1117 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(t.m5(), 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1118 SB(t.m7(), 6, 2, 1); // Set pre-NRT road type bits for conversion later.
1119 }
1120 break;
1121
1122 default: break;
1123 }
1124 }
1125 }
1126
1128 bool fix_roadtypes = !IsSavegameVersionBefore(SLV_61);
1129 bool old_bridge = IsSavegameVersionBefore(SLV_42);
1130
1131 for (auto t : Map::Iterate()) {
1132 switch (GetTileType(t)) {
1133 case TileType::Road:
1134 if (fix_roadtypes) SB(t.m7(), 6, 2, GB(t.m7(), 5, 3));
1135 SB(t.m7(), 5, 1, GB(t.m3(), 7, 1)); // snow/desert
1136 switch (GetRoadTileType(t)) {
1137 default: SlErrorCorrupt("Invalid road tile type");
1139 SB(t.m7(), 0, 4, GB(t.m3(), 0, 4)); // road works
1140 SB(t.m6(), 3, 3, GB(t.m3(), 4, 3)); // ground
1141 SB(t.m3(), 0, 4, GB(t.m4(), 4, 4)); // tram bits
1142 SB(t.m3(), 4, 4, GB(t.m5(), 0, 4)); // tram owner
1143 SB(t.m5(), 0, 4, GB(t.m4(), 0, 4)); // road bits
1144 break;
1145
1147 SB(t.m7(), 0, 5, GB(t.m4(), 0, 5)); // road owner
1148 SB(t.m6(), 3, 3, GB(t.m3(), 4, 3)); // ground
1149 SB(t.m3(), 4, 4, GB(t.m5(), 0, 4)); // tram owner
1150 SB(t.m5(), 0, 1, GB(t.m4(), 6, 1)); // road axis
1151 SB(t.m5(), 5, 1, GB(t.m4(), 5, 1)); // crossing state
1152 break;
1153
1155 break;
1156 }
1157 if (!IsRoadDepot(t) && !HasTownOwnedRoad(t)) {
1158 const Town *town = CalcClosestTownFromTile(t);
1159 if (town != nullptr) SetTownIndex(t, town->index);
1160 }
1161 t.m4() = 0;
1162 break;
1163
1164 case TileType::Station:
1165 if (!IsStationRoadStop(t)) break;
1166
1167 if (fix_roadtypes) SB(t.m7(), 6, 2, GB(t.m3(), 0, 3));
1168 SB(t.m7(), 0, 5, (HasBit(t.m6(), 2) ? OWNER_TOWN : GetTileOwner(t)).base());
1169 SB(t.m3(), 4, 4, t.m1());
1170 t.m4() = 0;
1171 break;
1172
1174 if (old_bridge && IsBridge(t) && HasBit(t.m5(), 6)) break;
1175 if (((old_bridge && IsBridge(t)) ? (TransportType)GB(t.m5(), 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
1176 if (fix_roadtypes) SB(t.m7(), 6, 2, GB(t.m3(), 0, 3));
1177
1178 Owner o = GetTileOwner(t);
1179 SB(t.m7(), 0, 5, o.base()); // road owner
1180 SB(t.m3(), 4, 4, (o == OWNER_NONE ? OWNER_TOWN : o).base()); // tram owner
1181 }
1182 SB(t.m6(), 2, 4, GB(t.m2(), 4, 4)); // bridge type
1183 SB(t.m7(), 5, 1, GB(t.m4(), 7, 1)); // snow/desert
1184
1185 t.m2() = 0;
1186 t.m4() = 0;
1187 break;
1188
1189 default: break;
1190 }
1191 }
1192 }
1193
1194 /* Railtype moved from m3 to m8 in version SLV_EXTEND_RAILTYPES. */
1196 for (auto t : Map::Iterate()) {
1197 switch (GetTileType(t)) {
1198 case TileType::Railway:
1199 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1200 break;
1201
1202 case TileType::Road:
1203 if (IsLevelCrossing(t)) {
1204 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1205 }
1206 break;
1207
1208 case TileType::Station:
1209 if (HasStationRail(t)) {
1210 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1211 }
1212 break;
1213
1216 SetRailType(t, (RailType)GB(t.m3(), 0, 4));
1217 }
1218 break;
1219
1220 default:
1221 break;
1222 }
1223 }
1224 }
1225
1227 for (auto t : Map::Iterate()) {
1229 if (IsBridgeTile(t)) {
1230 if (HasBit(t.m5(), 6)) { // middle part
1231 Axis axis = (Axis)GB(t.m5(), 0, 1);
1232
1233 if (HasBit(t.m5(), 5)) { // transport route under bridge?
1234 if (GB(t.m5(), 3, 2) == TRANSPORT_RAIL) {
1236 t,
1237 GetTileOwner(t),
1238 axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
1239 GetRailType(t)
1240 );
1241 } else {
1242 TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : TownID::Begin();
1243
1244 /* MakeRoadNormal */
1246 t.m2() = town.base();
1247 t.m3() = 0;
1248 t.m5() = (axis == AXIS_X ? ROAD_Y : ROAD_X).base() | to_underlying(RoadTileType::Normal) << 6;
1249 SB(t.m6(), 2, 4, 0);
1250 t.m7() = 1 << 6;
1252 }
1253 } else {
1254 if (GB(t.m5(), 3, 2) == 0) {
1256 } else {
1257 if (!IsTileFlat(t)) {
1258 MakeShore(t);
1259 } else {
1260 if (GetTileOwner(t) == OWNER_WATER) {
1261 MakeSea(t);
1262 } else {
1263 MakeCanal(t, GetTileOwner(t), Random());
1264 }
1265 }
1266 }
1267 }
1268 SetBridgeMiddle(t, axis);
1269 } else { // ramp
1270 Axis axis = (Axis)GB(t.m5(), 0, 1);
1271 uint north_south = GB(t.m5(), 5, 1);
1272 DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
1273 TransportType type = (TransportType)GB(t.m5(), 1, 2);
1274
1275 t.m5() = 1 << 7 | type << 2 | dir;
1276 }
1277 }
1278 }
1279
1280 for (Vehicle *v : Vehicle::Iterate()) {
1281 if (!v->IsGroundVehicle()) continue;
1282 if (IsBridgeTile(v->tile)) {
1284
1285 if (dir != DirToDiagDir(v->direction)) continue;
1286 switch (dir) {
1287 default: SlErrorCorrupt("Invalid vehicle direction");
1288 case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
1289 case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
1290 case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
1291 case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
1292 }
1293 } else if (v->z_pos > GetTileMaxPixelZ(TileVirtXY(v->x_pos, v->y_pos))) {
1294 v->tile = GetNorthernBridgeEnd(v->tile);
1295 v->UpdatePosition();
1296 } else {
1297 continue;
1298 }
1299 if (v->type == VehicleType::Train) {
1301 } else {
1303 }
1304 }
1305 }
1306
1308 /* Add road subtypes */
1309 for (auto t : Map::Iterate()) {
1310 bool has_road = false;
1311 switch (GetTileType(t)) {
1312 case TileType::Road:
1313 has_road = true;
1314 break;
1315 case TileType::Station:
1316 has_road = IsAnyRoadStop(t);
1317 break;
1320 break;
1321 default:
1322 break;
1323 }
1324
1325 if (has_road) {
1326 RoadType road_rt = HasBit(t.m7(), 6) ? ROADTYPE_ROAD : INVALID_ROADTYPE;
1327 RoadType tram_rt = HasBit(t.m7(), 7) ? ROADTYPE_TRAM : INVALID_ROADTYPE;
1328
1329 assert(road_rt != INVALID_ROADTYPE || tram_rt != INVALID_ROADTYPE);
1330 SetRoadTypes(t, road_rt, tram_rt);
1331 SB(t.m7(), 6, 2, 0); // Clear pre-NRT road type bits.
1332 }
1333 }
1334 }
1335
1336 /* Elrails got added in rev 24 */
1338 RailType min_rail = RAILTYPE_ELECTRIC;
1339
1340 for (Train *v : Train::Iterate()) {
1341 RailTypes rts = RailVehInfo(v->engine_type)->railtypes;
1342
1343 v->railtypes = rts;
1344 if (rts.Test(RAILTYPE_ELECTRIC)) min_rail = RAILTYPE_RAIL;
1345 }
1346
1347 /* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
1348 for (const auto t : Map::Iterate()) {
1349 switch (GetTileType(t)) {
1350 case TileType::Railway:
1351 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1352 break;
1353
1354 case TileType::Road:
1355 if (IsLevelCrossing(t)) {
1356 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1357 }
1358 break;
1359
1360 case TileType::Station:
1361 if (HasStationRail(t)) {
1362 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1363 }
1364 break;
1365
1368 SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
1369 }
1370 break;
1371
1372 default:
1373 break;
1374 }
1375 }
1376 }
1377
1378 /* In version 16.1 of the savegame a company can decide if trains, which get
1379 * replaced, shall keep their old length. In all prior versions, just default
1380 * to false */
1382 for (Company *c : Company::Iterate()) c->settings.renew_keep_length = false;
1383 }
1384
1386 /* Waypoints became subclasses of stations ... */
1388 /* ... and buoys were moved to waypoints. */
1390 }
1391
1392 /* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
1393 * room for PBS. Now in version 21 move it back :P. */
1395 for (auto t : Map::Iterate()) {
1396 switch (GetTileType(t)) {
1397 case TileType::Railway:
1398 if (HasSignals(t)) {
1399 /* Original signal type/variant was stored in m4 but since saveload
1400 * version 48 they are in m2. The bits has been already moved to m2
1401 * (see the code somewhere above) so don't use m4, use m2 instead. */
1402
1403 /* convert PBS signals to combo-signals */
1404 if (HasBit(t.m2(), 2)) SB(t.m2(), 0, 2, SIGTYPE_COMBO);
1405
1406 /* move the signal variant back */
1407 SB(t.m2(), 2, 1, HasBit(t.m2(), 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
1408 ClrBit(t.m2(), 3);
1409 }
1410
1411 /* Clear PBS reservation on track */
1412 if (!IsRailDepotTile(t)) {
1413 SB(t.m4(), 4, 4, 0);
1414 } else {
1415 ClrBit(t.m3(), 6);
1416 }
1417 break;
1418
1419 case TileType::Station: // Clear PBS reservation on station
1420 ClrBit(t.m3(), 6);
1421 break;
1422
1423 default: break;
1424 }
1425 }
1426 }
1427
1429 /* Remove obsolete VS_WAIT_FOR_SLOT state from road vehicles. */
1430 static constexpr VehStates OLD_VS_WAIT_FOR_SLOT{0x40};
1431 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
1432 rv->vehstatus.Reset(OLD_VS_WAIT_FOR_SLOT);
1433 }
1434 }
1435
1437 for (Station *st : Station::Iterate()) {
1438 st->last_vehicle_type = VehicleType::Invalid;
1439 }
1440 }
1441
1443
1446 }
1447
1448 for (Company *c : Company::Iterate()) {
1449 c->avail_railtypes = GetCompanyRailTypes(c->index);
1450 c->avail_roadtypes = GetCompanyRoadTypes(c->index);
1451 }
1452
1453 AfterLoadStations();
1454
1455 /* Time starts at 0 instead of 1920.
1456 * Account for this in older games by adding an offset */
1462
1466 for (Company *c : Company::Iterate()) c->inaugurated_year += EconomyTime::ORIGINAL_BASE_YEAR;
1467 for (Industry *i : Industry::Iterate()) i->last_prod_year += EconomyTime::ORIGINAL_BASE_YEAR;
1468
1469 for (Vehicle *v : Vehicle::Iterate()) {
1470 v->date_of_last_service += EconomyTime::DAYS_TILL_ORIGINAL_BASE_YEAR;
1471 v->build_year += CalendarTime::ORIGINAL_BASE_YEAR;
1472 }
1473 }
1474
1475 /* From 32 on we save the industry who made the farmland.
1476 * To give this prettiness to old savegames, we remove all farmfields and
1477 * plant new ones. */
1479 for (const auto t : Map::Iterate()) {
1481 /* remove fields */
1483 }
1484 }
1485
1486 for (Industry *i : Industry::Iterate()) {
1487 uint j;
1488
1490 for (j = 0; j != 50; j++) PlantRandomFarmField(i);
1491 }
1492 }
1493 }
1494
1495 /* Setting no refit flags to all orders in savegames from before refit in orders were added */
1497 for (OrderList *orderlist : OrderList::Iterate()) {
1498 for (Order &order : orderlist->GetOrders()) {
1499 order.SetRefit(CARGO_NO_REFIT);
1500 }
1501 }
1502
1503 for (Vehicle *v : Vehicle::Iterate()) {
1504 v->current_order.SetRefit(CARGO_NO_REFIT);
1505 }
1506 }
1507
1508 /* from version 38 we have optional elrails, since we cannot know the
1509 * preference of a user, let elrails enabled; it can be disabled manually */
1510 if (IsSavegameVersionBefore(SLV_38)) _settings_game.vehicle.disable_elrails = false;
1511 /* do the same as when elrails were enabled/disabled manually just now */
1512 UpdateDisableElrailSettingState(_settings_game.vehicle.disable_elrails, false);
1514
1515 /* From version 53, the map array was changed for house tiles to allow
1516 * space for newhouses grf features. A new byte, m7, was also added. */
1518 for (auto t : Map::Iterate()) {
1519 if (IsTileType(t, TileType::House)) {
1520 if (GB(t.m3(), 6, 2) != TOWN_HOUSE_COMPLETED) {
1521 /* Move the construction stage from m3[7..6] to m5[5..4].
1522 * The construction counter does not have to move. */
1523 SB(t.m5(), 3, 2, GB(t.m3(), 6, 2));
1524 SB(t.m3(), 6, 2, 0);
1525
1526 /* The "house is completed" bit is now in m6[2]. */
1527 SetHouseCompleted(t, false);
1528 } else {
1529 /* The "lift has destination" bit has been moved from
1530 * m5[7] to m7[0]. */
1531 AssignBit(t.m7(), 0, HasBit(t.m5(), 7));
1532 ClrBit(t.m5(), 7);
1533
1534 /* The "lift is moving" bit has been removed, as it does
1535 * the same job as the "lift has destination" bit. */
1536 ClrBit(t.m1(), 7);
1537
1538 /* The position of the lift goes from m1[7..0] to m6[7..2],
1539 * making m1 totally free, now. The lift position does not
1540 * have to be a full byte since the maximum value is 36. */
1541 SetLiftPosition(t, GB(t.m1(), 0, 6 ));
1542
1543 t.m1() = 0;
1544 t.m3() = 0;
1545 SetHouseCompleted(t, true);
1546 }
1547 }
1548 }
1549 }
1550
1552 for (auto t : Map::Iterate()) {
1553 if (IsTileType(t, TileType::House)) {
1554 /* House type is moved from m4 + m3[6] to m8. */
1555 SetHouseType(t, t.m4() | (GB(t.m3(), 6, 1) << 8));
1556 t.m4() = 0;
1557 ClrBit(t.m3(), 6);
1558 }
1559 }
1560 }
1561
1563 for (auto t : Map::Iterate()) {
1564 if (IsTileType(t, TileType::House)) {
1565 /* We now store house protection status in the map. Set this based on the house spec flags. */
1566 const HouseSpec *hs = HouseSpec::Get(GetHouseType(t));
1568 }
1569 }
1570 }
1571
1572 /* Check and update house and town values */
1574
1576 for (auto t : Map::Iterate()) {
1578 switch (GetIndustryGfx(t)) {
1579 case GFX_POWERPLANT_SPARKS:
1580 t.m3() = GB(t.m1(), 2, 5);
1581 break;
1582
1583 case GFX_OILWELL_ANIMATED_1:
1584 case GFX_OILWELL_ANIMATED_2:
1585 case GFX_OILWELL_ANIMATED_3:
1586 t.m3() = GB(t.m1(), 0, 2);
1587 break;
1588
1589 case GFX_COAL_MINE_TOWER_ANIMATED:
1590 case GFX_COPPER_MINE_TOWER_ANIMATED:
1591 case GFX_GOLD_MINE_TOWER_ANIMATED:
1592 t.m3() = t.m1();
1593 break;
1594
1595 default: // No animation states to change
1596 break;
1597 }
1598 }
1599 }
1600 }
1601
1603 /* Originally just the fact that some cargo had been paid for was
1604 * stored to stop people cheating and cashing in several times. This
1605 * wasn't enough though as it was cleared when the vehicle started
1606 * loading again, even if it didn't actually load anything, so now the
1607 * amount that has been paid is stored. */
1608 for (Vehicle *v : Vehicle::Iterate()) {
1609 v->vehicle_flags.Reset(VehicleFlag{2});
1610 }
1611 }
1612
1613 /* Buoys do now store the owner of the previous water tile, which can never
1614 * be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
1616 for (Waypoint *wp : Waypoint::Iterate()) {
1617 if (wp->facilities.Test(StationFacility::Dock) && IsTileOwner(wp->xy, OWNER_NONE) && TileHeight(wp->xy) == 0) SetTileOwner(wp->xy, OWNER_WATER);
1618 }
1619 }
1620
1622 /* Aircraft units changed from 8 mph to 1 km-ish/h */
1623 for (Aircraft *v : Aircraft::Iterate()) {
1624 if (v->subtype <= AIR_AIRCRAFT) {
1625 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
1626 v->cur_speed *= 128;
1627 v->cur_speed /= 10;
1628 v->acceleration = avi->acceleration;
1629 }
1630 }
1631 }
1632
1634 /* Perform conversion of very old face bits. */
1635 for (Company *c : Company::Iterate()) {
1636 c->face = ConvertFromOldCompanyManagerFace(c->face.bits);
1637 }
1639 /* Convert old gender and ethnicity bits to face style. */
1640 for (Company *c : Company::Iterate()) {
1641 SetCompanyManagerFaceStyle(c->face, GB(c->face.bits, 0, 2));
1642 }
1643 } else {
1644 /* Look up each company face style by its label. */
1645 for (Company *c : Company::Iterate()) {
1646 auto style = FindCompanyManagerFaceLabel(c->face.style_label);
1647 if (style.has_value()) {
1648 SetCompanyManagerFaceStyle(c->face, *style);
1649 } else {
1650 /* Style no longer exists, pick an entirely new face. */
1652 }
1653 }
1654 }
1655
1657 for (auto t : Map::Iterate()) {
1658 if (IsTileType(t, TileType::Object) && t.m5() == OBJECT_STATUE) {
1659 t.m2() = CalcClosestTownFromTile(t)->index.base();
1660 }
1661 }
1662 }
1663
1664 /* A setting containing the proportion of towns that grow twice as
1665 * fast was added in version 54. From version 56 this is now saved in the
1666 * town as cities can be built specifically in the scenario editor. */
1668 for (Town *t : Town::Iterate()) {
1669 if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
1670 t->larger_town = true;
1671 }
1672 }
1673 }
1674
1676 /* Added a FIFO queue of vehicles loading at stations */
1677 for (Vehicle *v : Vehicle::Iterate()) {
1678 if ((v->type != VehicleType::Train || Train::From(v)->IsFrontEngine()) && // for all locs
1679 !v->vehstatus.Any({VehState::Stopped, VehState::Crashed}) && // not stopped or crashed
1680 v->current_order.IsType(OT_LOADING)) { // loading
1681 Station::Get(v->last_station_visited)->loading_vehicles.push_back(v);
1682
1683 /* The loading finished flag is *only* set when actually completely
1684 * finished. Because the vehicle is loading, it is not finished. */
1685 v->vehicle_flags.Reset(VehicleFlag::LoadingFinished);
1686 }
1687 }
1688 } else if (IsSavegameVersionBefore(SLV_59)) {
1689 /* For some reason non-loading vehicles could be in the station's loading vehicle list */
1690
1691 for (Station *st : Station::Iterate()) {
1692 for (auto iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); /* nothing */) {
1693 Vehicle *v = *iter;
1694 if (!v->current_order.IsType(OT_LOADING)) {
1695 iter = st->loading_vehicles.erase(iter);
1696 } else {
1697 ++iter;
1698 }
1699 }
1700 }
1701 }
1702
1704 /* Setting difficulty industry_density other than zero get bumped to +1
1705 * since a new option (very low at position 1) has been added */
1706 if (_settings_game.difficulty.industry_density > IndustryDensity::FundedOnly) {
1707 _settings_game.difficulty.industry_density = static_cast<IndustryDensity>(to_underlying(_settings_game.difficulty.industry_density) + 1);
1708 }
1709
1710 /* Same goes for number of towns, although no test is needed, just an increment */
1711 _settings_game.difficulty.number_towns++;
1712 }
1713
1715 /* Since now we allow different signal types and variants on a single tile.
1716 * Move signal states to m4 to make room and clone the signal type/variant. */
1717 for (auto t : Map::Iterate()) {
1718 if (IsTileType(t, TileType::Railway) && HasSignals(t)) {
1719 /* move signal states */
1720 SetSignalStates(t, GB(t.m2(), 4, 4));
1721 SB(t.m2(), 4, 4, 0);
1722 /* clone signal type and variant */
1723 SB(t.m2(), 4, 3, GB(t.m2(), 0, 3));
1724 }
1725 }
1726 }
1727
1729 /* In some old savegames a bit was cleared when it should not be cleared */
1730 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
1731 if (rv->state == 250 || rv->state == 251) {
1732 SetBit(rv->state, 2);
1733 }
1734 }
1735 }
1736
1738 /* Added variables to support newindustries */
1739 for (Industry *i : Industry::Iterate()) i->founder = OWNER_NONE;
1740 }
1741
1742 /* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
1743 Replace the owner for those by OWNER_NONE. */
1745 for (const auto t : Map::Iterate()) {
1746 if (IsTileType(t, TileType::Water) &&
1748 GetTileOwner(t) == OWNER_WATER &&
1749 TileHeight(t) != 0) {
1751 }
1752 }
1753 }
1754
1755 /*
1756 * Add the 'previous' owner to the ship depots so we can reset it with
1757 * the correct values when it gets destroyed. This prevents that
1758 * someone can remove canals owned by somebody else and it prevents
1759 * making floods using the removal of ship depots.
1760 */
1762 for (auto t : Map::Iterate()) {
1763 if (IsShipDepotTile(t)) {
1764 t.m4() = (TileHeight(t) == 0 ? OWNER_WATER : OWNER_NONE).base();
1765 }
1766 }
1767 }
1768
1770 for (Station *st : Station::Iterate()) {
1771 for (GoodsEntry &ge : st->goods) {
1772 ge.last_speed = 0;
1774 }
1775 }
1776 }
1777
1778 /* At version 78, industry cargo types can be changed, and are stored with the industry. For older save versions
1779 * copy the IndustrySpec's cargo types over to the Industry. */
1781 for (Industry *i : Industry::Iterate()) {
1782 const IndustrySpec *indsp = GetIndustrySpec(i->type);
1783 for (uint j = 0; j < std::size(i->produced); j++) {
1784 i->produced[j].cargo = indsp->produced_cargo[j];
1785 }
1786 for (uint j = 0; j < std::size(i->accepted); j++) {
1787 i->accepted[j].cargo = indsp->accepts_cargo[j];
1788 }
1789 }
1790 }
1791
1792 /* Industry cargo slots were fixed size before (and including) SLV_VEHICLE_ECONOMY_AGE (either 2/3 or 16/16),
1793 * after this they are dynamic. Trim excess slots. */
1795 for (Industry *i : Industry::Iterate()) {
1797 }
1798 }
1799
1800 /* Before version 81, the density of grass was always stored as zero, and
1801 * grassy trees were always drawn fully grassy. Furthermore, trees on rough
1802 * land used to have zero density, now they have full density. Therefore,
1803 * make all grassy/rough land trees have a density of 3. */
1805 for (auto t : Map::Iterate()) {
1806 if (GetTileType(t) == TileType::Trees) {
1807 TreeGround ground_type = (TreeGround)GB(t.m2(), 4, 2);
1808 if (ground_type != TreeGround::SnowOrDesert) SB(t.m2(), 6, 2, 3);
1809 }
1810 }
1811 }
1812
1813
1815 /* Rework of orders. */
1816 for (OrderList *orderlist : OrderList::Iterate()) {
1817 for (Order &o : orderlist->GetOrders()) {
1818 o.ConvertFromOldSavegame();
1819 }
1820 }
1821
1822 for (Vehicle *v : Vehicle::Iterate()) {
1823 if (v->orders != nullptr && v->GetFirstOrder() != nullptr && v->GetFirstOrder()->IsType(OT_NOTHING)) {
1824 v->orders->FreeChain();
1825 v->orders = nullptr;
1826 }
1827
1828 v->current_order.ConvertFromOldSavegame();
1829 if (v->type == VehicleType::Road && v->IsPrimaryVehicle() && v->FirstShared() == v) {
1830 for (Order &order : v->Orders()) order.SetNonStopType(OrderNonStopFlag::NonStop);
1831 }
1832 }
1833 } else if (IsSavegameVersionBefore(SLV_94)) {
1834 /* Unload and transfer are now mutual exclusive. */
1835 for (OrderList *orderlist : OrderList::Iterate()) {
1836 for (Order &order : orderlist->GetOrders()) {
1837 if (order.GetUnloadType() == OrderUnloadType{3}) { // 3 used to mean transfer and don't load.
1838 order.SetUnloadType(OrderUnloadType::Transfer);
1839 order.SetLoadType(OrderLoadType::NoLoad);
1840 }
1841 }
1842 }
1843
1844 for (Vehicle *v : Vehicle::Iterate()) {
1845 if (v->current_order.GetUnloadType() == OrderUnloadType{3}) { // 3 used to mean transfer and don't load.
1846 v->current_order.SetUnloadType(OrderUnloadType::Transfer);
1847 v->current_order.SetLoadType(OrderLoadType::NoLoad);
1848 }
1849 }
1851 /* OrderDepotActionFlags were moved, instead of starting at bit 4 they now start at bit 3. */
1852 for (OrderList *orderlist : OrderList::Iterate()) {
1853 for (Order &order : orderlist->GetOrders()) {
1854 if (!order.IsType(OT_GOTO_DEPOT)) continue;
1855 order.SetDepotActionType(static_cast<OrderDepotActionFlags>(order.GetDepotActionType().base() >> 1));
1856 }
1857 }
1858
1859 for (Vehicle *v : Vehicle::Iterate()) {
1860 if (!v->current_order.IsType(OT_GOTO_DEPOT)) continue;
1861 v->current_order.SetDepotActionType(static_cast<OrderDepotActionFlags>(v->current_order.GetDepotActionType().base() >> 1));
1862 }
1863 }
1864
1865 /* The water class was moved/unified. */
1867 for (auto t : Map::Iterate()) {
1868 switch (GetTileType(t)) {
1869 case TileType::Station:
1870 switch (GetStationType(t)) {
1872 case StationType::Dock:
1873 case StationType::Buoy:
1874 SetWaterClass(t, (WaterClass)GB(t.m3(), 0, 2));
1875 SB(t.m3(), 0, 2, 0);
1876 break;
1877
1878 default:
1880 break;
1881 }
1882 break;
1883
1884 case TileType::Water:
1885 SetWaterClass(t, (WaterClass)GB(t.m3(), 0, 2));
1886 SB(t.m3(), 0, 2, 0);
1887 break;
1888
1889 case TileType::Object:
1891 break;
1892
1893 default:
1894 /* No water class. */
1895 break;
1896 }
1897 }
1898 }
1899
1901 for (auto t : Map::Iterate()) {
1902 /* Move river flag and update canals to use water class */
1903 if (IsTileType(t, TileType::Water)) {
1904 if (GetWaterClass(t) != WaterClass::River) {
1905 if (IsWater(t)) {
1906 Owner o = GetTileOwner(t);
1907 if (o == OWNER_WATER) {
1908 MakeSea(t);
1909 } else {
1910 MakeCanal(t, o, Random());
1911 }
1912 } else if (IsShipDepot(t)) {
1913 Owner o = (Owner)t.m4(); // Original water owner
1915 }
1916 }
1917 }
1918 }
1919
1920 /* Update locks, depots, docks and buoys to have a water class based
1921 * on its neighbouring tiles. Done after river and canal updates to
1922 * ensure neighbours are correct. */
1923 for (const auto t : Map::Iterate()) {
1924 if (!IsTileFlat(t)) continue;
1925
1928 }
1929 }
1930
1932 for (const auto t : Map::Iterate()) {
1933 /* skip oil rigs at borders! */
1934 if ((IsTileType(t, TileType::Water) || IsBuoyTile(t)) &&
1935 (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == Map::MaxX() - 1 || TileY(t) == Map::MaxY() - 1)) {
1936 /* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
1937 * This conversion has to be done before buoys with invalid owner are removed. */
1939 }
1940
1942 Owner o = GetTileOwner(t);
1943 if (o < MAX_COMPANIES && !Company::IsValidID(o)) {
1944 AutoRestoreBackup cur_company(_current_company, o);
1946 }
1947 if (IsBuoyTile(t)) {
1948 /* reset buoy owner to OWNER_NONE in the station struct
1949 * (even if it is owned by active company) */
1951 }
1952 } else if (IsTileType(t, TileType::Road)) {
1953 /* works for all RoadTileType */
1954 for (RoadTramType rtt : ROADTRAMTYPES_ALL) {
1955 /* update even non-existing road types to update tile owner too */
1956 Owner o = GetRoadOwner(t, rtt);
1957 if (o < MAX_COMPANIES && !Company::IsValidID(o)) SetRoadOwner(t, rtt, OWNER_NONE);
1958 }
1959 if (IsLevelCrossing(t)) {
1961 }
1962 } else if (IsPlainRailTile(t)) {
1964 }
1965 }
1966 }
1967
1969 /* Profits are now with 8 bit fract */
1970 for (Vehicle *v : Vehicle::Iterate()) {
1971 v->profit_this_year <<= 8;
1972 v->profit_last_year <<= 8;
1973 v->running_ticks = 0;
1974 }
1975 }
1976
1978 /* Increase HouseAnimationFrame from 5 to 7 bits */
1979 for (auto t : Map::Iterate()) {
1981 SB(t.m6(), 2, 6, GB(t.m6(), 3, 5));
1982 SB(t.m3(), 5, 1, 0);
1983 }
1984 }
1985 }
1986
1988 GroupStatistics::UpdateAfterLoad(); // Ensure statistics pool is initialised before trying to delete vehicles
1989 /* Remove all trams from savegames without tram support.
1990 * There would be trams without tram track under causing crashes sooner or later. */
1991 for (RoadVehicle *v : RoadVehicle::Iterate()) {
1992 if (v->First() == v && EngInfo(v->engine_type)->misc_flags.Test(EngineMiscFlag::RoadIsTram)) {
1993 ShowErrorMessage(GetEncodedString(STR_WARNING_LOADGAME_REMOVED_TRAMS), {}, WL_CRITICAL);
1994 delete v;
1995 }
1996 }
1997 }
1998
2000 for (auto t : Map::Iterate()) {
2001 /* Set newly introduced WaterClass of industry tiles */
2002 if (IsTileType(t, TileType::Station) && IsOilRig(t)) {
2004 }
2008 } else {
2010 }
2011 }
2012
2013 /* Replace "house construction year" with "house age" */
2016 }
2017 }
2018 }
2019
2020 /* Move the signal variant back up one bit for PBS. We don't convert the old PBS
2021 * format here, as an old layout wouldn't work properly anyway. To be safe, we
2022 * clear any possible PBS reservations as well. */
2024 for (auto t : Map::Iterate()) {
2025 switch (GetTileType(t)) {
2026 case TileType::Railway:
2027 if (HasSignals(t)) {
2028 /* move the signal variant */
2031 ClrBit(t.m2(), 2);
2032 ClrBit(t.m2(), 6);
2033 }
2034
2035 /* Clear PBS reservation on track */
2036 if (IsRailDepot(t)) {
2037 SetDepotReservation(t, false);
2038 } else {
2040 }
2041 break;
2042
2043 case TileType::Road: // Clear PBS reservation on crossing
2044 if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
2045 break;
2046
2047 case TileType::Station: // Clear PBS reservation on station
2048 if (HasStationRail(t)) SetRailStationReservation(t, false);
2049 break;
2050
2051 case TileType::TunnelBridge: // Clear PBS reservation on tunnels/bridges
2053 break;
2054
2055 default: break;
2056 }
2057 }
2058 }
2059
2060 /* Reserve all tracks trains are currently on. */
2062 for (const Train *t : Train::Iterate()) {
2063 if (t->First() == t) t->ReserveTrackUnderConsist();
2064 }
2065 }
2066
2068 /* Non-town-owned roads now store the closest town */
2070
2071 /* signs with invalid owner left from older savegames */
2072 for (Sign *si : Sign::Iterate()) {
2073 if (si->owner != OWNER_NONE && !Company::IsValidID(si->owner)) si->owner = OWNER_NONE;
2074 }
2075
2076 /* Station can get named based on an industry type, but the current ones
2077 * are not, so mark them as if they are not named by an industry. */
2078 for (Station *st : Station::Iterate()) {
2079 st->indtype = IT_INVALID;
2080 }
2081 }
2082
2084 for (Aircraft *a : Aircraft::Iterate()) {
2085 /* Set engine_type of shadow and rotor */
2086 if (!a->IsNormalAircraft()) {
2087 a->engine_type = a->First()->engine_type;
2088 }
2089 }
2090
2091 /* More companies ... */
2092 for (Company *c : Company::Iterate()) {
2093 if (c->bankrupt_asked.base() == 0xFF) c->bankrupt_asked.Set();
2094 }
2095
2096 for (Engine *e : Engine::Iterate()) {
2097 if (e->company_avail.base() == 0xFF) e->company_avail.Set();
2098 }
2099
2100 for (Town *t : Town::Iterate()) {
2101 if (t->have_ratings.base() == 0xFF) t->have_ratings.Set();
2102 t->ratings.fill(RATING_INITIAL);
2103 }
2104 }
2105
2107 for (auto t : Map::Iterate()) {
2108 /* Check for HQ bit being set, instead of using map accessor,
2109 * since we've already changed it code-wise */
2110 if (IsTileType(t, TileType::Object) && HasBit(t.m5(), 7)) {
2111 /* Move size and part identification of HQ out of the m5 attribute,
2112 * on new locations */
2113 t.m3() = GB(t.m5(), 0, 5);
2114 t.m5() = OBJECT_HQ;
2115 }
2116 }
2117 }
2119 for (auto t : Map::Iterate()) {
2120 if (!IsTileType(t, TileType::Object)) continue;
2121
2122 /* Reordering/generalisation of the object bits. */
2123 ObjectType type = t.m5();
2124 SB(t.m6(), 2, 4, type == OBJECT_HQ ? GB(t.m3(), 2, 3) : 0);
2125 t.m3() = type == OBJECT_HQ ? GB(t.m3(), 1, 1) | GB(t.m3(), 0, 1) << 4 : 0;
2126
2127 /* Make sure those bits are clear as well! */
2128 t.m4() = 0;
2129 t.m7() = 0;
2130 }
2131 }
2132
2134 /* Make real objects for object tiles. */
2135 for (auto t : Map::Iterate()) {
2136 if (!IsTileType(t, TileType::Object)) continue;
2137
2138 if (Town::GetNumItems() == 0) {
2139 /* No towns, so remove all objects! */
2140 DoClearSquare(t);
2141 } else {
2142 uint offset = t.m3();
2143
2144 /* Also move the animation state. */
2145 t.m3() = GB(t.m6(), 2, 4);
2146 SB(t.m6(), 2, 4, 0);
2147
2148 if (offset == 0) {
2149 /* No offset, so make the object. */
2150 ObjectType type = t.m5();
2151 int size = type == OBJECT_HQ ? 2 : 1;
2152
2153 if (!Object::CanAllocateItem()) {
2154 /* Nice... you managed to place 64k lighthouses and
2155 * antennae on the map... boohoo. */
2156 SlError(STR_ERROR_TOO_MANY_OBJECTS);
2157 }
2158
2159 Object *o = Object::Create();
2160 o->location.tile = (TileIndex)t;
2161 o->location.w = size;
2162 o->location.h = size;
2164 o->town = type == OBJECT_STATUE ? Town::Get(t.m2()) : CalcClosestTownFromTile(t, UINT_MAX);
2165 t.m2() = o->index.base();
2166 } else {
2167 /* We're at an offset, so get the ID from our "root". */
2168 Tile northern_tile = t - TileXY(GB(offset, 0, 4), GB(offset, 4, 4));
2169 assert(IsTileType(northern_tile, TileType::Object));
2170 t.m2() = northern_tile.m2();
2171 }
2172 }
2173 }
2174 }
2175
2177 /* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
2178 if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
2179 _settings_game.economy.allow_town_roads = false;
2180 _settings_game.economy.town_layout = TL_BETTER_ROADS;
2181 } else {
2182 _settings_game.economy.allow_town_roads = true;
2183 _settings_game.economy.town_layout = static_cast<TownLayout>(_settings_game.economy.town_layout - 1);
2184 }
2185
2186 /* Initialize layout of all towns. Older versions were using different
2187 * generator for random town layout, use it if needed. */
2188 for (Town *t : Town::Iterate()) {
2189 if (_settings_game.economy.town_layout != TL_RANDOM) {
2190 t->layout = _settings_game.economy.town_layout;
2191 continue;
2192 }
2193
2194 /* Use old layout randomizer code */
2195 uint8_t layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
2196 switch (layout) {
2197 default: break;
2198 case 5: layout = 1; break;
2199 case 0: layout = 2; break;
2200 }
2201 t->layout = static_cast<TownLayout>(layout - 1);
2202 }
2203 }
2204
2206 /* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
2207 * The conversion affects oil rigs and buoys too, but it doesn't matter as
2208 * they have st->owner == OWNER_NONE already. */
2209 for (Station *st : Station::Iterate()) {
2210 if (!Company::IsValidID(st->owner)) st->owner = OWNER_NONE;
2211 }
2212 }
2213
2214 /* Trains could now stop in a specific location. */
2216 for (OrderList *orderlist : OrderList::Iterate()) {
2217 for (Order &o : orderlist->GetOrders()) {
2218 if (o.IsType(OT_GOTO_STATION)) o.SetStopLocation(OrderStopLocation::FarEnd);
2219 }
2220 }
2221 }
2222
2225 for (Company *c : Company::Iterate()) {
2226 c->settings.vehicle = _old_vds;
2227 }
2228 }
2229
2231 /* Tile for no orders is now INVALID_TILE instead of 0. */
2232 for (Vehicle *v : Vehicle::Iterate()) {
2233 if (v->dest_tile == 0) v->SetDestTile(INVALID_TILE);
2234 }
2235 }
2236
2238 /* Delete small ufos heading for non-existing vehicles */
2240 if (v->subtype == 2 /* ST_SMALL_UFO */ && v->state != 0) {
2241 const Vehicle *u = Vehicle::GetIfValid(v->dest_tile.base());
2242 if (u == nullptr || u->type != VehicleType::Road || !RoadVehicle::From(u)->IsFrontEngine()) {
2243 delete v;
2244 }
2245 }
2246 }
2247
2248 /* We didn't store cargo payment yet, so make them for vehicles that are
2249 * currently at a station and loading/unloading. If they don't get any
2250 * payment anymore they just removed in the next load/unload cycle.
2251 * However, some 0.7 versions might have cargo payment. For those we just
2252 * add cargopayment for the vehicles that don't have it.
2253 */
2254 for (Station *st : Station::Iterate()) {
2255 for (Vehicle *v : st->loading_vehicles) {
2256 /* There are always as many CargoPayments as Vehicles. We need to make the
2257 * assert() in Pool::GetNew() happy by calling CanAllocateItem(). */
2260 if (v->cargo_payment == nullptr) v->cargo_payment = CargoPayment::Create(v);
2261 }
2262 }
2263 }
2264
2266 /* Animated tiles would sometimes not be actually animated or
2267 * in case of old savegames duplicate. */
2268
2269 extern std::vector<TileIndex> _animated_tiles;
2270
2271 for (auto tile = _animated_tiles.begin(); tile < _animated_tiles.end(); /* Nothing */) {
2272 /* Remove if tile is not animated */
2273 bool remove = !MayAnimateTile(*tile);
2274
2275 /* and remove if duplicate */
2276 for (auto j = _animated_tiles.begin(); !remove && j < tile; j++) {
2277 remove = *tile == *j;
2278 }
2279
2280 if (remove) {
2281 tile = _animated_tiles.erase(tile);
2282 } else {
2283 tile++;
2284 }
2285 }
2286 }
2287
2289 for (auto t : Map::Iterate()) {
2290 if (!IsTileType(t, TileType::Water)) continue;
2291 SetNonFloodingWaterTile(t, false);
2292 }
2293 }
2294
2296 /* Animated tile state is stored in the map array, allowing
2297 * quicker addition and deletion of animated tiles. */
2298
2299 extern std::vector<TileIndex> _animated_tiles;
2300
2301 for (auto t : Map::Iterate()) {
2302 /* Ensure there is no spurious animated tile state. */
2304 }
2305
2306 /* Set animated flag for all valid animated tiles. */
2307 for (const TileIndex &tile : _animated_tiles) {
2309 }
2310 }
2311
2313 /* The train station tile area was added, but for really old (TTDPatch) it's already valid. */
2314 for (Waypoint *wp : Waypoint::Iterate()) {
2315 if (wp->facilities.Test(StationFacility::Train)) {
2316 wp->train_station.tile = wp->xy;
2317 wp->train_station.w = 1;
2318 wp->train_station.h = 1;
2319 } else {
2320 wp->train_station.tile = INVALID_TILE;
2321 wp->train_station.w = 0;
2322 wp->train_station.h = 0;
2323 }
2324 }
2325 }
2326
2328 /* Convert old subsidies */
2329 for (Subsidy *s : Subsidy::Iterate()) {
2330 if (s->remaining < 12) {
2331 /* Converting nonawarded subsidy */
2332 s->remaining = 12 - s->remaining; // convert "age" to "remaining"
2333 s->awarded = CompanyID::Invalid(); // not awarded to anyone
2334 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2335 switch (cs->town_acceptance_effect) {
2338 /* Town -> Town */
2339 s->src.type = s->dst.type = SourceType::Town;
2340 if (Town::IsValidID(s->src.ToTownID()) && Town::IsValidID(s->dst.ToTownID())) continue;
2341 break;
2344 /* Industry -> Town */
2345 s->src.type = SourceType::Industry;
2346 s->dst.type = SourceType::Town;
2347 if (Industry::IsValidID(s->src.ToIndustryID()) && Town::IsValidID(s->dst.ToTownID())) continue;
2348 break;
2349 default:
2350 /* Industry -> Industry */
2351 s->src.type = s->dst.type = SourceType::Industry;
2352 if (Industry::IsValidID(s->src.ToIndustryID()) && Industry::IsValidID(s->dst.ToIndustryID())) continue;
2353 break;
2354 }
2355 } else {
2356 /* Do our best for awarded subsidies. The original source or destination industry
2357 * can't be determined anymore for awarded subsidies, so invalidate them.
2358 * Town -> Town subsidies are converted using simple heuristic */
2359 s->remaining = 24 - s->remaining; // convert "age of awarded subsidy" to "remaining"
2360 const CargoSpec *cs = CargoSpec::Get(s->cargo_type);
2361 switch (cs->town_acceptance_effect) {
2364 /* Town -> Town */
2365 const Station *ss = Station::GetIfValid(s->src.id);
2366 const Station *sd = Station::GetIfValid(s->dst.id);
2367 if (ss != nullptr && sd != nullptr && ss->owner == sd->owner &&
2369 s->src.type = s->dst.type = SourceType::Town;
2370 s->src.SetIndex(ss->town->index);
2371 s->dst.SetIndex(sd->town->index);
2372 s->awarded = ss->owner;
2373 continue;
2374 }
2375 break;
2376 }
2377 default:
2378 break;
2379 }
2380 }
2381 /* Awarded non-town subsidy or invalid source/destination, invalidate */
2382 delete s;
2383 }
2384 }
2385
2387 /* Recompute inflation based on old unround loan limit
2388 * Note: Max loan is 500000. With an inflation of 4% across 170 years
2389 * that results in a max loan of about 0.7 * 2^31.
2390 * So taking the 16 bit fractional part into account there are plenty of bits left
2391 * for unmodified savegames ...
2392 */
2393 uint64_t aimed_inflation = (_economy.old_max_loan_unround << 16 | _economy.old_max_loan_unround_fract) / _settings_game.difficulty.max_loan;
2394
2395 /* ... well, just clamp it then. */
2396 if (aimed_inflation > MAX_INFLATION) aimed_inflation = MAX_INFLATION;
2397
2398 /* Simulate the inflation, so we also get the payment inflation */
2399 while (_economy.inflation_prices < aimed_inflation) {
2400 if (AddInflation(false)) break;
2401 }
2402 }
2403
2405 for (const Depot *d : Depot::Iterate()) {
2406 Tile tile = d->xy;
2407 /* At some point, invalid depots were saved into the game (possibly those removed in the past?)
2408 * Remove them here, so they don't cause issues further down the line */
2409 if (!IsDepotTile(tile)) {
2410 Debug(sl, 0, "Removing invalid depot {} at {}, {}", d->index, TileX(d->xy), TileY(d->xy));
2411 delete d;
2412 d = nullptr;
2413 continue;
2414 }
2415 tile.m2() = d->index.base();
2416 if (IsTileType(tile, TileType::Water)) Tile(GetOtherShipDepotTile(tile)).m2() = d->index.base();
2417 }
2418 }
2419
2420 /* The behaviour of force_proceed has been changed. Now
2421 * it counts signals instead of some random time out. */
2423 for (Train *t : Train::Iterate()) {
2424 if (t->force_proceed != TFP_NONE) {
2425 t->force_proceed = TFP_STUCK;
2426 }
2427 }
2428 }
2429
2430 /* The bits for the tree ground and tree density have
2431 * been swapped (m2 bits 7..6 and 5..4. */
2433 for (auto t : Map::Iterate()) {
2434 if (IsTileType(t, TileType::Clear)) {
2435 if (GetClearGround(t) == ClearGround{4}) { // CLEAR_SNOW becomes ClearGround::Grass with IsSnowTile() set.
2437 SetBit(t.m3(), 4);
2438 } else {
2439 ClrBit(t.m3(), 4);
2440 }
2441 }
2442 if (IsTileType(t, TileType::Trees)) {
2443 uint density = GB(t.m2(), 6, 2);
2444 uint ground = GB(t.m2(), 4, 2);
2445 t.m2() = ground << 6 | density << 4;
2446 }
2447 }
2448 }
2449
2450 /* Wait counter and load/unload ticks got split. */
2452 for (Aircraft *a : Aircraft::Iterate()) {
2453 a->turn_counter = a->current_order.IsType(OT_LOADING) ? 0 : a->load_unload_ticks;
2454 }
2455
2456 for (Train *t : Train::Iterate()) {
2457 t->wait_counter = t->current_order.IsType(OT_LOADING) ? 0 : t->load_unload_ticks;
2458 }
2459 }
2460
2461 /* Airport tile animation uses animation frame instead of other graphics id */
2463 struct AirportTileConversion {
2464 uint8_t old_start;
2465 uint8_t num_frames;
2466 };
2467 static const AirportTileConversion atcs[] = {
2468 {31, 12}, // APT_RADAR_GRASS_FENCE_SW
2469 {50, 4}, // APT_GRASS_FENCE_NE_FLAG
2470 {62, 2}, // 1 unused tile
2471 {66, 12}, // APT_RADAR_FENCE_SW
2472 {78, 12}, // APT_RADAR_FENCE_NE
2473 {101, 10}, // 9 unused tiles
2474 {111, 8}, // 7 unused tiles
2475 {119, 15}, // 14 unused tiles (radar)
2476 {140, 4}, // APT_GRASS_FENCE_NE_FLAG_2
2477 };
2478 for (const auto t : Map::Iterate()) {
2479 if (IsAirportTile(t)) {
2480 StationGfx old_gfx = GetStationGfx(t);
2481 uint8_t offset = 0;
2482 for (const auto &atc : atcs) {
2483 if (old_gfx < atc.old_start) {
2484 SetStationGfx(t, old_gfx - offset);
2485 break;
2486 }
2487 if (old_gfx < atc.old_start + atc.num_frames) {
2488 SetAnimationFrame(t, old_gfx - atc.old_start);
2489 SetStationGfx(t, atc.old_start - offset);
2490 break;
2491 }
2492 offset += atc.num_frames - 1;
2493 }
2494 }
2495 }
2496 }
2497
2498 /* Oilrig was moved from id 15 to 9. */
2500 for (Station *st : Station::Iterate()) {
2501 if (st->airport.tile != INVALID_TILE && st->airport.type == 15) {
2502 st->airport.type = AT_OILRIG;
2503 }
2504 }
2505 }
2506
2508 for (Station *st : Station::Iterate()) {
2509 if (st->airport.tile != INVALID_TILE) {
2510 st->airport.w = st->airport.GetSpec()->size_x;
2511 st->airport.h = st->airport.GetSpec()->size_y;
2512 }
2513 }
2514 }
2515
2517 for (const auto t : Map::Iterate()) {
2518 /* Reset tropic zone for VOID tiles, they shall not have any. */
2520 }
2521
2522 /* We need to properly number/name the depots.
2523 * The first step is making sure none of the depots uses the
2524 * 'default' names, after that we can assign the names. */
2525 for (Depot *d : Depot::Iterate()) d->town_cn = UINT16_MAX;
2526
2527 for (Depot *d : Depot::Iterate()) MakeDefaultName(d);
2528 }
2529
2531 for (Depot *d : Depot::Iterate()) d->build_date = TimerGameCalendar::date;
2532 }
2533
2535 for (Station *st : Station::Iterate()) {
2536 if (st->facilities.Test(StationFacility::Airport)) st->airport.rotation = DIR_N;
2537 }
2538 }
2539
2540 /* In old versions it was possible to remove an airport while a plane was
2541 * taking off or landing. This gives all kind of problems when building
2542 * another airport in the same station so we don't allow that anymore.
2543 * For old savegames with such aircraft we just throw them in the air and
2544 * treat the aircraft like they were flying already. */
2546 for (Aircraft *v : Aircraft::Iterate()) {
2547 if (!v->IsNormalAircraft()) continue;
2549 if (st == nullptr && v->state != FLYING) {
2550 v->state = FLYING;
2553 /* get aircraft back on running altitude */
2554 if (!v->vehstatus.Test(VehState::Crashed)) {
2555 GetAircraftFlightLevelBounds(v, &v->z_pos, nullptr);
2556 SetAircraftPosition(v, v->x_pos, v->y_pos, GetAircraftFlightLevel(v));
2557 }
2558 }
2559 }
2560 }
2561
2562 /* Move the animation frame to the same location (m7) for all objects. */
2564 for (auto t : Map::Iterate()) {
2565 switch (GetTileType(t)) {
2566 case TileType::House:
2567 if (GetHouseType(t) >= NEW_HOUSE_OFFSET) {
2568 uint per_proc = t.m7();
2569 t.m7() = GB(t.m6(), 2, 6) | (GB(t.m3(), 5, 1) << 6);
2570 SB(t.m3(), 5, 1, 0);
2571 SB(t.m6(), 2, 6, std::min(per_proc, 63U));
2572 }
2573 break;
2574
2575 case TileType::Industry: {
2576 uint rand = t.m7();
2577 t.m7() = t.m3();
2578 t.m3() = rand;
2579 break;
2580 }
2581
2582 case TileType::Object:
2583 t.m7() = t.m3();
2584 t.m3() = 0;
2585 break;
2586
2587 default:
2588 /* For stations/airports it's already at m7 */
2589 break;
2590 }
2591 }
2592 }
2593
2594 /* Add (random) colour to all objects. */
2596 for (Object *o : Object::Iterate()) {
2597 Owner owner = GetTileOwner(o->location.tile);
2598 o->recolour_offset = (owner == OWNER_NONE) ? GB(Random(), 0, 4) : to_underlying(Company::Get(owner)->livery[0].colour1);
2599 }
2600 }
2601
2603 for (const auto t : Map::Iterate()) {
2604 if (!IsTileType(t, TileType::Station)) continue;
2605 if (!IsBuoy(t) && !IsOilRig(t) && !(IsDock(t) && IsTileFlat(t))) {
2607 }
2608 }
2609
2610 /* Waypoints with custom name may have a non-unique town_cn,
2611 * renumber those. First set all affected waypoints to the
2612 * highest possible number to get them numbered in the
2613 * order they have in the pool. */
2614 for (Waypoint *wp : Waypoint::Iterate()) {
2615 if (!wp->name.empty()) wp->town_cn = UINT16_MAX;
2616 }
2617
2618 for (Waypoint *wp : Waypoint::Iterate()) {
2619 if (!wp->name.empty()) MakeDefaultName(wp);
2620 }
2621 }
2622
2624 _industry_builder.Reset(); // Initialize industry build data.
2625
2626 /* The moment vehicles go from hidden to visible changed. This means
2627 * that vehicles don't always get visible anymore causing things to
2628 * get messed up just after loading the savegame. This fixes that. */
2629 for (Vehicle *v : Vehicle::Iterate()) {
2630 /* Not all vehicle types can be inside a tunnel. Furthermore,
2631 * testing IsTunnelTile() for invalid tiles causes a crash. */
2632 if (!v->IsGroundVehicle()) continue;
2633
2634 /* Is the vehicle in a tunnel? */
2635 if (!IsTunnelTile(v->tile)) continue;
2636
2637 /* Is the vehicle actually at a tunnel entrance/exit? */
2638 TileIndex vtile = TileVirtXY(v->x_pos, v->y_pos);
2639 if (!IsTunnelTile(vtile)) continue;
2640
2641 /* Are we actually in this tunnel? Or maybe a lower tunnel? */
2642 if (GetSlopePixelZ(v->x_pos, v->y_pos, true) != v->z_pos) continue;
2643
2644 /* What way are we going? */
2645 const DiagDirection dir = GetTunnelBridgeDirection(vtile);
2646 const DiagDirection vdir = DirToDiagDir(v->direction);
2647
2648 /* Have we passed the visibility "switch" state already? */
2649 uint8_t pos = (DiagDirToAxis(vdir) == AXIS_X ? v->x_pos : v->y_pos) & TILE_UNIT_MASK;
2650 uint8_t frame = (vdir == DIAGDIR_NE || vdir == DIAGDIR_NW) ? TILE_SIZE - 1 - pos : pos;
2651 extern const uint8_t _tunnel_visibility_frame[DIAGDIR_END];
2652
2653 /* Should the vehicle be hidden or not? */
2654 bool hidden;
2655 if (dir == vdir) { // Entering tunnel
2656 hidden = frame >= _tunnel_visibility_frame[dir];
2657 v->tile = vtile;
2658 } else if (dir == ReverseDiagDir(vdir)) { // Leaving tunnel
2659 hidden = frame < TILE_SIZE - _tunnel_visibility_frame[dir];
2660 /* v->tile changes at the moment when the vehicle leaves the tunnel. */
2661 v->tile = hidden ? GetOtherTunnelBridgeEnd(vtile) : vtile;
2662 } else {
2663 /* We could get here in two cases:
2664 * - for road vehicles, it is reversing at the end of the tunnel
2665 * - it is crashed in the tunnel entry (both train or RV destroyed by UFO)
2666 * Whatever case it is, do not change anything and use the old values.
2667 * Especially changing RV's state would break its reversing in the middle. */
2668 continue;
2669 }
2670
2671 if (hidden) {
2672 v->vehstatus.Set(VehState::Hidden);
2673
2674 switch (v->type) {
2677 default: NOT_REACHED();
2678 }
2679 } else {
2680 v->vehstatus.Reset(VehState::Hidden);
2681
2682 switch (v->type) {
2684 case VehicleType::Road: RoadVehicle::From(v)->state = DiagDirToDiagTrackdir(vdir); RoadVehicle::From(v)->frame = frame; break;
2685 default: NOT_REACHED();
2686 }
2687 }
2688 }
2689 }
2690
2692 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
2693 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) continue;
2694
2695 bool loading = rv->current_order.IsType(OT_LOADING) || rv->current_order.IsType(OT_LEAVESTATION);
2696 if (HasBit(rv->state, RVS_IN_ROAD_STOP)) {
2697 extern const uint8_t _road_stop_stop_frame[];
2698 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)]);
2699 } else if (HasBit(rv->state, RVS_IN_DT_ROAD_STOP)) {
2700 SB(rv->state, RVS_ENTERED_STOP, 1, loading || rv->frame > RVC_DRIVE_THROUGH_STOP_FRAME);
2701 }
2702 }
2703 }
2704
2706 /* The train's pathfinder lost flag got moved. */
2707 for (Train *t : Train::Iterate()) {
2708 if (!t->flags.Test(VehicleRailFlag{5})) continue;
2709
2710 t->flags.Reset(VehicleRailFlag{5});
2711 t->vehicle_flags.Set(VehicleFlag::PathfinderLost);
2712 }
2713
2714 /* Introduced terraform/clear limits. */
2715 for (Company *c : Company::Iterate()) {
2716 c->terraform_limit = _settings_game.construction.terraform_frame_burst << 16;
2717 c->clear_limit = _settings_game.construction.clear_frame_burst << 16;
2718 }
2719 }
2720
2721
2723 /*
2724 * The logic of GetPartialPixelZ has been changed, so the resulting Zs on
2725 * the map are consistent. This requires that the Z position of some
2726 * vehicles is updated to reflect this new situation.
2727 *
2728 * This needs to be before SLV_158, because that performs asserts using
2729 * GetSlopePixelZ which internally uses GetPartialPixelZ.
2730 */
2731 for (Vehicle *v : Vehicle::Iterate()) {
2732 if (v->IsGroundVehicle() && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2733 /* Vehicle is on the ground, and not in a wormhole. */
2734 v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos, true);
2735 }
2736 }
2737 }
2738
2740 for (Vehicle *v : Vehicle::Iterate()) {
2741 switch (v->type) {
2742 case VehicleType::Train: {
2743 Train *t = Train::From(v);
2744
2745 /* Clear old GOINGUP / GOINGDOWN flags.
2746 * It was changed in savegame version 139, but savegame
2747 * version 158 doesn't use these bits, so it doesn't hurt
2748 * to clear them unconditionally. */
2751
2752 /* Clear both bits first. */
2755
2756 /* Crashed vehicles can't be going up/down. */
2757 if (t->vehstatus.Test(VehState::Crashed)) break;
2758
2759 /* Only X/Y tracks can be sloped. */
2760 if (t->track != TRACK_BIT_X && t->track != TRACK_BIT_Y) break;
2761
2763 break;
2764 }
2765 case VehicleType::Road: {
2769
2770 /* Crashed vehicles can't be going up/down. */
2771 if (rv->vehstatus.Test(VehState::Crashed)) break;
2772
2773 if (rv->state == RVSB_IN_DEPOT || rv->state == RVSB_WORMHOLE) break;
2774
2775 TrackStatus ts = GetTileTrackStatus(rv->tile, TRANSPORT_ROAD, GetRoadTramType(rv->roadtype));
2776 TrackBits trackbits = TrackStatusToTrackBits(ts);
2777
2778 /* Only X/Y tracks can be sloped. */
2779 if (trackbits != TRACK_BIT_X && trackbits != TRACK_BIT_Y) break;
2780
2781 Direction dir = rv->direction;
2782
2783 /* Test if we are reversing. */
2784 Axis a = trackbits == TRACK_BIT_X ? AXIS_X : AXIS_Y;
2785 if (AxisToDirection(a) != dir &&
2786 AxisToDirection(a) != ReverseDir(dir)) {
2787 /* When reversing, the road vehicle is on the edge of the tile,
2788 * so it can be safely compared to the middle of the tile. */
2789 dir = INVALID_DIR;
2790 }
2791
2792 rv->gv_flags |= FixVehicleInclination(rv, dir);
2793 break;
2794 }
2795 case VehicleType::Ship:
2796 break;
2797
2798 default:
2799 continue;
2800 }
2801
2802 if (IsBridgeTile(v->tile) && TileVirtXY(v->x_pos, v->y_pos) == v->tile) {
2803 /* In old versions, z_pos was 1 unit lower on bridge heads.
2804 * However, this invalid state could be converted to new savegames
2805 * by loading and saving the game in a new version. */
2806 v->z_pos = GetSlopePixelZ(v->x_pos, v->y_pos, true);
2808 if (v->type == VehicleType::Train && !v->vehstatus.Test(VehState::Crashed) &&
2809 v->direction != DiagDirToDir(dir)) {
2810 /* If the train has left the bridge, it shouldn't have
2811 * track == TRACK_BIT_WORMHOLE - this could happen
2812 * when the train was reversed while on the last "tick"
2813 * on the ramp before leaving the ramp to the bridge. */
2815 }
2816 }
2817
2818 /* If the vehicle is really above v->tile (not in a wormhole),
2819 * it should have set v->z_pos correctly. */
2820 assert(v->tile != TileVirtXY(v->x_pos, v->y_pos) || v->z_pos == GetSlopePixelZ(v->x_pos, v->y_pos, true));
2821 }
2822
2823 /* Fill Vehicle::cur_real_order_index */
2824 for (Vehicle *v : Vehicle::Iterate()) {
2825 if (!v->IsPrimaryVehicle()) continue;
2826
2827 /* Older versions are less strict with indices being in range and fix them on the fly */
2828 if (v->cur_implicit_order_index >= v->GetNumOrders()) v->cur_implicit_order_index = 0;
2829
2830 v->cur_real_order_index = v->cur_implicit_order_index;
2831 v->UpdateRealOrderIndex();
2832 }
2833 }
2834
2836 /* If the savegame is old (before version 100), then the value of 255
2837 * for these settings did not mean "disabled". As such everything
2838 * before then did reverse.
2839 * To simplify stuff we disable all turning around or we do not
2840 * disable anything at all. So, if some reversing was disabled we
2841 * will keep reversing disabled, otherwise it'll be turned on. */
2842 _settings_game.pf.reverse_at_signals = IsSavegameVersionBefore(SLV_100) || (_settings_game.pf.wait_oneway_signal != 255 && _settings_game.pf.wait_twoway_signal != 255 && _settings_game.pf.wait_for_pbs_path != 255);
2843
2844 for (Train *t : Train::Iterate()) {
2845 _settings_game.vehicle.max_train_length = std::max<uint8_t>(_settings_game.vehicle.max_train_length, CeilDiv(t->gcache.cached_total_length, TILE_SIZE));
2846 }
2847 }
2848
2850 /* Setting difficulty industry_density other than zero get bumped to +1
2851 * since a new option (minimal at position 1) has been added */
2852 if (_settings_game.difficulty.industry_density > IndustryDensity::FundedOnly) {
2853 _settings_game.difficulty.industry_density = static_cast<IndustryDensity>(to_underlying(_settings_game.difficulty.industry_density) + 1);
2854 }
2855 }
2856
2858 /* Before savegame version 161, persistent storages were not stored in a pool. */
2859
2861 for (Industry *ind : Industry::Iterate()) {
2862 assert(ind->psa != nullptr);
2863
2864 /* Check if the old storage was empty. */
2865 bool is_empty = true;
2866 for (uint i = 0; i < sizeof(ind->psa->storage); i++) {
2867 if (ind->psa->GetValue(i) != 0) {
2868 is_empty = false;
2869 break;
2870 }
2871 }
2872
2873 if (!is_empty) {
2874 ind->psa->grfid = _industry_mngr.GetGRFID(ind->type);
2875 } else {
2876 delete ind->psa;
2877 ind->psa = nullptr;
2878 }
2879 }
2880 }
2881
2883 for (Station *st : Station::Iterate()) {
2884 if (!st->facilities.Test(StationFacility::Airport)) continue;
2885 assert(st->airport.psa != nullptr);
2886
2887 /* Check if the old storage was empty. */
2888 bool is_empty = true;
2889 for (uint i = 0; i < sizeof(st->airport.psa->storage); i++) {
2890 if (st->airport.psa->GetValue(i) != 0) {
2891 is_empty = false;
2892 break;
2893 }
2894 }
2895
2896 if (!is_empty) {
2897 st->airport.psa->grfid = _airport_mngr.GetGRFID(st->airport.type);
2898 } else {
2899 delete st->airport.psa;
2900 st->airport.psa = nullptr;
2901
2902 }
2903 }
2904 }
2905 }
2906
2907 /* This triggers only when old snow_lines were copied into the snow_line_height. */
2908 if (IsSavegameVersionBefore(SLV_164) && _settings_game.game_creation.snow_line_height >= MIN_SNOWLINE_HEIGHT * TILE_HEIGHT) {
2909 _settings_game.game_creation.snow_line_height /= TILE_HEIGHT;
2910 }
2911
2913 /* We store 4 fences in the field tiles instead of only SE and SW. */
2914 for (auto t : Map::Iterate()) {
2915 if (!IsTileType(t, TileType::Clear) && !IsTileType(t, TileType::Trees)) continue;
2917 uint fence = GB(t.m4(), 5, 3);
2918 if (fence != 0 && IsTileType(TileAddXY(t, 1, 0), TileType::Clear) && IsClearGround(TileAddXY(t, 1, 0), ClearGround::Fields)) {
2919 SetFence(TileAddXY(t, 1, 0), DIAGDIR_NE, fence);
2920 }
2921 fence = GB(t.m4(), 2, 3);
2922 if (fence != 0 && IsTileType(TileAddXY(t, 0, 1), TileType::Clear) && IsClearGround(TileAddXY(t, 0, 1), ClearGround::Fields)) {
2923 SetFence(TileAddXY(t, 0, 1), DIAGDIR_NW, fence);
2924 }
2925 SB(t.m4(), 2, 3, 0);
2926 SB(t.m4(), 5, 3, 0);
2927 }
2928 }
2929
2931 /* Vehicles used to be reversed immediately when entering depot.
2932 * Now they are reversed when the whole consist has entered.
2933 * Find trains in the process of entering a depot and un-reverse them. */
2934 for (Train *t : Train::Iterate()) {
2935 if (!t->IsPrimaryVehicle()) continue;
2936
2937 /* Front not in depot -> consist not entering depot */
2938 if (t->track != TRACK_BIT_DEPOT) continue;
2939 /* Back in depot -> consist completely in depot */
2940 if (t->Last()->track == TRACK_BIT_DEPOT) continue;
2941 for (Train *u = t; u->track == TRACK_BIT_DEPOT; u = u->Next()) {
2942 u->direction = ReverseDir(u->direction);
2943 }
2944 }
2945
2946 /* Update the setting for train flipping. */
2947 _settings_game.difficulty.train_flip_reverse_allowed = _settings_game.difficulty.line_reverse_mode ? TrainFlipReversingAllowed::EndOfLineOnly : TrainFlipReversingAllowed::All;
2948 }
2949
2951 for (Town *t : Town::Iterate()) {
2952 /* Set the default cargo requirement for town growth */
2953 switch (_settings_game.game_creation.landscape) {
2956 break;
2957
2961 break;
2962
2963 default:
2964 break;
2965 }
2966 }
2967 }
2968
2970 /* Adjust zoom level to account for new levels */
2971 _saved_scrollpos_zoom += ZOOM_BASE_SHIFT;
2972 _saved_scrollpos_x *= ZOOM_BASE;
2973 _saved_scrollpos_y *= ZOOM_BASE;
2974 }
2975
2976 /* When any NewGRF has been changed the availability of some vehicles might
2977 * have been changed too. e->company_avail must be set to 0 in that case
2978 * which is done by StartupEngines(). */
2980
2981 /* The road owner of standard road stops was not properly accounted for. */
2983 for (const auto t : Map::Iterate()) {
2984 if (!IsBayRoadStopTile(t)) continue;
2985 Owner o = GetTileOwner(t);
2988 }
2989 }
2990
2992 /* Introduced tree planting limit. */
2993 for (Company *c : Company::Iterate()) c->tree_limit = _settings_game.construction.tree_frame_burst << 16;
2994 }
2995
2997 /* Fix too high inflation rates */
2998 if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION;
2999 if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION;
3000
3001 /* We have to convert the quarters of bankruptcy into months of bankruptcy */
3002 for (Company *c : Company::Iterate()) {
3003 c->months_of_bankruptcy = 3 * c->months_of_bankruptcy;
3004 }
3005 }
3006
3008 /* Aircraft acceleration variable was bonkers */
3009 for (Aircraft *v : Aircraft::Iterate()) {
3010 if (v->subtype <= AIR_AIRCRAFT) {
3011 const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
3012 v->acceleration = avi->acceleration;
3013 }
3014 }
3015
3016 /* Blocked tiles could be reserved due to a bug, which causes
3017 * other places to assert upon e.g. station reconstruction. */
3018 for (const auto t : Map::Iterate()) {
3020 SetRailStationReservation(t, false);
3021 }
3022 }
3023 }
3024
3026 /* The global units configuration is split up in multiple configurations. */
3027 extern uint8_t _old_units;
3028 _settings_game.locale.units_velocity = Clamp(_old_units, 0, 2);
3029 _settings_game.locale.units_power = Clamp(_old_units, 0, 2);
3030 _settings_game.locale.units_weight = Clamp(_old_units, 1, 2);
3031 _settings_game.locale.units_volume = Clamp(_old_units, 1, 2);
3032 _settings_game.locale.units_force = 2;
3033 _settings_game.locale.units_height = Clamp(_old_units, 0, 2);
3034 }
3035
3037 /* Match nautical velocity with land velocity units. */
3038 _settings_game.locale.units_velocity_nautical = _settings_game.locale.units_velocity;
3039 }
3040
3042 /* Move ObjectType from map to pool */
3043 for (auto t : Map::Iterate()) {
3044 if (IsTileType(t, TileType::Object)) {
3045 Object *o = Object::Get(t.m2());
3046 o->type = t.m5();
3047 t.m5() = 0; // zero upper bits of (now bigger) ObjectID
3048 }
3049 }
3050 }
3051
3052 /* Beyond this point, tile types which can be accessed by vehicles must be in a valid state. */
3053
3054 /* Update all vehicles: Phase 2 */
3056
3057 /* The center of train vehicles was changed, fix up spacing. */
3059
3060 /* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
3061 * This has to be called after all map array updates */
3063
3065 /* Fix articulated road vehicles.
3066 * Some curves were shorter than other curves.
3067 * Now they have the same length, but that means that trailing articulated parts will
3068 * take longer to go through the curve than the parts in front which already left the curve.
3069 * So, make articulated parts catch up. */
3070 bool roadside = _settings_game.vehicle.road_side == 1;
3071 std::vector<uint> skip_frames;
3072 for (RoadVehicle *v : RoadVehicle::Iterate()) {
3073 if (!v->IsFrontEngine()) continue;
3074 skip_frames.clear();
3075 TileIndex prev_tile = v->tile;
3076 uint prev_tile_skip = 0;
3077 uint cur_skip = 0;
3078 for (RoadVehicle *u = v; u != nullptr; u = u->Next()) {
3079 if (u->tile != prev_tile) {
3080 prev_tile_skip = cur_skip;
3081 prev_tile = u->tile;
3082 } else {
3083 cur_skip = prev_tile_skip;
3084 }
3085
3086 uint &this_skip = skip_frames.emplace_back(prev_tile_skip);
3087
3088 /* The following 3 curves now take longer than before */
3089 switch (u->state) {
3090 case 2:
3091 cur_skip++;
3092 if (u->frame <= (roadside ? 9 : 5)) this_skip = cur_skip;
3093 break;
3094
3095 case 4:
3096 cur_skip++;
3097 if (u->frame <= (roadside ? 5 : 9)) this_skip = cur_skip;
3098 break;
3099
3100 case 5:
3101 cur_skip++;
3102 if (u->frame <= (roadside ? 4 : 2)) this_skip = cur_skip;
3103 break;
3104
3105 default:
3106 break;
3107 }
3108 }
3109 while (cur_skip > skip_frames[0]) {
3110 RoadVehicle *u = v;
3111 RoadVehicle *prev = nullptr;
3112 for (uint sf : skip_frames) {
3113 if (sf >= cur_skip) IndividualRoadVehicleController(u, prev);
3114
3115 prev = u;
3116 u = u->Next();
3117 }
3118 cur_skip--;
3119 }
3120 }
3121 }
3122
3124 for (OrderList *orderlist : OrderList::Iterate()) {
3125 for (Order &order : orderlist->GetOrders()) {
3126 order.SetTravelTimetabled(order.GetTravelTime() > 0);
3127 order.SetWaitTimetabled(order.GetWaitTime() > 0);
3128 }
3129 orderlist->RecalculateTimetableDuration();
3130 }
3131 }
3132
3133 /*
3134 * Only keep order-backups for network clients (and when replaying).
3135 * If we are a network server or not networking, then we just loaded a previously
3136 * saved-by-server savegame. There are no clients with a backup, so clear it.
3137 * Furthermore before savegame version SLV_192 the actual content was always corrupt.
3138 */
3140#ifndef DEBUG_DUMP_COMMANDS
3141 /* Note: We cannot use CleanPool since that skips part of the destructor
3142 * and then leaks un-reachable Orders in the order pool. */
3143 for (OrderBackup *ob : OrderBackup::Iterate()) {
3144 delete ob;
3145 }
3146#endif
3147 }
3148
3150 /* Convert towns growth_rate and grow_counter to ticks */
3151 for (Town *t : Town::Iterate()) {
3152 /* 0x8000 = TOWN_GROWTH_RATE_CUSTOM previously */
3153 if (t->growth_rate & 0x8000) t->flags.Set(TownFlag::CustomGrowth);
3154 if (t->growth_rate != TOWN_GROWTH_RATE_NONE) {
3155 t->growth_rate = TownTicksToGameTicks(t->growth_rate & ~0x8000);
3156 }
3157 /* Add t->index % TOWN_GROWTH_TICKS to spread growth across ticks. */
3158 t->grow_counter = TownTicksToGameTicks(t->grow_counter) + t->index % Ticks::TOWN_GROWTH_TICKS;
3159 }
3160 }
3161
3163 /* Make sure added industry cargo slots are cleared */
3164 for (Industry *i : Industry::Iterate()) {
3165 /* Make sure last_cargo_accepted_at is copied to elements for every valid input cargo.
3166 * The loading routine should put the original singular value into the first array element. */
3167 for (auto &a : i->accepted) {
3168 if (IsValidCargoType(a.cargo)) {
3169 a.last_accepted = i->GetAccepted(0).last_accepted;
3170 } else {
3171 a.last_accepted = EconomyTime::MIN_DATE;
3172 }
3173 }
3174 }
3175 }
3176
3178 /* Move ships from lock slope to upper or lower position. */
3179 for (Ship *s : Ship::Iterate()) {
3180 /* Suitable tile? */
3181 if (!IsTileType(s->tile, TileType::Water) || !IsLock(s->tile) || GetLockPart(s->tile) != LockPart::Middle) continue;
3182
3183 /* We don't need to adjust position when at the tile centre */
3184 int x = s->x_pos & 0xF;
3185 int y = s->y_pos & 0xF;
3186 if (x == 8 && y == 8) continue;
3187
3188 /* Test if ship is on the second half of the tile */
3189 bool second_half;
3190 DiagDirection shipdiagdir = DirToDiagDir(s->direction);
3191 switch (shipdiagdir) {
3192 default: NOT_REACHED();
3193 case DIAGDIR_NE: second_half = x < 8; break;
3194 case DIAGDIR_NW: second_half = y < 8; break;
3195 case DIAGDIR_SW: second_half = x > 8; break;
3196 case DIAGDIR_SE: second_half = y > 8; break;
3197 }
3198
3199 DiagDirection slopediagdir = GetInclinedSlopeDirection(GetTileSlope(s->tile));
3200
3201 /* Heading up slope == passed half way */
3202 if ((shipdiagdir == slopediagdir) == second_half) {
3203 /* On top half of lock */
3204 s->z_pos = GetTileMaxZ(s->tile) * (int)TILE_HEIGHT;
3205 } else {
3206 /* On lower half of lock */
3207 s->z_pos = GetTileZ(s->tile) * (int)TILE_HEIGHT;
3208 }
3209 }
3210 }
3211
3213 /* Ensure the original cargo generation mode is used */
3214 _settings_game.economy.town_cargogen_mode = TCGM_ORIGINAL;
3215 }
3216
3218 /* Ensure the original neutral industry/station behaviour is used */
3219 _settings_game.station.serve_neutral_industries = true;
3220
3221 /* Link oil rigs to their industry and back. */
3222 for (Station *st : Station::Iterate()) {
3223 if (IsTileType(st->xy, TileType::Station) && IsOilRig(st->xy)) {
3224 /* Industry tile is always adjacent during construction by TileDiffXY(0, 1) */
3225 st->industry = Industry::GetByTile(st->xy + TileDiffXY(0, 1));
3226 st->industry->neutral_station = st;
3227 }
3228 }
3229 } else {
3230 /* Link neutral station back to industry, as this is not saved. */
3231 for (Industry *ind : Industry::Iterate()) if (ind->neutral_station != nullptr) ind->neutral_station->industry = ind;
3232 }
3233
3235 /* Update water class for trees. */
3236 for (const auto t : Map::Iterate()) {
3238 }
3239 }
3240
3241 /* Update structures for multitile docks */
3243 for (const auto t : Map::Iterate()) {
3244 /* Clear docking tile flag from relevant tiles as it
3245 * was not previously cleared. */
3247 SetDockingTile(t, false);
3248 }
3249 /* Add docks and oilrigs to Station::ship_station. */
3250 if (IsTileType(t, TileType::Station)) {
3251 if (IsDock(t) || IsOilRig(t)) Station::GetByTile(t)->ship_station.Add(t);
3252 }
3253 }
3254 }
3255
3257 /* Placing objects on docking tiles was not updating adjacent station's docking tiles. */
3258 for (Station *st : Station::Iterate()) {
3259 if (st->ship_station.tile != INVALID_TILE) UpdateStationDockingTiles(st);
3260 }
3261 }
3262
3263 /* Make sure all industries exclusive supplier/consumer set correctly. */
3265 for (Industry *i : Industry::Iterate()) {
3266 i->exclusive_supplier = INVALID_OWNER;
3267 i->exclusive_consumer = INVALID_OWNER;
3268 }
3269 }
3270
3272 /* Propagate wagon removal flag for compatibility */
3273 /* Temporary bitmask of company wagon removal setting */
3274 CompanyMask wagon_removal{};
3275 for (const Company *c : Company::Iterate()) {
3276 if (c->settings.renew_keep_length) wagon_removal.Set(c->index);
3277 }
3278 for (Group *g : Group::Iterate()) {
3279 if (g->flags.Any()) {
3280 /* Convert old replace_protection value to flag. */
3282 }
3283 if (wagon_removal.Test(g->owner)) g->flags.Set(GroupFlag::ReplaceWagonRemoval);
3284 }
3285 }
3286
3287 /* Use current order time to approximate last loading time */
3289 for (Vehicle *v : Vehicle::Iterate()) {
3290 v->last_loading_tick = std::max(TimerGameTick::counter, static_cast<uint64_t>(v->current_order_time)) - v->current_order_time;
3291 }
3292 }
3293
3294 /* Road stops is 'only' updating some caches, but they are needed for PF calls in SLV_MULTITRACK_LEVEL_CROSSINGS teleporting. */
3296
3297 /* Road vehicles stopped on multitrack level crossings need teleporting to a depot
3298 * to avoid crashing into the side of the train they're waiting for. */
3300 /* Teleport road vehicles to the nearest depot. */
3301 for (RoadVehicle *rv : RoadVehicle::Iterate()) {
3302 /* Ignore trailers of articulated vehicles. */
3303 if (rv->IsArticulatedPart()) continue;
3304
3305 /* Ignore moving vehicles. */
3306 if (rv->cur_speed > 0) continue;
3307
3308 /* Ignore crashed vehicles. */
3309 if (rv->vehstatus.Test(VehState::Crashed)) continue;
3310
3311 /* Ignore vehicles not on level crossings. */
3312 TileIndex cur_tile = rv->tile;
3313 if (!IsLevelCrossingTile(cur_tile)) continue;
3314
3315 ClosestDepot closest_depot = rv->FindClosestDepot();
3316
3317 /* Try to find a depot with a distance limit of 512 tiles (Manhattan distance). */
3318 if (closest_depot.found && DistanceManhattan(rv->tile, closest_depot.location) < 512u) {
3319 /* Teleport all parts of articulated vehicles. */
3320 for (RoadVehicle *u = rv; u != nullptr; u = u->Next()) {
3321 u->tile = closest_depot.location;
3322 int x = TileX(closest_depot.location) * TILE_SIZE + TILE_SIZE / 2;
3323 int y = TileY(closest_depot.location) * TILE_SIZE + TILE_SIZE / 2;
3324 u->x_pos = x;
3325 u->y_pos = y;
3326 u->z_pos = GetSlopePixelZ(x, y, true);
3327
3328 u->vehstatus.Set(VehState::Hidden);
3329 u->state = RVSB_IN_DEPOT;
3330 u->UpdatePosition();
3331 }
3332 RoadVehLeaveDepot(rv, false);
3333 }
3334 }
3335
3337 /* Reset unused tree counters to reduce the savegame size. */
3338 for (auto t : Map::Iterate()) {
3339 if (IsTileType(t, TileType::Trees)) {
3340 SB(t.m2(), 0, 4, 0);
3341 }
3342 }
3343 }
3344
3345 /* Refresh all level crossings to bar adjacent crossing tiles, if needed. */
3346 for (const auto tile : Map::Iterate()) {
3347 if (IsLevelCrossingTile(tile)) UpdateLevelCrossing(tile, false);
3348 }
3349 }
3350
3351 /* Compute station catchment areas. This is needed here in case UpdateStationAcceptance is called below. */
3353
3354 /* Station acceptance is some kind of cache */
3356 for (Station *st : Station::Iterate()) UpdateStationAcceptance(st, false);
3357 }
3358
3361 }
3362
3364 /* For older savegames, we don't now the actual interval; so set it to the newgame value. */
3365 _settings_game.difficulty.competitors_interval = _settings_newgame.difficulty.competitors_interval;
3366
3367 /* We did load the "period" of the timer, but not the fired/elapsed. We can deduce that here. */
3369 _new_competitor_timeout.storage.elapsed = 0;
3370 _new_competitor_timeout.fired = _new_competitor_timeout.period.value == 0;
3371 }
3372
3374 /* Set service date provided to NewGRF. */
3375 for (Vehicle *v : Vehicle::Iterate()) {
3376 v->date_of_last_service_newgrf = TimerGameCalendar::Date{v->date_of_last_service.base()};
3377 }
3378 }
3379
3381 /* NewGRF acceleration information was added to ships. */
3382 for (Ship *s : Ship::Iterate()) {
3383 if (s->acceleration == 0) s->acceleration = ShipVehInfo(s->engine_type)->acceleration;
3384 }
3385 }
3386
3388 for (Company *c : Company::Iterate()) {
3389 c->max_loan = COMPANY_MAX_LOAN_DEFAULT;
3390 }
3391 }
3392
3394 ScriptObject::InitializeRandomizers();
3395 }
3396
3398 for (Company *c : Company::Iterate()) {
3399 c->inaugurated_year_calendar = _settings_game.game_creation.starting_year;
3400 }
3401 }
3402
3404 /* Between these two versions (actually from f8b1e303 to 77236258) EngineFlags had an off-by-one. Depending
3405 * on when the save was started, this may or may not affect existing engines. Here we try to detect invalid flags
3406 * and reset them to what they should be. */
3407 for (Engine *e : Engine::Iterate()) {
3408 if (e->flags.Test(EngineFlag::Available)) continue;
3409 if (e->flags.Test(EngineFlag{2}) || (e->flags.Test(EngineFlag::ExclusivePreview) && e->preview_asked.None())) {
3410 e->flags = EngineFlags(e->flags.base() >> 1U);
3411 }
3412 }
3413 }
3414
3416 /* Default waypoints were built with an incorrect layout that prevents building bridges over them. */
3417 for (auto tile : Map::Iterate()) {
3418 if (!IsRailWaypointTile(tile)) continue; // Not a waypoint.
3419 if (GetCustomStationSpecIndex(tile) > 0) continue; // Not a default waypoint.
3420 SetStationGfx(tile, GetStationGfx(tile) & 1);
3421 }
3422 }
3423
3424 for (Company *c : Company::Iterate()) {
3426 }
3427
3428 /* Update free group numbers data for each company, required regardless of savegame version. */
3429 for (Group *g : Group::Iterate()) {
3430 Company *c = Company::Get(g->owner);
3432 /* Use the index as group number when converting old savegames. */
3433 g->number = c->freegroups.UseID(g->index.base());
3434 } else {
3435 c->freegroups.UseID(g->number);
3436 }
3437 }
3438
3442
3443 _gamelog.PrintDebug(1);
3444
3446 /* Restore the signals */
3448
3450
3452
3453 /* Start the scripts. This MUST happen after everything else except
3454 * starting a new company. */
3455 StartScripts();
3456
3457 /* If Load Scenario / New (Scenario) Game is used,
3458 * a company does not exist yet. So create one here.
3459 * 1 exception: network-games. Those can have 0 companies
3460 * But this exception is not true for non-dedicated network servers! */
3462 CompanyID first_human_company = GetFirstPlayableCompanyID();
3463 if (!Company::IsValidID(first_human_company)) {
3464 Company *c = DoStartupNewCompany(false, first_human_company);
3465 c->settings = _settings_client.company;
3466 }
3467 }
3468
3469 return true;
3470}
3471
3481{
3482 /* reload grf data */
3486 /* reload vehicles */
3487 ResetVehicleHash();
3493 /* update station graphics */
3494 AfterLoadStations();
3495 /* Update company statistics. */
3497 /* Check and update house and town values */
3499 /* Delete news referring to no longer existing entities */
3501 /* Update livery selection windows */
3502 for (CompanyID i = CompanyID::Begin(); i < MAX_COMPANIES; ++i) InvalidateWindowData(WC_COMPANY_COLOUR, i);
3503 /* Update company infrastructure counts. */
3506 InvalidateAllPickerWindows();
3507 /* redraw the whole screen */
3510}
static void SetSignalHandlers()
Replaces signal handlers of SIGSEGV and SIGABRT and stores pointers to original handlers in memory.
static uint FixVehicleInclination(Vehicle *v, Direction dir)
Fixes inclination of a vehicle.
static void UpdateExclusiveRights()
Since savegame version 4.1, exclusive transport rights are stored at towns.
Company * DoStartupNewCompany(bool is_ai, CompanyID company=CompanyID::Invalid())
Create a new company and sets all company variables default values.
static void InitializeWindowsAndCaches()
Initialization of the windows and several kinds of caches.
static void CheckGroundVehiclesAtCorrectZ()
Check whether the ground vehicles are at the correct Z-coordinate.
static bool _saveload_crash_with_missing_newgrfs
Was the saveload crash because of missing NewGRFs?
static void HandleSavegameLoadCrash(int signum)
Signal handler used to give a user a more useful report for crashes during the savegame loading proce...
static void FixOwnerOfRailTrack(Tile t)
Tries to change owner of this rail tile to a valid owner.
static void UpdateVoidTiles()
Up to revision 1413 the invisible tiles at the southern border have not been TileType::Void,...
static bool MayHaveBridgeAbove(Tile t)
Checks for the possibility that a bridge may be on this tile These are in fact all the tile types on ...
static void UpdateCurrencies()
Since savegame version 4.2 the currencies are arranged differently.
void SetWaterClassDependingOnSurroundings(Tile t, bool include_invalid_water_class)
Makes a tile canal or water depending on the surroundings.
Definition afterload.cpp:91
static void StartScripts()
Start the scripts.
bool SaveloadCrashWithMissingNewGRFs()
Did loading the savegame cause a crash?
void UpdateAllVirtCoords()
Update the viewport coordinates of all signs.
void ClearOldOrders()
Clear all old orders.
Definition order_sl.cpp:114
bool AfterLoadGame()
Perform a (large) amount of savegame conversion magic in order to load older savegames and to fill th...
void ReloadNewGRFData()
Reload all NewGRF files during a running game.
static void ResetSignalHandlers()
Resets signal handlers back to original handlers.
Base functions for all AIs.
Base for aircraft.
void GetAircraftFlightLevelBounds(const Vehicle *v, int *min, int *max)
Get the 'flight level' bounds, in pixels from 'z_pos' 0 for a particular vehicle for normal flight si...
void AircraftNextAirportPos_and_Order(Aircraft *v)
Set the right pos when heading to other airports after takeoff.
Station * GetTargetAirportIfValid(const Aircraft *v)
Returns aircraft's target station if v->target_airport is a valid station with airport.
void SetAircraftPosition(Aircraft *v, int x, int y, int z)
Set aircraft position.
@ AIR_AIRCRAFT
an airplane
Definition aircraft.h:30
void UpdateAircraftCache(Aircraft *v, bool update_range=false)
Update cached values of an aircraft.
@ FLYING
Vehicle is flying in the air.
Definition airport.h:77
@ AT_OILRIG
Oilrig airport.
Definition airport.h:38
std::vector< TileIndex > _animated_tiles
The table/list with animated tiles.
Tile animation!
Maps accessors for animated tiles.
@ Animated
Tile is animated.
@ None
Tile is not animated.
void SetAnimatedTileState(Tile t, AnimatedTileState state)
Set the animated state of a tile.
Class for backupping variables and making sure they are restored later.
VehicleFlag
Bit numbers in Vehicle::vehicle_flags.
@ PathfinderLost
Vehicle's pathfinder is lost.
@ LoadingFinished
Vehicle has finished loading.
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
constexpr enable_if_t< is_integral_v< T >, T > byteswap(T x) noexcept
Custom implementation of std::byteswap; remove once we build with C++23.
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
TileIndex GetNorthernBridgeEnd(TileIndex t)
Finds the northern end of a bridge starting at a middle tile.
void SetBridgeMiddle(Tile t, Axis a)
Set that there is a bridge over the given axis.
Definition bridge_map.h:114
bool IsBridgeTile(Tile t)
checks if there is a bridge on this tile
Definition bridge_map.h:35
void ClearBridgeMiddle(Tile t)
Removes bridges from the given, that is bridges along the X and Y axis.
Definition bridge_map.h:103
bool IsBridge(Tile t)
Checks if this is a bridge, instead of a tunnel.
Definition bridge_map.h:24
void AfterLoadCompanyStats()
Rebuilding of company statistics after loading a savegame.
bool IsValidCargoType(CargoType cargo)
Test whether cargo type is not INVALID_CARGO.
Definition cargo_type.h:110
static constexpr CargoType CARGO_NO_REFIT
Do not refit cargo of a vehicle (used in vehicle orders and auto-replace/auto-renew).
Definition cargo_type.h:79
@ Food
Cargo behaves food/fizzy-drinks-like.
Definition cargotype.h:29
@ Water
Cargo behaves water-like.
Definition cargotype.h:28
@ Mail
Cargo behaves mail-like.
Definition cargotype.h:26
@ Passengers
Cargo behaves passenger-like.
Definition cargotype.h:25
@ Goods
Cargo behaves goods/candy-like.
Definition cargotype.h:27
static void StartNew(CompanyID company)
Start a new AI company.
Definition ai_core.cpp:36
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Tstorage base() const noexcept
Retrieve the raw value behind this bit set.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
UnitID UseID(UnitID index)
Use a unit number.
Definition vehicle.cpp:1881
static void StartNew()
Start up a new GameScript.
Definition game_core.cpp:70
static constexpr TimerGameTick::Ticks DAY_TICKS
1 day is 74 ticks; TimerGameCalendar::date_fract used to be uint16_t and incremented by 885.
static constexpr TimerGameTick::Ticks TOWN_GROWTH_TICKS
Cycle duration for towns trying to grow (this originates from the size of the town array in TTD).
Wrapper class to abstract away the way the tiles are stored.
Definition map_func.h:25
uint8_t & m5()
General purpose.
Definition map_func.h:156
uint8_t & m6()
General purpose.
Definition map_func.h:167
uint8_t & m7()
Primarily used for newgrf support.
Definition map_func.h:178
uint8_t & m3()
General purpose.
Definition map_func.h:134
uint16_t & m2()
Primarily used for indices to towns, industries and stations.
Definition map_func.h:123
A timeout timer will fire once after the interval.
Definition timer.h:116
static void SetDate(Date date, DateFract fract)
Set the date.
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static DateFract date_fract
Fractional part of the day.
static constexpr TimerGame< struct Economy >::Date MIN_DATE
static constexpr TimerGame< struct Calendar >::Year DEF_END_YEAR
static constexpr TimerGame< struct Economy >::Year MIN_YEAR
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_BASE_YEAR
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
static Date date
Current date in days (day counter).
static Year year
Current year, starting at 0.
static DateFract date_fract
Fractional part of the day.
static void SetDate(Date date, DateFract fract)
Set the date.
static TickCounter counter
Monotonic counter, in ticks, since start of game.
StrongType::Typedef< int32_t, DateTag< struct Economy >, StrongType::Compare, StrongType::Integer > Date
Map accessors for 'clear' tiles.
bool IsClearGround(Tile t, ClearGround ct)
Set the type of clear tile.
Definition clear_map.h:65
void SetFence(Tile t, DiagDirection side, uint h)
Sets the type of fence (and whether there is one) for the given border.
Definition clear_map.h:234
ClearGround
Ground types.
Definition clear_map.h:21
@ Fields
Farm fields (3).
Definition clear_map.h:25
@ Grass
Plain grass with dirt transition (0-3).
Definition clear_map.h:22
void MakeClear(Tile t, ClearGround g, uint density)
Make a clear tile.
Definition clear_map.h:253
ClearGround GetClearGround(Tile t)
Get the type of clear tile.
Definition clear_map.h:52
void SetClearGroundDensity(Tile t, ClearGround type, uint density)
Sets ground type and density in one go, also sets the counter to 0.
Definition clear_map.h:152
uint GetClearDensity(Tile t)
Get the density of a non-field clear tile.
Definition clear_map.h:77
TimeoutTimer< TimerGameTick > _new_competitor_timeout({ TimerGameTick::Priority::CompetitorTimeout, 0 }, []() { if(_game_mode==GM_MENU||!AI::CanStartNew()) return;if(_networking &&Company::GetNumItems() >=_settings_client.network.max_companies) return;if(_settings_game.difficulty.competitors_interval==0) return;uint8_t n=0;for(const Company *c :Company::Iterate()) { if(c->is_ai) n++;} if(n >=_settings_game.difficulty.max_no_competitors) return;Command< Commands::CompanyControl >::Post(CompanyCtrlAction::NewAI, CompanyID::Invalid(), CompanyRemoveReason::None, INVALID_CLIENT_ID);})
Start a new competitor company if possible.
void RandomiseCompanyManagerFace(CompanyManagerFace &cmf, Randomizer &randomizer)
Completely randomise a company manager face, including style.
void ResetCompanyLivery(Company *c)
Reset the livery schemes to the company's primary colour.
void UpdateCompanyLiveries(Company *c)
Update liveries for a company.
void SetCompanyManagerFaceStyle(CompanyManagerFace &cmf, uint style)
Set a company face style.
CompanyID GetFirstPlayableCompanyID()
Get the index of the first available company.
std::optional< uint > FindCompanyManagerFaceLabel(std::string_view label)
Find a company manager face style by label.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
CompanyManagerFace ConvertFromOldCompanyManagerFace(uint32_t face)
Converts an old company manager's face format to the new company manager's face format.
static constexpr Owner OWNER_TOWN
A town owns the tile, or a town is expanding.
static constexpr Owner OWNER_NONE
The tile has no ownership.
static constexpr Owner INVALID_OWNER
An invalid owner.
static constexpr Owner OWNER_WATER
The tile/execution is done by "water".
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
Base for all depots (except hangars).
bool IsDepotTile(Tile tile)
Is the given tile a tile with a depot on it?
Definition depot_map.h:45
Direction DiagDirToDir(DiagDirection dir)
Convert a DiagDirection to a Direction.
DiagDirection ReverseDiagDir(DiagDirection d)
Returns the reverse direction of the given DiagDirection.
Direction ReverseDir(Direction d)
Return the reverse of a direction.
Direction AxisToDirection(Axis a)
Converts an Axis to a Direction.
Axis DiagDirToAxis(DiagDirection d)
Convert a DiagDirection to the axis.
DiagDirection XYNSToDiagDir(Axis xy, uint ns)
Convert an axis and a flag for north/south into a DiagDirection.
DiagDirection DirToDiagDir(Direction dir)
Convert a Direction to a DiagDirection.
Direction
Defines the 8 directions on the map.
@ DIR_SW
Southwest.
@ DIR_NW
Northwest.
@ INVALID_DIR
Flag for an invalid direction.
@ DIR_N
North.
@ DIR_SE
Southeast.
@ DIR_NE
Northeast.
Axis
Allow incrementing of DiagDirDiff variables.
@ AXIS_X
The X axis.
@ AXIS_Y
The y axis.
DiagDirection
Enumeration for diagonal directions.
@ DIAGDIR_NE
Northeast, upper right on your monitor.
@ DIAGDIR_NW
Northwest.
@ DIAGDIR_SE
Southeast.
@ DIAGDIR_END
Used for iterations.
@ DIAGDIR_BEGIN
Used for iterations.
@ DIAGDIR_SW
Southwest.
All disaster vehicles.
void RecomputePrices()
Computes all prices, payments and maximum loan.
Definition economy.cpp:735
bool AddInflation(bool check_year)
Add monthly inflation.
Definition economy.cpp:697
Base classes related to the economy.
static const uint64_t MAX_INFLATION
Maximum inflation (including fractional part) without causing overflows in int64_t price computations...
Header file for electrified rail specific functions.
void StartupEngines()
Start/initialise all our engines.
Definition engine.cpp:826
Functions related to engines.
void CopyTempEngineData()
Copy data from temporary engine array into the real engine pool.
@ RoadIsTram
Road vehicle is a tram/light rail vehicle.
EngineFlag
Engine.flags is a bitmask, with the following values.
@ Available
This vehicle is available to everyone.
@ ExclusivePreview
This vehicle is in the exclusive preview stage, either being used or being offered to a company.
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
Functions related to errors.
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition error.h:27
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
@ Scenario
old or new scenario
Definition fileio_type.h:20
Declarations for savegames operations.
Base functions for all Games.
Gamelog _gamelog
Gamelog instance.
Definition gamelog.cpp:31
Declaration shared among gamelog.cpp and saveload/gamelog_sl.cpp.
void LoadStringWidthTable(FontSizes fontsizes)
Initialize _stringwidth_table cache for the specified font sizes.
Definition gfx.cpp:1261
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:51
void GfxLoadSprites()
Initialise and load all the sprites.
Definition gfxinit.cpp:334
Functions related to the graphics initialization.
@ GVF_GOINGDOWN_BIT
Vehicle is currently going downhill. (Cached track information for acceleration).
@ GVF_GOINGUP_BIT
Vehicle is currently going uphill. (Cached track information for acceleration).
void UpdateGroupChildren()
Update children list for each group.
Definition group_cmd.cpp:47
@ ReplaceProtection
If set, the global autoreplace has no effect on the group.
Definition group.h:68
@ ReplaceWagonRemoval
If set, autoreplace will perform wagon removal on vehicles in this group.
Definition group.h:69
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1554
void MarkTileDirtyByTile(TileIndex tile, int bridge_level_offset, int tile_height_override)
Mark a tile given by its index dirty for repaint.
@ BuildingIsProtected
towns and AI will not remove this house, while human players will be able to
Definition house.h:94
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition house.h:28
static const uint8_t TOWN_HOUSE_COMPLETED
Simple value that indicates the house has reached the final stage of construction.
Definition house.h:25
Base of all industries.
IndustryBuildData _industry_builder
In-game manager of industries.
void TrimIndustryAcceptedProduced(Industry *ind)
Remove unused industry accepted/produced slots – entries after the last slot with valid cargo.
const IndustrySpec * GetIndustrySpec(IndustryType thistype)
Accessor for array _industry_specs.
IndustryType GetIndustryType(Tile tile)
Retrieve the type for this industry.
IndustryGfx GetIndustryGfx(Tile t)
Get the industry graphics ID for the given industry tile.
@ PlantOnBuild
Fields are planted around when built (all farms).
@ BuiltOnWater
is built on water (oil rig)
void AfterLoadLabelMaps()
Perform rail type and road type conversion if necessary.
void ChangeTileOwner(TileIndex tile, Owner old_owner, Owner new_owner)
Change the owner of a tile.
TrackStatus GetTileTrackStatus(TileIndex tile, TransportType mode, RoadTramType sub_mode, DiagDirection side)
Returns information about trackdirs and signal states.
int GetSlopePixelZ(int x, int y, bool ground_vehicle)
Return world Z coordinate of a given point of a tile.
@ Arctic
Landscape with snow levels.
@ Tropic
Landscape with distinct rainforests and deserts,.
void AfterLoadLinkGraphs()
Spawn the threads for running link graph calculations.
@ Manual
Manual distribution. No link graph calculations are run.
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
Definition main_gui.cpp:554
uint DistanceManhattan(TileIndex t0, TileIndex t1)
Gets the Manhattan distance between the two given tiles.
Definition map.cpp:169
TileIndex TileAddXY(TileIndex tile, int x, int y)
Adds a given offset to a tile.
Definition map_func.h:474
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:407
TileIndex TileAddByDiagDir(TileIndex tile, DiagDirection dir)
Adds a DiagDir to a tile.
Definition map_func.h:615
TileIndexDiff TileDiffXY(int x, int y)
Calculates an offset for the given coordinate(-offset).
Definition map_func.h:392
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition map_func.h:376
static uint TileY(TileIndex tile)
Get the Y component of a tile.
Definition map_func.h:429
static uint TileX(TileIndex tile)
Get the X component of a tile.
Definition map_func.h:419
TileIndexDiff TileOffsByDiagDir(DiagDirection dir)
Convert a DiagDirection to a TileIndexDiff.
Definition map_func.h:574
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
constexpr To ClampTo(From value)
Clamp the given value down to lie within the requested type.
void GenerateSavegameId()
Generate an unique savegame ID.
Definition misc.cpp:89
ZoomLevel _saved_scrollpos_zoom
Definition misc_sl.cpp:37
int _saved_scrollpos_x
Definition misc_sl.cpp:35
int _saved_scrollpos_y
Definition misc_sl.cpp:36
bool _networking
are we in networking mode?
Definition network.cpp:67
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:70
bool _network_server
network-server is active
Definition network.cpp:68
Basic functions/variables used all over the place.
Network functions used by other parts of OpenTTD.
Base for the NewGRF implementation.
@ FakeTowns
Fake town GrfSpecFeature for NewGRF debugging (parent scope).
Definition newgrf.h:98
@ Airports
Airports feature.
Definition newgrf.h:86
@ Industries
Industries feature.
Definition newgrf.h:83
void ShowNewGRFError()
Show the first NewGRF error we can find.
uint8_t StationGfx
Copy from station_map.h.
GRFConfigList _grfconfig
First item in list of current GRF set up.
GRFListCompatibility IsGoodGRFConfigList(GRFConfigList &grfconfig)
Check if all GRFs in the GRF config from a savegame can be loaded.
GRFListCompatibility
Status of post-gameload GRF compatibility check.
@ NotFound
At least one GRF couldn't be found (higher priority than GRFListCompatibility::Compatible).
@ AllGood
All GRF needed by game are present.
@ Compatible
Compatible (eg. the same ID, but different checksum) GRF found in at least one case.
@ NotFound
GRF file was not found in the local cache.
@ Compatible
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches).
Header file for NewGRF stations.
Functions related to news.
void DeleteInvalidEngineNews()
Remove engine announcements for invalid engines.
Base for all objects.
Map accessors for object tiles.
uint16_t ObjectType
Types of objects.
Definition object_type.h:16
static const ObjectType OBJECT_STATUE
Statue in towns.
Definition object_type.h:20
static const ObjectType OBJECT_HQ
HeadQuarter of a player.
Definition object_type.h:22
@ Error
A game paused because a (critical) error.
Definition openttd.h:72
@ ActiveClients
A game paused for 'min_active_clients'.
Definition openttd.h:73
@ Normal
A game normally paused.
Definition openttd.h:69
@ Join
A game paused for 'pause_on_join'.
Definition openttd.h:71
Functions related to order backups.
OrderUnloadType
Unloading order types.
Definition order_type.h:67
@ Transfer
Transfer all cargo onto the platform.
Definition order_type.h:70
@ FarEnd
Stop at the far end of the platform.
Definition order_type.h:100
@ NonStop
The vehicle will not stop at any stations it passes except the destination, aka non-stop.
Definition order_type.h:88
@ NoLoad
Do not load anything.
Definition order_type.h:81
Functions/types etc.
RailTypes GetCompanyRailTypes(CompanyID company, bool introduces)
Get the rail types the given company can build.
Definition rail.cpp:137
void InitializeRailGUI()
Resets the rail GUI - sets default railtype to build and resets the signal GUI.
Functions/types etc.
static bool IsPlainRail(Tile t)
Returns whether this is plain rails, with or without signals.
Definition rail_map.h:49
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition rail_map.h:115
static bool IsRailDepot(Tile t)
Is this rail tile a rail depot?
Definition rail_map.h:95
RailGroundType GetRailGroundType(Tile t)
Get the ground type for rail tiles.
Definition rail_map.h:602
static bool IsPlainRailTile(Tile t)
Checks whether the tile is a rail tile or rail tile with signals.
Definition rail_map.h:60
void MakeRailNormal(Tile t, Owner o, TrackBits b, RailType r)
Make the given tile a normal rail.
Definition rail_map.h:625
void SetTrackReservation(Tile t, TrackBits b)
Sets the reserved track bits of the tile.
Definition rail_map.h:209
@ HalfTileWater
Grass with a fence and shore or water on the free halftile.
Definition rail_map.h:583
void SetDepotReservation(Tile t, bool b)
Set the reservation state of the depot.
Definition rail_map.h:269
bool HasSignals(Tile t)
Checks if a rail tile has signals.
Definition rail_map.h:72
void SetSignalVariant(Tile t, Track track, SignalVariant v)
Set the signal variant for a track on a tile.
Definition rail_map.h:399
static bool IsRailDepotTile(Tile t)
Is this tile rail tile and a rail depot?
Definition rail_map.h:105
void SetSignalStates(Tile tile, uint state)
Set the states of the signals (Along/AgainstTrackDir).
Definition rail_map.h:411
void SetRailType(Tile t, RailType r)
Sets the rail type of the given tile.
Definition rail_map.h:125
EnumBitSet< RailType, uint64_t > RailTypes
Allow incrementing of Track variables.
Definition rail_type.h:38
RailType
Enumeration for all possible railtypes.
Definition rail_type.h:25
@ RAILTYPE_ELECTRIC
Electric rails.
Definition rail_type.h:28
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition rail_type.h:27
Randomizer _random
Random used in the game state calculations.
RoadTypes GetCompanyRoadTypes(CompanyID company, bool introduces)
Get the road types the given company can build.
Definition road.cpp:210
void UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
Road related functions.
void UpdateLevelCrossing(TileIndex tile, bool sound=true, bool force_bar=false)
Update a level crossing to barred or open (crossing may include multiple adjacent tiles).
void SetRoadOwner(Tile t, RoadTramType rtt, Owner o)
Set the owner of a specific road type.
Definition road_map.h:261
static RoadTileType GetRoadTileType(Tile t)
Get the type of the road tile.
Definition road_map.h:36
bool HasTownOwnedRoad(Tile t)
Checks if given tile has town owned road.
Definition road_map.h:290
bool IsLevelCrossingTile(Tile t)
Return whether a tile is a level crossing tile.
Definition road_map.h:79
void SetRoadTypes(Tile t, RoadType road_rt, RoadType tram_rt)
Set the present road types of a tile.
Definition road_map.h:630
static bool IsRoadDepot(Tile t)
Return whether a tile is a road depot.
Definition road_map.h:90
@ Normal
Normal road.
Definition road_map.h:23
@ Depot
Depot (one entrance).
Definition road_map.h:25
@ Crossing
Level crossing.
Definition road_map.h:24
RoadBits GetCrossingRoadBits(Tile tile)
Get the road bits of a level crossing.
Definition road_map.h:358
Owner GetRoadOwner(Tile t, RoadTramType rtt)
Get the owner of a specific road type.
Definition road_map.h:244
void SetCrossingReservation(Tile t, bool b)
Set the reservation state of the rail crossing.
Definition road_map.h:403
bool IsLevelCrossing(Tile t)
Return whether a tile is a level crossing.
Definition road_map.h:69
static constexpr RoadBits ROAD_X
Full road along the x-axis (south-west + north-east).
Definition road_type.h:66
EnumBitSet< RoadBit, uint8_t > RoadBits
Bitset of RoadBit elements.
Definition road_type.h:64
static constexpr RoadBits ROAD_Y
Full road along the y-axis (north-west + south-east).
Definition road_type.h:67
static constexpr RoadTramTypes ROADTRAMTYPES_ALL
All possible RoadTramTypes.
Definition road_type.h:48
RoadType
The different roadtypes we support.
Definition road_type.h:23
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition road_type.h:28
@ ROADTYPE_TRAM
Trams.
Definition road_type.h:26
@ ROADTYPE_ROAD
Basic road type.
Definition road_type.h:25
RoadTramType
The different types of road type.
Definition road_type.h:37
@ Invalid
Invalid marker.
Definition road_type.h:41
@ Tram
Tram type.
Definition road_type.h:39
@ Road
Road type.
Definition road_type.h:38
Base class for roadstops.
Road vehicle states.
@ RVS_ENTERED_STOP
Only set when a vehicle has entered the stop.
Definition roadveh.h:43
@ RVSB_IN_ROAD_STOP
The vehicle is in a road stop.
Definition roadveh.h:49
@ RVS_IN_DT_ROAD_STOP
The vehicle is in a drive-through road stop.
Definition roadveh.h:46
@ RVS_IN_ROAD_STOP
The vehicle is in a road stop.
Definition roadveh.h:45
@ RVSB_IN_DEPOT
The vehicle is in a depot.
Definition roadveh.h:38
@ RVSB_WORMHOLE
The vehicle is in a tunnel and/or bridge.
Definition roadveh.h:39
@ RVS_DRIVE_SIDE
Only used when retrieving move data.
Definition roadveh.h:44
static const uint RVC_DRIVE_THROUGH_STOP_FRAME
Stop frame for a vehicle in a drive-through stop.
Definition roadveh.h:82
Command definitions related to road vehicles.
const uint8_t _road_stop_stop_frame[]
Table of road stop stop frames, when to stop at a road stop.
A number of safeguards to prevent using unsafe methods.
void SlError(StringID string, const std::string &extra_msg)
Error handler.
Definition saveload.cpp:339
void SetSaveLoadError(StringID str)
Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friend...
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition saveload.cpp:369
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Definition saveload.cpp:78
bool IsSavegameVersionBefore(SaveLoadVersion major, uint8_t minor=0)
Checks whether the savegame is below major.
Definition saveload.h:1304
@ SLV_AI_START_DATE
309 PR#10653 Removal of individual AI start dates and added a generic one.
Definition saveload.h:350
@ SLV_190
190 26547 Separate order travel and wait times
Definition saveload.h:271
@ SLV_91
91 12347
Definition saveload.h:152
@ SLV_49
49 8969
Definition saveload.h:101
@ SLV_90
90 12293
Definition saveload.h:151
@ SLV_64
64 10006
Definition saveload.h:119
@ SLV_69
69 10319
Definition saveload.h:125
@ SLV_ECONOMY_MODE_TIMEKEEPING_UNITS
327 PR#11341 Mode to display economy measurements in wallclock units.
Definition saveload.h:372
@ SLV_PROTECT_PLACED_HOUSES
351 PR#13270 Houses individually placed by players can be protected from town/AI removal.
Definition saveload.h:401
@ SLV_172
172 23947
Definition saveload.h:249
@ SLV_COMPANY_INAUGURATED_PERIOD_V2
349 PR#13448 Fix savegame storage for company inaugurated year in wallclock mode.
Definition saveload.h:398
@ SLV_182
182 25115 FS#5492, r25259, r25296 Goal status
Definition saveload.h:261
@ SLV_186
186 25833 Objects storage
Definition saveload.h:266
@ SLV_175
175 24136
Definition saveload.h:253
@ SLV_16
16.0 2817 16.1 3155
Definition saveload.h:60
@ SLV_87
87 12129
Definition saveload.h:147
@ SLV_SERVE_NEUTRAL_INDUSTRIES
210 PR#7234 Company stations can serve industries with attached neutral stations.
Definition saveload.h:296
@ SLV_147
147 20621
Definition saveload.h:219
@ SLV_188
188 26169 v1.4 FS#5831 Unify RV travel time
Definition saveload.h:268
@ SLV_61
61 9892
Definition saveload.h:116
@ SLV_84
84 11822
Definition saveload.h:143
@ SLV_25
25 4259
Definition saveload.h:73
@ SLV_15
15.0 2499
Definition saveload.h:59
@ SLV_198
198 PR#6763 Switch town growth rate and counter to actual game ticks
Definition saveload.h:281
@ SLV_36
36 6624
Definition saveload.h:86
@ SLV_26
26 4466
Definition saveload.h:74
@ SLV_96
96 13226
Definition saveload.h:158
@ SLV_EXTEND_RAILTYPES
200 PR#6805 Extend railtypes to 64, adding uint16_t to map array.
Definition saveload.h:284
@ SLV_17
17.0 3212 17.1 3218
Definition saveload.h:62
@ SLV_42
42 7573
Definition saveload.h:93
@ SLV_177
177 24619
Definition saveload.h:255
@ SLV_EXTEND_INDUSTRY_CARGO_SLOTS
202 PR#6867 Increase industry cargo slots to 16 in, 16 out
Definition saveload.h:286
@ SLV_103
103 14598
Definition saveload.h:166
@ SLV_100
100 13952
Definition saveload.h:163
@ SLV_GROUP_REPLACE_WAGON_REMOVAL
291 PR#7441 Per-group wagon removal flag.
Definition saveload.h:329
@ SLV_VELOCITY_NAUTICAL
305 PR#10594 Separation of land and nautical velocity (knots!)
Definition saveload.h:346
@ SLV_VEHICLE_ECONOMY_AGE
334 PR#12141 v14.0 Add vehicle age in economy year, for profit stats minimum age
Definition saveload.h:380
@ SLV_4
4.0 1 4.1 122 0.3.3, 0.3.4 4.2 1222 0.3.5 4.3 1417 4.4 1426
Definition saveload.h:37
@ SLV_TOWN_CARGOGEN
208 PR#6965 New algorithms for town building cargo generation.
Definition saveload.h:293
@ SLV_149
149 20832
Definition saveload.h:221
@ SLV_83
83 11589
Definition saveload.h:142
@ SLV_6
6.0 1721 6.1 1768
Definition saveload.h:46
@ SLV_34
34 6455
Definition saveload.h:83
@ SLV_LINKGRAPH_SECONDS
308 PR#10610 Store linkgraph update intervals in seconds instead of days.
Definition saveload.h:349
@ SLV_114
114 15601
Definition saveload.h:179
@ SLV_137
137 18912
Definition saveload.h:207
@ SLV_SAVEGAME_ID
313 PR#10719 Add an unique ID to every savegame (used to deduplicate surveys).
Definition saveload.h:355
@ SLV_131
131 18481
Definition saveload.h:200
@ SLV_11
11.0 2033 11.1 2041
Definition saveload.h:53
@ SLV_CALENDAR_SUB_DATE_FRACT
328 PR#11428 Add sub_date_fract to measure calendar days.
Definition saveload.h:373
@ SLV_120
120 16439
Definition saveload.h:187
@ SLV_99
99 13838
Definition saveload.h:161
@ SLV_123
123 16909
Definition saveload.h:190
@ SLV_46
46 8705
Definition saveload.h:98
@ SLV_122
122 16855
Definition saveload.h:189
@ SLV_FACE_STYLES
355 PR#14319 Addition of face styles, replacing gender and ethnicity.
Definition saveload.h:406
@ SLV_ENDING_YEAR
218 PR#7747 v1.10 Configurable ending year.
Definition saveload.h:305
@ SLV_141
141 19799
Definition saveload.h:212
@ SLV_112
112 15290
Definition saveload.h:177
@ SLV_125
125 17113
Definition saveload.h:193
@ SLV_166
166 23415
Definition saveload.h:242
@ SLV_STATIONS_UNDER_BRIDGES
359 PR#14477 Allow stations under bridges.
Definition saveload.h:410
@ SLV_98
98 13375
Definition saveload.h:160
@ SLV_WATER_TILE_TYPE
342 PR#13030 Simplify water tile type.
Definition saveload.h:390
@ SLV_117
117 16037
Definition saveload.h:183
@ SLV_140
140 19382
Definition saveload.h:211
@ SLV_126
126 17433
Definition saveload.h:194
@ SLV_138
138 18942 1.0.x
Definition saveload.h:208
@ SLV_ANIMATED_TILE_STATE_IN_MAP
347 PR#13082 Animated tile state saved for improved performance.
Definition saveload.h:396
@ SLV_MULTITILE_DOCKS
216 PR#7380 Multiple docks per station.
Definition saveload.h:303
@ SLV_86
86 12042
Definition saveload.h:146
@ SLV_ROAD_TYPES
214 PR#6811 NewGRF road types.
Definition saveload.h:300
@ SLV_1
1.0 0.1.x, 0.2.x
Definition saveload.h:33
@ SLV_GS_INDUSTRY_CONTROL
287 PR#7912 and PR#8115 GS industry control.
Definition saveload.h:324
@ SLV_164
164 23290
Definition saveload.h:239
@ SLV_160
160 21974 1.1.x
Definition saveload.h:235
@ SLV_38
38 7195
Definition saveload.h:88
@ SLV_145
145 20376
Definition saveload.h:217
@ SLV_48
48 8935
Definition saveload.h:100
@ SLV_57
57 9691
Definition saveload.h:111
@ SLV_104
104 14735
Definition saveload.h:167
@ SLV_52
52 9066
Definition saveload.h:105
@ SLV_134
134 18703
Definition saveload.h:203
@ SLV_165
165 23304
Definition saveload.h:241
@ SLV_144
144 20334
Definition saveload.h:215
@ SLV_2
2.0 0.3.0 2.1 0.3.1, 0.3.2
Definition saveload.h:34
@ SLV_INCREASE_HOUSE_LIMIT
348 PR#12288 Increase house limit to 4096.
Definition saveload.h:397
@ SLV_143
143 20048
Definition saveload.h:214
@ SLV_127
127 17439
Definition saveload.h:195
@ SLV_152
152 21171
Definition saveload.h:225
@ SLV_LAST_LOADING_TICK
301 PR#9693 Store tick of last loading for vehicles.
Definition saveload.h:341
@ SLV_76
76 11139
Definition saveload.h:134
@ SLV_SCRIPT_RANDOMIZER
333 PR#12063 v14.0-RC1 Save script randomizers.
Definition saveload.h:379
@ SLV_78
78 11176
Definition saveload.h:136
@ SLV_106
106 14919
Definition saveload.h:170
@ SLV_DEPOT_UNBUNCHING
331 PR#11945 Allow unbunching shared order vehicles at a depot.
Definition saveload.h:377
@ SLV_119
119 16242
Definition saveload.h:185
@ SLV_139
139 19346
Definition saveload.h:209
@ SLV_SHIP_ACCELERATION
329 PR#10734 Start using Vehicle's acceleration field for ships too.
Definition saveload.h:374
@ SLV_135
135 18719
Definition saveload.h:205
@ SLV_MULTITRACK_LEVEL_CROSSINGS
302 PR#9931 v13.0 Multi-track level crossings.
Definition saveload.h:342
@ SLV_121
121 16694
Definition saveload.h:188
@ SLV_192
192 26700 FS#6066 Fix saving of order backups
Definition saveload.h:274
@ SLV_58
58 9762
Definition saveload.h:112
@ SLV_94
94 12816
Definition saveload.h:155
@ SLV_153
153 21263
Definition saveload.h:226
@ SLV_101
101 14233
Definition saveload.h:164
@ SLV_95
95 12924
Definition saveload.h:157
@ SLV_158
158 21933
Definition saveload.h:232
@ SLV_133
133 18674
Definition saveload.h:202
@ SLV_93
93 12648
Definition saveload.h:154
@ SLV_81
81 11244
Definition saveload.h:140
@ SLV_72
72 10601
Definition saveload.h:129
@ SLV_43
43 7642
Definition saveload.h:94
@ SLV_113
113 15340
Definition saveload.h:178
@ SLV_ECONOMY_DATE
326 PR#10700 Split calendar and economy timers and dates.
Definition saveload.h:371
@ SLV_45
45 8501
Definition saveload.h:97
@ SLV_128
128 18281
Definition saveload.h:196
@ SLV_GROUP_NUMBERS
336 PR#12297 Add per-company group numbers.
Definition saveload.h:383
@ SLV_NEWGRF_LAST_SERVICE
317 PR#11124 Added stable date_of_last_service to avoid NewGRF trouble.
Definition saveload.h:360
@ SLV_53
53 9316
Definition saveload.h:106
@ SLV_161
161 22567
Definition saveload.h:236
@ SLV_74
74 11030
Definition saveload.h:131
@ SLV_184
184 25508 Unit localisation split
Definition saveload.h:263
@ SLV_DRIVE_BACKWARDS
365 PR#15379 Trains can drive backwards.
Definition saveload.h:418
@ SLV_INCREASE_STATION_TYPE_FIELD_SIZE
337 PR#12572 Increase size of StationType field in map array
Definition saveload.h:384
@ SLV_88
88 12134
Definition saveload.h:148
@ SLV_156
156 21728
Definition saveload.h:230
@ SLV_NONFLOODING_WATER_TILES
345 PR#13013 Store water tile non-flooding state.
Definition saveload.h:394
@ SLV_62
62 9905
Definition saveload.h:117
@ SLV_59
59 9779
Definition saveload.h:113
@ SLV_82
82 11410
Definition saveload.h:141
@ SLV_BUOYS_AT_0_0
364 PR#14983 Allow to build buoys at (0x0).
Definition saveload.h:416
@ SLV_194
194 26881 v1.5
Definition saveload.h:276
@ SLV_TREES_WATER_CLASS
213 PR#7405 WaterClass update for tree tiles.
Definition saveload.h:299
@ SLV_124
124 16993
Definition saveload.h:191
@ SLV_159
159 21962
Definition saveload.h:233
@ SLV_32
32 6001
Definition saveload.h:81
@ SLV_56
56 9667
Definition saveload.h:110
@ SLV_SHIPS_STOP_IN_LOCKS
206 PR#7150 Ship/lock movement changes.
Definition saveload.h:291
@ SLV_111
111 15190
Definition saveload.h:176
@ SLV_70
70 10541
Definition saveload.h:127
@ SLV_183
183 25363 Cargodist
Definition saveload.h:262
@ SLV_31
31 5999
Definition saveload.h:80
@ SLV_148
148 20659
Definition saveload.h:220
@ SLV_50
50 8973
Definition saveload.h:103
@ SLV_REPAIR_OBJECT_DOCKING_TILES
299 PR#9594 v12.0 Fixing issue with docking tiles overlapping objects.
Definition saveload.h:338
@ SLV_CONSISTENT_PARTIAL_Z
306 PR#10570 Conversion from an inconsistent partial Z calculation for slopes, to one that is (more) ...
Definition saveload.h:347
@ SLV_142
142 20003
Definition saveload.h:213
@ SLV_21
21 3472 0.4.x
Definition saveload.h:68
@ SLV_136
136 18764
Definition saveload.h:206
@ SLV_146
146 20446
Definition saveload.h:218
@ SLV_SCRIPT_SAVE_INSTANCES
352 PR#13556 Scripts are allowed to save instances.
Definition saveload.h:402
@ SLV_MAX_LOAN_FOR_COMPANY
330 PR#11224 Separate max loan for each company.
Definition saveload.h:376
@ SLV_24
24 4150
Definition saveload.h:71
@ SLV_9
9.0 1909
Definition saveload.h:50
bool IsSavegameVersionBeforeOrAt(SaveLoadVersion major)
Checks whether the savegame is below or at major.
Definition saveload.h:1318
Declaration of functions used in more save/load files.
void AfterLoadVehiclesPhase1(bool part_of_load)
Called after load for phase 1 of vehicle initialisation.
void ResetOldNames()
Free the memory of the old names array.
void FixupTrainLengths()
Fixup old train spacing.
void MoveBuoysToWaypoints()
Perform all steps to upgrade from the old station buoys to the new version that uses waypoints.
void UpdateOldAircraft()
need to be called to load aircraft from old version
void ConvertOldMultiheadToNew()
Converts all trains to the new subtype format introduced in savegame 16.2 It also links multiheaded e...
void ConnectMultiheadedTrains()
Link front and rear multiheaded engines to each other This is done when loading a savegame.
void AfterLoadRoadStops()
(Re)building of road stop caches after loading a savegame.
void MoveWaypointsToBaseStations()
Perform all steps to upgrade from the old waypoints to the new version that uses station.
void AfterLoadVehiclesPhase2(bool part_of_load)
Called after load for phase 2 of vehicle initialisation.
void UpdateHousesAndTowns()
Check and update town and house values.
Definition town_sl.cpp:65
std::string CopyFromOldName(StringID id)
Copy and convert old custom names to UTF-8.
void AfterLoadStoryBook()
Called after load to trash broken pages.
Definition story_sl.cpp:20
void ShowScriptDebugWindowIfScriptError()
Open the AI debug window if one of the AI scripts has crashed.
Window for configuring the scripts.
VehicleDefaultSettings _old_vds
Used for loading default vehicles settings from old savegames.
Definition settings.cpp:63
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition settings.cpp:62
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
IndustryDensity
Available industry map generation densities.
@ FundedOnly
The game does not build industries.
@ EndOfLineOnly
Trains can only flip when the track ends.
@ All
Trains can flip anywhere.
Base for ships.
@ SIGTYPE_COMBO
presignal inter-block
Definition signal_type.h:27
@ SIG_SEMAPHORE
Old-fashioned semaphore signal.
Definition signal_type.h:18
@ SIG_ELECTRIC
Light signal.
Definition signal_type.h:17
void UpdateAllSignVirtCoords()
Update the coordinates of all signs.
Definition signs.cpp:50
Base class for signs.
Functions related to signs.
DiagDirection GetInclinedSlopeDirection(Slope s)
Returns the direction of an inclined slope.
Definition slope_func.h:239
void BuildOwnerLegend()
Completes the array for the owned property legend.
Smallmap GUI functions.
@ Industry
Source/destination is an industry.
Definition source_type.h:21
@ Town
Source/destination is a town.
Definition source_type.h:22
Base classes/functions for stations.
void UpdateAllStationVirtCoords()
Update the virtual coords needed to draw the station sign for all stations.
void UpdateAirportsNoise()
Recalculate the noise generated by the airports of each town.
void UpdateStationAcceptance(Station *st, bool show_msg)
Update the acceptance for a station.
StationType GetStationType(Tile t)
Get the station type of this tile.
Definition station_map.h:44
StationGfx GetStationGfx(Tile t)
Get the station graphics of this tile.
Definition station_map.h:68
void SetStationGfx(Tile t, StationGfx gfx)
Set the station graphics of this tile.
Definition station_map.h:80
bool IsAirportTile(Tile t)
Is this tile a station tile and an airport tile?
bool IsBayRoadStopTile(Tile t)
Is tile t a bay (non-drive through) road stop station?
bool IsRailWaypointTile(Tile t)
Is this tile a station tile and a rail waypoint?
bool IsBuoy(Tile t)
Is tile t a buoy tile?
bool IsDriveThroughStopTile(Tile t)
Is tile t a drive through road stop station or waypoint?
bool HasStationTileRail(Tile t)
Has this station tile a rail?
uint GetCustomStationSpecIndex(Tile t)
Get the custom station spec for this tile.
void SetRailStationReservation(Tile t, bool b)
Set the reservation state of the rail station.
bool IsAnyRoadStop(Tile t)
Is the station at t a road station?
bool IsStationTileBlocked(Tile t)
Is tile t a blocked tile?
bool IsTruckStop(Tile t)
Is the station at t a truck stop?
bool IsStationRoadStop(Tile t)
Is the station at t a road station?
bool HasStationRail(Tile t)
Has this station tile a rail?
static const int GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET
The offset for the drive through parts.
Definition station_map.h:36
bool IsOilRig(Tile t)
Is tile t part of an oilrig?
bool IsBuoyTile(Tile t)
Is tile t a buoy tile?
bool IsDock(Tile t)
Is tile t a dock tile?
@ Dock
Station with a dock.
@ Train
Station with train station.
@ Airport
Station with an airport.
StationType
Station types.
@ Dock
Ship port.
@ Rail
Railways/train station.
@ Bus
Road stop for busses.
@ Truck
Road stop for trucks.
@ Buoy
Waypoint for ships.
@ Oilrig
Heliport on an oil rig.
@ Airport
Airports and heliports, excluding the ones on oil rigs.
Definition of base types and functions in a cross-platform compatible way.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:77
Functions related to low-level strings.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:90
Functions related to OTTD's strings.
static constexpr StringID SPECSTR_PRESIDENT_NAME
Special string for the president's name.
static constexpr StringID SPECSTR_TOWNNAME_START
Special strings for town names.
Information about a aircraft vehicle.
Aircraft, helicopters, rotors and their shadows belong to this class.
Definition aircraft.h:73
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
Base class for all station-ish types.
TileArea train_station
Tile area the train 'station' part covers.
Owner owner
The owner of this station.
StationRect rect
NOSAVE: Station spread out rectangle maintained by StationRect::xxx() functions.
Town * town
The town this station is associated with.
static BaseStation * GetByTile(TileIndex tile)
Get the base station belonging to a specific tile.
VehicleType type
Type of vehicle.
static void AfterLoad()
Savegame conversion for cargopackets.
Helper class to perform the cargo payment.
Specification of a cargo type.
Definition cargotype.h:75
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo type.
Definition cargotype.h:139
TownAcceptanceEffect town_acceptance_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition cargotype.h:87
Structure to return information about the closest depot location, and whether it could be found.
CompanySettings settings
settings specific for each company
static bool IsValidAiID(auto index)
Is this company a valid company, controlled by the computer (a NoAI program)?
Disasters, like submarines, skyrangers and their shadows, belong to this class.
Basic data to distinguish a GRF.
MD5Hash md5sum
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF).
Stores station stats for a single cargo.
uint8_t last_speed
Maximum speed (up to 255) of the last vehicle that tried to load this cargo.
States status
Status of this cargo, see State.
@ Rating
This indicates whether a cargo has a rating at the station.
uint AvailableCount() const
Returns sum of cargo still available for loading at the station.
static void UpdateAfterLoad()
Update all caches after loading a game, changing NewGRF, etc.
Group data.
Definition group.h:74
static HouseSpec * Get(size_t house_id)
Get the spec for a house ID.
HouseExtraFlags extra_flags
some more flags
Definition house.h:120
Defines the data structure for constructing industry.
std::array< CargoType, INDUSTRY_NUM_INPUTS > accepts_cargo
16 accepted cargoes.
IndustryBehaviours behaviour
How this industry will behave, and how others entities can use it.
Defines the internal data of a functional industry.
Definition industry.h:62
static Industry * GetByTile(TileIndex tile)
Get the industry of the given tile.
Definition industry.h:251
static uint SizeX()
Get the size of the map along the X.
Definition map_func.h:262
static uint SizeY()
Get the size of the map along the Y.
Definition map_func.h:271
static IterateWrapper Iterate()
Returns an iterable ensemble of all Tiles.
Definition map_func.h:366
static uint MaxY()
Gets the maximum Y coordinate within the map, including TileType::Void.
Definition map_func.h:298
static uint MaxX()
Gets the maximum X coordinate within the map, including TileType::Void.
Definition map_func.h:289
An object, such as transmitter, on the map.
Definition object_base.h:24
ObjectType type
Type of the object.
Definition object_base.h:25
Town * town
Town the object is built in.
Definition object_base.h:26
static void IncTypeCount(ObjectType type)
Increment the count of objects for this type.
Definition object_base.h:45
TimerGameCalendar::Date build_date
Date of construction.
Definition object_base.h:28
TileArea location
Location of the object.
Definition object_base.h:27
Data for backing up an order of a vehicle so it can be restored after a vehicle is rebuilt in the sam...
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition order_base.h:384
If you change this, keep in mind that it is also saved in 2 other places:
Definition order_base.h:34
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition order_base.h:67
uint16_t w
The width of the area.
TileIndex tile
The base tile of the area.
uint16_t h
The height of the area.
static Pool::IterateWrapper< Town > Iterate(size_t from=0)
static Town * Get(auto index)
static T * Create(Targs &&... args)
static Company * GetIfValid(auto index)
A Stop for a Road Vehicle.
Buses, trucks and trams belong to this class.
Definition roadveh.h:105
uint8_t state
Definition roadveh.h:107
RoadType roadtype
NOSAVE: Roadtype of this vehicle.
Definition roadveh.h:115
All ships have this type.
Definition ship.h:32
static bool IsExpected(const BaseStation *st)
static Pool::IterateWrapper< Station > Iterate(size_t from=0)
static Station * Get(auto index)
static Station * GetIfValid(auto index)
static Station * From(BaseStation *st)
T * Next() const
Get next vehicle in the chain.
static Train * From(Vehicle *v)
Station data structure.
RoadStop * bus_stops
All the road stops.
static void RecomputeCatchmentForAll()
Recomputes catchment of all stations.
Definition station.cpp:537
RoadStop * truck_stops
All the truck stops.
Struct about subsidies, offered and awarded.
Town data structure.
Definition town.h:63
'Train' is either a loco or a wagon.
Definition train.h:97
TrackBits track
On which track the train currently is.
Definition train.h:110
VehicleRailFlags flags
Which flags has this train currently set.
Definition train.h:98
Default settings for vehicles.
Vehicle data structure.
CargoPayment * cargo_payment
The cargo payment we're currently in.
Direction direction
facing
VehStates vehstatus
Status.
Order current_order
The current order (+ status, like: loading).
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
TileIndex tile
Current tile index.
Owner owner
Which company owns the vehicle?
Representation of a waypoint.
void RebuildSubsidisedSourceAndDestinationCache()
Perform a full rebuild of the subsidies cache.
Definition subsidy.cpp:103
Subsidy base class.
Functions related to subsidies.
bool MayAnimateTile(TileIndex tile)
Test if a tile may be animated.
Definition tile_cmd.h:268
bool IsTileFlat(TileIndex tile, int *h)
Check if a given tile is flat.
Definition tile_map.cpp:94
int GetTileMaxZ(TileIndex t)
Get top height of the tile inside the map.
Definition tile_map.cpp:135
int GetTileZ(TileIndex tile)
Get bottom height of the tile.
Definition tile_map.cpp:115
static bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition tile_map.h:150
uint TileHash(uint x, uint y)
Calculate a hash value from a tile position.
Definition tile_map.h:324
static uint TileHeight(Tile tile)
Returns the height of a tile.
Definition tile_map.h:29
bool IsTileOwner(Tile tile, Owner owner)
Checks if a tile belongs to the given owner.
Definition tile_map.h:214
void SetTileType(Tile tile, TileType type)
Set the type of a tile.
Definition tile_map.h:131
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition tile_map.h:178
void SetTileOwner(Tile tile, Owner owner)
Sets the owner of a tile.
Definition tile_map.h:198
int GetTileMaxPixelZ(TileIndex tile)
Get top height of the tile.
Definition tile_map.h:312
void SetAnimationFrame(Tile t, uint8_t frame)
Set a new animation frame.
Definition tile_map.h:262
Slope GetTileSlope(TileIndex tile)
Return the slope of a given tile inside the map.
Definition tile_map.h:279
void SetTropicZone(Tile tile, TropicZone type)
Set the tropic zone.
Definition tile_map.h:225
static TileType GetTileType(Tile tile)
Get the tiletype of a given tile.
Definition tile_map.h:96
static constexpr uint TILE_UNIT_MASK
For masking in/out the inner-tile world coordinate units.
Definition tile_type.h:16
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
@ Normal
Normal tropiczone.
Definition tile_type.h:82
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
static constexpr uint TILE_SIZE
Tile size in world coordinates.
Definition tile_type.h:15
static constexpr uint MIN_SNOWLINE_HEIGHT
Minimum snowline height.
Definition tile_type.h:32
static constexpr uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in ZOOM_BASE.
Definition tile_type.h:18
@ TunnelBridge
Tunnel entry/exit and bridge heads.
Definition tile_type.h:58
@ Water
Water tile.
Definition tile_type.h:55
@ Station
A tile of a station or airport.
Definition tile_type.h:54
@ Object
Contains objects such as transmitters and owned land.
Definition tile_type.h:59
@ Industry
Part of an industry.
Definition tile_type.h:57
@ Railway
A tile with railway.
Definition tile_type.h:50
@ Void
Invisible tiles at the SW and SE border.
Definition tile_type.h:56
@ Trees
Tile with one or more trees.
Definition tile_type.h:53
@ House
A house by a town.
Definition tile_type.h:52
@ Road
A tile with road and/or tram tracks.
Definition tile_type.h:51
@ Clear
A tile without any structures, i.e. grass, rocks, farm fields etc.
Definition tile_type.h:49
Definition of Interval and OneShot timers.
Definition of the game-calendar-timer.
Definition of the game-economy-timer.
Definition of the tick-based game-timer.
Base of the town class.
static const uint TOWN_GROWTH_WINTER
The town only needs this cargo in the winter (any amount).
Definition town.h:32
const CargoSpec * FindFirstCargoWithTownAcceptanceEffect(TownAcceptanceEffect effect)
Determines the first cargo with a certain town effect.
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
static const uint TOWN_GROWTH_DESERT
The town needs the cargo for growth when on desert (any amount).
Definition town.h:33
void UpdateTownMaxPass(Town *t)
Update the maximum amount of monthly passengers and mail for a town, based on its population.
void ClearAllTownCachedNames()
Clear the cached_name of all towns.
Definition town_cmd.cpp:419
Town * CalcClosestTownFromTile(TileIndex tile, uint threshold=UINT_MAX)
Return the town closest to the given tile within threshold.
@ CustomGrowth
Growth rate is controlled by GS.
Definition town.h:45
static const uint16_t TOWN_GROWTH_RATE_NONE
Special value for Town::growth_rate to disable town growth.
Definition town.h:34
void MakeDefaultName(T *obj)
Set the default name for a depot/waypoint.
Definition town.h:333
void UpdateAllTownVirtCoords()
Update the virtual coords needed to draw the town sign for all towns.
Definition town_cmd.cpp:411
HouseID GetHouseType(Tile t)
Get the type of this house, which is an index into the house spec array.
Definition town_map.h:60
void SetHouseType(Tile t, HouseID house_id)
Set the house type.
Definition town_map.h:71
void SetLiftPosition(Tile t, uint8_t pos)
Set the position of the lift on this animated house.
Definition town_map.h:157
void SetHouseCompleted(Tile t, bool status)
Mark this house as been completed.
Definition town_map.h:178
void SetHouseProtected(Tile t, bool house_protected)
Set a house as protected from removal by towns.
Definition town_map.h:93
void SetTownIndex(Tile t, TownID index)
Set the town index for a road or house tile.
Definition town_map.h:35
bool IsHouseCompleted(Tile t)
Get the completion of this house.
Definition town_map.h:167
static constexpr int RATING_INITIAL
initial rating
Definition town_type.h:45
@ TCGM_ORIGINAL
Original algorithm (quadratic cargo by population).
Definition town_type.h:117
TownLayout
Town Layouts.
Definition town_type.h:84
@ TL_RANDOM
Random town layout.
Definition town_type.h:91
@ TL_BETTER_ROADS
Extended original algorithm (min. 2 distance between roads).
Definition town_type.h:87
TrackBits DiagDirToDiagTrackBits(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal track bits incidating with that diagdir.
Definition track_func.h:529
Trackdir DiagDirToDiagTrackdir(DiagDirection diagdir)
Maps a (4-way) direction to the diagonal trackdir that runs in that direction.
Definition track_func.h:542
TrackBits TrackStatusToTrackBits(TrackStatus ts)
Returns the present-track-information of a TrackStatus.
Definition track_func.h:365
TrackBits
Allow incrementing of Track variables.
Definition track_type.h:35
@ TRACK_BIT_WORMHOLE
Bitflag for a wormhole (used for tunnels).
Definition track_type.h:52
@ TRACK_BIT_DEPOT
Bitflag for a depot.
Definition track_type.h:53
@ TRACK_BIT_Y
Y-axis track.
Definition track_type.h:38
@ TRACK_BIT_NONE
No track.
Definition track_type.h:36
@ TRACK_BIT_X
X-axis track.
Definition track_type.h:37
@ INVALID_TRACK
Flag for an invalid track.
Definition track_type.h:28
@ TRACK_LOWER
Track in the lower corner of the tile (south).
Definition track_type.h:24
@ TRACK_UPPER
Track in the upper corner of the tile (north).
Definition track_type.h:23
Base for the train class.
void CheckTrainsLengths()
Checks if lengths of all rail vehicles are valid.
Definition train_cmd.cpp:76
VehicleRailFlag
Rail vehicle flags.
Definition train.h:25
@ TFP_NONE
Normal operation.
Definition train.h:40
@ TFP_STUCK
Proceed till next signal, but ignore being stuck till then. This includes force leaving depots.
Definition train.h:41
TransportType
Available types of transport.
@ TRANSPORT_RAIL
Transport by train.
@ TRANSPORT_ROAD
Transport by road vehicle.
Map accessors for tree tiles.
TreeGround GetTreeGround(Tile t)
Returns the groundtype for tree tiles.
Definition tree_map.h:102
TreeGround
Enumeration for ground types of tiles with trees.
Definition tree_map.h:52
@ SnowOrDesert
Snow or desert, depending on landscape.
Definition tree_map.h:55
@ Shore
Shore.
Definition tree_map.h:56
bool IsTunnelTile(Tile t)
Is this a tunnel (entrance)?
Definition tunnel_map.h:34
const uint8_t _tunnel_visibility_frame[DIAGDIR_END]
Frame when a vehicle should be hidden in a tunnel with a certain direction.
Functions that have tunnels and bridges in common.
DiagDirection GetTunnelBridgeDirection(Tile t)
Get the direction pointing to the other end.
TransportType GetTunnelBridgeTransportType(Tile t)
Tunnel: Get the transport type of the tunnel (road or rail) Bridge: Get the transport type of the bri...
TileIndex GetOtherTunnelBridgeEnd(Tile t)
Determines type of the wormhole and returns its other end.
void SetTunnelBridgeReservation(Tile t, bool b)
Set the reservation state of the rail tunnel/bridge.
@ Crashed
Vehicle is crashed.
@ Hidden
Vehicle is not visible.
Functions related to vehicles.
@ Ship
Ship vehicle type.
@ Invalid
Non-existing type of vehicle.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
Functions related to (drawing on) viewports.
Declarations for accessing the k-d tree of viewports.
Map accessors for void tiles.
void MakeVoid(Tile t)
Make a nice void tile ;).
Definition void_map.h:19
Functions related to water management.
void MakeShore(Tile t)
Helper function to make a coast tile.
Definition water_map.h:385
void SetWaterClass(Tile t, WaterClass wc)
Set the water class at a tile.
Definition water_map.h:126
bool IsShipDepot(Tile t)
Is it a water tile with a ship depot on it?
Definition water_map.h:224
WaterClass
classes of water (for WaterTileType::Clear water tile type).
Definition water_map.h:39
@ River
River.
Definition water_map.h:42
@ Invalid
Used for industry tiles on land (also for oilrig if newgrf says so).
Definition water_map.h:43
@ Canal
Canal.
Definition water_map.h:41
@ Sea
Sea.
Definition water_map.h:40
bool IsShipDepotTile(Tile t)
Is it a ship depot tile?
Definition water_map.h:234
bool IsCoast(Tile t)
Is it a coast tile?
Definition water_map.h:203
WaterTileType GetWaterTileType(Tile t)
Get the water tile type of a tile.
Definition water_map.h:80
void SetNonFloodingWaterTile(Tile t, bool b)
Set the non-flooding water tile state of a tile.
Definition water_map.h:532
void SetWaterTileType(Tile t, WaterTileType type)
Set the water tile type of a tile.
Definition water_map.h:91
WaterClass GetWaterClass(Tile t)
Get the water class at a tile.
Definition water_map.h:114
void MakeCanal(Tile t, Owner o, uint8_t random_bits)
Make a canal tile.
Definition water_map.h:449
TileIndex GetOtherShipDepotTile(Tile t)
Get the other tile of the ship depot.
Definition water_map.h:280
@ Coast
Coast.
Definition water_map.h:33
@ Depot
Water Depot.
Definition water_map.h:35
@ Lock
Water lock.
Definition water_map.h:34
@ Clear
Plain water.
Definition water_map.h:32
void SetDockingTile(Tile t, bool b)
Set the docking tile state of a tile.
Definition water_map.h:364
@ Middle
Middle part of a lock.
Definition water_map.h:66
bool IsWater(Tile t)
Is it a plain water tile?
Definition water_map.h:149
bool IsLock(Tile t)
Is there a lock on a given water tile?
Definition water_map.h:305
void MakeSea(Tile t)
Make a sea tile.
Definition water_map.h:428
LockPart GetLockPart(Tile t)
Get the part of a lock.
Definition water_map.h:328
Base of waypoints.
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition window.cpp:1908
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3322
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3340
Window functions not directly related to making/drawing windows.
@ WC_COMPANY_INFRASTRUCTURE
Company infrastructure overview; Window numbers:
@ WC_COMPANY_COLOUR
Company colour selection; Window numbers:
@ WC_BUILD_TOOLBAR
Build toolbar; Window numbers:
Definition window_type.h:79
Entry point for OpenTTD to YAPF's cache.
void YapfNotifyTrackLayoutChange(TileIndex tile, Track track)
Use this function to notify YAPF that track layout (or signal configuration) has change.