]> git.tdb.fi Git - r2c2.git/blobdiff - source/libr2c2/trainrouter.cpp
Fix critical block logic
[r2c2.git] / source / libr2c2 / trainrouter.cpp
index c55105026e3710e859692c934a3a1353f3fb5662..3d8b9d4b7b42a3c7ee3c69c84a81407232107107 100644 (file)
@@ -15,15 +15,15 @@ namespace R2C2 {
 TrainRouter::TrainRouter(Train &t):
        TrainAI(t),
        priority(0),
-       arriving(0),
-       destination(0),
-       destination_changed(false),
+       arrival(ON_THE_WAY),
+       waypoints_changed(false),
        metrics_stale(false),
        current_sequence(0),
        sequence_check_pending(false)
 {
        train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
        train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
+       train.signal_rear_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_rear_advanced));
 }
 
 TrainRouter::~TrainRouter()
@@ -39,32 +39,13 @@ void TrainRouter::set_priority(int p)
 
 bool TrainRouter::set_route(const Route *r)
 {
-       BlockIter fncb = train.get_first_noncritical_block();
-
-       Route *lead = 0;
-       if(r && train.is_placed())
-       {
-               const BlockAllocator &allocator = train.get_block_allocator();
-               TrackIter first = allocator.first().track_iter();
-               TrackIter next = fncb.track_iter();
-               if(!r->has_track(*next))
-               {
-                       lead = Route::find(next, *r);
-                       if(!lead)
-                               return false;
-                       create_lead_route(lead, lead);
-               }
-               else if(!r->has_track(*first))
-                       lead = create_lead_route(0, r);
-       }
-
        routes.clear();
-       if(lead)
-               routes.push_back(lead);
        if(r)
+       {
                routes.push_back(r);
+               create_lead_route();
+       }
 
-       destination = 0;
        waypoints.clear();
        sequence_points.clear();
        current_sequence = 0;
@@ -82,32 +63,78 @@ const Route *TrainRouter::get_route() const
        return routes.front();
 }
 
+void TrainRouter::use_planned_route()
+{
+       if(!planner || planner->get_result()!=TrainRoutePlanner::COMPLETE)
+               return;
+
+       const list<Route *> &planned_routes = planner->get_routes_for(train);
+
+       routes.clear();
+       routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
+       create_lead_route();
+
+       sequence_points = planner->get_sequence_for(train);
+       current_sequence = 0;
+       sequence_check_pending = false;
+
+       route_changed();
+}
+
 void TrainRouter::route_changed()
 {
-       BlockIter fncb = train.get_first_noncritical_block();
+       BlockIter fncb = train.get_last_critical_block().next();
 
+       arrival = ON_THE_WAY;
        reserving_route = routes.begin();
-       bool already_at_end = false;
        if(!routes.empty())
        {
-               TrackIter track = train.get_block_allocator().first().track_iter();
+               /* Find the route that should be used for the next allocated block.  We
+               can't rely on the resync code in block_reserved since we may need to
+               clear the stop marker to continue allocation. */
+               const BlockAllocator &allocator = train.get_block_allocator();
+               TrackIter track = allocator.first().track_iter();
+               list<SequencePoint>::iterator seq_begin = sequence_points.begin();
                for(; track; track=track.next())
                {
-                       if(!advance_to_track(reserving_route, *track))
+                       if(!advance_to_track(reserving_route, track))
                        {
-                               already_at_end = true;
+                               arrival = (allocator.is_block_current(track->get_block()) ? ADVANCED_TO_END : RESERVED_TO_END);
                                break;
                        }
                        if(&track->get_block()==fncb.block())
                                break;
+
+                       if(seq_begin!=sequence_points.end() && seq_begin->block==&track->get_block())
+                       {
+                               // Assume any sequence points within critical blocks to be cleared
+                               current_sequence = seq_begin->sequence_out;
+                               ++seq_begin;
+                       }
+               }
+
+               sequence_points.erase(sequence_points.begin(), seq_begin);
+
+               if(!sequence_points.empty())
+               {
+                       const SequencePoint &sp = sequence_points.front();
+                       if(sp.block==fncb.block() && !sp.is_cleared())
+                       {
+                               arrival = WAITING_FOR_SEQUENCE;
+                               sequence_check_pending = true;
+                       }
                }
        }
 
-       if(!already_at_end)
-       {
+       /* Refresh from the first non-critical block to pick up any changes in the
+       route.  Set stop marker first in case an arrival condition was met within the
+       critical blocks. */
+       if(arrival)
+               train.stop_at(&*fncb.flip());
+       train.refresh_blocks_from(*fncb);
+       // If no arrival condition was found, clear a possible previous stop marker.
+       if(!arrival)
                train.stop_at(0);
-               train.refresh_blocks_from(*fncb);
-       }
 
        const Route *route = get_route();
        signal_route_changed.emit(route);
@@ -116,53 +143,53 @@ void TrainRouter::route_changed()
 
 void TrainRouter::set_destination(const TrackChain &d)
 {
-       destination = &d;
-       destination_changed = true;
-       metrics_stale = true;
-}
-
-bool TrainRouter::is_destination(Track &track) const
-{
-       if(destination)
-               return destination->has_track(track);
+       if(waypoints.empty())
+               waypoints.push_back(&d);
        else
-               return false;
+               waypoints.back() = &d;
+       waypoints_changed = true;
+       metrics_stale = true;
 }
 
 void TrainRouter::add_waypoint(const TrackChain &wp)
 {
        waypoints.push_back(&wp);
-       destination_changed = true;
+       waypoints_changed = true;
        metrics_stale = true;
 }
 
-bool TrainRouter::is_waypoint(unsigned index, Track &track) const
+const TrackChain &TrainRouter::get_waypoint(unsigned index) const
 {
        if(index>=waypoints.size())
                throw out_of_range("TrainRouter::is_waypoint");
 
-       return waypoints[index]->has_track(track);
+       return *waypoints[index];
 }
 
 const TrainRouteMetric &TrainRouter::get_metric(int index) const
 {
-       if(!destination)
+       if(waypoints.empty())
                throw logic_error("no metrics");
        else if(metrics_stale)
                throw logic_error("metrics are stale");
 
        if(index<0)
-               return *metrics.front();
+               return *metrics.back();
        else if(static_cast<unsigned>(index)>=waypoints.size())
                throw out_of_range("TrainRouter::get_metric");
        else
-               return *metrics[index+1];
+               return *metrics[index];
 }
 
 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
 {
        delay = d;
-       destination_changed = true;
+       waypoints_changed = true;
+}
+
+void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
+{
+       duration = d;
 }
 
 void TrainRouter::message(const Message &msg)
@@ -192,6 +219,8 @@ void TrainRouter::message(const Message &msg)
        }
        else if(msg.type=="set-departure-delay")
                set_departure_delay(msg.value.value<Time::TimeDelta>());
