]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/route.cpp
If a train is not on the specified route, find a route to it
[r2c2.git] / source / libmarklin / route.cpp
1 /* $Id$
2
3 This file is part of the MSP Märklin suite
4 Copyright © 2007-2010  Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
6 */
7
8 #include <queue>
9 #include <msp/strings/formatter.h>
10 #include "layout.h"
11 #include "route.h"
12 #include "track.h"
13 #include "tracktype.h"
14
15 using namespace std;
16 using namespace Msp;
17
18 namespace {
19
20 using namespace Marklin;
21
22 struct Node
23 {
24         const Track *track;
25         unsigned ep;
26         Node *prev;
27         float dist;
28
29         Node():
30                 track(0), ep(0), prev(0), dist(0)
31         { }
32
33         Node(const Track &t, unsigned e):
34                 track(&t), ep(e), prev(0), dist(0)
35         { }
36
37         Node(const Track &t, unsigned e, Node &r, float d):
38                 track(&t), ep(e), prev(&r), dist(prev->dist+d)
39         { }
40
41         bool operator<(const Node &other) const
42         { return dist>other.dist; }
43 };
44
45 struct TrackMatch
46 {
47         const Track &track;
48
49         TrackMatch(const Track &t): track(t) { }
50
51         bool operator()(const Track &t) const { return &t==&track; }
52 };
53
54 struct TrackInRoute
55 {
56         const Route &route;
57
58         TrackInRoute(const Route &r): route(r) { }
59
60         bool operator()(const Track &t) const { return route.get_tracks().count(&t); }
61 };
62
63 template<typename Pred>
64 list<const Track *> dijkstra(const Track &from, unsigned ep, const Pred &goal)
65 {
66         // XXX Fails to find some routes - should use track+ep as key
67         map<const Track *, Node> track_nodes;
68         priority_queue<Node> nodes;
69         Node *final = 0;
70
71         nodes.push(Node(from, ep));
72
73         while(!nodes.empty())
74         {
75                 Node lowest = nodes.top();
76                 nodes.pop();
77
78                 if(track_nodes.count(lowest.track))
79                         continue;
80
81                 Node &ref = track_nodes[lowest.track] = lowest;
82                 if(goal(*lowest.track))
83                 {
84                         final = &ref;
85                         break;
86                 }
87
88                 const TrackType &type = lowest.track->get_type();
89                 const vector<Endpoint> &eps = type.get_endpoints();
90                 const vector<Track *> &links = lowest.track->get_links();
91                 for(unsigned i=0; i<eps.size(); ++i)
92                 {
93                         if(i==lowest.ep || !links[i] || track_nodes.count(links[i]))
94                                 continue;
95
96                         unsigned mask = eps[i].paths&eps[lowest.ep].paths;
97                         if(!mask)
98                                 continue;
99
100                         unsigned path=0;
101                         for(; !(mask&1); ++path, mask>>=1) ;
102                         nodes.push(Node(*links[i], links[i]->get_endpoint_by_link(*lowest.track), ref, type.get_path_length(path)));
103                 }
104         }
105
106         if(!final)
107                 throw InvalidParameterValue("Could not find a route");
108
109         list<const Track *> result;
110         for(Node *node=final; node; node=node->prev)
111                 result.push_front(node->track);
112
113         return result;
114 }
115
116 unsigned count = 0;
117
118 template<typename Pred>
119 Route *create_route(const Track &from, unsigned ep, const Pred &goal)
120 {
121         list<const Track *> tracks = dijkstra(from, ep, goal);
122
123         Route *route = new Route(from.get_layout(), format("-%d-", ++count));
124         for(list<const Track *>::iterator i=tracks.begin(); i!=tracks.end(); ++i)
125                 route->add_track(**i);
126
127         return route;
128 }
129
130 }
131
132
133 namespace Marklin {
134
135 Route::Route(Layout &l, const string &n):
136         layout(l),
137         name(n)
138 {
139         layout.add_route(*this);
140         layout.signal_track_removed.connect(sigc::mem_fun(this, &Route::track_removed));
141 }
142
143 Route::~Route()
144 {
145         layout.remove_route(*this);
146 }
147
148 int Route::get_turnout(unsigned id) const
149 {
150         map<unsigned, int>::const_iterator i = turnouts.find(id);
151         if(i!=turnouts.end())
152                 return i->second;
153         return -1;
154 }
155
156 void Route::add_track(const Track &trk)
157 {
158         if(tracks.count(&trk))
159                 return;
160
161         if(!tracks.empty())
162         {
163                 unsigned valid = check_validity(trk);
164                 if(!(valid&1))
165                         throw Exception("Not linked to existing tracks");
166                 else if(!(valid&2))
167                         throw Exception("Branching routes not allowed");
168                 else if(!(valid&4))
169                         throw Exception("Route must be smooth");
170         }
171
172         tracks.insert(&trk);
173         update_turnouts();
174 }
175
176 void Route::add_tracks(const set<const Track *> &trks)
177 {
178         set<const Track *> pending;
179         for(set<const Track *>::const_iterator i=trks.begin(); i!=trks.end(); ++i)
180                 if(!tracks.count(*i))
181                         pending.insert(*i);
182
183         while(!pending.empty())
184         {
185                 bool found = false;
186                 for(set<const Track *>::const_iterator i=pending.begin(); i!=pending.end(); ++i)
187                         if(tracks.empty() || check_validity(**i)==7)
188                         {
189                                 tracks.insert(*i);
190                                 pending.erase(*i);
191                                 found = true;
192                                 break;
193                         }
194
195                 if(!found)
196                         throw Exception("Could not add all tracks to route");
197         }
198
199         update_turnouts();
200 }
201
202 void Route::save(list<DataFile::Statement> &st) const
203 {
204         for(map<unsigned, int>::const_iterator i=turnouts.begin(); i!=turnouts.end(); ++i)
205                 st.push_back((DataFile::Statement("turnout"), i->first, i->second));
206 }
207
208 void Route::update_turnouts()
209 {
210         set<unsigned> found;
211         for(set<const Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
212                 if(unsigned tid=(*i)->get_turnout_id())
213                 {
214                         found.insert(tid);
215
216                         const vector<Endpoint> &endpoints = (*i)->get_type().get_endpoints();
217                         const vector<Track *> &links = (*i)->get_links();
218
219                         // Build a combined path mask from linked endpoints
220                         unsigned mask = 15;
221                         for(unsigned j=0; j<endpoints.size(); ++j)
222                         {
223                                 if(!tracks.count(links[j]))
224                                         continue;
225
226                                 if(unsigned tid2=links[j]->get_turnout_id())
227                                 {
228                                         const Endpoint &ep = links[j]->get_type().get_endpoints()[links[j]->get_endpoint_by_link(**i)];
229                                         int p = get_turnout(tid2);
230                                         if(p>=0 && !(ep.paths&(1<<p)))
231                                         {
232                                                 // The linked track is a turnout and has a path which is incompatible with this endpoint
233                                                 mask &= ~endpoints[j].paths;
234                                                 continue;
235                                         }
236                                 }
237                                 mask &= endpoints[j].paths;
238                         }
239
240                         if(mask && !(mask&(mask-1)))
241                         {
242                                 // Exactly one possible choice, set the path accordingly
243                                 unsigned path = 0;
244                                 for(; (mask && !(mask&1)); mask>>=1, ++path) ;
245                                 turnouts[tid] = path;
246                         }
247                         else if(!turnouts.count(tid))
248                                 // More than one possible choice, and no existing entry - set as undecided
249                                 turnouts[tid] = -1;
250                 }
251
252         // Remove any turnouts that do not exist in the route
253         for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
254         {
255                 if(!found.count(i->first))
256                         turnouts.erase(i++);
257                 else
258                         ++i;
259         }
260 }
261
262 unsigned Route::check_validity(const Track &trk) const
263 {
264         unsigned result = 4;
265         for(set<const Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
266         {
267                 int epi=(*i)->get_endpoint_by_link(trk);
268                 if(epi>=0)
269                 {
270                         // Linked to an existing track - good
271                         result |= 1;
272                         const vector<Endpoint> &endpoints = (*i)->get_type().get_endpoints();
273                         if(unsigned tid=(*i)->get_turnout_id())
274                         {
275                                 int r = get_turnout(tid);
276                                 if(r>=0)
277                                 {
278                                         // Linking to a turnout with path set is only good if we're continuing that path
279                                         if(endpoints[epi].paths&(1<<r))
280                                                 result |= 2;
281                                 }
282                                 else
283                                 {
284                                         // Linked to a turnout with no path set - find out other linked tracks 
285                                         unsigned count = 0;
286                                         const vector<Track *> &links = (*i)->get_links();
287                                         int epj = -1;
288                                         for(unsigned k=0; k<endpoints.size(); ++k)
289                                                 if(tracks.count(links[k]))
290                                                 {
291                                                         ++count;
292                                                         epj = k;
293                                                 }
294
295                                         // Only good if at most one other track is linked to the turnout
296                                         if(count<=1)
297                                         {
298                                                 result |= 2;
299                                                 if(epj>=0 && !(endpoints[epi].paths&endpoints[epj].paths))
300                                                         // Impossible path through the turnout - not good
301                                                         result &= 3;
302                                         }
303                                 }
304                         }
305                         else
306                                 // Linked to something linear - good
307                                 result |= 2;
308                 }
309         }
310
311         return result;
312 }
313
314 void Route::track_removed(Track &t)
315 {
316         tracks.erase(&t);
317 }
318
319 Route *Route::find(const Track &from, unsigned ep, const Track &to)
320 {
321         return create_route(from, ep, TrackMatch(to));
322 }
323
324 Route *Route::find(const Track &from, unsigned ep, const Route &to)
325 {
326         return create_route(from, ep, TrackInRoute(to));
327 }
328
329
330 Route::Loader::Loader(Route &r):
331         DataFile::BasicLoader<Route>(r)
332 {
333         add("turnout", &Loader::turnout);
334 }
335
336 void Route::Loader::turnout(unsigned id, unsigned path)
337 {
338         obj.turnouts[id] = path;
339 }
340
341 } // namespace Marklin