]> git.tdb.fi Git - r2c2.git/commitdiff
Add a variant of Route::find that takes a set of tracks
authorMikko Rasa <tdb@tdb.fi>
Tue, 19 Oct 2010 16:32:20 +0000 (16:32 +0000)
committerMikko Rasa <tdb@tdb.fi>
Tue, 19 Oct 2010 16:32:20 +0000 (16:32 +0000)
Allow setting turnouts in a Route manually
Move Route::update_turnouts to its proper place
Add full route chaining to Train
Better logic for where to start pathfinding
Divert trains to an alternate route if possible when blocked

source/libmarklin/route.cpp
source/libmarklin/route.h
source/libmarklin/train.cpp
source/libmarklin/train.h

index 6cd58413d61ee562231b70e00c2ef44f3ec0e510..d2ed3b7c6fba23d4d0d0b200d619bb61e09dda81 100644 (file)
@@ -53,13 +53,13 @@ struct TrackMatch
        bool operator()(const Track &t) const { return &t==&track; }
 };
 
-struct TrackInRoute
+struct TrackInSet
 {
-       const Route &route;
+       const set<const Track *> &tracks;
 
-       TrackInRoute(const Route &r): route(r) { }
+       TrackInSet(const set<const Track *> &t): tracks(t) { }
 
-       bool operator()(const Track &t) const { return route.get_tracks().count(&t); }
+       bool operator()(const Track &t) const { return tracks.count(&t); }
 };
 
 template<typename Pred>
@@ -163,6 +163,72 @@ void Route::set_temporary(bool t)
        temporary = t;
 }
 
