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

OpenTTD Source 13.1

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