6 #include "trackchain.h"
7 #include "trainroutemetric.h"
8 #include "trainrouteplanner.h"
9 #include "trainrouter.h"
16 TrainRouter::TrainRouter(Train &t):
20 waypoints_changed(false),
23 sequence_check_pending(false)
25 train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
26 train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
27 train.signal_rear_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_rear_advanced));
30 TrainRouter::~TrainRouter()
32 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
36 void TrainRouter::set_priority(int p)
41 bool TrainRouter::set_route(const Route *r)
51 sequence_points.clear();
53 sequence_check_pending = false;
60 const Route *TrainRouter::get_route() const
64 return routes.front();
67 void TrainRouter::use_planned_route()
69 if(!planner || planner->get_result()!=TrainRoutePlanner::COMPLETE)
74 const list<Route *> &planned_routes = planner->get_routes_for(train);
77 routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
80 sequence_points = planner->get_sequence_for(train);
82 sequence_check_pending = false;
87 void TrainRouter::route_changed()
89 BlockIter fncb = train.get_last_critical_block().next();
92 reserving_route = routes.begin();
95 /* Find the route that should be used for the next allocated block. We
96 can't rely on the resync code in block_reserved since we may need to
97 clear the stop marker to continue allocation. */
98 const BlockAllocator &allocator = train.get_block_allocator();
99 TrackIter track = allocator.first().track_iter();
100 list<SequencePoint>::iterator seq_begin = sequence_points.begin();
101 for(; track; track=track.next())
103 if(!advance_to_track(reserving_route, track))
105 arrival = (allocator.is_block_current(track->get_block()) ? ADVANCED_TO_END : RESERVED_TO_END);
108 if(&track->get_block()==fncb.block())
111 if(seq_begin!=sequence_points.end() && seq_begin->block==&track->get_block())
113 // Assume any sequence points within critical blocks to be cleared
114 current_sequence = seq_begin->sequence_out;
119 sequence_points.erase(sequence_points.begin(), seq_begin);
121 if(!sequence_points.empty())
123 const SequencePoint &sp = sequence_points.front();
124 if(sp.block==fncb.block() && sp.preceding_train)
126 arrival = WAITING_FOR_SEQUENCE;
127 sequence_check_pending = true;
132 /* Refresh from the first non-critical block to pick up any changes in the
133 route. Set stop marker first in case an arrival condition was met within the
136 train.stop_at(&*fncb.flip());
137 train.refresh_blocks_from(*fncb);
138 // If no arrival condition was found, clear a possible previous stop marker.
142 const Route *route = get_route();
143 signal_route_changed.emit(route);
144 signal_event.emit(Message("route-changed", route));
147 void TrainRouter::set_destination(const TrackChain &d)
149 if(waypoints.empty())
150 waypoints.push_back(Waypoint(d));
152 waypoints.back() = Waypoint(d);
153 waypoints_changed = true;
154 metrics_stale = true;
157 void TrainRouter::add_waypoint(const TrackChain &chain, TrackChain::Direction dir)
159 waypoints.push_back(Waypoint(chain, dir));
160 waypoints_changed = true;
161 metrics_stale = true;
164 const TrainRouter::Waypoint &TrainRouter::get_waypoint(unsigned index) const
166 if(index>=waypoints.size())
167 throw out_of_range("TrainRouter::is_waypoint");
169 return waypoints[index];
172 const TrainRouteMetric &TrainRouter::get_metric(int index) const
174 if(waypoints.empty())
175 throw logic_error("no metrics");
176 else if(metrics_stale)
177 throw logic_error("metrics are stale");
180 return *metrics.back();
181 else if(static_cast<unsigned>(index)>=waypoints.size())
182 throw out_of_range("TrainRouter::get_metric");
184 return *metrics[index];
187 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
190 waypoints_changed = true;
193 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
198 void TrainRouter::message(const Message &msg)
200 if(msg.type=="set-route")
202 if(msg.value.check_type<Route *>())
203 set_route(msg.value.value<Route *>());
205 set_route(msg.value.value<const Route *>());
207 else if(msg.type=="clear-route")
209 else if(msg.type=="set-destination")
211 if(msg.value.check_type<TrackChain *>())
212 set_destination(*msg.value.value<TrackChain *>());
214 set_destination(*msg.value.value<const TrackChain *>());
216 else if(msg.type=="add-waypoint")
218 if(msg.value.check_type<Waypoint>())
220 Waypoint wp = msg.value.value<Waypoint>();
221 add_waypoint(*wp.chain, wp.direction);
223 else if(msg.value.check_type<TrackChain *>())
224 add_waypoint(*msg.value.value<TrackChain *>());
226 add_waypoint(*msg.value.value<const TrackChain *>());
228 else if(msg.type=="set-departure-delay")
229 set_departure_delay(msg.value.value<Time::TimeDelta>());
230 else if(msg.type=="set-trip-duration")
231 set_trip_duration(msg.value.value<Time::TimeDelta>());
234 void TrainRouter::tick(const Time::TimeDelta &dt)
236 if(waypoints_changed && !planner)
237 start_planning(train.get_layout());
239 if(planner && planner->check()!=TrainRoutePlanner::PENDING)
240 apply_plan(train.get_layout(), *planner);
242 Layout &layout = train.get_layout();
243 if(!layout.get_driver().is_halted() && !layout.get_clock().is_stopped())
250 duration = max(duration+delay, Time::zero);
255 duration = max(duration-dt, Time::zero);
258 if(sequence_check_pending)
260 if(sequence_points.front().is_cleared())
262 arrival = ON_THE_WAY;
265 sequence_check_pending = false;
268 if(arrival==ADVANCED_TO_END && !train.get_speed())
270 signal_arrived.emit(waypoints.back().chain);
271 signal_event.emit(Message("arrived", waypoints.back().chain));
274 else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
278 void TrainRouter::save(list<DataFile::Statement> &st) const
280 st.push_back((DataFile::Statement("priority"), priority));
284 RouteList::const_iterator i = routes.begin();
285 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
287 st.push_back((DataFile::Statement("route"), (*i)->get_name()));
291 void TrainRouter::block_reserved(Block &block, Train *t)
301 // Are we waiting for the other train to pass a sequence point?
302 SequencePoint &sp = sequence_points.front();
303 if(sp.preceding_train==t && sp.block==&block)
304 /* The other train's router will advance its sequence on the same
305 signal and may not have handled it yet. */
306 sequence_check_pending = true;
311 // Did we reach our next sequence point?
312 if(!sequence_points.empty())
314 SequencePoint &sp = sequence_points.front();
317 current_sequence = sp.sequence_out;
318 sequence_points.pop_front();
322 TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
324 // Is the block a turnout? If it is, set it to the correct path.
325 if(unsigned taddr = block.get_turnout_address())
327 int path = (*reserving_route)->get_turnout(taddr);
329 track->set_active_path(path);
332 /* If the allocator has released blocks from the front, we may need to
333 resync reserving_route. */
334 if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
336 reserving_route = routes.begin();
337 arrival = ON_THE_WAY;
338 track = t->get_block_allocator().first().track_iter();
339 for(; track; track=track.next())
341 if(!advance_to_track(reserving_route, track))
342 throw logic_error("internal error (reservation outside of route)");
343 else if(&track->get_block()==&block)
348 /* Keep reserving_route pointing to the route containing the block that is
349 expected to be allocated next. */
350 for(; track; track=track.next((*reserving_route)->get_path(*track)))
352 if(!advance_to_track(reserving_route, track))
354 // We've reached the end of the route. Stop here.
355 arrival = RESERVED_TO_END;
356 train.stop_at(&block);
359 if(&track->get_block()!=&block)
363 // Do we need to wait for another train to pass?
364 if(!sequence_points.empty())
366 SequencePoint &sp = sequence_points.front();
367 if(sp.block==&track->get_block() && !sp.is_cleared())
369 arrival = WAITING_FOR_SEQUENCE;
370 train.stop_at(&block);
375 void TrainRouter::train_advanced(Block &block)
377 if(!waypoints.empty())
379 // A waypoint is considered reached when the train has advanced through it.
380 BlockIter b_iter = train.get_block_allocator().iter_for(block);
381 const Waypoint &wp = waypoints.front();
382 TrackIter t_iter = b_iter.track_iter();
383 if(wp.chain->has_track(*t_iter))
387 TrackIter next = t_iter.next();
391 if(!wp.chain->has_track(*next))
393 if(wp.direction!=TrackChain::UNSPECIFIED)
394 if(t_iter!=wp.chain->iter_for(*t_iter, wp.direction))
397 if(waypoints.size()==1)
399 if(arrival==RESERVED_TO_END)
400 arrival = ADVANCED_TO_END;
404 const TrackChain *chain = wp.chain;
405 waypoints.erase(waypoints.begin());
406 metrics_stale = true;
407 signal_waypoint_reached.emit(chain);
408 signal_event.emit(Message("waypoint-reached", chain));
412 else if(!block.has_track(*next))
421 void TrainRouter::train_rear_advanced(Block &block)
423 Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
425 // Drop any routes that are now completely behind the train.
426 for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
427 if((*i)->has_track(track))
429 if(i!=routes.begin())
431 routes.erase(routes.begin(), i);
432 const Route *route = get_route();
433 signal_route_changed.emit(route);
434 signal_event.emit(Message("route-changed", route));
440 void TrainRouter::create_metrics()
442 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
446 metrics_stale = false;
448 if(waypoints.empty())
451 for(vector<Waypoint>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
452 metrics.push_back(new TrainRouteMetric(*i->chain, i->direction));
454 for(unsigned i=metrics.size()-1; i-->0; )
455 metrics[i]->chain_to(*metrics[i+1]);
458 bool TrainRouter::create_lead_route()
460 if(routes.empty() || !train.is_placed())
463 BlockIter lcb = train.get_last_critical_block();
464 TrackIter last_track_rev = lcb.reverse().track_iter();
467 for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
469 if(routes.front()->has_track(*i))
473 if(count==routes.front()->get_tracks().size())
479 TrackIter next_track = last_track_rev.flip();
480 if(!routes.front()->has_track(*last_track_rev) && !routes.front()->has_track(*next_track))
482 Route *pf = Route::find(next_track, *routes.front());
486 routes.push_front(pf);
490 for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
492 if(!lead && !routes.front()->has_track(*i))
494 lead = new Route(train.get_layout());
495 lead->set_name("Lead");
496 lead->set_temporary(true);
497 routes.push_front(lead);
499 TrackIter j = i.flip();
501 lead->add_track(*j.next());
511 bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
513 Track &prev_track = *track.flip();
514 unsigned taddr = (track->get_type().is_turnout() ? track->get_turnout_address() : 0);
515 for(unsigned i=0; route!=routes.end(); ++i)
517 bool in_route = (*route)->has_track(*track);
518 bool prev_in_route = (*route)->has_track(prev_track);
519 bool known_path = (!taddr || (*route)->get_turnout(taddr)>=0);
521 if(in_route && (known_path || !prev_in_route))
523 else if(i==0 || prev_in_route)
526 throw logic_error("internal error (routes are not continuous)");
532 void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers)
534 const map<unsigned, Train *> &trains = layout.get_trains();
535 routers.reserve(trains.size());
536 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
537 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
538 routers.push_back(router);
541 void TrainRouter::start_planning(Layout &layout)
543 vector<TrainRouter *> routers;
544 get_routers(layout, routers);
546 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
547 if((*i)->metrics_stale)
548 (*i)->create_metrics();
550 RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
551 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
553 (*i)->waypoints_changed = false;
554 (*i)->planner = planner;
557 planner->plan_async();
560 void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
562 if(planner.get_result()==TrainRoutePlanner::FAILED)
563 layout.emergency(0, "Route planning failed");
565 vector<TrainRouter *> routers;
566 get_routers(layout, routers);
568 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
569 if((*i)->planner.get()==&planner)
571 (*i)->use_planned_route();
577 TrainRouter::Waypoint::Waypoint(const TrackChain &c, TrackChain::Direction d):
583 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
590 bool TrainRouter::SequencePoint::is_cleared() const
595 TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
596 return router->get_current_sequence()>=sequence_in;
600 TrainRouter::Loader::Loader(TrainRouter &r):
601 DataFile::ObjectLoader<TrainRouter>(r)
603 add("priority", &TrainRouter::priority);
604 add("route", &Loader::route);
607 void TrainRouter::Loader::route(const string &n)
609 obj.set_route(&obj.train.get_layout().get_route(n));