1 #include <msp/core/maputils.h>
2 #include <msp/time/utils.h>
7 #include "trainroutemetric.h"
8 #include "trainrouteplanner.h"
9 #include "trainrouter.h"
17 TrainRoutePlanner::TrainRoutePlanner(Layout &layout):
19 timeout(10*Time::sec),
23 const map<unsigned, Train *> &trains = layout.get_trains();
24 for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
26 TrainRoutingInfo info(*i->second);
27 if(!info.waypoints.empty())
28 routed_trains.push_back(info);
32 TrainRoutePlanner::~TrainRoutePlanner()
41 void TrainRoutePlanner::set_timeout(const Time::TimeDelta &t)
46 TrainRoutePlanner::Result TrainRoutePlanner::plan()
56 void TrainRoutePlanner::plan_async()
59 throw logic_error("already planning");
62 thread = new PlanningThread(*this);
65 TrainRoutePlanner::Result TrainRoutePlanner::check()
67 if(result==PENDING && goal)
81 const list<Route *> &TrainRoutePlanner::get_routes_for(const Train &train) const
83 return get_train_info(train).routes;
86 const list<TrainRouter::SequencePoint> &TrainRoutePlanner::get_sequence_for(const Train &train) const
88 return get_train_info(train).sequence;
91 const TrainRoutePlanner::TrainRoutingInfo &TrainRoutePlanner::get_train_info(const Train &train) const
93 for(vector<TrainRoutingInfo>::const_iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
97 throw key_error(train.get_name());
100 const TrainRoutePlanner::RoutingStep &TrainRoutePlanner::get_step()
102 steps.splice(steps.end(), queue, queue.begin());
106 void TrainRoutePlanner::prepare_plan()
113 queue.push_back(RoutingStep());
114 RoutingStep &start = queue.back();
115 for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
116 start.trains.push_back(TrainRoutingState(*i));
117 start.update_estimate();
120 void TrainRoutePlanner::create_plan()
122 Time::TimeStamp timeout_stamp = Time::now()+timeout;
124 while(!queue.empty())
126 const RoutingStep &step = get_step();
137 if(Time::now()>timeout_stamp)
146 void TrainRoutePlanner::add_steps(const RoutingStep &step)
148 list<RoutingStep> new_steps;
149 step.create_successors(new_steps);
151 queue.merge(new_steps);
154 void TrainRoutePlanner::finalize_plan()
156 for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
160 for(unsigned j=0; j<2; ++j)
161 i->track_history[j] = 0;
164 map<Track *, TrainRouter::SequencePoint *> sequenced_tracks;
165 unsigned sequence = steps.size();
166 for(const RoutingStep *i=goal; i; i=i->prev)
167 for(vector<TrainRoutingState>::const_iterator j=i->trains.begin(); j!=i->trains.end(); ++j)
169 Track **history = j->info->track_history;
170 // Don't process the same track again.
171 if(j->track.track()==history[0])
175 bool start_new_route = true;
176 if(!j->info->routes.empty())
178 /* If we already have a route and this track or any linked track is
179 in it, start a new one to avoid loops. */
180 route = j->info->routes.front();
181 start_new_route = route->has_track(*j->track);
184 unsigned nls = j->track->get_n_link_slots();
185 for(unsigned k=0; (!start_new_route && k<nls); ++k)
187 Track *link = j->track->get_link(k);
188 start_new_route = (link && link!=history[0] && route->has_track(*link));
195 route = new Route(j->info->train->get_layout());
196 route->set_name("Router");
197 route->set_temporary(true);
198 /* Have the routes overlap by two tracks to ensure that turnout
199 paths can be deduced. */
200 for(unsigned k=0; (k<2 && history[k]); ++k)
201 route->add_track(*history[k]);
202 j->info->routes.push_front(route);
205 route->add_track(*j->track.track());
206 history[1] = history[0];
207 history[0] = j->track.track();
209 bool waitable = j->track.endpoint().paths!=j->track->get_type().get_paths();
210 map<Track *, TrainRouter::SequencePoint *>::iterator k = sequenced_tracks.find(j->track.track());
211 if(k!=sequenced_tracks.end())
213 // Add a sequence point if another train uses this track afterwards.
214 if(!k->second->preceding_train)
216 k->second->preceding_train = j->info->train;
217 k->second->sequence_in = sequence;
219 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
221 k->second = &j->info->sequence.front();
226 /* Create a sequence point if it's possible to wait and let another
228 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
229 sequenced_tracks[j->track.track()] = &j->info->sequence.front();
238 TrainRoutePlanner::TrainRoutingInfo::TrainRoutingInfo(Train &t):
240 speed(train->get_maximum_speed()),
241 first_noncritical(train->get_last_critical_block().next().block()),
242 router(train->get_ai_of_type<TrainRouter>()),
245 if(unsigned n_wps = router->get_n_waypoints())
247 waypoints.reserve(n_wps),
248 metrics.reserve(n_wps);
249 for(unsigned i=0; i<n_wps; ++i)
251 waypoints.push_back(router->get_waypoint(i));
252 metrics.push_back(&router->get_metric(i));
254 has_duration = router->get_trip_duration();
257 // If no maximum speed is specified, use a sensible default
259 speed = 20*train->get_layout().get_catalogue().get_scale();
263 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(Track &t, unsigned p, OccupiedTrack *n):
265 path_length(track->get_type().get_path_length(p)),
267 n_tracks(next ? next->n_tracks+1 : 1),
274 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(const OccupiedTrack &other):
276 path_length(other.path_length),
278 n_tracks(other.n_tracks),
285 TrainRoutePlanner::OccupiedTrack::~OccupiedTrack()
287 if(next && !--next->refcount)
292 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
297 delay(info->router->get_departure_delay()),
298 duration(info->router->get_trip_duration()),
302 const Vehicle *veh = &info->train->get_vehicle(0);
304 TrackOffsetIter track_and_offs = veh->get_placement().get_position(VehiclePlacement::FRONT_BUFFER);
305 track = track_and_offs.track_iter();
306 offset = track_and_offs.offset();
307 path = track->get_active_path();
309 while(Vehicle *next = veh->get_link(1))
311 track_and_offs = veh->get_placement().get_position(VehiclePlacement::BACK_BUFFER);
312 back_offset = track_and_offs.offset();
314 TrackIter iter = track_and_offs.track_iter();
317 occupied_tracks = new OccupiedTrack(*iter, iter->get_active_path(), occupied_tracks);
318 if(iter.track()==track.track())
326 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(const TrainRoutingState &other):
330 critical(other.critical),
331 occupied_tracks(other.occupied_tracks),
332 offset(other.offset),
333 back_offset(other.back_offset),
336 duration(other.duration),
337 waypoint(other.waypoint),
338 distance_traveled(other.distance_traveled),
339 remaining_estimate(other.remaining_estimate),
340 wait_time(other.wait_time),
341 blocked_by(other.blocked_by)
343 ++occupied_tracks->refcount;
346 TrainRoutePlanner::TrainRoutingState::~TrainRoutingState()
348 if(occupied_tracks && !--occupied_tracks->refcount)
349 delete occupied_tracks;
352 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_next_track() const
354 return ((track->get_type().get_path_length(path)-offset)/info->speed)*Time::sec+delay;
357 bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
359 if(state==ARRIVED && !duration && info->has_duration)
362 OccupiedTrack *occ = occupied_tracks;
363 for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
369 bool TrainRoutePlanner::TrainRoutingState::check_arrival()
371 TrackIter next_track = track.next(path);
373 // Check if we're about the exit the current waypoint's tracks.
374 const TrainRouter::Waypoint &wp = info->waypoints[waypoint];
375 if(wp.chain->has_track(*track) && !wp.chain->has_track(*next_track))
376 if(wp.direction==TrackChain::UNSPECIFIED || track==wp.chain->iter_for(*track, wp.direction))
378 if(waypoint+1<info->waypoints.size())
387 // If we're entering the first non-critical block, clear the critical flag.
388 if(info->first_noncritical->has_track(*next_track))
394 void TrainRoutePlanner::TrainRoutingState::advance(float distance)
397 back_offset += distance;
399 // See if the tail end of the train has passed any sensors.
400 unsigned count_to_free = 0;
401 unsigned last_sensor_addr = 0;
402 float distance_after_sensor = 0;
403 OccupiedTrack *occ = occupied_tracks;
404 for(unsigned n=occupied_tracks->n_tracks; n>0; --n)
406 if(unsigned saddr = occ->track->get_sensor_address())
408 if(saddr!=last_sensor_addr)
411 distance_after_sensor = 0;
413 last_sensor_addr = saddr;
417 distance_after_sensor += occ->path_length;
422 // Free the last passed sensor and any tracks behind it.
423 if(count_to_free && back_offset>distance_after_sensor)
425 back_offset -= distance_after_sensor;
426 if(occupied_tracks->refcount>1)
428 --occupied_tracks->refcount;
429 occupied_tracks = new OccupiedTrack(*occupied_tracks);
431 occupied_tracks->n_tracks -= count_to_free;
434 distance_traveled += distance;
435 remaining_estimate -= distance;
438 void TrainRoutePlanner::TrainRoutingState::advance(const Time::TimeDelta &dt)
446 float secs = dt/Time::sec;
447 // There may be negative delay remaining after previous step.
450 secs -= delay/Time::sec;
455 duration = max(duration-secs*Time::sec, Time::zero);
458 advance(info->speed*secs);
459 else if(state!=ARRIVED)
460 wait_time += secs*Time::sec;
463 void TrainRoutePlanner::TrainRoutingState::advance_track(unsigned next_path)
465 float distance = occupied_tracks->path_length-offset;
466 track = track.next(path);
468 occupied_tracks = new OccupiedTrack(*track, path, occupied_tracks);
473 void TrainRoutePlanner::TrainRoutingState::update_estimate()
475 TrackIter iter = track.reverse(path);
476 remaining_estimate = info->metrics[waypoint]->get_distance_from(*iter.track(), iter.entry());
477 if(remaining_estimate>=0)
478 remaining_estimate += track->get_type().get_path_length(path)-offset;
481 bool TrainRoutePlanner::TrainRoutingState::is_viable() const
483 if(remaining_estimate<0)
485 if(critical && state==BLOCKED)
491 TrainRoutePlanner::RoutingStep::RoutingStep():
495 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
498 cost_estimate(p->cost_estimate),
503 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
505 RoutingStep next(this);
506 if(next.update_states() && next.check_deadlocks())
509 int train_index = find_next_train();
513 TrainRoutingState &train = next.trains[train_index];
515 Time::TimeDelta dt = train.get_time_to_next_track();
518 /* Check arrival after the train has advanced to the end of its current track
519 so travel time and occupied tracks will be correct. */
520 if(train.check_arrival())
522 new_steps.push_back(next);
526 train.advance_track(0);
528 const TrackType::Endpoint &entry_ep = train.track.endpoint();
531 /* Only create a successor step matching the currently set path for a
533 unsigned critical_path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
534 create_successor(next, train_index, critical_path, new_steps);
538 // Create successor steps for all possible paths through the new track.
539 for(unsigned i=0; entry_ep.paths>>i; ++i)
540 if(entry_ep.has_path(i))
541 create_successor(next, train_index, i, new_steps);
545 for(list<RoutingStep>::iterator i=new_steps.begin(); ++i!=new_steps.end(); )
547 i->penalty += 5*Time::sec;
548 i->update_estimate();
551 if(entry_ep.paths!=train.track->get_type().get_paths() && !train.critical)
553 /* Create a waiting state before the track if there's at least one path
554 that doesn't pass through the entry endpoint. */
555 RoutingStep wait(this);
557 wait.trains[train_index].state = WAITING;
558 wait.penalty += 15*Time::sec;
559 wait.update_estimate();
561 new_steps.push_back(wait);
565 void TrainRoutePlanner::RoutingStep::create_successor(RoutingStep &next, unsigned train_index, unsigned path, list<RoutingStep> &new_steps)
567 TrainRoutingState &train = next.trains[train_index];
570 train.update_estimate();
571 next.update_estimate();
573 new_steps.push_back(next);
576 bool TrainRoutePlanner::RoutingStep::update_states()
578 bool changes = false;
579 for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
581 if(i->state==ARRIVED)
584 TrainState old_state = i->state;
586 TrackIter next_track = i->track.next(i->path);
589 i->blocked_by = get_occupant(*next_track);
592 /* If the train is still traversing its last critical track, the
593 flag needs to be cleared here to pass viability test. */
594 if(i->info->first_noncritical->has_track(*next_track))
597 /* Trains in the WAITING state will also transition to BLOCKED and
598 then to MOVING when the other train has passed. */
601 else if(i->state==BLOCKED)
607 if(i->state!=old_state)
614 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
616 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
618 if(i->state!=BLOCKED)
621 // A train blocked by end of track is always considered a deadlock.
625 /* Use the tortoise and hare algorithm to check if trains are blocked
626 cyclically (A blocks B, which blocks ..., which blocks A). */
627 int slow = i->blocked_by;
628 int fast = trains[slow].blocked_by;
629 while(fast>=0 && trains[fast].blocked_by>=0)
634 slow = trains[slow].blocked_by;
635 fast = trains[trains[fast].blocked_by].blocked_by;
642 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
644 for(unsigned i=0; i<trains.size(); ++i)
645 if(trains[i].is_occupying(track))
651 int TrainRoutePlanner::RoutingStep::find_next_train() const
653 Time::TimeDelta min_dt;
655 for(unsigned i=0; i<trains.size(); ++i)
656 if(trains[i].state==MOVING)
658 Time::TimeDelta dt = trains[i].get_time_to_next_track();
659 if(dt<min_dt || next_train<0)
669 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
672 for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
676 void TrainRoutePlanner::RoutingStep::update_estimate()
678 cost_estimate = penalty;
679 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
680 if(i->remaining_estimate>=0)
681 cost_estimate += i->wait_time+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
684 bool TrainRoutePlanner::RoutingStep::is_viable() const
686 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
690 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
697 bool TrainRoutePlanner::RoutingStep::is_goal() const
699 for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
700 if(i->state!=ARRIVED)
705 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
707 return cost_estimate<other.cost_estimate;
711 TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
717 void TrainRoutePlanner::PlanningThread::main()
719 planner.create_plan();