3 This file is part of the MSP Märklin suite
4 Copyright © 2007-2009 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
11 #include "tracktype.h"
18 Route::Route(Layout &layout, const string &n):
21 layout.signal_track_removed.connect(sigc::mem_fun(this, &Route::track_removed));
24 int Route::get_turnout(unsigned id) const
26 map<unsigned, int>::const_iterator i = turnouts.find(id);
32 void Route::add_track(const Track &trk)
34 if(tracks.count(&trk))
39 unsigned valid = check_validity(trk);
41 throw Exception("Not linked to existing tracks");
43 throw Exception("Branching routes not allowed");
45 throw Exception("Route must be smooth");
52 void Route::add_tracks(const set<const Track *> &trks)
54 set<const Track *> pending;
55 for(set<const Track *>::const_iterator i=trks.begin(); i!=trks.end(); ++i)
59 while(!pending.empty())
62 for(set<const Track *>::const_iterator i=pending.begin(); i!=pending.end(); ++i)
63 if(tracks.empty() || check_validity(**i)==7)
72 throw Exception("Could not add all tracks to route");
78 void Route::save(list<DataFile::Statement> &st) const
80 for(map<unsigned, int>::const_iterator i=turnouts.begin(); i!=turnouts.end(); ++i)
81 st.push_back((DataFile::Statement("turnout"), i->first, i->second));
84 void Route::update_turnouts()
87 for(set<const Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
88 if(unsigned tid=(*i)->get_turnout_id())
92 const vector<Endpoint> &endpoints = (*i)->get_type().get_endpoints();
93 const vector<Track *> &links = (*i)->get_links();
96 for(unsigned j=0; j<endpoints.size(); ++j)
98 if(!tracks.count(links[j]))
100 if(unsigned tid2=links[j]->get_turnout_id())
102 const Endpoint &ep = links[j]->get_type().get_endpoints()[links[j]->get_endpoint_by_link(**i)];
103 int r = get_turnout(tid2);
104 if(r>=0 && !(ep.routes&(1<<r)))
106 mask &= ~endpoints[j].routes;
110 mask &= endpoints[j].routes;
116 for(; (mask && !(mask&1)); mask>>=1, ++route) ;
117 turnouts[tid] = route;
123 for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
125 if(!found.count(i->first))
132 unsigned Route::check_validity(const Track &trk) const
135 for(set<const Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
137 int epi=(*i)->get_endpoint_by_link(trk);
141 const vector<Endpoint> &endpoints = (*i)->get_type().get_endpoints();
142 if(unsigned tid=(*i)->get_turnout_id())
144 int r = get_turnout(tid);
147 if(endpoints[epi].routes&(1<<r))
153 const vector<Track *> &links = (*i)->get_links();
155 for(unsigned k=0; k<endpoints.size(); ++k)
156 if(tracks.count(links[k]))
164 if(epj>=0 && !(endpoints[epi].routes&endpoints[epj].routes))
177 void Route::track_removed(Track &t)
183 Route::Loader::Loader(Route &r):
184 DataFile::BasicLoader<Route>(r)
186 add("turnout", &Loader::turnout);
189 void Route::Loader::turnout(unsigned id, unsigned route)
191 obj.turnouts[id] = route;
194 } // namespace Marklin