+void Route::set_turnout(unsigned addr, unsigned path)
+{
+       if(!addr)
+               throw InvalidParameterValue("Invalid turnout address");
+       map<unsigned, int>::iterator i = turnouts.find(addr);
+       if(i==turnouts.end())
+               throw KeyError("Turnout is not in this route");
+       if(i->second>=0 && path!=static_cast<unsigned>(i->second))
+               throw InvalidState("Setting conflicts with route");
+       i->second = path;
+}
+
+void Route::update_turnouts()
+{
+       set<unsigned> found;
+       for(set<const Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
+               if(unsigned tid = (*i)->get_turnout_id())
+               {
+                       found.insert(tid);
+
+                       const vector<Endpoint> &endpoints = (*i)->get_type().get_endpoints();
+                       const vector<Track *> &links = (*i)->get_links();
+
+                       // Build a combined path mask from linked endpoints
+                       unsigned mask = 15;
+                       for(unsigned j=0; j<endpoints.size(); ++j)
+                       {
+                               if(!tracks.count(links[j]))
+                                       continue;
+
+                               if(unsigned tid2 = links[j]->get_turnout_id())
+                               {
+                                       const Endpoint &ep = links[j]->get_type().get_endpoints()[links[j]->get_endpoint_by_link(**i)];
+                                       int p = get_turnout(tid2);
+                                       if(p>=0 && !(ep.paths&(1<<p)))
+                                       {
+                                               // The linked track is a turnout and has a path which is incompatible with this endpoint
+                                               mask &= ~endpoints[j].paths;
+                                               continue;
+                                       }
+                               }
+                               mask &= endpoints[j].paths;
+                       }
+
+                       if(mask && !(mask&(mask-1)))
+                       {
+                               // Exactly one possible choice, set the path accordingly
+                               unsigned path = 0;
+                               for(; (mask && !(mask&1)); mask>>=1, ++path) ;
+                               turnouts[tid] = path;
+                       }
+                       else if(!turnouts.count(tid))
+                               // More than one possible choice, and no existing entry - set as undecided
+                               turnouts[tid] = -1;
+               }
+
+       // Remove any turnouts that do not exist in the route
+       for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
+       {
+               if(!found.count(i->first))
+                       turnouts.erase(i++);
+               else
+                       ++i;
+       }
+}
+
 int Route::get_turnout(unsigned id) const
 {
        map<unsigned, int>::const_iterator i = turnouts.find(id);
@@ -250,60 +316,6 @@ void Route::add_track_chain(const Track &start, unsigned ep, const TurnoutMap &t
        }
 }
 
-void Route::update_turnouts()
-{
-       set<unsigned> found;
-       for(set<const Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
-               if(unsigned tid = (*i)->get_turnout_id())
-               {
-                       found.insert(tid);
-
-                       const vector<Endpoint> &endpoints = (*i)->get_type().get_endpoints();
-                       const vector<Track *> &links = (*i)->get_links();
-
-                       // Build a combined path mask from linked endpoints
-                       unsigned mask = 15;
-                       for(unsigned j=0; j<endpoints.size(); ++j)
-                       {
-                               if(!tracks.count(links[j]))
-                                       continue;
-
-                               if(unsigned tid2 = links[j]->get_turnout_id())
-                               {
-                                       const Endpoint &ep = links[j]->get_type().get_endpoints()[links[j]->get_endpoint_by_link(**i)];
-                                       int p = get_turnout(tid2);
-                                       if(p>=0 && !(ep.paths&(1<<p)))
-                                       {
-                                               // The linked track is a turnout and has a path which is incompatible with this endpoint
-                                               mask &= ~endpoints[j].paths;
-                                               continue;
-                                       }
-                               }
-                               mask &= endpoints[j].paths;
-                       }
-
-                       if(mask && !(mask&(mask-1)))
-                       {
-                               // Exactly one possible choice, set the path accordingly
-                               unsigned path = 0;
-                               for(; (mask && !(mask&1)); mask>>=1, ++path) ;
-                               turnouts[tid] = path;
-                       }
-                       else if(!turnouts.count(tid))
-                               // More than one possible choice, and no existing entry - set as undecided
-                               turnouts[tid] = -1;
-               }
-
-       // Remove any turnouts that do not exist in the route
-       for(map<unsigned, int>::iterator i=turnouts.begin(); i!=turnouts.end();)
-       {
-               if(!found.count(i->first))
-                       turnouts.erase(i++);
-               else
-                       ++i;
-       }
-}
-
 void Route::save(list<DataFile::Statement> &st) const
 {
        st.push_back((DataFile::Statement("name"), name));
@@ -375,7 +387,12 @@ Route *Route::find(const Track &from, unsigned ep, const Track &to)
 
 Route *Route::find(const Track &from, unsigned ep, const Route &to)
 {
-       return create_route(from, ep, TrackInRoute(to));
+       return create_route(from, ep, TrackInSet(to.get_tracks()));
+}
+
+Route *Route::find(const Track &from, unsigned ep, const set<const Track *> &to)
+{
+       return create_route(from, ep, TrackInSet(to));
 }
 
 
index 7c188b00e702bf37bf7786ccbdbd0af010799b20..3825c7eb286b233ef9bb29f291db2b3633460484 100644 (file)
@@ -53,6 +53,7 @@ public:
        const std::string &get_name() const { return name; }
        void set_temporary(bool);
        bool is_temporary() const { return temporary; }
+       void set_turnout(unsigned, unsigned);
        void update_turnouts();
        int get_turnout(unsigned) const;
        const std::map<unsigned, int> &get_turnouts() const { return turnouts; }
@@ -68,6 +69,7 @@ private:
 public:
        static Route *find(const Track &, unsigned, const Track &);
        static Route *find(const Track &, unsigned, const Route &);
+       static Route *find(const Track &, unsigned, const std::set<const Track *> &);
 };
 
 } // namespace Marklin
index bd813d3fbe4cdc3ed380bcc8d2878d770b6e2560..baa58db0e813ee042141b589812f634f06163f2c 100644 (file)
@@ -55,8 +55,6 @@ Train::Train(Layout &l, const VehicleType &t, unsigned a):
        speed_changing(false),
        reverse(false),
        functions(0),
-       route(0),
-       next_route(0),
        end_of_route(false),
        status("Unplaced"),
        travel_dist(0),
@@ -207,35 +205,29 @@ void Train::set_timetable(Timetable *tt)
 
 void Train::set_route(const Route *r)
 {
-       if(!rsv_blocks.empty())
-       {
-               for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
-                       if(i->block->get_sensor_id())
-                       {
-                               release_blocks(rsv_blocks, ++i, rsv_blocks.end());
-                               break;
-                       }
-       }
+       free_noncritical_blocks();
 
-       route = r;
-       next_route = 0;
+       routes.clear();
+       if(r)
+               routes.push_back(r);
        end_of_route = false;
 
-       if(route && !cur_blocks.empty())
+       if(r && !cur_blocks.empty())
        {
                BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
                BlockRef next = last.next();
                const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
-               if(!route->get_tracks().count(ep.track))
-               {
-                       next_route = route;
-                       route = Route::find(*ep.track, ep.track_ep, *next_route);
-               }
+               if(!r->get_tracks().count(ep.track))
+                       routes.push_front(Route::find(*ep.track, ep.track_ep, *r));
+
+               /* XXX This is sort of a hack, but it keeps divert() happy.  Need to come
+               up with a better solution when there is time. */
+               routes.push_front(create_lead_route());
        }
 
        reserve_more();
 
-       signal_route_changed.emit(route);
+       signal_route_changed.emit(get_route());
 }
 
 void Train::go_to(const Track &to)
@@ -248,20 +240,138 @@ void Train::go_to(const Track &to)
                        return;
                }
 
