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