5 #include "trackchain.h"
6 #include "trainroutemetric.h"
7 #include "trainrouteplanner.h"
8 #include "trainrouter.h"
15 TrainRouter::TrainRouter(Train &t):
19 waypoints_changed(false),
22 sequence_check_pending(false)
24 train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
25 train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
26 train.signal_rear_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_rear_advanced));
29 TrainRouter::~TrainRouter()
31 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
35 void TrainRouter::set_priority(int p)
40 bool TrainRouter::set_route(const Route *r)
50 sequence_points.clear();
52 sequence_check_pending = false;
59 const Route *TrainRouter::get_route() const
63 return routes.front();
66 void TrainRouter::use_planned_route()
68 if(!planner || planner->get_result()!=TrainRoutePlanner::COMPLETE)
71 const list<Route *> &planned_routes = planner->get_routes_for(train);
74 routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
77 sequence_points = planner->get_sequence_for(train);
79 sequence_check_pending = false;
84 void TrainRouter::route_changed()
86 BlockIter fncb = train.get_first_noncritical_block();
88 reserving_route = routes.begin();
89 bool already_at_end = false;
92 /* Find the route that should be used for the next allocated block. We
93 can't rely on the resync code in block_reserved since we may need to
94 clear the stop marker to continue allocation. */
95 TrackIter track = train.get_block_allocator().first().track_iter();
96 list<SequencePoint>::iterator seq_begin = sequence_points.begin();
97 for(; track; track=track.next())
99 if(!advance_to_track(reserving_route, track))
101 already_at_end = true;
104 if(&track->get_block()==fncb.block())
107 if(seq_begin!=sequence_points.end() && seq_begin->block==&track->get_block())
109 current_sequence = seq_begin->sequence_out;
114 sequence_points.erase(sequence_points.begin(), seq_begin);
119 // We are not at the end of the route now, but might have been before.
120 arrival = ON_THE_WAY;
121 train.refresh_blocks_from(*fncb);
127 /* If arrival wasn't set before (perhaps because we weren't on a route),
129 arrival = RESERVED_TO_END;
130 train.stop_at(&*fncb.flip());
131 train.refresh_blocks_from(*fncb);
134 const Route *route = get_route();
135 signal_route_changed.emit(route);
136 signal_event.emit(Message("route-changed", route));
139 void TrainRouter::set_destination(const TrackChain &d)
141 if(waypoints.empty())
142 waypoints.push_back(&d);
144 waypoints.back() = &d;
145 waypoints_changed = true;
146 metrics_stale = true;
149 void TrainRouter::add_waypoint(const TrackChain &wp)
151 waypoints.push_back(&wp);
152 waypoints_changed = true;
153 metrics_stale = true;
156 const TrackChain &TrainRouter::get_waypoint(unsigned index) const
158 if(index>=waypoints.size())
159 throw out_of_range("TrainRouter::is_waypoint");
161 return *waypoints[index];
164 const TrainRouteMetric &TrainRouter::get_metric(int index) const
166 if(waypoints.empty())
167 throw logic_error("no metrics");
168 else if(metrics_stale)
169 throw logic_error("metrics are stale");
172 return *metrics.back();
173 else if(static_cast<unsigned>(index)>=waypoints.size())
174 throw out_of_range("TrainRouter::get_metric");
176 return *metrics[index];
179 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
182 waypoints_changed = true;
185 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
190 void TrainRouter::message(const Message &msg)
192 if(msg.type=="set-route")
194 if(msg.value.check_type<Route *>())
195 set_route(msg.value.value<Route *>());
197 set_route(msg.value.value<const Route *>());
199 else if(msg.type=="clear-route")
201 else if(msg.type=="set-destination")
203 if(msg.value.check_type<TrackChain *>())
204 set_destination(*msg.value.value<TrackChain *>());
206 set_destination(*msg.value.value<const TrackChain *>());
208 else if(msg.type=="add-waypoint")
210 if(msg.value.check_type<TrackChain *>())
211 add_waypoint(*msg.value.value<TrackChain *>());
213 add_waypoint(*msg.value.value<const TrackChain *>());
215 else if(msg.type=="set-departure-delay")
216 set_departure_delay(msg.value.value<Time::TimeDelta>());
217 else if(msg.type=="set-trip-duration")
218 set_trip_duration(msg.value.value<Time::TimeDelta>());
221 void TrainRouter::tick(const Time::TimeDelta &dt)
228 duration = max(duration+delay, Time::zero);
233 duration = max(duration-dt, Time::zero);
235 if(waypoints_changed && !planner)
236 start_planning(train.get_layout());
238 if(planner && planner->check()!=TrainRoutePlanner::PENDING)
239 apply_plan(train.get_layout(), *planner);
241 if(sequence_check_pending)
243 if(sequence_points.front().is_cleared())
245 sequence_check_pending = false;
248 if(arrival==RESERVED_TO_END && !train.get_speed())
250 signal_arrived.emit(waypoints.back());
251 signal_event.emit(Message("arrived", waypoints.back()));
254 else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
258 void TrainRouter::save(list<DataFile::Statement> &st) const
260 st.push_back((DataFile::Statement("priority"), priority));
264 RouteList::const_iterator i = routes.begin();
265 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
267 st.push_back((DataFile::Statement("route"), (*i)->get_name()));
271 void TrainRouter::block_reserved(Block &block, Train *t)
281 // Are we waiting for the other train to pass a sequence point?
282 SequencePoint &sp = sequence_points.front();
283 if(sp.preceding_train==t && sp.block==&block)
284 /* The other train's router will advance its sequence on the same
285 signal and may not have handled it yet. */
286 sequence_check_pending = true;
291 // Did we reach our next sequence point?
292 if(!sequence_points.empty())
294 SequencePoint &sp = sequence_points.front();
297 current_sequence = sp.sequence_out;
298 sequence_points.pop_front();
302 TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
304 // Is the block a turnout? If it is, set it to the correct path.
305 if(unsigned taddr = block.get_turnout_address())
307 int path = (*reserving_route)->get_turnout(taddr);
309 track->set_active_path(path);
312 /* If the allocator has released blocks from the front, we may need to
313 resync reserving_route. */
314 if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
316 reserving_route = routes.begin();
317 arrival = ON_THE_WAY;
318 track = t->get_block_allocator().first().track_iter();
319 for(; track; track=track.next())
321 if(!advance_to_track(reserving_route, track))
322 throw logic_error("internal error (reservation outside of route)");
323 else if(&track->get_block()==&block)
328 /* Keep reserving_route pointing to the route containing the block that is
329 expected to be allocated next. */
330 for(; track; track=track.next((*reserving_route)->get_path(*track)))
332 if(!advance_to_track(reserving_route, track))
334 // We've reached the end of the route. Stop here.
335 arrival = RESERVED_TO_END;
336 train.stop_at(&block);
339 if(&track->get_block()!=&block)
343 // Do we need to wait for another train to pass?
344 if(!sequence_points.empty())
346 SequencePoint &sp = sequence_points.front();
347 if(sp.block==&track->get_block() && !sp.is_cleared())
348 train.stop_at(&block);
352 void TrainRouter::train_advanced(Block &block)
354 BlockIter b_iter = train.get_block_allocator().iter_for(block);
356 if(waypoints.size()>1)
358 // A waypoint is considered reached when the train has advanced through it.
359 const TrackChain &wp = *waypoints.front();
360 TrackIter t_iter = b_iter.track_iter();
361 if(wp.has_track(*t_iter))
363 for(; t_iter; t_iter=t_iter.next())
365 if(!wp.has_track(*t_iter))
367 waypoints.erase(waypoints.begin());
368 metrics_stale = true;
369 signal_waypoint_reached.emit(&wp);
370 signal_event.emit(Message("waypoint-reached", &wp));
373 else if(!block.has_track(*t_iter))
380 void TrainRouter::train_rear_advanced(Block &block)
382 Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
384 // Drop any routes that are now completely behind the train.
385 for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
386 if((*i)->has_track(track))
388 if(i!=routes.begin())
390 routes.erase(routes.begin(), i);
391 const Route *route = get_route();
392 signal_route_changed.emit(route);
393 signal_event.emit(Message("route-changed", route));
399 void TrainRouter::create_metrics()
401 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
405 metrics_stale = false;
407 if(waypoints.empty())
410 for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
411 metrics.push_back(new TrainRouteMetric(**i));
413 for(unsigned i=metrics.size()-1; i-->0; )
414 metrics[i]->chain_to(*metrics[i+1]);
417 bool TrainRouter::create_lead_route()
419 if(routes.empty() || !train.is_placed())
422 BlockIter fncb = train.get_first_noncritical_block();
423 TrackIter next_track = fncb.track_iter();
426 for(TrackIter i=next_track.flip(); (i && i->get_block().get_train()==&train); i=i.next())
428 if(routes.front()->has_track(*i))
432 if(count==routes.front()->get_tracks().size())
433 next_track = i.flip();
438 if(!routes.front()->has_track(*next_track) && !routes.front()->has_track(*next_track.flip()))
440 Route *pf = Route::find(next_track, *routes.front());
444 routes.push_front(pf);
448 for(TrackIter i=next_track.flip(); (i && i->get_block().get_train()==&train); i=i.next())
450 if(!lead && !routes.front()->has_track(*i))
452 lead = new Route(train.get_layout());
453 lead->set_name("Lead");
454 lead->set_temporary(true);
455 routes.push_front(lead);
457 TrackIter j = i.flip();
459 lead->add_track(*j.next());
469 bool TrainRouter::is_valid_for_track(const Route &route, const TrackIter &track) const
471 if(!route.has_track(*track))
473 if(track->get_type().is_turnout() && route.get_turnout(track->get_turnout_address())<0 && route.has_track(*track.flip()))
478 bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
480 if(!is_valid_for_track(**route, track))
483 if(route==routes.end())
485 if(!is_valid_for_track(**route, track))
486 throw logic_error("internal error (routes are not continuous)");
492 void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers)
494 const map<unsigned, Train *> &trains = layout.get_trains();
495 routers.reserve(trains.size());
496 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
497 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
498 routers.push_back(router);
501 void TrainRouter::start_planning(Layout &layout)
503 vector<TrainRouter *> routers;
504 get_routers(layout, routers);
506 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
507 if((*i)->metrics_stale)
508 (*i)->create_metrics();
510 RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
511 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
513 (*i)->waypoints_changed = false;
514 (*i)->planner = planner;
517 planner->plan_async();
520 void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
522 vector<TrainRouter *> routers;
523 get_routers(layout, routers);
525 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
526 if((*i)->planner.get()==&planner)
528 (*i)->use_planned_route();
534 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
541 bool TrainRouter::SequencePoint::is_cleared() const
546 TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
547 return router->get_current_sequence()>=sequence_in;
551 TrainRouter::Loader::Loader(TrainRouter &r):
552 DataFile::ObjectLoader<TrainRouter>(r)
554 add("priority", &TrainRouter::priority);
555 add("route", &Loader::route);
558 void TrainRouter::Loader::route(const string &n)
560 obj.set_route(&obj.train.get_layout().get_route(n));