-       BlockRef *last = 0;
-       if(rsv_blocks.empty())
-               last = &cur_blocks.back();
+       free_noncritical_blocks();
+
+       BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
+       BlockRef next = last.next();
+       const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
+
+       set_route(Route::find(*ep.track, ep.track_ep, to));
+}
+
+bool Train::divert(Track &from)
+{
+       if(!from.get_turnout_id())
+               throw InvalidParameterValue("Can't divert from a non-turnout");
+       if(routes.empty())
+               return false;
+
+       int path = -1;
+       unsigned from_ep = 0;
+       list<RouteRef>::iterator route = routes.begin();
+       Block *block = cur_blocks.back().block;
+       unsigned entry = cur_blocks.back().entry;
+       set<const Track *> visited;
+
+       // Follow our routes to find out where we're entering the turnout
+       while(1)
+       {
+               Block *link = block->get_link(block->traverse(entry, route->route));
+               entry = link->get_endpoint_by_link(*block);
+               block = link;
+
+               const Block::Endpoint &entry_ep = block->get_endpoints()[entry];
+
+               if(visited.count(entry_ep.track))
+                       return false;
+               visited.insert(entry_ep.track);
+
+               if(!advance_route(route, *entry_ep.track))
+                       return false;
+
+               if(entry_ep.track==&from)
+               {
+                       if(block->get_train()==this && !free_block(*block))
+                               return false;
+
+                       from_ep = entry_ep.track_ep;
+                       path = route->route->get_turnout(from.get_turnout_id());
+                       break;
+               }
+       }
+
+       // Check that more than one path is available
+       unsigned ep_paths = from.get_type().get_endpoints()[from_ep].paths;
+       if(!(ep_paths&(ep_paths-1)))
+               return false;
+
+       // Choose some other path
+       for(int i=0; ep_paths>>i; ++i)
+               if((ep_paths&(1<<i)) && i!=path)
+               {
+                       path = i;
+                       break;
+               }
+
+       Track *track = from.get_link(from.traverse(from_ep, path));
+       if(!track)
+               return false;
+
+       unsigned ep = track->get_endpoint_by_link(from);
+
+       set<const Track *> tracks;
+       for(list<RouteRef>::iterator i=routes.begin(); i!=routes.end(); ++i)
+               tracks.insert(i->route->get_tracks().begin(), i->route->get_tracks().end());
+       Route *diversion = 0;
+       try
+       {
+               diversion = Route::find(*track, ep, tracks);
+       }
+       catch(const Msp::Exception &)
+       {
+               return false;
+       }
+
+       diversion->set_name("Diversion");
+       diversion->add_track(from);
+       diversion->set_turnout(from.get_turnout_id(), path);
+
+       if(!is_valid_diversion(*diversion, from, from_ep))
+       {
+               delete diversion;
+               return false;
+       }
+
+       // Follow the diversion route until we get back to the original route
+       list<RouteRef>::iterator end = routes.end();
+       while(1)
+       {
+               path = 0;
+               if(track->get_turnout_id())
+                       path = diversion->get_turnout(track->get_turnout_id());
+               Track *next = track->get_link(track->traverse(ep, path));
+
+               for(list<RouteRef>::iterator i=route; (end==routes.end() && i!=routes.end()); ++i)
+                       if(i->route->get_tracks().count(next))
+                               end = i;
+
+               if(end!=routes.end())
+                       break;
+               else if(!diversion->get_tracks().count(next))
+                       throw Exception("Pathfinder returned a bad route");
+
+               ep = next->get_endpoint_by_link(*track);
+               track = next;
+       }
+
+       if(route==end)
+               // We are rejoining the same route we diverted from, duplicate it
+               routes.insert(end, *route);
        else
        {
-               for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
-                       if(i->block->get_sensor_id())
-                               last = &*i;
+               ++route;
+               routes.erase(route, end);
        }
+       routes.insert(end, RouteRef(diversion, from.get_turnout_id()));
 
-       BlockRef next = last->next();
-       const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
+       return true;
+}
 