+       else if(msg.type=="set-trip-duration")
+               set_trip_duration(msg.value.value<Time::TimeDelta>());
 }
 
 void TrainRouter::tick(const Time::TimeDelta &dt)
@@ -199,47 +228,38 @@ void TrainRouter::tick(const Time::TimeDelta &dt)
        if(delay)
        {
                delay -= dt;
-               if(delay<=Time::zero)
-                       delay = Time::zero;
-       }
-
-       if(destination_changed)
-       {
-               if(!planner)
-                       start_planning(train.get_layout());
-               else if(planner->get_result()!=TrainRoutePlanner::PENDING)
+               if(delay<Time::zero)
                {
-                       destination_changed = false;
-                       if(planner->get_result()==TrainRoutePlanner::COMPLETE)
-                       {
-                               const list<Route *> &planned_routes = planner->get_routes_for(train);
-                               routes.clear();
-                               routes.push_back(create_lead_route(0, planned_routes.front()));
-                               routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
-                               sequence_points = planner->get_sequence_for(train);
-                               current_sequence = 0;
-                               sequence_check_pending = false;
-
-                               route_changed();
-                       }
-                       planner = 0;
+                       duration = max(duration+delay, Time::zero);
+                       delay = Time::zero;
                }
        }
+       else if(duration)
+               duration = max(duration-dt, Time::zero);
+
+       if(waypoints_changed && !planner)
+               start_planning(train.get_layout());
+
+       if(planner && planner->check()!=TrainRoutePlanner::PENDING)
+               apply_plan(train.get_layout(), *planner);
 
        if(sequence_check_pending)
        {
                if(sequence_points.front().is_cleared())
+               {
+                       arrival = ON_THE_WAY;
                        train.stop_at(0);
+               }
                sequence_check_pending = false;
        }
 
-       if(arriving==1 && !train.get_speed())
+       if(arrival==ADVANCED_TO_END && !train.get_speed())
        {
-               signal_arrived.emit(destination);
-               signal_event.emit(Message("arrived", destination));
-               arriving = 2;
+               signal_arrived.emit(waypoints.back());
+               signal_event.emit(Message("arrived", waypoints.back()));
+               arrival = ARRIVED;
        }
-       else if(arriving==2 && !train.get_block_allocator().is_active())
+       else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
                set_route(0);
 }
 
@@ -266,18 +286,17 @@ void TrainRouter::block_reserved(Block &block, Train *t)
                if(!t)
                        return;
 
+               // Are we waiting for the other train to pass a sequence point?
                SequencePoint &sp = sequence_points.front();
                if(sp.preceding_train==t && sp.block==&block)
