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)
43 BlockIter fncb = train.get_first_noncritical_block();
46 if(r && train.is_placed())
48 const BlockAllocator &allocator = train.get_block_allocator();
49 TrackIter first = allocator.first().track_iter();
50 TrackIter next = fncb.track_iter();
51 if(!r->has_track(*next))
53 lead = Route::find(next, *r);
56 create_lead_route(lead, lead);
58 else if(!r->has_track(*first))
59 lead = create_lead_route(0, r);
64 routes.push_back(lead);
70 sequence_points.clear();
72 sequence_check_pending = false;
79 const Route *TrainRouter::get_route() const
83 return routes.front();
86 void TrainRouter::route_changed()
88 BlockIter fncb = train.get_first_noncritical_block();
90 reserving_route = routes.begin();
91 bool already_at_end = false;
94 /* Find the route that should be used for the next allocated block. We
95 can't rely on the resync code in block_reserved since we may need to
96 clear the stop marker to continue allocation. */
97 TrackIter track = train.get_block_allocator().first().track_iter();
98 for(; track; track=track.next())
100 if(!advance_to_track(reserving_route, *track))
102 already_at_end = true;
105 if(&track->get_block()==fncb.block())
112 // We are not at the end of the route now, but might have been before.
113 arrival = ON_THE_WAY;
114 train.refresh_blocks_from(*fncb);
120 /* If arrival wasn't set before (perhaps because we weren't on a route),
122 arrival = RESERVED_TO_END;
123 train.stop_at(&*fncb.flip());
124 train.refresh_blocks_from(*fncb);
127 const Route *route = get_route();
128 signal_route_changed.emit(route);
129 signal_event.emit(Message("route-changed", route));
132 void TrainRouter::set_destination(const TrackChain &d)
135 destination_changed = true;
136 metrics_stale = true;
139 bool TrainRouter::is_destination(Track &track) const
142 return destination->has_track(track);
147 void TrainRouter::add_waypoint(const TrackChain &wp)
149 waypoints.push_back(&wp);
150 destination_changed = true;
151 metrics_stale = true;
154 bool TrainRouter::is_waypoint(unsigned index, Track &track) const
156 if(index>=waypoints.size())
157 throw out_of_range("TrainRouter::is_waypoint");
159 return waypoints[index]->has_track(track);
162 const TrainRouteMetric &TrainRouter::get_metric(int index) const
165 throw logic_error("no metrics");
166 else if(metrics_stale)
167 throw logic_error("metrics are stale");
170 return *metrics.front();
171 else if(static_cast<unsigned>(index)>=waypoints.size())
172 throw out_of_range("TrainRouter::get_metric");
174 return *metrics[index+1];
177 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
180 destination_changed = true;
183 void TrainRouter::message(const Message &msg)
185 if(msg.type=="set-route")
187 if(msg.value.check_type<Route *>())
188 set_route(msg.value.value<Route *>());
190 set_route(msg.value.value<const Route *>());
192 else if(msg.type=="clear-route")
194 else if(msg.type=="set-destination")
196 if(msg.value.check_type<TrackChain *>())
197 set_destination(*msg.value.value<TrackChain *>());
199 set_destination(*msg.value.value<const TrackChain *>());
201 else if(msg.type=="add-waypoint")
203 if(msg.value.check_type<TrackChain *>())
204 add_waypoint(*msg.value.value<TrackChain *>());
206 add_waypoint(*msg.value.value<const TrackChain *>());
208 else if(msg.type=="set-departure-delay")
209 set_departure_delay(msg.value.value<Time::TimeDelta>());
212 void TrainRouter::tick(const Time::TimeDelta &dt)
217 if(delay<=Time::zero)
221 if(destination_changed && !planner)
222 start_planning(train.get_layout());
224 if(planner && planner->get_result()!=TrainRoutePlanner::PENDING)
226 destination_changed = false;
227 if(planner->get_result()==TrainRoutePlanner::COMPLETE)
229 const list<Route *> &planned_routes = planner->get_routes_for(train);
231 routes.push_back(create_lead_route(0, planned_routes.front()));
232 routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
233 sequence_points = planner->get_sequence_for(train);
234 current_sequence = 0;
235 sequence_check_pending = false;
242 if(sequence_check_pending)
244 if(sequence_points.front().is_cleared())
246 sequence_check_pending = false;
249 if(arrival==RESERVED_TO_END && !train.get_speed())
251 signal_arrived.emit(destination);
252 signal_event.emit(Message("arrived", destination));
255 else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
259 void TrainRouter::save(list<DataFile::Statement> &st) const
261 st.push_back((DataFile::Statement("priority"), priority));
265 RouteList::const_iterator i = routes.begin();
266 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
268 st.push_back((DataFile::Statement("route"), (*i)->get_name()));
272 void TrainRouter::block_reserved(Block &block, Train *t)
282 // Are we waiting for the other train to pass a sequence point?
283 SequencePoint &sp = sequence_points.front();
284 if(sp.preceding_train==t && sp.block==&block)
285 /* The other train's router will advance its sequence on the same
286 signal and may not have handled it yet. */
287 sequence_check_pending = true;
292 // Did we reach our next sequence point?
293 if(!sequence_points.empty())
295 SequencePoint &sp = sequence_points.front();
298 current_sequence = sp.sequence_out;
299 sequence_points.pop_front();
303 TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
305 // Is the block a turnout? If it is, set it to the correct path.
306 if(unsigned taddr = block.get_turnout_address())
308 int path = (*reserving_route)->get_turnout(taddr);
310 track->set_active_path(path);
313 /* If the allocator has released blocks from the front, we may need to
314 resync reserving_route. */
315 if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
317 reserving_route = routes.begin();
318 arrival = ON_THE_WAY;
319 track = t->get_block_allocator().first().track_iter();
320 for(; track; track=track.next())
322 if(!advance_to_track(reserving_route, *track))
323 throw logic_error("internal error (reservation outside of route)");
324 else if(&track->get_block()==&block)
329 /* Keep reserving_route pointing to the route containing the block that is
330 expected to be allocated next. */
331 for(; track; track=track.next((*reserving_route)->get_path(*track)))
333 if(!advance_to_track(reserving_route, *track))
335 // We've reached the end of the route. Stop here.
336 arrival = RESERVED_TO_END;
337 train.stop_at(&block);
340 if(&track->get_block()!=&block)
344 // Do we need to wait for another train to pass?
345 if(!sequence_points.empty())
347 SequencePoint &sp = sequence_points.front();
348 if(sp.block==&track->get_block() && !sp.is_cleared())
349 train.stop_at(&block);
353 void TrainRouter::train_advanced(Block &block)
355 BlockIter b_iter = train.get_block_allocator().iter_for(block);
357 if(!waypoints.empty())
359 // A waypoint is considered reached when the train has advanced through it.
360 const TrackChain &wp = *waypoints.front();
361 TrackIter t_iter = b_iter.track_iter();
362 if(wp.has_track(*t_iter))
364 for(; t_iter; t_iter=t_iter.next())
366 if(!wp.has_track(*t_iter))
368 waypoints.erase(waypoints.begin());
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)
408 metrics.push_back(new TrainRouteMetric(*destination));
409 for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
410 metrics.push_back(new TrainRouteMetric(**i));
412 for(unsigned i=metrics.size(); --i>0; )
413 metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
416 Route *TrainRouter::create_lead_route(Route *lead, const Route *target)
420 lead = new Route(train.get_layout());
421 lead->set_name("Lead");
422 lead->set_temporary(true);
425 bool target_reached = false;
426 for(TrackIter i=train.get_block_allocator().first().track_iter(); i; i=i.next())
428 if(i->get_block().get_train()!=&train)
432 if(target->has_track(*i))
433 target_reached = true;
434 else if(target_reached)
443 bool TrainRouter::is_valid_for_track(const Route &route, Track &track) const
445 if(!route.has_track(track))
447 if(track.get_type().is_turnout() && route.get_turnout(track.get_turnout_address())<0)
452 bool TrainRouter::advance_to_track(RouteList::iterator &route, Track &track)
454 if(!is_valid_for_track(**route, track))
457 if(route==routes.end())
459 if(!is_valid_for_track(**route, track))
460 throw logic_error("internal error (routes are not continuous)");
466 void TrainRouter::start_planning(Layout &layout)
468 RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
470 const map<unsigned, Train *> &trains = layout.get_trains();
471 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
472 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
474 if(router->metrics_stale)
476 router->create_metrics();
477 router->metrics_stale = false;
479 router->planner = planner;
486 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
493 bool TrainRouter::SequencePoint::is_cleared() const
498 TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
499 return router->get_current_sequence()>=sequence_in;
503 TrainRouter::Loader::Loader(TrainRouter &r):
504 DataFile::ObjectLoader<TrainRouter>(r)
506 add("priority", &TrainRouter::priority);
507 add("route", &Loader::route);
510 void TrainRouter::Loader::route(const string &n)
512 obj.set_route(&obj.train.get_layout().get_route(n));