OpenTTD Source: src/linkgraph/linkgraphjob.cpp Source File

OpenTTD Source 15.3

linkgraphjob.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
10#include "../stdafx.h"
11#include "../core/pool_func.hpp"
12#include "../window_func.h"
13#include "linkgraphjob.h"
14#include "linkgraphschedule.h"
15
16#include "../safeguards.h"
17
18/* Initialize the link-graph-job-pool */
19 LinkGraphJobPool _link_graph_job_pool("LinkGraphJob");
20 INSTANTIATE_POOL_METHODS(LinkGraphJob)
21
22
27/* static */ Path *Path::invalid_path = new Path(INVALID_NODE, true);
28
35 LinkGraphJob::LinkGraphJob(const LinkGraph &orig) :
36 /* Copying the link graph here also copies its index member.
37 * This is on purpose. */
38 link_graph(orig),
39 settings(_settings_game.linkgraph),
40 join_date(TimerGameEconomy::date + (_settings_game.linkgraph.recalc_time / EconomyTime::SECONDS_PER_DAY))
41{
42}
43
48 void LinkGraphJob::EraseFlows(StationID from)
49{
50 for (NodeID node_id = 0; node_id < this->Size(); ++node_id) {
51 (*this)[node_id].flows.erase(from);
52 }
53}
54
59 void LinkGraphJob::SpawnThread()
60{
61 if (!StartNewThread(&this->thread, "ottd:linkgraph", &(LinkGraphSchedule::Run), this)) {
62 /* Of course this will hang a bit.
63 * On the other hand, if you want to play games which make this hang noticeably
64 * on a platform without threads then you'll probably get other problems first.
65 * OK:
66 * If someone comes and tells me that this hangs for them, I'll implement a
67 * smaller grained "Step" method for all handlers and add some more ticks where
68 * "Step" is called. No problem in principle. */
69 LinkGraphSchedule::Run(this);
70 }
71}
72
76 void LinkGraphJob::JoinThread()
77{
78 if (this->thread.joinable()) {
79 this->thread.join();
80 }
81}
82
86LinkGraphJob::~LinkGraphJob()
87{
88 this->JoinThread();
89
90 /* Don't update stuff from other pools, when everything is being removed.
91 * Accessing other pools may be invalid. */
92 if (CleaningPool()) return;
93
94 /* If the job has been aborted, the job state is invalid.
95 * This should never be reached, as once the job has been marked as aborted
96 * the only valid job operation is to clear the LinkGraphJob pool. */
97 assert(!this->IsJobAborted());
98
99 /* Link graph has been merged into another one. */
100 if (!LinkGraph::IsValidID(this->link_graph.index)) return;
101
102 uint16_t size = this->Size();
103 for (NodeID node_id = 0; node_id < size; ++node_id) {
104 NodeAnnotation &from = this->nodes[node_id];
105
106 /* The station can have been deleted. Remove all flows originating from it then. */
107 Station *st = Station::GetIfValid(from.base.station);
108 if (st == nullptr) {
109 this->EraseFlows(from.base.station);
110 continue;
111 }
112
113 /* Link graph merging and station deletion may change around IDs. Make
114 * sure that everything is still consistent or ignore it otherwise. */
115 GoodsEntry &ge = st->goods[this->Cargo()];
116 if (ge.link_graph != this->link_graph.index || ge.node != node_id) {
117 this->EraseFlows(from.base.station);
118 continue;
119 }
120
121 LinkGraph *lg = LinkGraph::Get(ge.link_graph);
122 FlowStatMap &flows = from.flows;
123 FlowStatMap &geflows = ge.GetOrCreateData().flows;
124
125 for (const auto &edge : from.edges) {
126 if (edge.Flow() == 0) continue;
127 NodeID dest_id = edge.base.dest_node;
128 StationID to = this->nodes[dest_id].base.station;
129 Station *st2 = Station::GetIfValid(to);
130 if (st2 == nullptr || st2->goods[this->Cargo()].link_graph != this->link_graph.index ||
131 st2->goods[this->Cargo()].node != dest_id ||
132 !(*lg)[node_id].HasEdgeTo(dest_id) ||
133 (*lg)[node_id][dest_id].LastUpdate() == EconomyTime::INVALID_DATE) {
134 /* Edge has been removed. Delete flows. */
135 std::vector<StationID> erased = flows.DeleteFlows(to);
136 /* Delete old flows for source stations which have been deleted
137 * from the new flows. This avoids flow cycles between old and
138 * new flows. */
139 for (const StationID &station : erased) geflows.erase(station);
140 } else if ((*lg)[node_id][dest_id].last_unrestricted_update == EconomyTime::INVALID_DATE) {
141 /* Edge is fully restricted. */
142 flows.RestrictFlows(to);
143 }
144 }
145
146 /* Swap shares and invalidate ones that are completely deleted. Don't
147 * really delete them as we could then end up with unroutable cargo
148 * somewhere. Do delete them and also reroute relevant cargo if
149 * automatic distribution has been turned off for that cargo. */
150 for (FlowStatMap::iterator it(geflows.begin()); it != geflows.end();) {
151 FlowStatMap::iterator new_it = flows.find(it->first);
152 if (new_it == flows.end()) {
153 if (_settings_game.linkgraph.GetDistributionType(this->Cargo()) != DT_MANUAL) {
154 it->second.Invalidate();
155 ++it;
156 } else {
157 FlowStat shares(StationID::Invalid(), 1);
158 it->second.SwapShares(shares);
159 geflows.erase(it++);
160 for (FlowStat::SharesMap::const_iterator shares_it(shares.GetShares()->begin());
161 shares_it != shares.GetShares()->end(); ++shares_it) {
162 RerouteCargo(st, this->Cargo(), shares_it->second, st->index);
163 }
164 }
165 } else {
166 it->second.SwapShares(new_it->second);
167 flows.erase(new_it);
168 ++it;
169 }
170 }
171 geflows.insert(flows.begin(), flows.end());
172 if (ge.GetData().IsEmpty()) ge.ClearData();
173 InvalidateWindowData(WC_STATION_VIEW, st->index, this->Cargo());
174 }
175}
176
182 void LinkGraphJob::Init()
183{
184 uint size = this->Size();
185 this->nodes.reserve(size);
186 for (uint i = 0; i < size; ++i) {
187 this->nodes.emplace_back(this->link_graph.nodes[i], this->link_graph.Size());
188 }
189}
190
199 void Path::Fork(Path *base, uint cap, int free_cap, uint dist)
200{
201 this->capacity = std::min(base->capacity, cap);
202 this->free_capacity = std::min(base->free_capacity, free_cap);
203 this->distance = base->distance + dist;
204 assert(this->distance > 0);
205 if (this->parent != base) {
206 this->Detach();
207 this->parent = base;
208 this->parent->num_children++;
209 }
210 this->origin = base->origin;
211}
212
221uint Path::AddFlow(uint new_flow, LinkGraphJob &job, uint max_saturation)
222{
223 if (this->parent != nullptr) {
224 LinkGraphJob::EdgeAnnotation &edge = job[this->parent->node][this->node];
225 if (max_saturation != UINT_MAX) {
226 uint usable_cap = edge.base.capacity * max_saturation / 100;
227 if (usable_cap > edge.Flow()) {
228 new_flow = std::min(new_flow, usable_cap - edge.Flow());
229 } else {
230 return 0;
231 }
232 }
233 new_flow = this->parent->AddFlow(new_flow, job, max_saturation);
234 if (this->flow == 0 && new_flow > 0) {
235 job[this->parent->node].paths.push_front(this);
236 }
237 edge.AddFlow(new_flow);
238 }
239 this->flow += new_flow;
240 return new_flow;
241}
242
248Path::Path(NodeID n, bool source) :
249 distance(source ? 0 : UINT_MAX),
250 capacity(source ? UINT_MAX : 0),
251 free_capacity(source ? INT_MAX : INT_MIN),
252 flow(0), node(n), origin(source ? n : INVALID_NODE),
253 num_children(0), parent(nullptr)
254{}
255
EconomyTime
Storage class for Economy time constants.
Definition timer_game_economy.h:50
FlowStatMap
Flow descriptions by origin stations.
Definition station_base.h:149
FlowStatMap::DeleteFlows
std::vector< StationID > DeleteFlows(StationID via)
Delete all flows at a station for specific cargo and destination.
Definition station_cmd.cpp:5276
FlowStatMap::RestrictFlows
void RestrictFlows(StationID via)
Restrict all flows at a station for specific cargo and destination.
Definition station_cmd.cpp:5296
FlowStat
Flow statistics telling how much flow should be sent along a link.
Definition station_base.h:33
FlowStat::GetShares
const SharesMap * GetShares() const
Get the actual shares as a const pointer so that they can be iterated over.
Definition station_base.h:89
LinkGraphJob
Class for calculation jobs to be run on link graphs.
Definition linkgraphjob.h:29
LinkGraphJob::nodes
NodeAnnotationVector nodes
Extra node data necessary for link graph calculation.
Definition linkgraphjob.h:166
LinkGraphJob::~LinkGraphJob
~LinkGraphJob()
Join the link graph job and destroy it.
Definition linkgraphjob.cpp:86
LinkGraphJob::LinkGraphJob
LinkGraphJob()
Bare constructor, only for save/load.
Definition linkgraphjob.h:179
LinkGraphJob::IsJobAborted
bool IsJobAborted() const
Check if job has been aborted.
Definition linkgraphjob.h:198
LinkGraphJob::Init
void Init()
Initialize the link graph job: Resize nodes and edges and populate them.
Definition linkgraphjob.cpp:182
LinkGraphJob::SpawnThread
void SpawnThread()
Spawn a thread if possible and run the link graph job in the thread.
Definition linkgraphjob.cpp:59
LinkGraphJob::Cargo
CargoType Cargo() const
Get the cargo of the underlying link graph.
Definition linkgraphjob.h:249
LinkGraphJob::EraseFlows
void EraseFlows(StationID from)
Erase all flows originating at a specific station.
Definition linkgraphjob.cpp:48
LinkGraphJob::Size
NodeID Size() const
Get the size of the underlying link graph.
Definition linkgraphjob.h:243
LinkGraphJob::link_graph
const LinkGraph link_graph
Link graph to by analyzed. Is copied when job is started and mustn't be modified later.
Definition linkgraphjob.h:162
LinkGraphJob::JoinThread
void JoinThread()
Join the calling thread with this job's thread if threading is enabled.
Definition linkgraphjob.cpp:76
LinkGraphJob::thread
std::thread thread
Thread the job is running in or a default-constructed thread if it's running in the main thread.
Definition linkgraphjob.h:164
LinkGraphSchedule::Run
static void Run(LinkGraphJob *job)
Run all handlers for the given Job.
Definition linkgraphschedule.cpp:87
LinkGraph
A connected component of a link graph.
Definition linkgraph.h:37
LinkGraph::nodes
NodeVector nodes
Nodes in the component.
Definition linkgraph.h:266
Path
A leg of a path in the link graph.
Definition linkgraphjob.h:273
Path::Path
Path(NodeID n, bool source=false)
Create a leg of a path in the link graph.
Definition linkgraphjob.cpp:248
Path::AddFlow
void AddFlow(uint f)
Increase the flow on this leg only by the specified amount.
Definition linkgraphjob.h:323
Path::invalid_path
static Path * invalid_path
Static instance of an invalid path.
Definition linkgraphjob.h:275
Path::origin
NodeID origin
Link graph node this path originates from.
Definition linkgraphjob.h:359
Path::num_children
uint num_children
Number of child legs that have been forked from this path.
Definition linkgraphjob.h:360
Path::Detach
void Detach()
Detach this path from its parent.
Definition linkgraphjob.h:334
Path::flow
uint flow
Flow the current run of the mcf solver assigns.
Definition linkgraphjob.h:357
Path::distance
uint distance
Sum(distance of all legs up to this one).
Definition linkgraphjob.h:354
Path::Fork
void Fork(Path *base, uint cap, int free_cap, uint dist)
Add this path as a new child to the given base path, thus making this path a "fork" of the base path.
Definition linkgraphjob.cpp:199
Path::node
NodeID node
Link graph node this leg passes.
Definition linkgraphjob.h:358
Path::capacity
uint capacity
This capacity is min(capacity) fom all edges.
Definition linkgraphjob.h:355
Path::parent
Path * parent
Parent leg of this one.
Definition linkgraphjob.h:361
Path::free_capacity
int free_capacity
This capacity is min(edge.capacity - edge.flow) for the current run of Dijkstra.
Definition linkgraphjob.h:356
TimerGameConst< struct Economy >::INVALID_DATE
static constexpr TimerGame< struct Economy >::Date INVALID_DATE
Representation of an invalid date.
Definition timer_game_common.h:193
TimerGameEconomy
Timer that is increased every 27ms, and counts towards economy time units, expressed in days / months...
Definition timer_game_economy.h:32
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition fluidsynth.cpp:25
DT_MANUAL
@ DT_MANUAL
Manual distribution. No link graph calculations are run.
Definition linkgraph_type.h:24
linkgraphjob.h
Declaration of link graph job classes used for cargo distribution.
linkgraphschedule.h
Declaration of link graph schedule used for cargo distribution.
INSTANTIATE_POOL_METHODS
#define INSTANTIATE_POOL_METHODS(name)
Force instantiation of pool methods so we don't get linker errors.
Definition pool_func.hpp:210
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
RerouteCargo
void RerouteCargo(Station *st, CargoType cargo, StationID avoid, StationID avoid2)
Reroute cargo of type c at station st or in any vehicles unloading there.
Definition station_cmd.cpp:4144
GameSettings::linkgraph
LinkGraphSettings linkgraph
settings for link graph calculations
Definition settings_type.h:643
GoodsEntry::GoodsEntryData::flows
FlowStatMap flows
Planned flows through this station.
Definition station_base.h:214
GoodsEntry
Stores station stats for a single cargo.
Definition station_base.h:167
GoodsEntry::ClearData
void ClearData()
Clear optional cargo packet/flow data.
Definition station_base.h:310
GoodsEntry::node
NodeID node
ID of node in link graph referring to this goods entry.
Definition station_base.h:223
GoodsEntry::GetData
const GoodsEntryData & GetData() const
Get optional cargo packet/flow data.
Definition station_base.h:317
GoodsEntry::link_graph
LinkGraphID link_graph
Link graph this station belongs to.
Definition station_base.h:224
GoodsEntry::GetOrCreateData
GoodsEntryData & GetOrCreateData()
Get optional cargo packet/flow data.
Definition station_base.h:338
LinkGraphJob::EdgeAnnotation
Annotation for a link graph edge.
Definition linkgraphjob.h:42
LinkGraphJob::EdgeAnnotation::base
const LinkGraph::BaseEdge & base
Reference to the edge that is annotated.
Definition linkgraphjob.h:43
LinkGraphJob::EdgeAnnotation::Flow
uint Flow() const
Get the total flow on the edge.
Definition linkgraphjob.h:52
LinkGraphJob::EdgeAnnotation::AddFlow
void AddFlow(uint flow)
Add some flow.
Definition linkgraphjob.h:58
LinkGraphJob::NodeAnnotation
Annotation for a link graph node.
Definition linkgraphjob.h:79
LinkGraphJob::NodeAnnotation::base
const LinkGraph::BaseNode & base
Reference to the node that is annotated.
Definition linkgraphjob.h:80
LinkGraphJob::NodeAnnotation::edges
std::vector< EdgeAnnotation > edges
Annotations for all edges originating at this node.
Definition linkgraphjob.h:86
LinkGraphJob::NodeAnnotation::flows
FlowStatMap flows
Planned flows to other nodes.
Definition linkgraphjob.h:84
LinkGraph::BaseEdge::capacity
uint capacity
Capacity of the link.
Definition linkgraph.h:43
LinkGraph::BaseNode::station
StationID station
Station ID.
Definition linkgraph.h:93
PoolID< uint16_t, struct StationIDTag, 64000, 0xFFFF >
Pool::PoolItem<&_link_graph_pool >::Get
static Titem * Get(auto index)
Returns Titem with given index.
Definition pool_type.hpp:387
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition pool_type.hpp:286
Pool::PoolItem<&_link_graph_pool >::IsValidID
static bool IsValidID(auto index)
Tests whether given index can be used to get valid (non-nullptr) Titem.
Definition pool_type.hpp:376
Pool::PoolItem<&_link_graph_job_pool >::CleaningPool
static bool CleaningPool()
Returns current state of pool cleaning - yes or no.
Definition pool_type.hpp:366
Pool
Base class for all pools.
Definition pool_type.hpp:133
SpecializedStation< Station, false >::GetIfValid
static Station * GetIfValid(auto index)
Returns station if the index is a valid index for this station type.
Definition base_station_base.h:257
Station
Station data structure.
Definition station_base.h:520
Station::goods
std::array< GoodsEntry, NUM_CARGO > goods
Goods at this station.
Definition station_base.h:549
StartNewThread
bool StartNewThread(std::thread *thr, std::string_view name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition thread.h:47
InvalidateWindowData
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:3297
WC_STATION_VIEW
@ WC_STATION_VIEW
Station view; Window numbers:
Definition window_type.h:350