(svn r28004) -Update from Eints:
[openttd.git] / src / linkgraph / linkgraphjob.cpp
blob537303cf358dd059e7cba3760f796624a2b58161
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file linkgraphjob.cpp Definition of link graph job classes used for cargo distribution. */
12 #include "../stdafx.h"
13 #include "../core/pool_func.hpp"
14 #include "../window_func.h"
15 #include "linkgraphjob.h"
16 #include "linkgraphschedule.h"
18 #include "../safeguards.h"
20 /* Initialize the link-graph-job-pool */
21 LinkGraphJobPool _link_graph_job_pool("LinkGraphJob");
22 INSTANTIATE_POOL_METHODS(LinkGraphJob)
24 /**
25 * Static instance of an invalid path.
26 * Note: This instance is created on task start.
27 * Lazy creation on first usage results in a data race between the CDist threads.
29 /* static */ Path *Path::invalid_path = new Path(INVALID_NODE, true);
31 /**
32 * Create a link graph job from a link graph. The link graph will be copied so
33 * that the calculations don't interfer with the normal operations on the
34 * original. The job is immediately started.
35 * @param orig Original LinkGraph to be copied.
37 LinkGraphJob::LinkGraphJob(const LinkGraph &orig) :
38 /* Copying the link graph here also copies its index member.
39 * This is on purpose. */
40 link_graph(orig),
41 settings(_settings_game.linkgraph),
42 thread(NULL),
43 join_date(_date + _settings_game.linkgraph.recalc_time)
47 /**
48 * Erase all flows originating at a specific node.
49 * @param from Node to erase flows for.
51 void LinkGraphJob::EraseFlows(NodeID from)
53 for (NodeID node_id = 0; node_id < this->Size(); ++node_id) {
54 (*this)[node_id].Flows().erase(from);
58 /**
59 * Spawn a thread if possible and run the link graph job in the thread. If
60 * that's not possible run the job right now in the current thread.
62 void LinkGraphJob::SpawnThread()
64 if (!ThreadObject::New(&(LinkGraphSchedule::Run), this, &this->thread, "ottd:linkgraph")) {
65 this->thread = NULL;
66 /* Of course this will hang a bit.
67 * On the other hand, if you want to play games which make this hang noticably
68 * on a platform without threads then you'll probably get other problems first.
69 * OK:
70 * If someone comes and tells me that this hangs for him/her, I'll implement a
71 * smaller grained "Step" method for all handlers and add some more ticks where
72 * "Step" is called. No problem in principle. */
73 LinkGraphSchedule::Run(this);
77 /**
78 * Join the calling thread with this job's thread if threading is enabled.
80 void LinkGraphJob::JoinThread()
82 if (this->thread != NULL) {
83 this->thread->Join();
84 delete this->thread;
85 this->thread = NULL;
89 /**
90 * Join the link graph job and destroy it.
92 LinkGraphJob::~LinkGraphJob()
94 this->JoinThread();
96 /* Don't update stuff from other pools, when everything is being removed.
97 * Accessing other pools may be invalid. */
98 if (CleaningPool()) return;
100 /* Link graph has been merged into another one. */
101 if (!LinkGraph::IsValidID(this->link_graph.index)) return;
103 uint size = this->Size();
104 for (NodeID node_id = 0; node_id < size; ++node_id) {
105 Node from = (*this)[node_id];
107 /* The station can have been deleted. Remove all flows originating from it then. */
108 Station *st = Station::GetIfValid(from.Station());
109 if (st == NULL) {
110 this->EraseFlows(node_id);
111 continue;
114 /* Link graph merging and station deletion may change around IDs. Make
115 * sure that everything is still consistent or ignore it otherwise. */
116 GoodsEntry &ge = st->goods[this->Cargo()];
117 if (ge.link_graph != this->link_graph.index || ge.node != node_id) {
118 this->EraseFlows(node_id);
119 continue;
122 LinkGraph *lg = LinkGraph::Get(ge.link_graph);
123 FlowStatMap &flows = from.Flows();
125 for (EdgeIterator it(from.Begin()); it != from.End(); ++it) {
126 if (from[it->first].Flow() == 0) continue;
127 StationID to = (*this)[it->first].Station();
128 Station *st2 = Station::GetIfValid(to);
129 if (st2 == NULL || st2->goods[this->Cargo()].link_graph != this->link_graph.index ||
130 st2->goods[this->Cargo()].node != it->first ||
131 (*lg)[node_id][it->first].LastUpdate() == INVALID_DATE) {
132 /* Edge has been removed. Delete flows. */
133 StationIDStack erased = flows.DeleteFlows(to);
134 /* Delete old flows for source stations which have been deleted
135 * from the new flows. This avoids flow cycles between old and
136 * new flows. */
137 while (!erased.IsEmpty()) ge.flows.erase(erased.Pop());
138 } else if ((*lg)[node_id][it->first].LastUnrestrictedUpdate() == INVALID_DATE) {
139 /* Edge is fully restricted. */
140 flows.RestrictFlows(to);
144 /* Swap shares and invalidate ones that are completely deleted. Don't
145 * really delete them as we could then end up with unroutable cargo
146 * somewhere. Do delete them and also reroute relevant cargo if
147 * automatic distribution has been turned off for that cargo. */
148 for (FlowStatMap::iterator it(ge.flows.begin()); it != ge.flows.end();) {
149 FlowStatMap::iterator new_it = flows.find(it->first);
150 if (new_it == flows.end()) {
151 if (_settings_game.linkgraph.GetDistributionType(this->Cargo()) != DT_MANUAL) {
152 it->second.Invalidate();
153 ++it;
154 } else {
155 FlowStat shares(INVALID_STATION, 1);
156 it->second.SwapShares(shares);
157 ge.flows.erase(it++);
158 for (FlowStat::SharesMap::const_iterator shares_it(shares.GetShares()->begin());
159 shares_it != shares.GetShares()->end(); ++shares_it) {
160 RerouteCargo(st, this->Cargo(), shares_it->second, st->index);
163 } else {
164 it->second.SwapShares(new_it->second);
165 flows.erase(new_it);
166 ++it;
169 ge.flows.insert(flows.begin(), flows.end());
170 InvalidateWindowData(WC_STATION_VIEW, st->index, this->Cargo());
175 * Initialize the link graph job: Resize nodes and edges and populate them.
176 * This is done after the constructor so that we can do it in the calculation
177 * thread without delaying the main game.
179 void LinkGraphJob::Init()
181 uint size = this->Size();
182 this->nodes.Resize(size);
183 this->edges.Resize(size, size);
184 for (uint i = 0; i < size; ++i) {
185 this->nodes[i].Init(this->link_graph[i].Supply());
186 EdgeAnnotation *node_edges = this->edges[i];
187 for (uint j = 0; j < size; ++j) {
188 node_edges[j].Init();
194 * Initialize a linkgraph job edge.
196 void LinkGraphJob::EdgeAnnotation::Init()
198 this->demand = 0;
199 this->flow = 0;
200 this->unsatisfied_demand = 0;
204 * Initialize a Linkgraph job node. The underlying memory is expected to be
205 * freshly allocated, without any constructors having been called.
206 * @param supply Initial undelivered supply.
208 void LinkGraphJob::NodeAnnotation::Init(uint supply)
210 this->undelivered_supply = supply;
211 new (&this->flows) FlowStatMap;
212 new (&this->paths) PathList;
216 * Add this path as a new child to the given base path, thus making this path
217 * a "fork" of the base path.
218 * @param base Path to fork from.
219 * @param cap Maximum capacity of the new leg.
220 * @param free_cap Remaining free capacity of the new leg.
221 * @param dist Distance of the new leg.
223 void Path::Fork(Path *base, uint cap, int free_cap, uint dist)
225 this->capacity = min(base->capacity, cap);
226 this->free_capacity = min(base->free_capacity, free_cap);
227 this->distance = base->distance + dist;
228 assert(this->distance > 0);
229 if (this->parent != base) {
230 this->Detach();
231 this->parent = base;
232 this->parent->num_children++;
234 this->origin = base->origin;
238 * Push some flow along a path and register the path in the nodes it passes if
239 * successful.
240 * @param new_flow Amount of flow to push.
241 * @param job Link graph job this node belongs to.
242 * @param max_saturation Maximum saturation of edges.
243 * @return Amount of flow actually pushed.
245 uint Path::AddFlow(uint new_flow, LinkGraphJob &job, uint max_saturation)
247 if (this->parent != NULL) {
248 LinkGraphJob::Edge edge = job[this->parent->node][this->node];
249 if (max_saturation != UINT_MAX) {
250 uint usable_cap = edge.Capacity() * max_saturation / 100;
251 if (usable_cap > edge.Flow()) {
252 new_flow = min(new_flow, usable_cap - edge.Flow());
253 } else {
254 return 0;
257 new_flow = this->parent->AddFlow(new_flow, job, max_saturation);
258 if (this->flow == 0 && new_flow > 0) {
259 job[this->parent->node].Paths().push_front(this);
261 edge.AddFlow(new_flow);
263 this->flow += new_flow;
264 return new_flow;
268 * Create a leg of a path in the link graph.
269 * @param n Id of the link graph node this path passes.
270 * @param source If true, this is the first leg of the path.
272 Path::Path(NodeID n, bool source) :
273 distance(source ? 0 : UINT_MAX),
274 capacity(source ? UINT_MAX : 0),
275 free_capacity(source ? INT_MAX : INT_MIN),
276 flow(0), node(n), origin(source ? n : INVALID_NODE),
277 num_children(0), parent(NULL)