# linkgraphjob.cpp

Go to the documentation of this file.

    00001 /* $Id: linkgraphjob.cpp 26347 2014-02-16 18:42:59Z fonsinchen $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "../stdafx.h"
    00013 #include "../core/pool_func.hpp"
    00014 #include "../window_func.h"
    00015 #include "linkgraphjob.h"
    00016 #include "linkgraphschedule.h"
    00017
    00018 /* Initialize the link-graph-job-pool */
    00019 LinkGraphJobPool _link_graph_job_pool("LinkGraphJob");
    00020 INSTANTIATE_POOL_METHODS(LinkGraphJob)
    00021
    00022
    00028 LinkGraphJob::LinkGraphJob(const LinkGraph &orig) :
    00029     /* Copying the link graph here also copies its index member.
    00030      * This is on purpose. */
    00031     link_graph(orig),
    00032     settings(_settings_game.linkgraph),
    00033     thread(NULL),
    00034     join_date(_date + _settings_game.linkgraph.recalc_time)
    00035 {
    00036 }
    00037
    00042 void LinkGraphJob::EraseFlows(NodeID from)
    00043 {
    00044   for (NodeID node_id = 0; node_id < this->Size(); ++node_id) {
    00045     (*this)[node_id].Flows().erase(from);
    00046   }
    00047 }
    00048
    00053 void LinkGraphJob::SpawnThread()
    00054 {
    00055   if (!ThreadObject::New(&(LinkGraphSchedule::Run), this, &this->thread)) {
    00056     this->thread = NULL;
    00057     /* Of course this will hang a bit.
    00058      * On the other hand, if you want to play games which make this hang noticably
    00059      * on a platform without threads then you'll probably get other problems first.
    00060      * OK:
    00061      * If someone comes and tells me that this hangs for him/her, I'll implement a
    00062      * smaller grained "Step" method for all handlers and add some more ticks where
    00063      * "Step" is called. No problem in principle. */
    00064     LinkGraphSchedule::Run(this);
    00065   }
    00066 }
    00067
    00071 void LinkGraphJob::JoinThread()
    00072 {
    00073   if (this->thread != NULL) {
    00074     this->thread->Join();
    00075     delete this->thread;
    00076     this->thread = NULL;
    00077   }
    00078 }
    00079
    00083 LinkGraphJob::~LinkGraphJob()
    00084 {
    00085   this->JoinThread();
    00086
    00087   /* Don't update stuff from other pools, when everything is being removed.
    00088    * Accessing other pools may be invalid. */
    00089   if (CleaningPool()) return;
    00090
    00091   /* Link graph has been merged into another one. */
    00092   if (!LinkGraph::IsValidID(this->link_graph.index)) return;
    00093
    00094   uint size = this->Size();
    00095   for (NodeID node_id = 0; node_id < size; ++node_id) {
    00096     Node from = (*this)[node_id];
    00097
    00098     /* The station can have been deleted. Remove all flows originating from it then. */
    00099     Station *st = Station::GetIfValid(from.Station());
    00100     if (st == NULL) {
    00101       this->EraseFlows(node_id);
    00102       continue;
    00103     }
    00104
    00105     /* Link graph merging and station deletion may change around IDs. Make
    00106      * sure that everything is still consistent or ignore it otherwise. */
    00107     GoodsEntry &ge = st->goods[this->Cargo()];
    00108     if (ge.link_graph != this->link_graph.index || ge.node != node_id) {
    00109       this->EraseFlows(node_id);
    00110       continue;
    00111     }
    00112
    00113     LinkGraph *lg = LinkGraph::Get(ge.link_graph);
    00114     FlowStatMap &flows = from.Flows();
    00115
    00116     for (EdgeIterator it(from.Begin()); it != from.End(); ++it) {
    00117       if (from[it->first].Flow() == 0) continue;
    00118       StationID to = (*this)[it->first].Station();
    00119       Station *st2 = Station::GetIfValid(to);
    00120       if (st2 == NULL || st2->goods[this->Cargo()].link_graph != this->link_graph.index ||
    00121           st2->goods[this->Cargo()].node != it->first ||
    00122           (*lg)[node_id][it->first].LastUpdate() == INVALID_DATE) {
    00123         /* Edge has been removed. Delete flows. */
    00124         StationIDStack erased = flows.DeleteFlows(to);
    00125         /* Delete old flows for source stations which have been deleted
    00126          * from the new flows. This avoids flow cycles between old and
    00127          * new flows. */
    00128         while (!erased.IsEmpty()) ge.flows.erase(erased.Pop());
    00129       } else if ((*lg)[node_id][it->first].LastUnrestrictedUpdate() == INVALID_DATE) {
    00130         /* Edge is fully restricted. */
    00131         flows.RestrictFlows(to);
    00132       }
    00133     }
    00134
    00135     /* Swap shares and invalidate ones that are completely deleted. Don't
    00136      * really delete them as we could then end up with unroutable cargo
    00137      * somewhere. Do delete them and also reroute relevant cargo if
    00138      * automatic distribution has been turned off for that cargo. */
    00139     for (FlowStatMap::iterator it(ge.flows.begin()); it != ge.flows.end();) {
    00140       FlowStatMap::iterator new_it = flows.find(it->first);
    00141       if (new_it == flows.end()) {
    00142         if (_settings_game.linkgraph.GetDistributionType(this->Cargo()) != DT_MANUAL) {
    00143           it->second.Invalidate();
    00144           ++it;
    00145         } else {
    00146           FlowStat shares(INVALID_STATION, 1);
    00147           it->second.SwapShares(shares);
    00148           ge.flows.erase(it++);
    00149           for (FlowStat::SharesMap::const_iterator shares_it(shares.GetShares()->begin());
    00150               shares_it != shares.GetShares()->end(); ++shares_it) {
    00151             RerouteCargo(st, this->Cargo(), shares_it->second, st->index);
    00152           }
    00153         }
    00154       } else {
    00155         it->second.SwapShares(new_it->second);
    00156         flows.erase(new_it);
    00157         ++it;
    00158       }
    00159     }
    00160     ge.flows.insert(flows.begin(), flows.end());
    00161     InvalidateWindowData(WC_STATION_VIEW, st->index, this->Cargo());
    00162   }
    00163 }
    00164
    00170 void LinkGraphJob::Init()
    00171 {
    00172   uint size = this->Size();
    00173   this->nodes.Resize(size);
    00174   this->edges.Resize(size, size);
    00175   for (uint i = 0; i < size; ++i) {
    00176     this->nodes[i].Init(this->link_graph[i].Supply());
    00177     EdgeAnnotation *node_edges = this->edges[i];
    00178     for (uint j = 0; j < size; ++j) {
    00179       node_edges[j].Init();
    00180     }
    00181   }
    00182 }
    00183
    00187 void LinkGraphJob::EdgeAnnotation::Init()
    00188 {
    00189   this->demand = 0;
    00190   this->flow = 0;
    00191   this->unsatisfied_demand = 0;
    00192 }
    00193
    00199 void LinkGraphJob::NodeAnnotation::Init(uint supply)
    00200 {
    00201   this->undelivered_supply = supply;
    00202   new (&this->flows) FlowStatMap;
    00203   new (&this->paths) PathList;
    00204 }
    00205
    00214 void Path::Fork(Path *base, uint cap, int free_cap, uint dist)
    00215 {
    00216   this->capacity = min(base->capacity, cap);
    00217   this->free_capacity = min(base->free_capacity, free_cap);
    00218   this->distance = base->distance + dist;
    00219   assert(this->distance > 0);
    00220   if (this->parent != base) {
    00221     this->Detach();
    00222     this->parent = base;
    00223     this->parent->num_children++;
    00224   }
    00225   this->origin = base->origin;
    00226 }
    00227
    00236 uint Path::AddFlow(uint new_flow, LinkGraphJob &job, uint max_saturation)
    00237 {
    00238   if (this->parent != NULL) {
    00239     LinkGraphJob::Edge edge = job[this->parent->node][this->node];
    00240     if (max_saturation != UINT_MAX) {
    00241       uint usable_cap = edge.Capacity() * max_saturation / 100;
    00242       if (usable_cap > edge.Flow()) {
    00243         new_flow = min(new_flow, usable_cap - edge.Flow());
    00244       } else {
    00245         return 0;
    00246       }
    00247     }
    00248     new_flow = this->parent->AddFlow(new_flow, job, max_saturation);
    00249     if (this->flow == 0 && new_flow > 0) {
    00250       job[this->parent->node].Paths().push_front(this);
    00251     }
    00252     edge.AddFlow(new_flow);
    00253   }
    00254   this->flow += new_flow;
    00255   return new_flow;
    00256 }
    00257
    00263 Path::Path(NodeID n, bool source) :
    00264   distance(source ? 0 : UINT_MAX),
    00265   capacity(source ? UINT_MAX : 0),
    00266   free_capacity(source ? INT_MAX : INT_MIN),
    00267   flow(0), node(n), origin(source ? n : INVALID_NODE),
    00268   num_children(0), parent(NULL)
    00269 {}
    00270