-       set_route(Route::find(*ep.track, ep.track_ep, to));
+const Route *Train::get_route() const
+{
+       if(routes.empty())
+               return 0;
+       return routes.front().route;
 }
 
 void Train::place(Block &block, unsigned entry)
@@ -337,6 +447,75 @@ bool Train::free_block(Block &block)
        return false;
 }
 
+void Train::free_noncritical_blocks()
+{
+       if(cur_blocks.empty() || rsv_blocks.empty())
+               return;
+
+       if(controller->get_speed()==0)
+       {
+               release_blocks(rsv_blocks);
+               return;
+       }
+
+       float margin = 10*layout.get_catalogue().get_scale();
+       float min_dist = controller->get_braking_distance()*1.3+margin;
+
+       Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
+
+       Track *track = veh.get_track();
+       list<BlockRef>::iterator block = cur_blocks.begin();
+       bool in_rsv = false;
+       while(block!=rsv_blocks.end() && !block->block->get_tracks().count(track))
+       {
+               ++block;
+               if(block==cur_blocks.end())
+               {
+                       block = rsv_blocks.begin();
+                       in_rsv = true;
+               }
+       }
+
+       unsigned entry = veh.get_entry();
+       float dist = veh.get_offset();
+       if(reverse)
+               entry = track->traverse(entry);
+       else
+               dist = track->get_type().get_path_length(track->get_active_path())-dist;
+       dist -= veh.get_type().get_length()/2;
+
+       bool nsens = 0;
+       while(1)
+       {
+               Track *next = track->get_link(track->traverse(entry));
+               entry = next->get_endpoint_by_link(*track);
+               track = next;
+
+               if(!block->block->get_tracks().count(track))
+               {
+                       ++block;
+                       if(block==cur_blocks.end())
+                       {
+                               block = rsv_blocks.begin();
+                               in_rsv = true;
+                       }
+                       if(block==rsv_blocks.end())
+                               return;
+
+                       if(dist>min_dist && nsens>0)
+                       {
+                               release_blocks(rsv_blocks, block, rsv_blocks.end());
+                               return;
+                       }
+
+                       if(in_rsv && block->block->get_sensor_id())
+                               ++nsens;
+               }
+
+               dist += track->get_type().get_path_length(track->get_active_path());
+       }
+}
+
 int Train::get_entry_to_block(Block &block) const
 {
        for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
@@ -435,7 +614,7 @@ void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
                if(dist>10*layout.get_catalogue().get_scale())
                {
                        cur_blocks.front().block->reserve(0);
-                       cur_blocks.erase(cur_blocks.begin());
+                       cur_blocks.pop_front();
                }
        }
 }
