OpenTTD Source: src/saveload/waypoint_sl.cpp Source File

OpenTTD Source 14.0-beta3

waypoint_sl.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 <http://www.gnu.org/licenses/>.
6 */
7
10 #include "../stdafx.h"
11 #include "../waypoint_base.h"
12 #include "../debug.h"
13 #include "../newgrf_station.h"
14 #include "../vehicle_base.h"
15 #include "../town.h"
16 #include "../newgrf.h"
17 #include "../timer/timer_game_calendar.h"
18
19 #include "table/strings.h"
20
21 #include "saveload_internal.h"
22
23 #include "../safeguards.h"
24
26 struct OldWaypoint {
27 size_t index;
28 TileIndex xy;
29 TownID town_index;
30 Town *town;
31 uint16_t town_cn;
32 StringID string_id;
33 std::string name;
34 uint8_t delete_ctr;
35 TimerGameCalendar::Date build_date;
36 uint8_t localidx;
37 uint32_t grfid;
38 const StationSpec *spec;
39 Owner owner;
40
41 size_t new_index;
42 };
43
45 static std::vector<OldWaypoint> _old_waypoints;
46
51 static void UpdateWaypointOrder(Order *o)
52 {
53 if (!o->IsType(OT_GOTO_WAYPOINT)) return;
54
55 for (OldWaypoint &wp : _old_waypoints) {
56 if (wp.index != o->GetDestination()) continue;
57
58 o->SetDestination((DestinationID)wp.new_index);
59 return;
60 }
61 }
62
67 void MoveWaypointsToBaseStations()
68 {
69 /* In version 17, ground type is moved from m2 to m4 for depots and
70 * waypoints to make way for storing the index in m2. The custom graphics
71 * id which was stored in m4 is now saved as a grf/id reference in the
72 * waypoint struct. */
73 if (IsSavegameVersionBefore(SLV_17)) {
74 for (OldWaypoint &wp : _old_waypoints) {
75 if (wp.delete_ctr != 0) continue; // The waypoint was deleted
76
77 /* Waypoint indices were not added to the map prior to this. */
78 Tile tile = wp.xy;
79 tile.m2() = (StationID)wp.index;
80
81 if (HasBit(tile.m3(), 4)) {
82 wp.spec = StationClass::Get(STAT_CLASS_WAYP)->GetSpec(tile.m4() + 1);
83 }
84 }
85 } else {
86 /* As of version 17, we recalculate the custom graphic ID of waypoints
87 * from the GRF ID / station index. */
88 for (OldWaypoint &wp : _old_waypoints) {
89 StationClass *stclass = StationClass::Get(STAT_CLASS_WAYP);
90 for (uint i = 0; i < stclass->GetSpecCount(); i++) {
91 const StationSpec *statspec = stclass->GetSpec(i);
92 if (statspec != nullptr && statspec->grf_prop.grffile->grfid == wp.grfid && statspec->grf_prop.local_id == wp.localidx) {
93 wp.spec = statspec;
94 break;
95 }
96 }
97 }
98 }
99
100 if (!Waypoint::CanAllocateItem(_old_waypoints.size())) SlError(STR_ERROR_TOO_MANY_STATIONS_LOADING);
101
102 /* All saveload conversions have been done. Create the new waypoints! */
103 for (OldWaypoint &wp : _old_waypoints) {
104 TileIndex t = wp.xy;
105 /* Sometimes waypoint (sign) locations became disconnected from their actual location in
106 * the map array. If this is the case, try to locate the actual location in the map array */
107 if (!IsTileType(t, MP_RAILWAY) || GetRailTileType(t) != 2 /* RAIL_TILE_WAYPOINT */ || Tile(t).m2() != wp.index) {
108 Debug(sl, 0, "Found waypoint tile {} with invalid position", t);
109 for (t = 0; t < Map::Size(); t++) {
110 if (IsTileType(t, MP_RAILWAY) && GetRailTileType(t) == 2 /* RAIL_TILE_WAYPOINT */ && Tile(t).m2() == wp.index) {
111 Debug(sl, 0, "Found actual waypoint position at {}", t);
112 break;
113 }
114 }
115 }
116 if (t == Map::Size()) {
117 SlErrorCorrupt("Waypoint with invalid tile");
118 }
119
120 Waypoint *new_wp = new Waypoint(t);
121 new_wp->town = wp.town;
122 new_wp->town_cn = wp.town_cn;
123 new_wp->name = wp.name;
124 new_wp->delete_ctr = 0; // Just reset delete counter for once.
125 new_wp->build_date = wp.build_date;
126 new_wp->owner = wp.owner;
127 new_wp->string_id = STR_SV_STNAME_WAYPOINT;
128
129 /* The tile might've been reserved! */
130 Tile tile(t);
131 bool reserved = !IsSavegameVersionBefore(SLV_100) && HasBit(tile.m5(), 4);
132
133 /* The tile really has our waypoint, so reassign the map array */
134 MakeRailWaypoint(tile, GetTileOwner(tile), new_wp->index, (Axis)GB(tile.m5(), 0, 1), 0, GetRailType(tile));
135 new_wp->facilities |= FACIL_TRAIN;
136 new_wp->owner = GetTileOwner(tile);
137
138 SetRailStationReservation(tile, reserved);
139
140 if (wp.spec != nullptr) {
141 SetCustomStationSpecIndex(tile, AllocateSpecToStation(wp.spec, new_wp, true));
142 }
143 new_wp->rect.BeforeAddTile(tile, StationRect::ADD_FORCE);
144
145 wp.new_index = new_wp->index;
146 }
147
148 /* Update the orders of vehicles */
149 for (OrderList *ol : OrderList::Iterate()) {
150 if (ol->GetFirstSharedVehicle()->type != VEH_TRAIN) continue;
151
152 for (Order *o = ol->GetFirstOrder(); o != nullptr; o = o->next) UpdateWaypointOrder(o);
153 }
154
155 for (Vehicle *v : Vehicle::Iterate()) {
156 if (v->type != VEH_TRAIN) continue;
157
158 UpdateWaypointOrder(&v->current_order);
159 }
160
161 ResetOldWaypoints();
162 }
163
164 void ResetOldWaypoints()
165 {
166 _old_waypoints.clear();
167 _old_waypoints.shrink_to_fit();
168 }
169
170 static const SaveLoad _old_waypoint_desc[] = {
171 SLE_CONDVAR(OldWaypoint, xy, SLE_FILE_U16 | SLE_VAR_U32, SL_MIN_VERSION, SLV_6),
172 SLE_CONDVAR(OldWaypoint, xy, SLE_UINT32, SLV_6, SL_MAX_VERSION),
173 SLE_CONDVAR(OldWaypoint, town_index, SLE_UINT16, SLV_12, SLV_122),
174 SLE_CONDREF(OldWaypoint, town, REF_TOWN, SLV_122, SL_MAX_VERSION),
175 SLE_CONDVAR(OldWaypoint, town_cn, SLE_FILE_U8 | SLE_VAR_U16, SLV_12, SLV_89),
176 SLE_CONDVAR(OldWaypoint, town_cn, SLE_UINT16, SLV_89, SL_MAX_VERSION),
177 SLE_CONDVAR(OldWaypoint, string_id, SLE_STRINGID, SL_MIN_VERSION, SLV_84),
178 SLE_CONDSSTR(OldWaypoint, name, SLE_STR, SLV_84, SL_MAX_VERSION),
179 SLE_VAR(OldWaypoint, delete_ctr, SLE_UINT8),
180
181 SLE_CONDVAR(OldWaypoint, build_date, SLE_FILE_U16 | SLE_VAR_I32, SLV_3, SLV_31),
182 SLE_CONDVAR(OldWaypoint, build_date, SLE_INT32, SLV_31, SL_MAX_VERSION),
183 SLE_CONDVAR(OldWaypoint, localidx, SLE_UINT8, SLV_3, SL_MAX_VERSION),
184 SLE_CONDVAR(OldWaypoint, grfid, SLE_UINT32, SLV_17, SL_MAX_VERSION),
185 SLE_CONDVAR(OldWaypoint, owner, SLE_UINT8, SLV_101, SL_MAX_VERSION),
186 };
187
188 struct CHKPChunkHandler : ChunkHandler {
189 CHKPChunkHandler() : ChunkHandler('CHKP', CH_READONLY) {}
190
191 void Load() const override
192 {
193 /* Precaution for when loading failed and it didn't get cleared */
194 ResetOldWaypoints();
195
196 int index;
197
198 while ((index = SlIterateArray()) != -1) {
199 OldWaypoint *wp = &_old_waypoints.emplace_back();
200
201 wp->index = index;
202 SlObject(wp, _old_waypoint_desc);
203 }
204 }
205
206 void FixPointers() const override
207 {
208 for (OldWaypoint &wp : _old_waypoints) {
209 SlObject(&wp, _old_waypoint_desc);
210
211 if (IsSavegameVersionBefore(SLV_12)) {
212 wp.town_cn = (wp.string_id & 0xC000) == 0xC000 ? (wp.string_id >> 8) & 0x3F : 0;
213 wp.town = ClosestTownFromTile(wp.xy, UINT_MAX);
214 } else if (IsSavegameVersionBefore(SLV_122)) {
215 /* Only for versions 12 .. 122 */
216 if (!Town::IsValidID(wp.town_index)) {
217 /* Upon a corrupted waypoint we'll likely get here. The next step will be to
218 * loop over all Ptrs procs to nullptr the pointers. However, we don't know
219 * whether we're in the nullptr or "normal" Ptrs proc. So just clear the list
220 * of old waypoints we constructed and then this waypoint (and the other
221 * possibly corrupt ones) will not be queried in the nullptr Ptrs proc run. */
222 _old_waypoints.clear();
223 SlErrorCorrupt("Referencing invalid Town");
224 }
225 wp.town = Town::Get(wp.town_index);
226 }
227 if (IsSavegameVersionBefore(SLV_84)) {
228 wp.name = CopyFromOldName(wp.string_id);
229 }
230 }
231 }
232 };
233
234 static const CHKPChunkHandler CHKP;
235 static const ChunkHandlerRef waypoint_chunk_handlers[] = {
236 CHKP,
237 };
238
239 extern const ChunkHandlerTable _waypoint_chunk_handlers(waypoint_chunk_handlers);
AllocateSpecToStation
int AllocateSpecToStation(const StationSpec *statspec, BaseStation *st, bool exec)
Allocate a StationSpec to a Station.
Definition: newgrf_station.cpp:689
BaseStation::facilities
StationFacility facilities
The facilities that this station has.
Definition: base_station_base.h:75
MakeRailWaypoint
void MakeRailWaypoint(Tile t, Owner o, StationID sid, Axis a, byte section, RailType rt)
Make the given tile a rail waypoint tile.
Definition: station_map.h:665
Order::IsType
bool IsType(OrderType type) const
Check whether this order is of the given type.
Definition: order_base.h:71
Pool::PoolItem<&_town_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:335
CHKPChunkHandler
Definition: waypoint_sl.cpp:188
REF_TOWN
@ REF_TOWN
Load/save a reference to a town.
Definition: saveload.h:583
ClosestTownFromTile
Town * ClosestTownFromTile(TileIndex tile, uint threshold)
Return the town closest (in distance or ownership) to a given tile, within a given threshold.
Definition: town_cmd.cpp:3744
SLE_CONDSSTR
#define SLE_CONDSSTR(base, variable, type, from, to)
Storage of a std::string in some savegame versions.
Definition: saveload.h:909
BaseStation::town
Town * town
The town this station is associated with.
Definition: base_station_base.h:73
Axis
Axis
Allow incrementing of DiagDirDiff variables.
Definition: direction_type.h:116
NewGRFClass::GetSpecCount
uint GetSpecCount() const
Get the number of allocated specs within the class.
Definition: newgrf_class.h:44
Order::GetDestination
DestinationID GetDestination() const
Gets the destination of this order.
Definition: order_base.h:104
ChunkHandlerRef
std::reference_wrapper< const ChunkHandler > ChunkHandlerRef
A reference to ChunkHandler.
Definition: saveload.h:488
MoveWaypointsToBaseStations
void MoveWaypointsToBaseStations()
Perform all steps to upgrade from the old waypoints to the new version that uses station.
Definition: waypoint_sl.cpp:67
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
SL_MIN_VERSION
@ SL_MIN_VERSION
First savegame version.
Definition: saveload.h:31
GB
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:234
SLE_CONDVAR
#define SLE_CONDVAR(base, variable, type, from, to)
Storage of a variable in some savegame versions.
Definition: saveload.h:844
OldWaypoint
Helper structure to convert from the old waypoint system.
Definition: waypoint_sl.cpp:26
SlErrorCorrupt
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition: saveload.cpp:362
Waypoint::town_cn
uint16_t town_cn
The N-1th waypoint for this town (consecutive number)
Definition: waypoint_base.h:17
Waypoint
Representation of a waypoint.
Definition: waypoint_base.h:16
MP_RAILWAY
@ MP_RAILWAY
A railway.
Definition: tile_type.h:49
Tile
Wrapper class to abstract away the way the tiles are stored.
Definition: map_func.h:25
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > >
Tile::m5
debug_inline byte & m5()
General purpose.
Definition: map_func.h:161
ChunkHandler
Handlers and description of chunk.
Definition: saveload.h:442
Vehicle
Vehicle data structure.
Definition: vehicle_base.h:240
GetRailType
RailType GetRailType(Tile t)
Gets the rail type of the given tile.
Definition: rail_map.h:115
Owner
Owner
Enum for all companies/owners.
Definition: company_type.h:18
BaseStation::owner
Owner owner
The owner of this station.
Definition: base_station_base.h:74
Tile::m4
debug_inline byte & m4()
General purpose.
Definition: map_func.h:149
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
SLV_6
@ SLV_6
6.0 1721 6.1 1768
Definition: saveload.h:46
BaseStation::string_id
StringID string_id
Default name (town area) of station.
Definition: base_station_base.h:70
SLV_89
@ SLV_89
89 12160
Definition: saveload.h:149
SetCustomStationSpecIndex
void SetCustomStationSpecIndex(Tile t, byte specindex)
Set the custom station spec for this tile.
Definition: station_map.h:537
Tile::m2
debug_inline uint16_t & m2()
Primarily used for indices to towns, industries and stations.
Definition: map_func.h:125
STAT_CLASS_WAYP
@ STAT_CLASS_WAYP
Waypoint class.
Definition: newgrf_station.h:86
CH_READONLY
@ CH_READONLY
Chunk is never saved.
Definition: saveload.h:438
BaseStation::rect
StationRect rect
NOSAVE: Station spread out rectangle maintained by StationRect::xxx() functions.
Definition: base_station_base.h:90
IsSavegameVersionBefore
bool IsSavegameVersionBefore(SaveLoadVersion major, byte minor=0)
Checks whether the savegame is below major.
Definition: saveload.h:1203
Order::SetDestination
void SetDestination(DestinationID destination)
Sets the destination of this order.
Definition: order_base.h:111
CopyFromOldName
std::string CopyFromOldName(StringID id)
Copy and convert old custom names to UTF-8.
Definition: strings_sl.cpp:61
NewGRFClass
Struct containing information relating to NewGRF classes for stations and airports.
Definition: newgrf_class.h:20
CHKPChunkHandler::FixPointers
void FixPointers() const override
Fix the pointers.
Definition: waypoint_sl.cpp:206
UpdateWaypointOrder
static void UpdateWaypointOrder(Order *o)
Update the waypoint orders to get the new waypoint ID.
Definition: waypoint_sl.cpp:51
SLE_CONDREF
#define SLE_CONDREF(base, variable, type, from, to)
Storage of a reference in some savegame versions.
Definition: saveload.h:865
SLV_31
@ SLV_31
31 5999
Definition: saveload.h:80
_old_waypoints
static std::vector< OldWaypoint > _old_waypoints
Temporary array with old waypoints.
Definition: waypoint_sl.cpp:45
BaseStation::name
std::string name
Custom name.
Definition: base_station_base.h:69
GetTileOwner
Owner GetTileOwner(Tile tile)
Returns the owner of a tile.
Definition: tile_map.h:178
SL_MAX_VERSION
@ SL_MAX_VERSION
Highest possible saveload version.
Definition: saveload.h:379
GetRailTileType
static debug_inline RailTileType GetRailTileType(Tile t)
Returns the RailTileType (normal with or without signals, waypoint or depot).
Definition: rail_map.h:36
SetRailStationReservation
void SetRailStationReservation(Tile t, bool b)
Set the reservation state of the rail station.
Definition: station_map.h:478
GRFFilePropsBase::local_id
uint16_t local_id
id defined by the grf file for this entity
Definition: newgrf_commons.h:318
SLV_84
@ SLV_84
84 11822
Definition: saveload.h:143
SLE_VAR
#define SLE_VAR(base, variable, type)
Storage of a variable in every version of a savegame.
Definition: saveload.h:948
Pool::PoolItem<&_orderlist_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:384
StationSpec
Station specification.
Definition: newgrf_station.h:112
SLV_3
@ SLV_3
3.x lost
Definition: saveload.h:36
FACIL_TRAIN
@ FACIL_TRAIN
Station with train station.
Definition: station_type.h:52
Map::Size
static debug_inline uint Size()
Get the size of the map.
Definition: map_func.h:288
OrderList
Shared order list linking together the linked list of orders and the list of vehicles sharing this or...
Definition: order_base.h:260
Pool::PoolItem<&_station_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:305
ChunkHandlerTable
std::span< const ChunkHandlerRef > ChunkHandlerTable
A table of ChunkHandler entries.
Definition: saveload.h:491
BaseStation::delete_ctr
byte delete_ctr
Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is ...
Definition: base_station_base.h:67
saveload_internal.h
Town
Town data structure.
Definition: town.h:50
StationSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_station.h:124
NewGRFClass::Get
static NewGRFClass * Get(Tid cls_id)
Get a particular class.
Definition: newgrf_class_func.h:98
SLV_12
@ SLV_12
12.1 2046
Definition: saveload.h:55
SlError
void SlError(StringID string, const std::string &extra_msg)
Error handler.
Definition: saveload.cpp:332
SLV_17
@ SLV_17
17.0 3212 17.1 3218
Definition: saveload.h:62
IsTileType
static debug_inline bool IsTileType(Tile tile, TileType type)
Checks if a tile is a given tiletype.
Definition: tile_map.h:150
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
Pool::PoolItem<&_town_pool >::IsValidID
static bool IsValidID(size_t index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition: pool_type.hpp:324
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:319
SlObject
void SlObject(void *object, const SaveLoadTable &slt)
Main SaveLoad function.
Definition: saveload.cpp:1652
SaveLoad
SaveLoad type struct.
Definition: saveload.h:694
SLV_101
@ SLV_101
101 14233
Definition: saveload.h:164
Tile::m3
debug_inline byte & m3()
General purpose.
Definition: map_func.h:137
SLV_100
@ SLV_100
100 13952
Definition: saveload.h:163
Order::next
Order * next
Pointer to next order. If nullptr, end of list.
Definition: order_base.h:59
CHKPChunkHandler::Load
void Load() const override
Load the chunk.
Definition: waypoint_sl.cpp:191
Order
Definition: order_base.h:36
SLV_122
@ SLV_122
122 16855
Definition: saveload.h:189
SlIterateArray
int SlIterateArray()
Iterate through the elements of an array and read the whole thing.
Definition: saveload.cpp:647
BaseStation::build_date
TimerGameCalendar::Date build_date
Date of construction.
Definition: base_station_base.h:80
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103