-               {
-                       if(sp.is_cleared())
-                               train.stop_at(0);
-                       else
-                               sequence_check_pending = true;
-               }
+                       /* The other train's router will advance its sequence on the same
+                       signal and may not have handled it yet. */
+                       sequence_check_pending = true;
 
                return;
        }
 
+       // Did we reach our next sequence point?
        if(!sequence_points.empty())
        {
                SequencePoint &sp = sequence_points.front();
@@ -290,7 +309,7 @@ void TrainRouter::block_reserved(Block &block, Train *t)
 
        TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
 
-       // Is the block a turnout?  If so, set it to the proper path.
+       // Is the block a turnout?  If it is, set it to the correct path.
        if(unsigned taddr = block.get_turnout_address())
        {
                int path = (*reserving_route)->get_turnout(taddr);
@@ -298,24 +317,30 @@ void TrainRouter::block_reserved(Block &block, Train *t)
                        track->set_active_path(path);
        }
 
+       /* If the allocator has released blocks from the front, we may need to
+       resync reserving_route. */
        if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
        {
                reserving_route = routes.begin();
+               arrival = ON_THE_WAY;
                track = t->get_block_allocator().first().track_iter();
                for(; track; track=track.next())
                {
-                       if(!advance_to_track(reserving_route, *track))
+                       if(!advance_to_track(reserving_route, track))
                                throw logic_error("internal error (reservation outside of route)");
                        else if(&track->get_block()==&block)
                                break;
                }
        }
 
-       // Do we need to move to the next route?
+       /* Keep reserving_route pointing to the route containing the block that is
+       expected to be allocated next. */
        for(; track; track=track.next((*reserving_route)->get_path(*track)))
        {
-               if(!advance_to_track(reserving_route, *track))
+               if(!advance_to_track(reserving_route, track))
                {
+                       // We've reached the end of the route.  Stop here.
+                       arrival = RESERVED_TO_END;
                        train.stop_at(&block);
                        return;
                }
@@ -323,11 +348,15 @@ void TrainRouter::block_reserved(Block &block, Train *t)
                        break;
        }
 
+       // Do we need to wait for another train to pass?
        if(!sequence_points.empty())
        {
                SequencePoint &sp = sequence_points.front();
                if(sp.block==&track->get_block() && !sp.is_cleared())
+               {
+                       arrival = WAITING_FOR_SEQUENCE;
                        train.stop_at(&block);
+               }
        }
 }
 
@@ -335,29 +364,9 @@ void TrainRouter::train_advanced(Block &block)
 {
        BlockIter b_iter = train.get_block_allocator().iter_for(block);
 
-       // Check if we've reached the next route
-       if(routes.size()>1)
-       {
-               Track &track = *b_iter.endpoint().track;
-               const Route *route = get_route();
-               bool change_route = false;
-               if(route->is_loop())
-                       change_route = (*++routes.begin())->has_track(track);
-               else
-                       change_route = !route->has_track(track);
-
-               if(change_route)
-               {
-                       routes.pop_front();
-                       route = get_route();
-                       // XXX Exceptions?
-                       signal_route_changed.emit(route);
-                       signal_event.emit(Message("route-changed", route));
-               }
-       }
-
        if(!waypoints.empty())
        {
+               // A waypoint is considered reached when the train has advanced through it.
                const TrackChain &wp = *waypoints.front();
                TrackIter t_iter = b_iter.track_iter();
                if(wp.has_track(*t_iter))
@@ -366,9 +375,18 @@ void TrainRouter::train_advanced(Block &block)
                        {
                                if(!wp.has_track(*t_iter))
                                {
-                                       waypoints.erase(waypoints.begin());
-                                       signal_waypoint_reached.emit(&wp);
-                                       signal_event.emit(Message("waypoint-reached", &wp));
+                                       if(waypoints.size()==1)
+                                       {
+                                               if(arrival==RESERVED_TO_END)
+                                                       arrival = ADVANCED_TO_END;
+                                       }
+                                       else
+                                       {
+                                               waypoints.erase(waypoints.begin());
+                                               metrics_stale = true;
+                                               signal_waypoint_reached.emit(&wp);
+                                               signal_event.emit(Message("waypoint-reached", &wp));
+                                       }
                                        break;
                                }
                                else if(!block.has_track(*t_iter))
@@ -376,13 +394,25 @@ void TrainRouter::train_advanced(Block &block)
                        }
                }
        }
+}
 
-       if(!routes.empty())
-       {
-               b_iter = b_iter.next();
-               if(b_iter && !is_on_route(*b_iter))
-                       arriving = 1;
-       }
+void TrainRouter::train_rear_advanced(Block &block)
+{
+       Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
+
+       // Drop any routes that are now completely behind the train.
+       for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
+               if((*i)->has_track(track))
+               {
+                       if(i!=routes.begin())
+                       {
+                               routes.erase(routes.begin(), i);
+                               const Route *route = get_route();
+                               signal_route_changed.emit(route);
+                               signal_event.emit(Message("route-changed", route));
+                       }
+                       break;
+               }
 }
 
 void TrainRouter::create_metrics()