@@ -467,12 +646,12 @@ void Train::save(list<DataFile::Statement> &st) const
                        st.push_back((DataFile::Statement("block"), i->block->get_id()));
        }
 
-       if(route)
+       if(!routes.empty())
        {
-               if(!route->is_temporary())
-                       st.push_back((DataFile::Statement("route"), route->get_name()));
-               else if(next_route && !next_route->is_temporary())
-                       st.push_back((DataFile::Statement("route"), next_route->get_name()));
+               list<RouteRef>::const_iterator i = routes.begin();
+               for(; (i!=routes.end() && i->route->is_temporary()); ++i) ;
+               if(i!=routes.end())
+                       st.push_back((DataFile::Statement("route"), i->route->get_name()));
        }
 
        if(timetable)
@@ -577,16 +756,15 @@ void Train::sensor_event(unsigned addr, bool state)
                        overshoot_dist = 0;
 
                        // Check if we've reached the next route
-                       if(next_route)
+                       if(routes.size()>1)
                        {
-                               const set<const Track *> &rtracks = next_route->get_tracks();
+                               const set<const Track *> &rtracks = (++routes.begin())->route->get_tracks();
                                for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
                                        if(rtracks.count(j->block->get_endpoints()[j->entry].track))
                                        {
-                                               route = next_route;
-                                               next_route = 0;
+                                               routes.pop_front();
                                                // XXX Exceptions?
-                                               signal_route_changed.emit(route);
+                                               signal_route_changed.emit(routes.front().route);
                                                break;
                                        }
                        }
