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_last_critical_block().next();
89 reserving_route = routes.begin();
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 const BlockAllocator &allocator = train.get_block_allocator();
96 TrackIter track = allocator.first().track_iter();
97 list<SequencePoint>::iterator seq_begin = sequence_points.begin();
98 for(; track; track=track.next())
100 if(!advance_to_track(reserving_route, track))
102 arrival = (allocator.is_block_current(track->get_block()) ? ADVANCED_TO_END : RESERVED_TO_END);
105 if(&track->get_block()==fncb.block())
108 if(seq_begin!=sequence_points.end() && seq_begin->block==&track->get_block())
110 // Assume any sequence points within critical blocks to be cleared
111 current_sequence = seq_begin->sequence_out;
116 sequence_points.erase(sequence_points.begin(), seq_begin);
118 if(!sequence_points.empty())
120 const SequencePoint &sp = sequence_points.front();
121 if(sp.block==fncb.block() && !sp.is_cleared())
123 arrival = WAITING_FOR_SEQUENCE;
124 sequence_check_pending = true;
129 /* Refresh from the first non-critical block to pick up any changes in the
130 route. Set stop marker first in case an arrival condition was met within the
133 train.stop_at(&*fncb.flip());
134 train.refresh_blocks_from(*fncb);
135 // If no arrival condition was found, clear a possible previous stop marker.
139 const Route *route = get_route();
140 signal_route_changed.emit(route);
141 signal_event.emit(Message("route-changed", route));
144 void TrainRouter::set_destination(const TrackChain &d)
146 if(waypoints.empty())
147 waypoints.push_back(&d);
149 waypoints.back() = &d;
150 waypoints_changed = true;
151 metrics_stale = true;
154 void TrainRouter::add_waypoint(const TrackChain &wp)
156 waypoints.push_back(&wp);
157 waypoints_changed = true;
158 metrics_stale = true;
161 const TrackChain &TrainRouter::get_waypoint(unsigned index) const
163 if(index>=waypoints.size())
164 throw out_of_range("TrainRouter::is_waypoint");
166 return *waypoints[index];
169 const TrainRouteMetric &TrainRouter::get_metric(int index) const
171 if(waypoints.empty())
172 throw logic_error("no metrics");
173 else if(metrics_stale)
174 throw logic_error("metrics are stale");
177 return *metrics.back();
178 else if(static_cast<unsigned>(index)>=waypoints.size())
179 throw out_of_range("TrainRouter::get_metric");
181 return *metrics[index];
184 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
187 waypoints_changed = true;
190 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
195 void TrainRouter::message(const Message &msg)
197 if(msg.type=="set-route")
199 if(msg.value.check_type<Route *>())
200 set_route(msg.value.value<Route *>());
202 set_route(msg.value.value<const Route *>());
204 else if(msg.type=="clear-route")
206 else if(msg.type=="set-destination")
208 if(msg.value.check_type<TrackChain *>())
209 set_destination(*msg.value.value<TrackChain *>());
211 set_destination(*msg.value.value<const TrackChain *>());
213 else if(msg.type=="add-waypoint")
215 if(msg.value.check_type<TrackChain *>())
216 add_waypoint(*msg.value.value<TrackChain *>());
218 add_waypoint(*msg.value.value<const TrackChain *>());
220 else if(msg.type=="set-departure-delay")
221 set_departure_delay(msg.value.value<Time::TimeDelta>());
222 else if(msg.type=="set-trip-duration")
223 set_trip_duration(msg.value.value<Time::TimeDelta>());
226 void TrainRouter::tick(const Time::TimeDelta &dt)
233 duration = max(duration+delay, Time::zero);
238 duration = max(duration-dt, Time::zero);
240 if(waypoints_changed && !planner)
241 start_planning(train.get_layout());
243 if(planner && planner->check()!=TrainRoutePlanner::PENDING)
244 apply_plan(train.get_layout(), *planner);
246 if(sequence_check_pending)
248 if(sequence_points.front().is_cleared())
250 arrival = ON_THE_WAY;
253 sequence_check_pending = false;
256 if(arrival==ADVANCED_TO_END && !train.get_speed())
258 signal_arrived.emit(waypoints.back());
259 signal_event.emit(Message("arrived", waypoints.back()));
262 else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
266 void TrainRouter::save(list<DataFile::Statement> &st) const
268 st.push_back((DataFile::Statement("priority"), priority));
272 RouteList::const_iterator i = routes.begin();
273 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
275 st.push_back((DataFile::Statement("route"), (*i)->get_name()));
279 void TrainRouter::block_reserved(Block &block, Train *t)
289 // Are we waiting for the other train to pass a sequence point?
290 SequencePoint &sp = sequence_points.front();
291 if(sp.preceding_train==t && sp.block==&block)
292 /* The other train's router will advance its sequence on the same
293 signal and may not have handled it yet. */
294 sequence_check_pending = true;
299 // Did we reach our next sequence point?
300 if(!sequence_points.empty())
302 SequencePoint &sp = sequence_points.front();
305 current_sequence = sp.sequence_out;
306 sequence_points.pop_front();
310 TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
312 // Is the block a turnout? If it is, set it to the correct path.
313 if(unsigned taddr = block.get_turnout_address())
315 int path = (*reserving_route)->get_turnout(taddr);
317 track->set_active_path(path);
320 /* If the allocator has released blocks from the front, we may need to
321 resync reserving_route. */
322 if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
324 reserving_route = routes.begin();
325 arrival = ON_THE_WAY;
326 track = t->get_block_allocator().first().track_iter();
327 for(; track; track=track.next())
329 if(!advance_to_track(reserving_route, track))
330 throw logic_error("internal error (reservation outside of route)");
331 else if(&track->get_block()==&block)
336 /* Keep reserving_route pointing to the route containing the block that is
337 expected to be allocated next. */
338 for(; track; track=track.next((*reserving_route)->get_path(*track)))
340 if(!advance_to_track(reserving_route, track))
342 // We've reached the end of the route. Stop here.
343 arrival = RESERVED_TO_END;
344 train.stop_at(&block);
347 if(&track->get_block()!=&block)
351 // Do we need to wait for another train to pass?
352 if(!sequence_points.empty())
354 SequencePoint &sp = sequence_points.front();
355 if(sp.block==&track->get_block() && !sp.is_cleared())
357 arrival = WAITING_FOR_SEQUENCE;
358 train.stop_at(&block);
363 void TrainRouter::train_advanced(Block &block)
365 BlockIter b_iter = train.get_block_allocator().iter_for(block);
367 if(!waypoints.empty())
369 // A waypoint is considered reached when the train has advanced through it.
370 const TrackChain &wp = *waypoints.front();
371 TrackIter t_iter = b_iter.track_iter();
372 if(wp.has_track(*t_iter))
374 for(; t_iter; t_iter=t_iter.next())
376 if(!wp.has_track(*t_iter))
378 if(waypoints.size()==1)
380 if(arrival==RESERVED_TO_END)
381 arrival = ADVANCED_TO_END;
385 waypoints.erase(waypoints.begin());
386 metrics_stale = true;
387 signal_waypoint_reached.emit(&wp);
388 signal_event.emit(Message("waypoint-reached", &wp));
392 else if(!block.has_track(*t_iter))
399 void TrainRouter::train_rear_advanced(Block &block)
401 Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
403 // Drop any routes that are now completely behind the train.
404 for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
405 if((*i)->has_track(track))
407 if(i!=routes.begin())
409 routes.erase(routes.begin(), i);
410 const Route *route = get_route();
411 signal_route_changed.emit(route);
412 signal_event.emit(Message("route-changed", route));
418 void TrainRouter::create_metrics()
420 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
424 metrics_stale = false;
426 if(waypoints.empty())
429 for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
430 metrics.push_back(new TrainRouteMetric(**i));
432 for(unsigned i=metrics.size()-1; i-->0; )
433 metrics[i]->chain_to(*metrics[i+1]);
436 bool TrainRouter::create_lead_route()
438 if(routes.empty() || !train.is_placed())
441 BlockIter lcb = train.get_last_critical_block();
442 TrackIter last_track_rev = lcb.reverse().track_iter();
445 for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
447 if(routes.front()->has_track(*i))
451 if(count==routes.front()->get_tracks().size())
457 TrackIter next_track = last_track_rev.flip();
458 if(!routes.front()->has_track(*last_track_rev) && !routes.front()->has_track(*next_track))
460 Route *pf = Route::find(next_track, *routes.front());
464 routes.push_front(pf);
468 for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
470 if(!lead && !routes.front()->has_track(*i))
472 lead = new Route(train.get_layout());
473 lead->set_name("Lead");
474 lead->set_temporary(true);
475 routes.push_front(lead);
477 TrackIter j = i.flip();
479 lead->add_track(*j.next());
489 bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
491 Track &prev_track = *track.flip();
492 unsigned taddr = (track->get_type().is_turnout() ? track->get_turnout_address() : 0);
493 for(unsigned i=0; route!=routes.end(); ++i)
495 bool in_route = (*route)->has_track(*track);
496 bool prev_in_route = (*route)->has_track(prev_track);
497 bool known_path = (!taddr || (*route)->get_turnout(taddr)>=0);
499 if(in_route && (known_path || !prev_in_route))
501 else if(i==0 || prev_in_route)
504 throw logic_error("internal error (routes are not continuous)");
510 void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers)
512 const map<unsigned, Train *> &trains = layout.get_trains();
513 routers.reserve(trains.size());
514 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
515 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
516 routers.push_back(router);
519 void TrainRouter::start_planning(Layout &layout)
521 vector<TrainRouter *> routers;
522 get_routers(layout, routers);
524 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
525 if((*i)->metrics_stale)
526 (*i)->create_metrics();
528 RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
529 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
531 (*i)->waypoints_changed = false;
532 (*i)->planner = planner;
535 planner->plan_async();
538 void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
540 if(planner.get_result()==TrainRoutePlanner::FAILED)
541 layout.emergency(0, "Route planning failed");
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)->planner.get()==&planner)
549 (*i)->use_planned_route();
555 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
562 bool TrainRouter::SequencePoint::is_cleared() const
567 TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
568 return router->get_current_sequence()>=sequence_in;
572 TrainRouter::Loader::Loader(TrainRouter &r):
573 DataFile::ObjectLoader<TrainRouter>(r)
575 add("priority", &TrainRouter::priority);
576 add("route", &Loader::route);
579 void TrainRouter::Loader::route(const string &n)
581 obj.set_route(&obj.train.get_layout().get_route(n));