]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/route.cpp
d2ed3b7c6fba23d4d0d0b200d619bb61e09dda81
[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 typedef std::pair<const Track *, unsigned> Key;
23
24 struct Node
25 {
26         const Track *track;
27         unsigned ep;
28         Node *prev;
29         float dist;
30
31         Node():
32                 track(0), ep(0), prev(0), dist(0)
33         { }
34
35         Node(const Track &t, unsigned e):
36                 track(&t), ep(e), prev(0), dist(0)
37         { }
38
39         Node(const Track &t, unsigned e, Node &r, float d):
40                 track(&t), ep(e), prev(&r), dist(prev->dist+d)
41         { }
42
43         bool operator<(const Node &other) const
44         { return dist>other.dist; }
45 };
46
47 struct TrackMatch
48 {
49         const Track &track;
50
51         TrackMatch(const Track &t): track(t) { }
52
53         bool operator()(const Track &t) const { return &t==&track; }
54 };
55
56 struct TrackInSet
57 {
58         const set<const Track *> &tracks;
59
60         TrackInSet(const set<const Track *> &t): tracks(t) { }
61
62         bool operator()(const Track &t) const { return tracks.count(&t); }
63 };
64
65 template<typename Pred>
66 list<const Track *> dijkstra(const Track &from, unsigned ep, const Pred &goal)
67 {
68         map<Key, Node> track_nodes;
69         priority_queue<Node> nodes;
70         Node *final = 0;
71
72         nodes.push(Node(from, ep));
73
74         while(!nodes.empty())
75         {
76                 Node lowest = nodes.top();
77                 nodes.pop();
78
79                 Key key(lowest.track, lowest.ep);
80                 if(track_nodes.count(key))
81                         continue;
82
83                 Node &ref = track_nodes[key] = lowest;
84                 if(goal(*lowest.track))
85                 {
86                         final = &ref;
87                         break;
88                 }
89
90                 const TrackType &type = lowest.track->get_type();
91                 const vector<Endpoint> &eps = type.get_endpoints();
92                 const vector<Track *> &links = lowest.track->get_links();
93                 for(unsigned i=0; i<eps.size(); ++i)
94                 {
95                         if(i==lowest.ep || !links[i])
96                                 continue;
97
98                         unsigned link_ep = links[i]->get_endpoint_by_link(*lowest.track);
99                         if(track_nodes.count(Key(links[i], link_ep)))
100                                 continue;
101
102                         unsigned mask = eps[i].paths&eps[lowest.ep].paths;
103                         if(!mask)
104                                 continue;
105
106                         unsigned path=0;
107                         for(; !(mask&1); ++path, mask>>=1) ;
108                         nodes.push(Node(*links[i], links[i]->get_endpoint_by_link(*lowest.track), ref, type.get_path_length(path)));
109                 }
110         }
111
112         if(!final)
113                 throw InvalidParameterValue("Could not find a route");
114
115         list<const Track *> result;
116         for(Node *node=final; node; node=node->prev)
117                 result.push_front(node->track);
118
119         return result;
120 }
121
122 template<typename Pred>
123 Route *create_route(const Track &from, unsigned ep, const Pred &goal)
124 {
125         list<const Track *> tracks = dijkstra(from, ep, goal);
126
127         Route *route = new Route(from.get_layout());
128         for(list<const Track *>::iterator i=tracks.begin(); i!=tracks.end(); ++i)
129                 route->add_track(**i);
130
131         route->set_name("Pathfinder");
132         route->set_temporary(true);
133
134         return route;
135 }
136
137 }
138
139
140 namespace Marklin {
141
142 Route::Route(Layout &l):
143         layout(l),
144         temporary(false)
145 {
146         layout.add_route(*this);
147         layout.signal_track_removed.connect(sigc::mem_fun(this, &Route::track_removed));
148 }
149
150 Route::~Route()
151 {
152         layout.remove_route(*this);
153 }
154
155 void Route::set_name(const string &n)
156 {
157         name = n;
158         signal_name_changed.emit(name);
159 }
160
161 void Route::set_temporary(bool t)
162 {
163         temporary = t;
164 }
165
166 void Route::set_turnout(unsigned addr, unsigned path)
167 {
168         if(!addr)
169                 throw InvalidParameterValue("Invalid turnout address");
170         map<unsigned, int>::iterator i = turnouts.find(addr);
171         if(i==turnouts.end())
172                 throw KeyError("Turnout is not in this route");
173         if(i->second>=0 && path!=static_cast<unsigned>(i->second))
174                 throw InvalidState("Setting conflicts with route");
175         i->second = path;
176 }
177
178 void Route::update_turnouts()
179 {
180         set<unsigned> found;
181         for(set<const Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
182                 if(unsigned tid = (*i)->get_turnout_id())
183                 {
184                         found.insert(tid);
185
186                         const vector<Endpoint> &endpoints = (*i)->get_type().get_endpoints();
187                         const vector<Track *> &links = (*i)->get_links();
188
189                         // Build a combined path mask from linked endpoints
190                         unsigned mask = 15;
191                         for(unsigned j=0; j<endpoints.size(); ++j)
192                         {
193                                 if(!tracks.count(links[j]))
194                                         continue;
195
196                                 if(unsigned tid2 = links[j]->get_turnout_id())
197                                 {
198                                         const Endpoint &ep = links[j]->get_type().get_endpoints()[links[j]->get_endpoint_by_link(**i)];
199                                         int p = get_turnout(tid2);
200                                         if(p>=0 && !(ep.paths&(1<<p)))
201                                         {
202                                                 // The linked track is a turnout and has a path which is incompatible with this endpoint
203                                                 mask &= ~endpoints[j].paths;
204                                                 continue;
205                                         }
206                                 }
207                                 mask &= endpoints[j].paths;
208                         }
209
210                         if(mask && !(mask&(mask-1)))
211                         {
212                                 // Exactly one possible choice, set the path accordingly
213                                 unsigned path = 0;
214                                 for(; (mask && !(mask&1)); mask>>=1, ++path) ;
215                                 turnouts[tid] = path;
216                         }
217                         else if(!turnouts.count(tid))
218                                 // More than one possible choice, and no existing entry - set as undecided
219                                 turnouts[tid] = -1;
220                 }
221
222         // Remove any turnouts that do not exist in the route
223         for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
224         {
225                 if(!found.count(i->first))
226                         turnouts.erase(i++);
227                 else
228                         ++i;
229         }
230 }
231
232 int Route::get_turnout(unsigned id) const
233 {
234         map<unsigned, int>::const_iterator i = turnouts.find(id);
235         if(i!=turnouts.end())
236                 return i->second;
237         return -1;
238 }
239
240 void Route::add_track(const Track &trk)
241 {
242         if(tracks.count(&trk))
243                 return;
244
245         if(!tracks.empty())
246         {
247                 unsigned valid = check_validity(trk);
248                 if(!(valid&1))
249                         throw Exception("Not linked to existing tracks");
250                 else if(!(valid&2))
251                         throw Exception("Branching routes not allowed");
252                 else if(!(valid&4))
253                         throw Exception("Route must be smooth");
254         }
255
256         tracks.insert(&trk);
257         update_turnouts();
258 }
259
260 void Route::add_tracks(const set<const Track *> &trks)
261 {
262         set<const Track *> pending;
263         for(set<const Track *>::const_iterator i=trks.begin(); i!=trks.end(); ++i)
264                 if(!tracks.count(*i))
265                         pending.insert(*i);
266
267         while(!pending.empty())
268         {
269                 bool found = false;
270                 for(set<const Track *>::const_iterator i=pending.begin(); i!=pending.end(); ++i)
271                         if(tracks.empty() || check_validity(**i)==7)
272                         {
273                                 tracks.insert(*i);
274                                 pending.erase(*i);
275                                 found = true;
276                                 break;
277                         }
278
279                 if(!found)
280                         throw Exception("Could not add all tracks to route");
281         }
282
283         update_turnouts();
284 }
285
286 void Route::add_track_chain(const Track &start, unsigned ep, const TurnoutMap &trnts)
287 {
288         const Track *track = &start;
289         while(1)
290         {
291                 if(track->get_type().is_dead_end())
292                         break;
293
294                 if(tracks.count(track))
295                         break;
296
297                 int path = 0;
298                 if(track->get_turnout_id())
299                 {
300                         TurnoutMap::const_iterator i = trnts.find(track->get_turnout_id());
301                         if(i==trnts.end())
302                                 break;
303
304                         path = i->second;
305                 }
306
307                 add_track(*track);
308
309                 unsigned out_ep = track->traverse(ep, path);
310                 Track *next = track->get_links()[out_ep];
311                 if(!next)
312                         break;
313
314                 ep = next->get_endpoint_by_link(*track);
315                 track = next;
316         }
317 }
318
319 void Route::save(list<DataFile::Statement> &st) const
320 {
321         st.push_back((DataFile::Statement("name"), name));
322         for(map<unsigned, int>::const_iterator i=turnouts.begin(); i!=turnouts.end(); ++i)
323                 st.push_back((DataFile::Statement("turnout"), i->first, i->second));
324 }
325
326 unsigned Route::check_validity(const Track &trk) const
327 {
328         unsigned result = 4;
329         for(set<const Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
330         {
331                 int epi=(*i)->get_endpoint_by_link(trk);
332                 if(epi>=0)
333                 {
334                         // Linked to an existing track - good
335                         result |= 1;
336                         const vector<Endpoint> &endpoints = (*i)->get_type().get_endpoints();
337                         if(unsigned tid=(*i)->get_turnout_id())
338                         {
339                                 int r = get_turnout(tid);
340                                 if(r>=0)
341                                 {
342                                         // Linking to a turnout with path set is only good if we're continuing that path
343                                         if(endpoints[epi].paths&(1<<r))
344                                                 result |= 2;
345                                 }
346                                 else
347                                 {
348                                         // Linked to a turnout with no path set - find out other linked tracks 
349                                         unsigned count = 0;
350                                         const vector<Track *> &links = (*i)->get_links();
351                                         int epj = -1;
352                                         for(unsigned k=0; k<endpoints.size(); ++k)
353                                                 if(tracks.count(links[k]))
354                                                 {
355                                                         ++count;
356                                                         epj = k;
357                                                 }
358
359                                         // Only good if at most one other track is linked to the turnout
360                                         if(count<=1)
361                                         {
362                                                 result |= 2;
363                                                 if(epj>=0 && !(endpoints[epi].paths&endpoints[epj].paths))
364                                                         // Impossible path through the turnout - not good
365                                                         result &= 3;
366                                         }
367                                 }
368                         }
369                         else
370                                 // Linked to something linear - good
371                                 result |= 2;
372                 }
373         }
374
375         return result;
376 }
377
378 void Route::track_removed(Track &t)
379 {
380         tracks.erase(&t);
381 }
382
383 Route *Route::find(const Track &from, unsigned ep, const Track &to)
384 {
385         return create_route(from, ep, TrackMatch(to));
386 }
387
388 Route *Route::find(const Track &from, unsigned ep, const Route &to)
389 {
390         return create_route(from, ep, TrackInSet(to.get_tracks()));
391 }
392
393 Route *Route::find(const Track &from, unsigned ep, const set<const Track *> &to)
394 {
395         return create_route(from, ep, TrackInSet(to));
396 }
397
398
399 Route::Loader::Loader(Route &r):
400         DataFile::BasicLoader<Route>(r)
401 {
402         add("name",    &Route::name);
403         add("turnout", &Loader::turnout);
404 }
405
406 void Route::Loader::finish()
407 {
408         const set<Track *> &ltracks = obj.layout.get_tracks();
409         for(set<Track *>::const_iterator i=ltracks.begin(); i!=ltracks.end(); ++i)
410         {
411                 unsigned tid = (*i)->get_turnout_id();
412                 if(!tid)
413                         continue;
414
415                 TurnoutMap::iterator j = turnouts.find(tid);
416                 if(j==turnouts.end())
417                         continue;
418
419                 unsigned path_mask = 1<<j->second;
420                 const vector<Endpoint> &eps = (*i)->get_type().get_endpoints();
421                 for(unsigned k=0; k<eps.size(); ++k)
422                         if(eps[k].paths&path_mask)
423                         {
424                                 Track *link = (*i)->get_link(k);
425                                 if(!obj.tracks.count(link))
426                                         obj.add_track_chain(*link, link->get_endpoint_by_link(**i), turnouts);
427                                 if(!obj.tracks.count(*i))
428                                         obj.add_track_chain(**i, k, turnouts);
429                                 break;
430                         }
431         }
432 }
433
434 void Route::Loader::turnout(unsigned id, unsigned path)
435 {
436         turnouts[id] = path;
437 }
438
439 } // namespace Marklin