]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/route.cpp
Move Endpoint inside TrackType
[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 "trackiter.h"
14 #include "tracktype.h"
15
16 using namespace std;
17 using namespace Msp;
18
19 namespace {
20
21 using namespace Marklin;
22
23 typedef std::pair<Track *, unsigned> Key;
24
25 struct Node
26 {
27         Track *track;
28         unsigned ep;
29         Node *prev;
30         float dist;
31
32         Node():
33                 track(0), ep(0), prev(0), dist(0)
34         { }
35
36         Node(Track &t, unsigned e):
37                 track(&t), ep(e), prev(0), dist(0)
38         { }
39
40         Node(Track &t, unsigned e, Node &r, float d):
41                 track(&t), ep(e), prev(&r), dist(prev->dist+d)
42         { }
43
44         bool operator<(const Node &other) const
45         { return dist>other.dist; }
46 };
47
48 struct TrackMatch
49 {
50         Track &track;
51
52         TrackMatch(Track &t): track(t) { }
53
54         bool operator()(Track &t) const { return &t==&track; }
55 };
56
57 struct TrackInSet
58 {
59         const set<Track *> &tracks;
60
61         TrackInSet(const set<Track *> &t): tracks(t) { }
62
63         bool operator()(Track &t) const { return tracks.count(&t); }
64 };
65
66 template<typename Pred>
67 list<Track *> dijkstra(Track &from, unsigned ep, const Pred &goal)
68 {
69         map<Key, Node> track_nodes;
70         priority_queue<Node> nodes;
71         Node *final = 0;
72
73         nodes.push(Node(from, ep));
74
75         while(!nodes.empty())
76         {
77                 Node lowest = nodes.top();
78                 nodes.pop();
79
80                 Key key(lowest.track, lowest.ep);
81                 if(track_nodes.count(key))
82                         continue;
83
84                 Node &ref = track_nodes[key] = lowest;
85                 if(goal(*lowest.track))
86                 {
87                         final = &ref;
88                         break;
89                 }
90
91                 const TrackType &type = lowest.track->get_type();
92                 const vector<TrackType::Endpoint> &eps = type.get_endpoints();
93                 const vector<Track *> &links = lowest.track->get_links();
94                 for(unsigned i=0; i<eps.size(); ++i)
95                 {
96                         if(i==lowest.ep || !links[i])
97                                 continue;
98
99                         unsigned link_ep = links[i]->get_endpoint_by_link(*lowest.track);
100                         if(track_nodes.count(Key(links[i], link_ep)))
101                                 continue;
102
103                         unsigned mask = eps[i].paths&eps[lowest.ep].paths;
104                         if(!mask)
105                                 continue;
106
107                         unsigned path=0;
108                         for(; !(mask&1); ++path, mask>>=1) ;
109                         nodes.push(Node(*links[i], links[i]->get_endpoint_by_link(*lowest.track), ref, type.get_path_length(path)));
110                 }
111         }
112
113         if(!final)
114                 throw InvalidParameterValue("Could not find a route");
115
116         list<Track *> result;
117         for(Node *node=final; node; node=node->prev)
118                 result.push_front(node->track);
119
120         return result;
121 }
122
123 template<typename Pred>
124 Route *create_route(Track &from, unsigned ep, const Pred &goal)
125 {
126         list<Track *> tracks = dijkstra(from, ep, goal);
127
128         Route *route = new Route(from.get_layout());
129         for(list<Track *>::iterator i=tracks.begin(); i!=tracks.end(); ++i)
130                 route->add_track(**i);
131
132         route->set_name("Pathfinder");
133         route->set_temporary(true);
134
135         return route;
136 }
137
138 }
139
140
141 namespace Marklin {
142
143 Route::Route(Layout &l):
144         layout(l),
145         temporary(false)
146 {
147         layout.add_route(*this);
148         layout.signal_track_removed.connect(sigc::mem_fun(this, &Route::track_removed));
149 }
150
151 Route::~Route()
152 {
153         layout.remove_route(*this);
154 }
155
156 void Route::set_name(const string &n)
157 {
158         name = n;
159         signal_name_changed.emit(name);
160 }
161
162 void Route::set_temporary(bool t)
163 {
164         temporary = t;
165 }
166
167 void Route::set_turnout(unsigned addr, unsigned path)
168 {
169         if(!addr)
170                 throw InvalidParameterValue("Invalid turnout address");
171         map<unsigned, int>::iterator i = turnouts.find(addr);
172         if(i==turnouts.end())
173                 throw KeyError("Turnout is not in this route");
174         if(i->second>=0 && path!=static_cast<unsigned>(i->second))
175                 throw InvalidState("Setting conflicts with route");
176         i->second = path;
177 }
178
179 void Route::update_turnouts()
180 {
181         set<unsigned> found;
182         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
183                 if(unsigned tid = (*i)->get_turnout_id())
184                 {
185                         found.insert(tid);
186
187                         const vector<TrackType::Endpoint> &endpoints = (*i)->get_type().get_endpoints();
188                         const vector<Track *> &links = (*i)->get_links();
189
190                         // Build a combined path mask from linked endpoints
191                         unsigned mask = 15;
192                         for(unsigned j=0; j<endpoints.size(); ++j)
193                         {
194                                 if(!tracks.count(links[j]))
195                                         continue;
196
197                                 if(unsigned tid2 = links[j]->get_turnout_id())
198                                 {
199                                         const TrackType::Endpoint &ep = links[j]->get_type().get_endpoints()[links[j]->get_endpoint_by_link(**i)];
200                                         int p = get_turnout(tid2);
201                                         if(p>=0 && !(ep.paths&(1<<p)))
202                                         {
203                                                 // The linked track is a turnout and has a path which is incompatible with this endpoint
204                                                 mask &= ~endpoints[j].paths;
205                                                 continue;
206                                         }
207                                 }
208                                 mask &= endpoints[j].paths;
209                         }
210
211                         if(mask && !(mask&(mask-1)))
212                         {
213                                 // Exactly one possible choice, set the path accordingly
214                                 unsigned path = 0;
215                                 for(; (mask && !(mask&1)); mask>>=1, ++path) ;
216                                 turnouts[tid] = path;
217                         }
218                         else if(!turnouts.count(tid))
219                                 // More than one possible choice, and no existing entry - set as undecided
220                                 turnouts[tid] = -1;
221                 }
222
223         // Remove any turnouts that do not exist in the route
224         for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
225         {
226                 if(!found.count(i->first))
227                         turnouts.erase(i++);
228                 else
229                         ++i;
230         }
231 }
232
233 int Route::get_turnout(unsigned id) const
234 {
235         map<unsigned, int>::const_iterator i = turnouts.find(id);
236         if(i!=turnouts.end())
237                 return i->second;
238         return -1;
239 }
240
241 void Route::add_track(Track &trk)
242 {
243         if(tracks.count(&trk))
244                 return;
245
246         if(!tracks.empty())
247         {
248                 unsigned valid = check_validity(trk);
249                 if(!(valid&1))
250                         throw Exception("Not linked to existing tracks");
251                 else if(!(valid&2))
252                         throw Exception("Branching routes not allowed");
253                 else if(!(valid&4))
254                         throw Exception("Route must be smooth");
255         }
256
257         tracks.insert(&trk);
258         update_turnouts();
259 }
260
261 void Route::add_tracks(const set<Track *> &trks)
262 {
263         set<Track *> pending;
264         for(set<Track *>::const_iterator i=trks.begin(); i!=trks.end(); ++i)
265                 if(!tracks.count(*i))
266                         pending.insert(*i);
267
268         while(!pending.empty())
269         {
270                 bool found = false;
271                 for(set<Track *>::const_iterator i=pending.begin(); i!=pending.end(); ++i)
272                         if(tracks.empty() || check_validity(**i)==7)
273                         {
274                                 tracks.insert(*i);
275                                 pending.erase(*i);
276                                 found = true;
277                                 break;
278                         }
279
280                 if(!found)
281                         throw Exception("Could not add all tracks to route");
282         }
283
284         update_turnouts();
285 }
286
287 void Route::add_track_chain(Track &start, unsigned ep, const TurnoutMap &trnts)
288 {
289         TrackIter iter(&start, ep);
290         while(iter)
291         {
292                 if(iter->get_type().is_dead_end())
293                         break;
294
295                 if(has_track(*iter))
296                         break;
297
298                 int path = 0;
299                 if(iter->get_turnout_id())
300                 {
301                         TurnoutMap::const_iterator i = trnts.find(iter->get_turnout_id());
302                         if(i==trnts.end())
303                                 break;
304
305                         path = i->second;
306                 }
307
308                 add_track(*iter);
309
310                 iter = iter.next(path);
311         }
312 }
313
314 bool Route::has_track(Track &t) const
315 {
316         return tracks.count(&t);
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(Track &trk) const
327 {
328         unsigned result = 4;
329         for(set<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<TrackType::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(Track &from, unsigned ep, Track &to)
384 {
385         return create_route(from, ep, TrackMatch(to));
386 }
387
388 Route *Route::find(Track &from, unsigned ep, const Route &to)
389 {
390         return create_route(from, ep, TrackInSet(to.get_tracks()));
391 }
392
393 Route *Route::find(Track &from, unsigned ep, const set<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<TrackType::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                 break;
433         }
434 }
435
436 void Route::Loader::turnout(unsigned id, unsigned path)
437 {
438         turnouts[id] = path;
439 }
440
441 } // namespace Marklin