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)
72 const list<Route *> &planned_routes = planner->get_routes_for(train);
75 routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
78 sequence_points = planner->get_sequence_for(train);
80 sequence_check_pending = false;
85 void TrainRouter::route_changed()
87 BlockIter fncb = train.get_last_critical_block().next();
90 reserving_route = routes.begin();
93 /* Find the route that should be used for the next allocated block. We
94 can't rely on the resync code in block_reserved since we may need to
95 clear the stop marker to continue allocation. */
96 const BlockAllocator &allocator = train.get_block_allocator();
97 TrackIter track = allocator.first().track_iter();
98 list<SequencePoint>::iterator seq_begin = sequence_points.begin();
99 for(; track; track=track.next())
101 if(!advance_to_track(reserving_route, track))
103 arrival = (allocator.is_block_current(track->get_block()) ? ADVANCED_TO_END : RESERVED_TO_END);
106 if(&track->get_block()==fncb.block())
109 if(seq_begin!=sequence_points.end() && seq_begin->block==&track->get_block())
111 // Assume any sequence points within critical blocks to be cleared
112 current_sequence = seq_begin->sequence_out;
117 sequence_points.erase(sequence_points.begin(), seq_begin);
119 if(!sequence_points.empty())
121 const SequencePoint &sp = sequence_points.front();
122 if(sp.block==fncb.block() && !sp.is_cleared())
124 arrival = WAITING_FOR_SEQUENCE;
125 sequence_check_pending = true;
130 /* Refresh from the first non-critical block to pick up any changes in the
131 route. Set stop marker first in case an arrival condition was met within the
134 train.stop_at(&*fncb.flip());
135 train.refresh_blocks_from(*fncb);
136 // If no arrival condition was found, clear a possible previous stop marker.
140 const Route *route = get_route();
141 signal_route_changed.emit(route);
142 signal_event.emit(Message("route-changed", route));
145 void TrainRouter::set_destination(const TrackChain &d)
147 if(waypoints.empty())
148 waypoints.push_back(&d);
150 waypoints.back() = &d;
151 waypoints_changed = true;
152 metrics_stale = true;
155 void TrainRouter::add_waypoint(const TrackChain &wp)
157 waypoints.push_back(&wp);
158 waypoints_changed = true;
159 metrics_stale = true;
162 const TrackChain &TrainRouter::get_waypoint(unsigned index) const
164 if(index>=waypoints.size())
165 throw out_of_range("TrainRouter::is_waypoint");
167 return *waypoints[index];
170 const TrainRouteMetric &TrainRouter::get_metric(int index) const
172 if(waypoints.empty())
173 throw logic_error("no metrics");
174 else if(metrics_stale)
175 throw logic_error("metrics are stale");
178 return *metrics.back();
179 else if(static_cast<unsigned>(index)>=waypoints.size())
180 throw out_of_range("TrainRouter::get_metric");
182 return *metrics[index];
185 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
188 waypoints_changed = true;
191 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
196 void TrainRouter::message(const Message &msg)
198 if(msg.type=="set-route")
200 if(msg.value.check_type<Route *>())
201 set_route(msg.value.value<Route *>());
203 set_route(msg.value.value<const Route *>());
205 else if(msg.type=="clear-route")
207 else if(msg.type=="set-destination")
209 if(msg.value.check_type<TrackChain *>())
210 set_destination(*msg.value.value<TrackChain *>());
212 set_destination(*msg.value.value<const TrackChain *>());
214 else if(msg.type=="add-waypoint")
216 if(msg.value.check_type<TrackChain *>())
217 add_waypoint(*msg.value.value<TrackChain *>());
219 add_waypoint(*msg.value.value<const TrackChain *>());
221 else if(msg.type=="set-departure-delay")
222 set_departure_delay(msg.value.value<Time::TimeDelta>());
223 else if(msg.type=="set-trip-duration")
224 set_trip_duration(msg.value.value<Time::TimeDelta>());
227 void TrainRouter::tick(const Time::TimeDelta &dt)
229 if(waypoints_changed && !planner)
230 start_planning(train.get_layout());
232 if(planner && planner->check()!=TrainRoutePlanner::PENDING)
233 apply_plan(train.get_layout(), *planner);
235 if(!train.get_layout().get_driver().is_halted())
242 duration = max(duration+delay, Time::zero);
247 duration = max(duration-dt, Time::zero);
250 if(sequence_check_pending)
252 if(sequence_points.front().is_cleared())
254 arrival = ON_THE_WAY;
257 sequence_check_pending = false;
260 if(arrival==ADVANCED_TO_END && !train.get_speed())
262 signal_arrived.emit(waypoints.back());
263 signal_event.emit(Message("arrived", waypoints.back()));
266 else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
270 void TrainRouter::save(list<DataFile::Statement> &st) const
272 st.push_back((DataFile::Statement("priority"), priority));
276 RouteList::const_iterator i = routes.begin();
277 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
279 st.push_back((DataFile::Statement("route"), (*i)->get_name()));
283 void TrainRouter::block_reserved(Block &block, Train *t)
293 // Are we waiting for the other train to pass a sequence point?
294 SequencePoint &sp = sequence_points.front();
295 if(sp.preceding_train==t && sp.block==&block)
296 /* The other train's router will advance its sequence on the same
297 signal and may not have handled it yet. */
298 sequence_check_pending = true;
303 // Did we reach our next sequence point?
304 if(!sequence_points.empty())
306 SequencePoint &sp = sequence_points.front();
309 current_sequence = sp.sequence_out;
310 sequence_points.pop_front();
314 TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
316 // Is the block a turnout? If it is, set it to the correct path.
317 if(unsigned taddr = block.get_turnout_address())
319 int path = (*reserving_route)->get_turnout(taddr);
321 track->set_active_path(path);
324 /* If the allocator has released blocks from the front, we may need to
325 resync reserving_route. */
326 if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
328 reserving_route = routes.begin();
329 arrival = ON_THE_WAY;
330 track = t->get_block_allocator().first().track_iter();
331 for(; track; track=track.next())
333 if(!advance_to_track(reserving_route, track))
334 throw logic_error("internal error (reservation outside of route)");
335 else if(&track->get_block()==&block)
340 /* Keep reserving_route pointing to the route containing the block that is
341 expected to be allocated next. */
342 for(; track; track=track.next((*reserving_route)->get_path(*track)))
344 if(!advance_to_track(reserving_route, track))
346 // We've reached the end of the route. Stop here.
347 arrival = RESERVED_TO_END;
348 train.stop_at(&block);
351 if(&track->get_block()!=&block)
355 // Do we need to wait for another train to pass?
356 if(!sequence_points.empty())
358 SequencePoint &sp = sequence_points.front();
359 if(sp.block==&track->get_block() && !sp.is_cleared())
361 arrival = WAITING_FOR_SEQUENCE;
362 train.stop_at(&block);
367 void TrainRouter::train_advanced(Block &block)
369 BlockIter b_iter = train.get_block_allocator().iter_for(block);
371 if(!waypoints.empty())
373 // A waypoint is considered reached when the train has advanced through it.
374 const TrackChain &wp = *waypoints.front();
375 TrackIter t_iter = b_iter.track_iter();
376 if(wp.has_track(*t_iter))
378 for(; t_iter; t_iter=t_iter.next())
380 if(!wp.has_track(*t_iter))
382 if(waypoints.size()==1)
384 if(arrival==RESERVED_TO_END)
385 arrival = ADVANCED_TO_END;
389 waypoints.erase(waypoints.begin());
390 metrics_stale = true;
391 signal_waypoint_reached.emit(&wp);
392 signal_event.emit(Message("waypoint-reached", &wp));
396 else if(!block.has_track(*t_iter))
403 void TrainRouter::train_rear_advanced(Block &block)
405 Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
407 // Drop any routes that are now completely behind the train.
408 for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
409 if((*i)->has_track(track))
411 if(i!=routes.begin())
413 routes.erase(routes.begin(), i);
414 const Route *route = get_route();
415 signal_route_changed.emit(route);
416 signal_event.emit(Message("route-changed", route));
422 void TrainRouter::create_metrics()
424 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
428 metrics_stale = false;
430 if(waypoints.empty())
433 for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
434 metrics.push_back(new TrainRouteMetric(**i));
436 for(unsigned i=metrics.size()-1; i-->0; )
437 metrics[i]->chain_to(*metrics[i+1]);
440 bool TrainRouter::create_lead_route()
442 if(routes.empty() || !train.is_placed())
445 BlockIter lcb = train.get_last_critical_block();
446 TrackIter last_track_rev = lcb.reverse().track_iter();
449 for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
451 if(routes.front()->has_track(*i))
455 if(count==routes.front()->get_tracks().size())
461 TrackIter next_track = last_track_rev.flip();
462 if(!routes.front()->has_track(*last_track_rev) && !routes.front()->has_track(*next_track))
464 Route *pf = Route::find(next_track, *routes.front());
468 routes.push_front(pf);
472 for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
474 if(!lead && !routes.front()->has_track(*i))
476 lead = new Route(train.get_layout());
477 lead->set_name("Lead");
478 lead->set_temporary(true);
479 routes.push_front(lead);
481 TrackIter j = i.flip();
483 lead->add_track(*j.next());
493 bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
495 Track &prev_track = *track.flip();
496 unsigned taddr = (track->get_type().is_turnout() ? track->get_turnout_address() : 0);
497 for(unsigned i=0; route!=routes.end(); ++i)
499 bool in_route = (*route)->has_track(*track);
500 bool prev_in_route = (*route)->has_track(prev_track);
501 bool known_path = (!taddr || (*route)->get_turnout(taddr)>=0);
503 if(in_route && (known_path || !prev_in_route))
505 else if(i==0 || prev_in_route)
508 throw logic_error("internal error (routes are not continuous)");
514 void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers)
516 const map<unsigned, Train *> &trains = layout.get_trains();
517 routers.reserve(trains.size());
518 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
519 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
520 routers.push_back(router);
523 void TrainRouter::start_planning(Layout &layout)
525 vector<TrainRouter *> routers;
526 get_routers(layout, routers);
528 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
529 if((*i)->metrics_stale)
530 (*i)->create_metrics();
532 RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
533 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
535 (*i)->waypoints_changed = false;
536 (*i)->planner = planner;
539 planner->plan_async();
542 void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
544 if(planner.get_result()==TrainRoutePlanner::FAILED)
545 layout.emergency(0, "Route planning failed");
547 vector<TrainRouter *> routers;
548 get_routers(layout, routers);
550 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
551 if((*i)->planner.get()==&planner)
553 (*i)->use_planned_route();
559 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
566 bool TrainRouter::SequencePoint::is_cleared() const
571 TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
572 return router->get_current_sequence()>=sequence_in;
576 TrainRouter::Loader::Loader(TrainRouter &r):
577 DataFile::ObjectLoader<TrainRouter>(r)
579 add("priority", &TrainRouter::priority);
580 add("route", &Loader::route);
583 void TrainRouter::Loader::route(const string &n)
585 obj.set_route(&obj.train.get_layout().get_route(n));