OpenTTD Source 20261112-master-gbcbec5e63f
linkgraph_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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../stdafx.h"
11
12#include "saveload.h"
13#include "saveload_error.hpp"
15
19#include "../network/network.h"
21#include "../settings_table.h"
22
23#include "../safeguards.h"
24
25typedef LinkGraph::BaseNode Node;
26typedef LinkGraph::BaseEdge Edge;
27
28static uint16_t _num_nodes;
30static NodeID _linkgraph_from;
31
32class SlLinkgraphEdge : public DefaultSaveLoadHandler<SlLinkgraphEdge, Node> {
33public:
34 static inline const SaveLoad description[] = {
38 SaveLoad::Variable<VarFileType::I32>("last_unrestricted_update", SLE_OBJECT_ADDRESS(Edge, last_unrestricted_update)),
39 SaveLoad::Variable<VarFileType::I32>("last_restricted_update", SLE_OBJECT_ADDRESS(Edge, last_restricted_update), SaveLoadVersion::LinkgraphRestrictedFlow),
40 SaveLoad::Variable<VarFileType::U16>("dest_node", SLE_OBJECT_ADDRESS(Edge, dest_node)),
42 };
43 static inline const SaveLoadCompatTable compat_description = _linkgraph_edge_sl_compat;
44
45 void Save(Node *bn) const override
46 {
47 SlSetStructListLength(bn->edges.size());
48 for (Edge &e : bn->edges) {
49 SlObject(&e, this->GetDescription());
50 }
51 }
52
53 void Load(Node *bn) const override
54 {
56 uint16_t max_size = _linkgraph->Size();
57 std::vector<Edge> edges(max_size);
58
60 /* We used to save the full matrix ... */
61 for (NodeID to = 0; to < max_size; ++to) {
62 SlObject(&edges[to], this->GetLoadDescription());
63 }
64 } else {
66
67 /* ... but as that wasted a lot of space we save a sparse matrix now. */
68 for (NodeID to = _linkgraph_from; to != INVALID_NODE; to = edges[to].dest_node) {
69 if (used_size == 0) SlErrorCorrupt("Link graph structure overflow");
70 used_size--;
71
72 if (to >= max_size) SlErrorCorrupt("Link graph structure overflow");
73 SlObject(&edges[to], this->GetLoadDescription());
74 }
75
76 if (!IsSavegameVersionBefore(SaveLoadVersion::SaveloadListLength) && used_size > 0) SlErrorCorrupt("Corrupted link graph");
77 }
78
79 /* Build edge list from edge matrix. */
80 for (NodeID to = edges[_linkgraph_from].dest_node; to != INVALID_NODE; to = edges[to].dest_node) {
81 auto &edge = bn->edges.emplace_back(edges[to]);
82 edge.dest_node = to;
83 }
84 /* Sort by destination. */
85 std::sort(bn->edges.begin(), bn->edges.end());
86 } else {
87 /* Edge data is now a simple vector and not any kind of matrix. */
88 size_t size = SlGetStructListLength(UINT16_MAX);
89 for (size_t i = 0; i < size; i++) {
90 auto &edge = bn->edges.emplace_back();
91 SlObject(&edge, this->GetLoadDescription());
92 }
93 }
94 }
95};
96
97class SlLinkgraphNode : public DefaultSaveLoadHandler<SlLinkgraphNode, LinkGraph> {
98public:
99 static inline const SaveLoad description[] = {
104 SaveLoad::Variable<VarFileType::I32>("last_update", SLE_OBJECT_ADDRESS(Node, last_update)),
106 };
107 static inline const SaveLoadCompatTable compat_description = _linkgraph_node_sl_compat;
108
109 void Save(LinkGraph *lg) const override
110 {
111 _linkgraph = lg;
112
114 for (NodeID from = 0; from < lg->Size(); ++from) {
115 _linkgraph_from = from;
116 SlObject(&lg->nodes[from], this->GetDescription());
117 }
118 }
119
120 void Load(LinkGraph *lg) const override
121 {
122 _linkgraph = lg;
123
124 uint16_t length = IsSavegameVersionBefore(SaveLoadVersion::SaveloadListLength) ? _num_nodes : (uint16_t)SlGetStructListLength(UINT16_MAX);
125 lg->Init(length);
126 for (NodeID from = 0; from < length; ++from) {
127 _linkgraph_from = from;
128 SlObject(&lg->nodes[from], this->GetLoadDescription());
129 }
130 }
131};
132
147
155class SlLinkgraphJobProxy : public DefaultSaveLoadHandler<SlLinkgraphJobProxy, LinkGraphJob> {
156public:
157 static inline const SaveLoad description[] = {{}};
158 SaveLoadTable GetDescription() const override { return GetLinkGraphDesc(); }
159 static inline const SaveLoadCompatTable compat_description = _linkgraph_sl_compat;
160
161 void Save(LinkGraphJob *lgj) const override
162 {
163 SlObject(const_cast<LinkGraph *>(&lgj->Graph()), this->GetDescription());
164 }
165
166 void Load(LinkGraphJob *lgj) const override
167 {
168 SlObject(const_cast<LinkGraph *>(&lgj->Graph()), this->GetLoadDescription());
169 }
170};
171
182{
183 static std::vector<SaveLoad> saveloads;
184
185 static const SaveLoad job_desc[] = {
186 SaveLoad::Variable<VarFileType::I32>("join_date", SLE_OBJECT_ADDRESS(LinkGraphJob, join_date)),
187 SaveLoad::Variable<VarFileType::U16>("link_graph.index", SLE_OBJECT_ADDRESS(LinkGraphJob, link_graph.index)),
189 };
190
191 /* The member offset arithmetic below is only valid if the types in question
192 * are standard layout types. Otherwise, it would be undefined behaviour. */
193 static_assert(std::is_standard_layout<LinkGraphSettings>::value, "LinkGraphSettings needs to be a standard layout type");
194
195 /* We store the offset of each member of the #LinkGraphSettings in the
196 * extra data of the saveload struct. Use it together with the address
197 * of the settings struct inside the job to find the final memory address. */
198 static SaveLoad::AddressFunction<> const func = [](const void *b, size_t extra) -> const void * { return reinterpret_cast<const char *>(std::addressof(static_cast<const LinkGraphJob *>(b)->settings)) + extra; };
199
200 /* Build the SaveLoad array on first call and don't touch it later on */
201 if (saveloads.empty()) {
202 GetSaveLoadFromSettingTable(_linkgraph_settings, saveloads);
203
204 for (auto &sl : saveloads) {
205 sl.address_func = func;
206 }
207
208 for (auto &sld : job_desc) {
209 saveloads.push_back(sld);
210 }
211 }
212
213 return saveloads;
214}
215
228
234{
236 for (LinkGraph *lg : LinkGraph::Iterate()) {
237 for (NodeID node_id = 0; node_id < lg->Size(); ++node_id) {
238 const Station *st = Station::GetIfValid((*lg)[node_id].station);
239 if (st != nullptr) (*lg)[node_id].UpdateLocation(st->xy);
240 }
241 }
242
243 for (LinkGraphJob *lgj : LinkGraphJob::Iterate()) {
244 LinkGraph *lg = &(const_cast<LinkGraph &>(lgj->Graph()));
245 for (NodeID node_id = 0; node_id < lg->Size(); ++node_id) {
246 const Station *st = Station::GetIfValid((*lg)[node_id].station);
247 if (st != nullptr) (*lg)[node_id].UpdateLocation(st->xy);
248 }
249 }
250 }
251
253
256 }
257}
258
262struct LGRPChunkHandler : ChunkHandler {
263 LGRPChunkHandler() : ChunkHandler("LGRP", ChunkType::Table) {}
264
265 void Save() const override
266 {
268
269 for (LinkGraph *lg : LinkGraph::Iterate()) {
270 SlSetArrayIndex(lg->index);
272 }
273 }
274
275 void Load() const override
276 {
277 const std::vector<SaveLoad> slt = SlCompatTableHeader(GetLinkGraphDesc(), _linkgraph_sl_compat);
278
279 int index;
280 while ((index = SlIterateArray()) != -1) {
281 LinkGraph *lg = LinkGraph::CreateAtIndex(LinkGraphID(index));
282 SlObject(lg, slt);
283 }
284 }
285};
286
290struct LGRJChunkHandler : ChunkHandler {
291 LGRJChunkHandler() : ChunkHandler("LGRJ", ChunkType::Table) {}
292
293 void Save() const override
294 {
296
297 for (LinkGraphJob *lgj : LinkGraphJob::Iterate()) {
298 SlSetArrayIndex(lgj->index);
300 }
301 }
302
303 void Load() const override
304 {
305 const std::vector<SaveLoad> slt = SlCompatTableHeader(GetLinkGraphJobDesc(), _linkgraph_job_sl_compat);
306
307 int index;
308 while ((index = SlIterateArray()) != -1) {
309 LinkGraphJob *lgj = LinkGraphJob::CreateAtIndex(LinkGraphJobID(index));
310 SlObject(lgj, slt);
311 }
312 }
313};
314
318struct LGRSChunkHandler : ChunkHandler {
319 LGRSChunkHandler() : ChunkHandler("LGRS", ChunkType::Table) {}
320
321 void Save() const override
322 {
324
325 SlSetArrayIndex(0);
327 }
328
329 void Load() const override
330 {
332
336 }
337
342};
343
344static const LGRPChunkHandler LGRP;
345static const LGRJChunkHandler LGRJ;
346static const LGRSChunkHandler LGRS;
347static const ChunkHandlerRef linkgraph_chunk_handlers[] = {
348 LGRP,
349 LGRJ,
350 LGRS,
351};
352
353extern const ChunkHandlerTable _linkgraph_chunk_handlers(linkgraph_chunk_handlers);
Default handler for saving/loading an object to/from disk.
Definition saveload.h:585
SaveLoadTable GetDescription() const override
Definition saveload.h:587
Class for calculation jobs to be run on link graphs.
const LinkGraph & Graph() const
Get a reference to the underlying link graph.
LinkGraphSchedule()
Create a link graph schedule and initialize its handlers.
GraphList schedule
Queue for new jobs.
static LinkGraphSchedule instance
Static instance of LinkGraphSchedule.
JobList running
Currently running jobs.
A connected component of a link graph.
Definition linkgraph.h:35
void Init(uint size)
Resize the component and fill it with empty nodes and edges.
CargoType cargo
Cargo of this component's link graph.
Definition linkgraph.h:277
NodeVector nodes
Nodes in the component.
Definition linkgraph.h:279
NodeID Size() const
Get the current size of the component.
Definition linkgraph.h:243
LinkGraph(LinkGraphID index, CargoType cargo=INVALID_CARGO)
Real constructor.
Definition linkgraph.h:209
TimerGameEconomy::Date last_compression
Last time the capacities and supplies were compressed.
Definition linkgraph.h:278
SaveLoadTable GetLoadDescription() const
Get the description for how to load the chunk.
void Save(Node *bn) const override
Save the object to disk.
void Load(Node *bn) const override
Load the object from disk.
Proxy to reuse LinkGraph to save/load a LinkGraphJob.
SaveLoadTable GetDescription() const override
Get the description of the fields in the savegame.
void Save(LinkGraphJob *lgj) const override
Save the object to disk.
void Load(LinkGraphJob *lgj) const override
Load the object from disk.
static const SaveLoad description[]
Needed to keep DefaultSaveLoadHandler happy.
void Save(LinkGraph *lg) const override
Save the object to disk.
void Load(LinkGraph *lg) const override
Load the object from disk.
fluid_settings_t * settings
FluidSynth settings handle.
Declaration of link graph classes used for cargo distribution.
SaveLoadTable GetLinkGraphDesc()
Get a SaveLoad array for a link graph.
SaveLoadTable GetLinkGraphScheduleDesc()
Get a SaveLoad array for the link graph schedule.
static LinkGraph * _linkgraph
Contains the current linkgraph being saved/loaded.
void AfterLoadLinkGraphs()
Spawn the threads for running link graph calculations.
SaveLoadTable GetLinkGraphJobDesc()
Get a SaveLoad array for a link graph job.
static NodeID _linkgraph_from
Contains the current "from" node being saved/loaded.
Loading of linkgraph chunks before table headers were added.
const SaveLoadCompat _linkgraph_node_sl_compat[]
Original field order for SlLinkgraphNode.
const SaveLoadCompat _linkgraph_edge_sl_compat[]
Original field order for SlLinkgraphEdge.
const SaveLoadCompat _linkgraph_schedule_sl_compat[]
Original field order for schedule_desc.
const SaveLoadCompat _linkgraph_job_sl_compat[]
Original field order for job_desc.
const SaveLoadCompat _linkgraph_sl_compat[]
Original field order for link_graph_desc.
Declaration of link graph job classes used for cargo distribution.
void AfterLoad_LinkGraphPauseControl()
Pause the game on load if we would do a join with the next link graph job, but it is still running,...
Declaration of link graph schedule used for cargo distribution.
bool _networking
are we in networking mode?
Definition network.cpp:63
bool _network_server
network-server is active
Definition network.cpp:64
Basic functions/variables used all over the place.
A number of safeguards to prevent using unsafe methods.
std::vector< SaveLoad > SlCompatTableHeader(const SaveLoadTable &slt, const SaveLoadCompatTable &slct)
Load a table header in a savegame compatible way.
size_t SlGetStructListLength(size_t limit)
Get the length of this list; if it exceeds the limit, error out.
int SlIterateArray()
Iterate through the elements of an array and read the whole thing.
Definition saveload.cpp:748
void SlErrorCorrupt(const std::string &msg)
Error handler for corrupt savegames.
Definition saveload.cpp:372
void SlObject(void *object, const SaveLoadTable &slt)
Main SaveLoad function.
std::vector< SaveLoad > SlTableHeader(const SaveLoadTable &slt)
Save or Load a table header.
void SlSetStructListLength(size_t length)
Set the length of this list.
Functions/types related to saving and loading games.
#define SLE_OBJECT_ADDRESS(base, variable)
Macro to be able to pass the variable type and construct the SaveLoad::AddressFunction given a base c...
Definition saveload.h:753
#define SLE_GLOBAL_ADDRESS(variable)
Macro to be able to pass the variable type and construct the SaveLoad::AddressFunction given a global...
Definition saveload.h:760
std::reference_wrapper< const ChunkHandler > ChunkHandlerRef
A reference to ChunkHandler.
Definition saveload.h:512
std::span< const ChunkHandlerRef > ChunkHandlerTable
A table of ChunkHandler entries.
Definition saveload.h:515
std::span< const struct SaveLoadCompat > SaveLoadCompatTable
A table of SaveLoadCompat entries.
Definition saveload.h:518
bool IsSavegameVersionBefore(SaveLoadVersion major, uint8_t minor=0)
Checks whether the savegame is below major.
Definition saveload.h:1225
@ LinkgraphRestrictedFlow
Saveload version: 187, SVN revision: 25899 Linkgraph - restricted flows.
Definition saveload.h:273
@ LinkgraphEdges
Saveload version: 304, GitHub pull request: 10314 Explicitly store link graph edges destination,...
Definition saveload.h:349
@ LinkgraphLocationDisasterStore
Saveload version: 191, SVN revision: 26636, 26646 Fix disaster vehicle storage, Linkgraph - store lo...
Definition saveload.h:278
@ LinkgraphTravelTime
Saveload version: 297, GitHub pull request: 9457, release: 12.0-RC1 Store travel time in the linkgra...
Definition saveload.h:341
@ MinVersion
First savegame version.
Definition saveload.h:36
@ SaveloadListLength
Saveload version: 293, GitHub pull request: 9374 Consistency in list length with SaveLoadType::Struc...
Definition saveload.h:336
@ RiffToArray
Saveload version: 294, GitHub pull request: 9375 Changed many ChunkType::Riff chunks to ChunkType::A...
Definition saveload.h:337
@ Table
An Array with a header describing the elements.
Definition saveload.h:449
Functions/types related to errors from savegames.
std::span< const struct SaveLoad > SaveLoadTable
A table of SaveLoad entries.
void GetSaveLoadFromSettingTable(SettingTable settings, std::vector< SaveLoad > &saveloads)
Get the SaveLoad for all settings in the settings table.
Functions and types used internally for the settings configurations.
Definition of the configuration tables of the settings.
Definition of base types and functions in a cross-platform compatible way.
TileIndex xy
Base tile of the station.
ChunkHandler(ChunkId id, ChunkType type)
Create this ChunkHandler.
Definition saveload.h:469
All link graph jobs.
void Save() const override
Save the chunk.
void Load() const override
Load the chunk.
All link graphs.
void Load() const override
Load the chunk.
void Save() const override
Save the chunk.
Link graph schedule.
void FixPointers() const override
Fix the pointers.
void Load() const override
Load the chunk.
void Save() const override
Save the chunk.
An edge in the link graph.
Definition linkgraph.h:40
Node of the link graph.
Definition linkgraph.h:103
std::vector< BaseEdge > edges
Sorted list of outgoing edges from this node.
Definition linkgraph.h:110
static Pool::IterateWrapper< LinkGraph > Iterate(size_t from=0)
static T * CreateAtIndex(LinkGraphID index, Targs &&... args)
SaveLoad type struct.
Definition saveload.h:763
static SaveLoad StructList(std::string name, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a list of structs, optionally in some savegame versions.
Definition saveload.h:1102
static SaveLoad Variable(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion, size_t extra=0)
Storage of a variable in some savegame versions.
Definition saveload.h:925
static SaveLoad ReferenceList(std::string name, AddressFunction< T > address_func, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a list of references to pool elements in some savegame versions.
Definition saveload.h:1077
const R *(*)(const void *base, size_t extra) AddressFunction
Function that returns the address of a variable.
Definition saveload.h:773
static SaveLoad Struct(std::string name, SaveLoadVersion from=SaveLoadVersion::MinVersion, SaveLoadVersion to=SaveLoadVersion::MaxVersion)
Storage of a structs, optionally in some savegame versions.
Definition saveload.h:1000
static Station * GetIfValid(auto index)
Station data structure.