@@ -631,7 +809,7 @@ void Train::sensor_event(unsigned addr, bool state)
 
 void Train::turnout_event(unsigned addr, bool)
 {
-       if(pending_block)
+       if(pending_block && (!pending_block->get_train() || pending_block->get_train()==this))
        {
                unsigned pending_addr = pending_block->get_turnout_id();
                bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
@@ -690,24 +868,16 @@ unsigned Train::reserve_more()
        if(end_of_route)
                return nsens;
 
-       const Route *cur_route = 0;
-       if(route)
-       {
-               const set<Track *> &tracks = start->block->get_tracks();
-               for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
-               {
-                       if(route->get_tracks().count(*i))
-                               cur_route = route;
-                       else if(next_route && next_route->get_tracks().count(*i))
-                               cur_route = next_route;
-               }
-       }
+       list<RouteRef>::iterator cur_route = routes.begin();
+       advance_route(cur_route, *start->block->get_endpoints()[start->entry].track);
 
        float approach_margin = 50*layout.get_catalogue().get_scale();
        float min_dist = controller->get_braking_distance()*1.3+approach_margin*2;
 
        BlockRef *last = start;
        BlockRef *good = start;
+       Track *divert_track = 0;
+       bool try_divert = false;
        unsigned good_sens = nsens;
        float good_dist = dist;
        Train *blocking_train = 0;
@@ -719,8 +889,12 @@ unsigned Train::reserve_more()
        {
                // Traverse to the next block
                float length = 0;
-               unsigned exit = last->block->traverse(last->entry, cur_route, &length);
-               Block *link = last->block->get_link(exit);
+               Block *link = 0;
+               {
+                       const Route *route = (cur_route!=routes.end() ? cur_route->route : 0);
+                       unsigned exit = last->block->traverse(last->entry, route, &length);
+                       link = last->block->get_link(exit);
+               }
                if(!link)
                        break;
 
@@ -730,11 +904,9 @@ unsigned Train::reserve_more()
 
                const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
 
-               if(cur_route)
+               if(cur_route!=routes.end())
                {
-                       if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
-                               cur_route = next_route;
-                       else if(!cur_route->get_tracks().count(entry_ep.track))
+                       if(!advance_route(cur_route, *entry_ep.track))
                        {
                                // Keep the blocks if we arrived at the end of the route
                                if(!blocking_train)
@@ -747,8 +919,8 @@ unsigned Train::reserve_more()
                                break;
                        }
                }
-               else if(route && route->get_tracks().count(entry_ep.track))
-                       cur_route = route;
+               else if(!routes.empty() && routes.front().route->get_tracks().count(entry_ep.track))
+                       cur_route = routes.begin();
 
                if(link->get_endpoints().size()<2)
                {
@@ -765,11 +937,12 @@ unsigned Train::reserve_more()
                {
                        if(link->get_train()!=blocking_train)
                        {
-                               // XXX is it possible that this won't free all the blocks we want?
                                if(blocking_train->free_block(*contested_blocks.back().block))
                                {
                                        // Roll back and start actually reserving the blocks
                                        last = &rsv_blocks.back();
+                                       cur_route = routes.begin();
+                                       advance_route(cur_route, *last->block->get_endpoints()[last->entry].track);
                                        if(blocking_train->get_priority()==priority)
                                                blocking_train->yield_to(*this);
                                        blocking_train = 0;
@@ -777,7 +950,9 @@ unsigned Train::reserve_more()
                                }
                                else
                                {
+                                       yield_to(*blocking_train);
                                        pending_block = contested_blocks.front().block;
+                                       try_divert = divert_track;
                                        break;
                                }
                        }
@@ -801,24 +976,27 @@ unsigned Train::reserve_more()
                        if(other_entry<0)
                                throw LogicError("Block reservation inconsistency");
 
-                       int other_prio = other_train->get_priority();
-
                        bool entry_conflict = (static_cast<unsigned>(entry)==link->traverse(other_entry));
                        bool exit_conflict = (link->traverse(entry)==static_cast<unsigned>(other_entry));
-                       if(!entry_conflict && !exit_conflict)
+                       if(!entry_conflict && !last->block->get_turnout_id())
                        {
-                               /* Same direction, keep the blocks we got so far and wait for the
-                               other train to pass */
+                               /* The other train is not coming to the blocks we're holding, so we
+                               can keep them. */
                                good = last;
                                good_sens = nsens;
                                good_dist = dist;
+                       }
+
+                       int other_prio = other_train->get_priority();
 
-                               // Ask a lesser priority train to free the block for us
-                               if(other_train->get_priority()<priority)
-                                       if(other_train->free_block(*link))
-                                               reserved = link->reserve(this);
+                       if(!entry_conflict && !exit_conflict && other_prio<priority)
+                       {
+                               /* Ask a lesser priority train going to the same direction to free
+                               the block for us */
+                               if(other_train->free_block(*link))
+                                       reserved = link->reserve(this);
                        }
-                       else if(other_prio<priority || (other_prio==priority && other_train!=yielding_to && entry_conflict))
+                       else if(other_train!=yielding_to && (other_prio<priority || (other_prio==priority && entry_conflict)))
                        {
                                /* A lesser priority train is coming at us, we must ask it to free
                                enough blocks to get clear of it to avoid a potential deadlock */
@@ -828,6 +1006,9 @@ unsigned Train::reserve_more()
                                last = &contested_blocks.back();
                                continue;
                        }
+                       else if(divert_track && (entry_conflict || exit_conflict))
+                               // We are blocked, but there's a diversion possibility
+                               try_divert = true;
 
                        if(!reserved)
                        {
@@ -839,22 +1020,29 @@ unsigned Train::reserve_more()
                if(link->get_turnout_id())
                {
                        const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
+                       bool multiple_paths = (track_ep.paths&(track_ep.paths-1));
 
-                       // Keep the blocks reserved so far, as either us or the other train can diverge
-                       good = last;
-                       good_sens = nsens;
-                       good_dist = dist;
+                       if(multiple_paths || !last->block->get_turnout_id())
+                       {
+                               /* We can keep the blocks reserved so far if we are facing the
+                               points or if there was no turnout immediately before this one.
+                               With multiple successive turnouts (as is common in crossovers) it's
+                               best to hold at one we can divert from. */
+                               good = last;
+                               good_sens = nsens;
+                               good_dist = dist;
+                       }
 
                        // Figure out what path we'd like to take on the turnout
                        int path = -1;
-                       if(cur_route)
-                               path = cur_route->get_turnout(link->get_turnout_id());
+                       for(list<RouteRef>::iterator i=cur_route; (path<0 && i!=routes.end()); ++i)
+                               path = i->route->get_turnout(link->get_turnout_id());
                        if(path<0)
                                path = entry_ep.track->get_active_path();
-                       if(!((track_ep.paths>>path)&1))
+                       if(!(track_ep.paths&(1<<path)))
                        {
                                for(unsigned i=0; track_ep.paths>>i; ++i)
-                                       if((track_ep.paths>>i)&1)
+                                       if(track_ep.paths&(1<<i))
                                                path = i;
                        }
 
@@ -869,6 +1057,11 @@ unsigned Train::reserve_more()
                                        break;
                                }
                        }
+
+                       if(multiple_paths && cur_route!=routes.end() && cur_route->diversion!=link->get_turnout_id())
+                               /* There's multiple paths to be taken and we are on a route - take
+                               note of the diversion possibility */
+                               divert_track = entry_ep.track;
                }
 
                if(!contested_blocks.empty() && contested_blocks.front().block==link)
@@ -886,7 +1079,7 @@ unsigned Train::reserve_more()
        while(!rsv_blocks.empty() && &rsv_blocks.back()!=good)
        {
                rsv_blocks.back().block->reserve(0);
-               rsv_blocks.erase(--rsv_blocks.end());
+               rsv_blocks.pop_back();
        }
 
        if(!rsv_blocks.empty() && &rsv_blocks.back()!=start)
@@ -899,6 +1092,9 @@ unsigned Train::reserve_more()
        if(i!=rsv_blocks.begin())
                cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
 
+       if(try_divert && divert(*divert_track))
+               return reserve_more();
+
        return good_sens;
 }
 
@@ -1072,6 +1268,94 @@ void Train::reverse_blocks(list<BlockRef> &blocks) const
                i->entry = i->block->traverse(i->entry);
 }
 
+bool Train::advance_route(list<RouteRef>::iterator &iter, const Track &track)
+{
+       while(iter!=routes.end() && !iter->route->get_tracks().count(&track))
+               ++iter;
+       if(iter==routes.end())
+               return false;
+
+       list<RouteRef>::iterator next = iter;
+       ++next;
+       if(next!=routes.end() && next->diversion && next->route->get_tracks().count(&track))
+               iter = next;
+
+       return true;
+}
+
+Route *Train::create_lead_route()
+{
+       Route *lead = new Route(layout);
+       lead->set_name("Lead");
+       lead->set_temporary(true);
+
+       for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=rsv_blocks.end(); )
+       {
+               // XXX Make Route eat non-const tracks to get rid of this idiocy and various const_casts
+               const set<Track *> &btracks = i->block->get_tracks();
+               set<const Track *> tracks(btracks.begin(), btracks.end());
+               lead->add_tracks(tracks);
+
+               if(++i==cur_blocks.end())
+                       i = rsv_blocks.begin();
+       }
+
+       return lead;
+}
+
+bool Train::is_valid_diversion(const Route &diversion, const Track &from, unsigned from_ep)
+{
+       float diversion_len = 0;
+       const Track *track = &from;
+       unsigned ep = from_ep;
+       while(diversion.get_tracks().count(track))
+       {
+               unsigned path = 0;
+               if(track->get_turnout_id())
+                       path = diversion.get_turnout(track->get_turnout_id());
+               diversion_len += track->get_type().get_path_length(path);
+
+               const Track *next = track->get_link(track->traverse(ep, path));
+               ep = next->get_endpoint_by_link(*track);
+               track = next;
+
+               if(track==&from)
+                       return false;
+       }
+
+       list<RouteRef>::iterator route = routes.begin();
+       if(!advance_route(route, from))
+               return false;
+
+       set<const Track *> visited;
+       float route_len = 0;
+       track = &from;
+       ep = from_ep;
+       while(1)
+       {
+               unsigned path = 0;
+               if(track->get_turnout_id())
+                       path = route->route->get_turnout(track->get_turnout_id());
+               route_len += track->get_type().get_path_length(path);
+
+               if(track!=&from && diversion.get_tracks().count(track))
+                       break;
+
+               if(visited.count(track))
+                       return false;
+               visited.insert(track);
+
+               const Track *next = track->get_link(track->traverse(ep, path));
+               ep = next->get_endpoint_by_link(*track);
+               track = next;
+
+               if(!advance_route(route, *track))
+                       return false;
+       }
+
+       return diversion_len<route_len*1.2;
+}
+
 
 Train::BlockRef::BlockRef(Block *b, unsigned e):
        block(b),
@@ -1092,6 +1376,12 @@ Train::BlockRef Train::BlockRef::next() const
 }
 
 