@@ -391,54 +421,81 @@ void TrainRouter::create_metrics()
                delete *i;
        metrics.clear();
 
-       if(!destination)
+       metrics_stale = false;
+
+       if(waypoints.empty())
                return;
 
-       metrics.push_back(new TrainRouteMetric(*destination));
        for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
                metrics.push_back(new TrainRouteMetric(**i));
 
-       for(unsigned i=metrics.size(); --i>0; )
-               metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
+       for(unsigned i=metrics.size()-1; i-->0; )
+               metrics[i]->chain_to(*metrics[i+1]);
 }
 
-Route *TrainRouter::create_lead_route(Route *lead, const Route *target)
+bool TrainRouter::create_lead_route()
 {
-       if(!lead)
+       if(routes.empty() || !train.is_placed())
+               return false;
+
+       BlockIter lcb = train.get_last_critical_block();
+       TrackIter last_track_rev = lcb.reverse().track_iter();
+
+       unsigned count = 0;
+       for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
        {
-               lead = new Route(train.get_layout());
-               lead->set_name("Lead");
-               lead->set_temporary(true);
+               if(routes.front()->has_track(*i))
+                       ++count;
+               else if(count>0)
+               {
+                       if(count==routes.front()->get_tracks().size())
+                               last_track_rev = i;
+                       break;
+               }
        }
 
-       bool target_reached = false;
-       for(TrackIter i=train.get_block_allocator().first().track_iter(); i; i=i.next())
+       TrackIter next_track = last_track_rev.flip();
+       if(!routes.front()->has_track(*last_track_rev) && !routes.front()->has_track(*next_track))
        {
-               if(i->get_block().get_train()!=&train)
-                       break;
-               if(target)
+               Route *pf = Route::find(next_track, *routes.front());
+               if(!pf)
+                       return false;
+
+               routes.push_front(pf);
+       }
+
+       Route *lead = 0;
+       for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
+       {
+               if(!lead && !routes.front()->has_track(*i))
                {
-                       if(target->has_track(*i))
-                               target_reached = true;
-                       else if(target_reached)
-                               break;
+                       lead = new Route(train.get_layout());
+                       lead->set_name("Lead");
+                       lead->set_temporary(true);
+                       routes.push_front(lead);
+
+                       TrackIter j = i.flip();
+                       lead->add_track(*j);
+                       lead->add_track(*j.next());
                }
-               lead->add_track(*i);
+
+               if(lead)
+                       lead->add_track(*i);
        }
 
-       return lead;
+       return true;
 }
 
-bool TrainRouter::is_valid_for_track(const Route &route, Track &track) const
+bool TrainRouter::is_valid_for_track(const Route &route, const TrackIter &track) const
 {
-       if(!route.has_track(track))
+       if(!route.has_track(*track))
                return false;
-       if(track.get_type().is_turnout() && route.get_turnout(track.get_turnout_address())<0)
+       if(track->get_type().is_turnout() && route.get_turnout(track->get_turnout_address())<0 && route.has_track(*track.flip()))
                return false;
        return true;
 }
 
-bool TrainRouter::advance_to_track(RouteList::iterator &route, Track &track)
+bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
 {
        if(!is_valid_for_track(**route, track))
        {
@@ -452,23 +509,45 @@ bool TrainRouter::advance_to_track(RouteList::iterator &route, Track &track)
        return true;
 }
 
-void TrainRouter::start_planning(Layout &layout)
+void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers)
 {
-       RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
-
        const map<unsigned, Train *> &trains = layout.get_trains();
+       routers.reserve(trains.size());
        for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
                if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
+                       routers.push_back(router);
+}
+
+void TrainRouter::start_planning(Layout &layout)
+{
+       vector<TrainRouter *> routers;
+       get_routers(layout, routers);
+
+       for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
+               if((*i)->metrics_stale)
+                       (*i)->create_metrics();
+
+       RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
+       for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
+       {
+               (*i)->waypoints_changed = false;
+               (*i)->planner = planner;
+       }
+
+       planner->plan_async();
+}
+
+void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
+{
+       vector<TrainRouter *> routers;
+       get_routers(layout, routers);
+
+       for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
+               if((*i)->planner.get()==&planner)
                {
-                       if(router->metrics_stale)
-                       {
-                               router->create_metrics();
-                               router->metrics_stale = false;
-                       }
-                       router->planner = planner;
+                       (*i)->use_planned_route();
+                       (*i)->planner = 0;
                }
-
-       planner->plan();
 }