5 #include "trackchain.h"
6 #include "trainroutemetric.h"
7 #include "trainrouteplanner.h"
8 #include "trainrouter.h"
15 TrainRouter::TrainRouter(Train &t):
20 destination_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)
52 sequence_points.clear();
54 sequence_check_pending = false;
61 const Route *TrainRouter::get_route() const
65 return routes.front();
68 void TrainRouter::route_changed()
70 BlockIter fncb = train.get_first_noncritical_block();
72 reserving_route = routes.begin();
73 bool already_at_end = false;
76 /* Find the route that should be used for the next allocated block. We
77 can't rely on the resync code in block_reserved since we may need to
78 clear the stop marker to continue allocation. */
79 TrackIter track = train.get_block_allocator().first().track_iter();
80 for(; track; track=track.next())
82 if(!advance_to_track(reserving_route, *track))
84 already_at_end = true;
87 if(&track->get_block()==fncb.block())
94 // We are not at the end of the route now, but might have been before.
96 train.refresh_blocks_from(*fncb);
102 /* If arrival wasn't set before (perhaps because we weren't on a route),
104 arrival = RESERVED_TO_END;
105 train.stop_at(&*fncb.flip());
106 train.refresh_blocks_from(*fncb);
109 const Route *route = get_route();
110 signal_route_changed.emit(route);
111 signal_event.emit(Message("route-changed", route));
114 void TrainRouter::set_destination(const TrackChain &d)
117 destination_changed = true;
118 metrics_stale = true;
121 void TrainRouter::add_waypoint(const TrackChain &wp)
123 waypoints.push_back(&wp);
124 destination_changed = true;
125 metrics_stale = true;
128 const TrackChain &TrainRouter::get_waypoint(unsigned index) const
130 if(index>=waypoints.size())
131 throw out_of_range("TrainRouter::is_waypoint");
133 return *waypoints[index];
136 const TrainRouteMetric &TrainRouter::get_metric(int index) const
139 throw logic_error("no metrics");
140 else if(metrics_stale)
141 throw logic_error("metrics are stale");
144 return *metrics.front();
145 else if(static_cast<unsigned>(index)>=waypoints.size())
146 throw out_of_range("TrainRouter::get_metric");
148 return *metrics[index+1];
151 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
154 destination_changed = true;
157 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
162 void TrainRouter::message(const Message &msg)
164 if(msg.type=="set-route")
166 if(msg.value.check_type<Route *>())
167 set_route(msg.value.value<Route *>());
169 set_route(msg.value.value<const Route *>());
171 else if(msg.type=="clear-route")
173 else if(msg.type=="set-destination")
175 if(msg.value.check_type<TrackChain *>())
176 set_destination(*msg.value.value<TrackChain *>());
178 set_destination(*msg.value.value<const TrackChain *>());
180 else if(msg.type=="add-waypoint")
182 if(msg.value.check_type<TrackChain *>())
183 add_waypoint(*msg.value.value<TrackChain *>());
185 add_waypoint(*msg.value.value<const TrackChain *>());
187 else if(msg.type=="set-departure-delay")
188 set_departure_delay(msg.value.value<Time::TimeDelta>());
189 else if(msg.type=="set-trip-duration")
190 set_trip_duration(msg.value.value<Time::TimeDelta>());
193 void TrainRouter::tick(const Time::TimeDelta &dt)
200 duration = max(duration+delay, Time::zero);
205 duration = max(duration-dt, Time::zero);
207 if(destination_changed && !planner)
208 start_planning(train.get_layout());
210 if(planner && planner->check()!=TrainRoutePlanner::PENDING)
212 destination_changed = false;
213 if(planner->get_result()==TrainRoutePlanner::COMPLETE)
215 const list<Route *> &planned_routes = planner->get_routes_for(train);
218 routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
221 sequence_points = planner->get_sequence_for(train);
222 current_sequence = 0;
223 sequence_check_pending = false;
230 if(sequence_check_pending)
232 if(sequence_points.front().is_cleared())
234 sequence_check_pending = false;
237 if(arrival==RESERVED_TO_END && !train.get_speed())
239 signal_arrived.emit(destination);
240 signal_event.emit(Message("arrived", destination));
243 else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
247 void TrainRouter::save(list<DataFile::Statement> &st) const
249 st.push_back((DataFile::Statement("priority"), priority));
253 RouteList::const_iterator i = routes.begin();
254 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
256 st.push_back((DataFile::Statement("route"), (*i)->get_name()));
260 void TrainRouter::block_reserved(Block &block, Train *t)
270 // Are we waiting for the other train to pass a sequence point?
271 SequencePoint &sp = sequence_points.front();
272 if(sp.preceding_train==t && sp.block==&block)
273 /* The other train's router will advance its sequence on the same
274 signal and may not have handled it yet. */
275 sequence_check_pending = true;
280 // Did we reach our next sequence point?
281 if(!sequence_points.empty())
283 SequencePoint &sp = sequence_points.front();
286 current_sequence = sp.sequence_out;
287 sequence_points.pop_front();
291 TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
293 // Is the block a turnout? If it is, set it to the correct path.
294 if(unsigned taddr = block.get_turnout_address())
296 int path = (*reserving_route)->get_turnout(taddr);
298 track->set_active_path(path);
301 /* If the allocator has released blocks from the front, we may need to
302 resync reserving_route. */
303 if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
305 reserving_route = routes.begin();
306 arrival = ON_THE_WAY;
307 track = t->get_block_allocator().first().track_iter();
308 for(; track; track=track.next())
310 if(!advance_to_track(reserving_route, *track))
311 throw logic_error("internal error (reservation outside of route)");
312 else if(&track->get_block()==&block)
317 /* Keep reserving_route pointing to the route containing the block that is
318 expected to be allocated next. */
319 for(; track; track=track.next((*reserving_route)->get_path(*track)))
321 if(!advance_to_track(reserving_route, *track))
323 // We've reached the end of the route. Stop here.
324 arrival = RESERVED_TO_END;
325 train.stop_at(&block);
328 if(&track->get_block()!=&block)
332 // Do we need to wait for another train to pass?
333 if(!sequence_points.empty())
335 SequencePoint &sp = sequence_points.front();
336 if(sp.block==&track->get_block() && !sp.is_cleared())
337 train.stop_at(&block);
341 void TrainRouter::train_advanced(Block &block)
343 BlockIter b_iter = train.get_block_allocator().iter_for(block);
345 if(!waypoints.empty())
347 // A waypoint is considered reached when the train has advanced through it.
348 const TrackChain &wp = *waypoints.front();
349 TrackIter t_iter = b_iter.track_iter();
350 if(wp.has_track(*t_iter))
352 for(; t_iter; t_iter=t_iter.next())
354 if(!wp.has_track(*t_iter))
356 waypoints.erase(waypoints.begin());
357 signal_waypoint_reached.emit(&wp);
358 signal_event.emit(Message("waypoint-reached", &wp));
361 else if(!block.has_track(*t_iter))
368 void TrainRouter::train_rear_advanced(Block &block)
370 Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
372 // Drop any routes that are now completely behind the train.
373 for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
374 if((*i)->has_track(track))
376 if(i!=routes.begin())
378 routes.erase(routes.begin(), i);
379 const Route *route = get_route();
380 signal_route_changed.emit(route);
381 signal_event.emit(Message("route-changed", route));
387 void TrainRouter::create_metrics()
389 for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
396 metrics.push_back(new TrainRouteMetric(*destination));
397 for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
398 metrics.push_back(new TrainRouteMetric(**i));
400 for(unsigned i=metrics.size(); --i>0; )
401 metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
403 metrics_stale = false;
406 bool TrainRouter::create_lead_route()
408 if(routes.empty() || !train.is_placed())
411 BlockIter fncb = train.get_first_noncritical_block();
412 TrackIter next_track = fncb.track_iter();
413 if(!routes.front()->has_track(*next_track.flip()))
415 Route *pf = Route::find(next_track, *routes.front());
419 routes.push_front(pf);
422 TrackIter first_track = train.get_block_allocator().first().track_iter();
423 if(!routes.front()->has_track(*first_track))
425 Route *lead = new Route(train.get_layout());
426 lead->set_name("Lead");
427 lead->set_temporary(true);
429 unsigned target_tracks = 0;
430 for(TrackIter i=first_track; (target_tracks<2 && i); i=i.next())
432 if(i->get_block().get_train()!=&train)
434 if(routes.front()->has_track(*i))
436 else if(target_tracks>0)
441 routes.push_front(lead);
447 bool TrainRouter::is_valid_for_track(const Route &route, Track &track) const
449 if(!route.has_track(track))
451 if(track.get_type().is_turnout() && route.get_turnout(track.get_turnout_address())<0)
456 bool TrainRouter::advance_to_track(RouteList::iterator &route, Track &track)
458 if(!is_valid_for_track(**route, track))
461 if(route==routes.end())
463 if(!is_valid_for_track(**route, track))
464 throw logic_error("internal error (routes are not continuous)");
470 void TrainRouter::start_planning(Layout &layout)
472 vector<TrainRouter *> routers;
473 const map<unsigned, Train *> &trains = layout.get_trains();
474 routers.reserve(trains.size());
475 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
476 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
477 routers.push_back(router);
479 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
480 if((*i)->metrics_stale)
481 (*i)->create_metrics();
483 RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
484 for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
485 (*i)->planner = planner;
487 planner->plan_async();
491 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
498 bool TrainRouter::SequencePoint::is_cleared() const
503 TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
504 return router->get_current_sequence()>=sequence_in;
508 TrainRouter::Loader::Loader(TrainRouter &r):
509 DataFile::ObjectLoader<TrainRouter>(r)
511 add("priority", &TrainRouter::priority);
512 add("route", &Loader::route);
515 void TrainRouter::Loader::route(const string &n)
517 obj.set_route(&obj.train.get_layout().get_route(n));