+Train::RouteRef::RouteRef(const Route *r, unsigned d):
+       route(r),
+       diversion(d)
+{ }
+
+
 Train::RealSpeed::RealSpeed():
        speed(0),
        weight(0)
index 02d1d52de1b8751d411bc5aa063300f46d2fb110..e675c4b8cadba41a749e38464b704a2ee957ad56 100644 (file)
@@ -60,6 +60,14 @@ private:
                BlockRef next() const;
        };
 
+       struct RouteRef
+       {
+               const Route *route;
+               unsigned diversion;
+
+               RouteRef(const Route *, unsigned = 0);
+       };
+
        struct RealSpeed
        {
                float speed;
@@ -89,8 +97,7 @@ private:
        bool reverse;
        Msp::Time::TimeStamp stop_timeout;
        unsigned functions;
-       const Route *route;
-       const Route *next_route;
+       std::list<RouteRef> routes;
        bool end_of_route;
        std::string status;
 
@@ -135,11 +142,13 @@ public:
 
        void set_route(const Route *);
        void go_to(const Track &);
-       const Route *get_route() const { return route; }
+       bool divert(Track &);
+       const Route *get_route() const;
        void place(Block &, unsigned);
        void unplace();
        bool is_placed() const { return !cur_blocks.empty(); }
        bool free_block(Block &);
+       void free_noncritical_blocks();
        int get_entry_to_block(Block &) const;
        float get_reserved_distance() const;
 
@@ -165,6 +174,9 @@ private:
        void release_blocks(std::list<BlockRef> &);
        void release_blocks(std::list<BlockRef> &, std::list<BlockRef>::iterator, std::list<BlockRef>::iterator);
        void reverse_blocks(std::list<BlockRef> &) const;
+       bool advance_route(std::list<RouteRef>::iterator &, const Track &);
+       Route *create_lead_route();
+       bool is_valid_diversion(const Route &, const Track &, unsigned);
 };
 
 } // namespace Marklin