linkgraph.cpp

Go to the documentation of this file.
00001 /* $Id$ */
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 "../map_func.h"
00014 #include "../core/bitmath_func.hpp"
00015 #include "../debug.h"
00016 #include "../window_func.h"
00017 #include "../window_gui.h"
00018 #include "linkgraph.h"
00019 #include "demands.h"
00020 #include "mcf.h"
00021 #include "flowmapper.h"
00022 #include <queue>
00023 
00027 LinkGraph _link_graphs[NUM_CARGO];
00028 
00032 LinkGraphJob::HandlerList LinkGraphJob::_handlers;
00033 
00040 inline void Node::Init(StationID st, uint sup, uint dem)
00041 {
00042   this->supply = sup;
00043   this->undelivered_supply = sup;
00044   this->demand = dem;
00045   this->station = st;
00046 
00047   for (PathSet::iterator i = this->paths.begin(); i != this->paths.end(); ++i) {
00048     delete *i;
00049   }
00050   this->paths.clear();
00051   this->flows.clear();
00052 }
00053 
00059 inline void Edge::Init(uint distance, uint capacity)
00060 {
00061   this->distance = distance;
00062   this->capacity = capacity;
00063   this->demand = 0;
00064   this->unsatisfied_demand = 0;
00065   this->flow = 0;
00066   this->next_edge = INVALID_NODE;
00067 }
00068 
00069 
00077 void LinkGraph::CreateComponent(Station *first)
00078 {
00079   std::map<Station *, NodeID> index;
00080   index[first] = this->AddNode(first);
00081 
00082   std::queue<Station *> search_queue;
00083   search_queue.push(first);
00084 
00085   /* Find all stations belonging to the current component. */
00086   while (!search_queue.empty()) {
00087     Station *source = search_queue.front();
00088     search_queue.pop();
00089 
00090     const LinkStatMap &links = source->goods[this->cargo].link_stats;
00091     for (LinkStatMap::const_iterator i = links.begin(); i != links.end(); ++i) {
00092       Station *target = Station::GetIfValid(i->first);
00093       if (target == NULL) continue;
00094 
00095       std::map<Station *, NodeID>::iterator index_it = index.find(target);
00096       if (index_it == index.end()) {
00097         search_queue.push(target);
00098         NodeID node = this->AddNode(target);
00099         index[target] = node;
00100 
00101         this->AddEdge(index[source], node, i->second.Capacity());
00102       } else {
00103         this->AddEdge(index[source], index_it->second, i->second.Capacity());
00104       }
00105     }
00106   }
00107 
00108   /* Here the list of nodes and edges for this component is complete. */
00109   this->SpawnThread();
00110 }
00111 
00125 void LinkGraph::NextComponent()
00126 {
00127   /* Check for no stations to avoid problems with Station::GetPoolSize()
00128    * being 0 later and to avoid searching an empty pool.
00129    */
00130   if (Station::GetNumItems() == 0) return;
00131 
00132   /* Don't mess with running jobs (might happen when changing interval).*/
00133   if (this->GetSize() > 0) return;
00134 
00135   /* The station pool may shrink when saving and subsequently loading a game as
00136    * NULL entries at the end are cut off then. If the current station id points
00137    * to one of those NULL entries we have to clamp it here to avoid an infinite
00138    * loop later.
00139    */
00140   StationID last_station_id = min(this->current_station_id, Station::GetPoolSize() - 1);
00141   LinkGraphComponentID current_component_id = this->LinkGraphComponent::index;
00142 
00143   do {
00144     if (++this->current_station_id >= Station::GetPoolSize()) {
00145       /* Wrap around and recycle the component IDs. Use different
00146        * divisibility by 2 than in the last run so that we can find out
00147        * which stations haven't been seen in this run.
00148        */
00149       this->current_station_id = 0;
00150       current_component_id = (current_component_id + 1) % 2;
00151     }
00152 
00153     /* Find first station of next component */
00154     Station *station = Station::GetIfValid(this->current_station_id);
00155     if (station != NULL) continue;
00156     const GoodsEntry &ge = station->goods[this->cargo];
00157 
00158     /* Same divisibility by 2: We've seen that station before. */
00159     if (ge.last_component != INVALID_LINKGRAPH_COMPONENT &&
00160         (ge.last_component + current_component_id) % 2 == 0) {
00161       continue;
00162     }
00163 
00164     /* Different divisibility by 2: This station has not been seen
00165      * in the current run over the link graph. */
00166     if (!ge.link_stats.empty()) {
00167       this->LinkGraphComponent::Init(current_component_id + 2);
00168       this->CreateComponent(station);
00169       return;
00170     }
00171 
00172   } while (this->current_station_id != last_station_id);
00173 }
00174 
00180 void OnTick_LinkGraph()
00181 {
00182   if (_date_fract != LinkGraph::COMPONENTS_SPAWN_TICK &&
00183       _date_fract != LinkGraph::COMPONENTS_JOIN_TICK) {
00184     return;
00185   }
00186 
00187   /* This creates a round robin distribution of all link graphs' turns over the
00188    * available dates. */
00189   for (uint cargo = _date % _settings_game.linkgraph.recalc_interval; cargo < NUM_CARGO;
00190       cargo += _settings_game.linkgraph.recalc_interval) {
00191 
00192     /* Don't calculate a link graph if the distribution is manual */
00193     if (_settings_game.linkgraph.GetDistributionType(cargo) == DT_MANUAL) continue;
00194 
00195     if (_date_fract == LinkGraph::COMPONENTS_SPAWN_TICK) {
00196       _link_graphs[cargo].NextComponent();
00197     } else /* LinkGraph::COMPONENTS_JOIN_TICK */ {
00198       _link_graphs[cargo].Join();
00199     }
00200   }
00201 }
00202 
00211 NodeID LinkGraphComponent::AddNode(Station *st)
00212 {
00213   GoodsEntry &good = st->goods[this->cargo];
00214   good.last_component = this->index;
00215 
00216   bool do_resize = (this->nodes.size() == this->num_nodes);
00217 
00218   if (do_resize) {
00219     this->nodes.push_back(Node());
00220     this->edges.push_back(std::vector<Edge>(this->num_nodes + 1));
00221   }
00222 
00223   this->nodes[this->num_nodes].Init(st->index, good.supply,
00224       HasBit(good.acceptance_pickup, GoodsEntry::GES_ACCEPTANCE));
00225 
00226   std::vector<Edge> &new_edges = this->edges[this->num_nodes];
00227 
00228   /* reset the first edge starting at the new node */
00229   new_edges[this->num_nodes].next_edge = INVALID_NODE;
00230 
00231   for (NodeID i = 0; i < this->num_nodes; ++i) {
00232     uint distance = DistanceManhattan(st->xy, Station::Get(this->nodes[i].station)->xy);
00233     if (do_resize) this->edges[i].push_back(Edge());
00234     new_edges[i].Init(distance);
00235     this->edges[i][this->num_nodes].Init(distance);
00236   }
00237   return this->num_nodes++;
00238 }
00239 
00246 inline void LinkGraphComponent::AddEdge(NodeID from, NodeID to, uint capacity)
00247 {
00248   assert(from != to);
00249   Edge &edge = this->edges[from][to];
00250   Edge &first = this->edges[from][from];
00251   edge.capacity = capacity;
00252   edge.next_edge = first.next_edge;
00253   first.next_edge = to;
00254 }
00255 
00265 void LinkGraphComponent::SetSize()
00266 {
00267   if (this->nodes.size() < this->num_nodes) {
00268     for (EdgeMatrix::iterator i = this->edges.begin(); i != this->edges.end(); ++i) {
00269       i->resize(this->num_nodes);
00270     }
00271     this->nodes.resize(this->num_nodes);
00272     this->edges.resize(this->num_nodes, std::vector<Edge>(this->num_nodes));
00273   }
00274 
00275   for (uint i = 0; i < this->num_nodes; ++i) {
00276     this->nodes[i].Init();
00277     for (uint j = 0; j < this->num_nodes; ++j) {
00278       this->edges[i][j].Init();
00279     }
00280   }
00281 }
00282 
00286 LinkGraphComponent::LinkGraphComponent() :
00287     settings(_settings_game.linkgraph),
00288     cargo(INVALID_CARGO),
00289     num_nodes(0),
00290     index(INVALID_LINKGRAPH_COMPONENT)
00291 {}
00292 
00296 void LinkGraphComponent::Init(LinkGraphComponentID id)
00297 {
00298   assert(this->num_nodes == 0);
00299   this->index = id;
00300   this->settings = _settings_game.linkgraph;
00301 }
00302 
00303 
00312 void Node::ExportFlows(FlowMap::iterator &it, FlowStatMap &station_flows, CargoID cargo)
00313 {
00314   FlowStat *dest = NULL;
00315   StationID source = it->first;
00316   FlowViaMap &source_flows = it->second;
00317   if (!Station::IsValidID(source)) {
00318     source_flows.clear();
00319   } else {
00320     Station *curr_station = Station::Get(this->station);
00321     for (FlowViaMap::iterator update = source_flows.begin(); update != source_flows.end();) {
00322       StationID next = update->first;
00323       int planned = update->second;
00324       assert(planned >= 0);
00325 
00326       Station *via = Station::GetIfValid(next);
00327       if (planned > 0 && via != NULL) {
00328         if (next == this->station ||
00329             curr_station->goods[cargo].link_stats.find(next) !=
00330             curr_station->goods[cargo].link_stats.end()) {
00331           if (dest == NULL) {
00332             dest = &(station_flows.insert(std::make_pair(it->first, FlowStat(next, planned))).first->second);
00333           } else {
00334             dest->AddShare(next, planned);
00335           }
00336         }
00337       }
00338       source_flows.erase(update++);
00339     }
00340   }
00341 
00342   assert(source_flows.empty());
00343 
00344   this->flows.erase(it++);
00345 }
00346 
00351 void Node::ExportFlows(CargoID cargo)
00352 {
00353   FlowStatMap &station_flows = Station::Get(this->station)->goods[cargo].flows;
00354   station_flows.clear();
00355 
00356   /* loop over flows in the node's map and insert them into the station */
00357   for (FlowMap::iterator it(this->flows.begin()); it != this->flows.end();) {
00358     this->ExportFlows(it, station_flows, cargo);
00359   }
00360   assert(this->flows.empty());
00361 }
00362 
00366 void LinkGraph::Join()
00367 {
00368   this->LinkGraphJob::Join();
00369 
00370   for (NodeID node_id = 0; node_id < this->GetSize(); ++node_id) {
00371     Node &node = this->GetNode(node_id);
00372     if (Station::IsValidID(node.station)) {
00373       node.ExportFlows(this->cargo);
00374       InvalidateWindowData(WC_STATION_VIEW, node.station, this->GetCargo());
00375     }
00376   }
00377 
00378   this->LinkGraphComponent::Clear();
00379 }
00380 
00385 /* static */ void LinkGraphJob::RunLinkGraphJob(void *j)
00386 {
00387   LinkGraphJob *job = (LinkGraphJob *)j;
00388   for (HandlerList::iterator i = LinkGraphJob::_handlers.begin(); i != LinkGraphJob::_handlers.end(); ++i) {
00389     (*i)->Run(job);
00390   }
00391 }
00392 
00396 /* static */ void LinkGraphJob::ClearHandlers()
00397 {
00398   for (HandlerList::iterator i = LinkGraphJob::_handlers.begin(); i != LinkGraphJob::_handlers.end(); ++i) {
00399     delete *i;
00400   }
00401   LinkGraphJob::_handlers.clear();
00402 }
00403 
00411 void Path::Fork(Path *base, uint cap, int free_cap, uint dist)
00412 {
00413   this->capacity = min(base->capacity, cap);
00414   this->free_capacity = min(base->free_capacity, free_cap);
00415   this->distance = base->distance + dist;
00416   assert(this->distance > 0);
00417   if (this->parent != base) {
00418     this->Detach();
00419     this->parent = base;
00420     this->parent->num_children++;
00421   }
00422   this->origin = base->origin;
00423 }
00424 
00433 uint Path::AddFlow(uint new_flow, LinkGraphComponent *graph, bool only_positive)
00434 {
00435   if (this->parent != NULL) {
00436     Edge &edge = graph->GetEdge(this->parent->node, this->node);
00437     if (only_positive) {
00438       uint usable_cap = edge.capacity * graph->GetSettings().short_path_saturation / 100;
00439       if (usable_cap > edge.flow) {
00440         new_flow = min(new_flow, usable_cap - edge.flow);
00441       } else {
00442         return 0;
00443       }
00444     }
00445     new_flow = this->parent->AddFlow(new_flow, graph, only_positive);
00446     if (new_flow > 0) {
00447       graph->GetNode(this->parent->node).paths.insert(this);
00448     }
00449     edge.flow += new_flow;
00450   }
00451   this->flow += new_flow;
00452   return new_flow;
00453 }
00454 
00460 Path::Path(NodeID n, bool source) :
00461   distance(source ? 0 : UINT_MAX),
00462   capacity(0),
00463   free_capacity(source ? INT_MAX : INT_MIN),
00464   flow(0), node(n), origin(source ? n : INVALID_NODE),
00465   num_children(0), parent(NULL)
00466 {}
00467 
00471 inline void LinkGraphJob::Join()
00472 {
00473   if (this->thread == NULL) return;
00474   this->thread->Join();
00475   delete this->thread;
00476   this->thread = NULL;
00477 }
00478 
00483 void LinkGraphJob::SpawnThread()
00484 {
00485   assert(this->thread == NULL);
00486   if (!ThreadObject::New(&(LinkGraphJob::RunLinkGraphJob), this, &(this->thread))) {
00487     this->thread = NULL;
00488     /* Of course this will hang a bit.
00489      * On the other hand, if you want to play games which make this hang noticably
00490      * on a platform without threads then you'll probably get other problems first.
00491      * OK:
00492      * If someone comes and tells me that this hangs for him/her, I'll implement a
00493      * smaller grained "Step" method for all handlers and add some more ticks where
00494      * "Step" is called. No problem in principle.
00495      */
00496     LinkGraphJob::RunLinkGraphJob(this);
00497   }
00498 }
00499 
00505 void LinkGraph::Init(CargoID cargo)
00506 {
00507   this->LinkGraphJob::Join();
00508   this->LinkGraphComponent::Clear();
00509 
00510   this->current_station_id = 0;
00511   this->LinkGraphComponent::cargo = cargo;
00512 }
00513 
00517 void InitializeLinkGraphs()
00518 {
00519   for (CargoID c = 0; c < NUM_CARGO; ++c) _link_graphs[c].Init(c);
00520 
00521   LinkGraphJob::ClearHandlers();
00522   LinkGraphJob::AddHandler(new DemandHandler);
00523   LinkGraphJob::AddHandler(new MCFHandler<MCF1stPass>);
00524   LinkGraphJob::AddHandler(new FlowMapper);
00525   LinkGraphJob::AddHandler(new MCFHandler<MCF2ndPass>);
00526   LinkGraphJob::AddHandler(new FlowMapper);
00527 }