]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouteplanner.cpp
Avoid negative values of wait_time
[r2c2.git] / source / libr2c2 / trainrouteplanner.cpp
1 #include <msp/core/maputils.h>
2 #include <msp/time/utils.h>
3 #include "catalogue.h"
4 #include "layout.h"
5 #include "route.h"
6 #include "train.h"
7 #include "trainroutemetric.h"
8 #include "trainrouteplanner.h"
9 #include "trainrouter.h"
10 #include "vehicle.h"
11
12 using namespace std;
13 using namespace Msp;
14
15 namespace R2C2 {
16
17 TrainRoutePlanner::TrainRoutePlanner(Layout &layout):
18         goal(0),
19         path_switch_bias(15*Time::sec),
20         timeout(10*Time::sec),
21         result(PENDING),
22         thread(0)
23 {
24         const map<unsigned, Train *> &trains = layout.get_trains();
25         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
26         {
27                 TrainRoutingInfo info(*i->second);
28                 if(!info.waypoints.empty())
29                         routed_trains.push_back(info);
30         }
31 }
32
33 TrainRoutePlanner::~TrainRoutePlanner()
34 {
35         if(thread)
36         {
37                 thread->join();
38                 delete thread;
39         }
40 }
41
42 void TrainRoutePlanner::set_timeout(const Time::TimeDelta &t)
43 {
44         timeout = t;
45 }
46
47 TrainRoutePlanner::Result TrainRoutePlanner::plan()
48 {
49         prepare_plan();
50         create_plan();
51         if(result==PENDING)
52                 finalize_plan();
53
54         return result;
55 }
56
57 void TrainRoutePlanner::plan_async()
58 {
59         if(thread)
60                 throw logic_error("already planning");
61
62         prepare_plan();
63         thread = new PlanningThread(*this);
64 }
65
66 TrainRoutePlanner::Result TrainRoutePlanner::check()
67 {
68         if(result==PENDING && goal)
69         {
70                 if(thread)
71                 {
72                         thread->join();
73                         delete thread;
74                         thread = 0;
75                 }
76                 finalize_plan();
77         }
78
79         return result;
80 }
81
82 const list<Route *> &TrainRoutePlanner::get_routes_for(const Train &train) const
83 {
84         return get_train_info(train).routes;
85 }
86
87 const list<TrainRouter::SequencePoint> &TrainRoutePlanner::get_sequence_for(const Train &train) const
88 {
89         return get_train_info(train).sequence;
90 }
91
92 const TrainRoutePlanner::TrainRoutingInfo &TrainRoutePlanner::get_train_info(const Train &train) const
93 {
94         for(vector<TrainRoutingInfo>::const_iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
95                 if(i->train==&train)
96                         return *i;
97
98         throw key_error(train.get_name());
99 }
100
101 const TrainRoutePlanner::RoutingStep &TrainRoutePlanner::get_step()
102 {
103         steps.splice(steps.end(), queue, queue.begin());
104         return steps.back();
105 }
106
107 void TrainRoutePlanner::prepare_plan()
108 {
109         steps.clear();
110         queue.clear();
111         goal = 0;
112         result = PENDING;
113
114         queue.push_back(RoutingStep());
115         RoutingStep &start = queue.back();
116         for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
117                 start.trains.push_back(TrainRoutingState(*i));
118         start.update_estimate();
119 }
120
121 void TrainRoutePlanner::create_plan()
122 {
123         Time::TimeStamp timeout_stamp = Time::now()+timeout;
124         unsigned count = 0;
125         while(!queue.empty())
126         {
127                 const RoutingStep &step = get_step();
128                 if(step.is_goal())
129                 {
130                         goal = &step;
131                         return;
132                 }
133
134                 add_steps(step);
135
136                 if(++count>=1000)
137                 {
138                         if(Time::now()>timeout_stamp)
139                                 break;
140                         count = 0;
141                 }
142         }
143
144         result = FAILED;
145 }
146
147 void TrainRoutePlanner::add_steps(const RoutingStep &step)
148 {
149         list<RoutingStep> new_steps;
150         step.create_successors(new_steps);
151         if(new_steps.empty())
152                 return;
153
154         new_steps.sort();
155         if(!queue.empty() && new_steps.front().cost_estimate<queue.front().cost_estimate+path_switch_bias)
156                 new_steps.front().preferred = true;
157         queue.merge(new_steps);
158 }
159
160 void TrainRoutePlanner::finalize_plan()
161 {
162         for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
163         {
164                 i->routes.clear();
165                 i->sequence.clear();
166                 for(unsigned j=0; j<2; ++j)
167                         i->track_history[j] = 0;
168         }
169
170         map<Track *, TrainRouter::SequencePoint *> sequenced_tracks;
171         unsigned sequence = steps.size();
172         for(const RoutingStep *i=goal; i; i=i->prev)
173                 for(vector<TrainRoutingState>::const_iterator j=i->trains.begin(); j!=i->trains.end(); ++j)
174                 {
175                         Track **history = j->info->track_history;
176                         // Don't process the same track again.
177                         if(j->track.track()==history[0])
178                                 continue;
179
180                         Route *route = 0;
181                         bool start_new_route = true;
182                         if(!j->info->routes.empty())
183                         {
184                                 /* If we already have a route and this track or any linked track is
185                                 in it, start a new one to avoid loops. */
186                                 route = j->info->routes.front();
187                                 start_new_route = route->has_track(*j->track);
188                                 if(!start_new_route)
189                                 {
190                                         unsigned nls = j->track->get_n_link_slots();
191                                         for(unsigned k=0; (!start_new_route && k<nls); ++k)
192                                         {
193                                                 Track *link = j->track->get_link(k);
194                                                 start_new_route = (link && link!=history[0] && route->has_track(*link));
195                                         }
196                                 }
197                         }
198
199                         if(start_new_route)
200                         {
201                                 route = new Route(j->info->train->get_layout());
202                                 route->set_name("Router");
203                                 route->set_temporary(true);
204                                 /* Have the routes overlap by two tracks to ensure that turnout
205                                 paths can be deduced. */
206                                 for(unsigned k=0; (k<2 && history[k]); ++k)
207                                         route->add_track(*history[k]);
208                                 j->info->routes.push_front(route);
209                         }
210
211                         route->add_track(*j->track.track());
212                         history[1] = history[0];
213                         history[0] = j->track.track();
214
215                         bool waitable = j->track.endpoint().paths!=j->track->get_type().get_paths();
216                         map<Track *, TrainRouter::SequencePoint *>::iterator k = sequenced_tracks.find(j->track.track());
217                         if(k!=sequenced_tracks.end())
218                         {
219                                 // Add a sequence point if another train uses this track afterwards.
220                                 if(!k->second->preceding_train)
221                                 {
222                                         k->second->preceding_train = j->info->train;
223                                         k->second->sequence_in = sequence;
224                                 }
225                                 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
226                                 if(waitable)
227                                         k->second = &j->info->sequence.front();
228                                 --sequence;
229                         }
230                         else if(waitable)
231                         {
232                                 /* Create a sequence point if it's possible to wait and let another
233                                 train past. */
234                                 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
235                                 sequenced_tracks[j->track.track()] = &j->info->sequence.front();
236                                 --sequence;
237                         }
238                 }
239
240         result = COMPLETE;
241 }
242
243
244 TrainRoutePlanner::TrainRoutingInfo::TrainRoutingInfo(Train &t):
245         train(&t),
246         length(0),
247         speed(train->get_maximum_speed()),
248         first_noncritical(train->get_last_critical_block().next().block()),
249         router(train->get_ai_of_type<TrainRouter>()),
250         has_duration(false)
251 {
252         if(unsigned n_wps = router->get_n_waypoints())
253         {
254                 waypoints.reserve(n_wps),
255                 metrics.reserve(n_wps);
256                 for(unsigned i=0; i<n_wps; ++i)
257                 {
258                         waypoints.push_back(router->get_waypoint(i));
259                         metrics.push_back(&router->get_metric(i));
260                 }
261                 has_duration = router->get_trip_duration();
262         }
263
264         unsigned n_vehs = train->get_n_vehicles();
265         for(unsigned i=0; i<n_vehs; ++i)
266                 length += train->get_vehicle(i).get_type().get_length();
267
268         // If no maximum speed is specified, use a sensible default
269         if(!speed)
270                 speed = 20*train->get_layout().get_catalogue().get_scale();
271 }
272
273
274 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(Track &t, unsigned p, OccupiedTrack *n):
275         track(&t),
276         path_length(track->get_type().get_path_length(p)),
277         next(n),
278         n_tracks(next ? next->n_tracks+1 : 1),
279         refcount(1)
280 {
281         if(next)
282                 ++next->refcount;
283 }
284
285 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(const OccupiedTrack &other):
286         track(other.track),
287         path_length(other.path_length),
288         next(other.next),
289         n_tracks(other.n_tracks),
290         refcount(1)
291 {
292         if(next)
293                 ++next->refcount;
294 }
295
296 TrainRoutePlanner::OccupiedTrack::~OccupiedTrack()
297 {
298         if(next && !--next->refcount)
299                 delete next;
300 }
301
302
303 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
304         info(&inf),
305         critical(true),
306         occupied_tracks(0),
307         state(MOVING),
308         delay(info->router->get_departure_delay()),
309         duration(info->router->get_trip_duration()),
310         waypoint(0),
311         distance_traveled(0),
312         blocked_by(-1)
313 {
314         const Vehicle *veh = &info->train->get_vehicle(0);
315         // TODO margins
316         TrackOffsetIter track_and_offs = veh->get_placement().get_position(VehiclePlacement::FRONT_BUFFER);
317         track = track_and_offs.track_iter();
318         offset = track_and_offs.offset();
319         path = track->get_active_path();
320
321         while(Vehicle *next = veh->get_link(1))
322                 veh = next;
323         track_and_offs = veh->get_placement().get_position(VehiclePlacement::BACK_BUFFER);
324         back_offset = track_and_offs.offset();
325
326         TrackIter iter = track_and_offs.track_iter();
327         while(1)
328         {
329                 occupied_tracks = new OccupiedTrack(*iter, iter->get_active_path(), occupied_tracks);
330                 if(iter.track()==track.track())
331                         break;
332                 iter = iter.next();
333         }
334
335         travel_multiplier = info->metrics[waypoint]->get_travel_multiplier(*track, track.reverse(path).entry());
336
337         update_estimate();
338 }
339
340 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(const TrainRoutingState &other):
341         info(other.info),
342         track(other.track),
343         path(other.path),
344         critical(other.critical),
345         occupied_tracks(other.occupied_tracks),
346         offset(other.offset),
347         back_offset(other.back_offset),
348         state(other.state),
349         delay(other.delay),
350         duration(other.duration),
351         waypoint(other.waypoint),
352         travel_multiplier(other.travel_multiplier),
353         distance_traveled(other.distance_traveled),
354         remaining_estimate(other.remaining_estimate),
355         wait_time(other.wait_time),
356         estimated_wait(other.estimated_wait),
357         blocked_by(other.blocked_by)
358 {
359         ++occupied_tracks->refcount;
360 }
361
362 TrainRoutePlanner::TrainRoutingState::~TrainRoutingState()
363 {
364         if(occupied_tracks && !--occupied_tracks->refcount)
365                 delete occupied_tracks;
366 }
367
368 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_next_track() const
369 {
370         return ((occupied_tracks->path_length-offset)/info->speed)*Time::sec+delay;
371 }
372
373 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_pass(Track &trk) const
374 {
375         if(is_occupying(trk))
376         {
377                 float passed_length = 0;
378                 for(const OccupiedTrack *occ=occupied_tracks; (occ && occ->track!=&trk); occ=occ->next)
379                         passed_length += occ->path_length;
380                 return (max(info->length-passed_length, 0.0f)/info->speed)*Time::sec+delay;
381         }
382
383         for(unsigned wp=waypoint; wp<info->waypoints.size(); ++wp)
384         {
385                 float distance = info->metrics[wp]->get_distance_from(trk);
386                 if(distance>=0 && distance<remaining_estimate)
387                         return ((remaining_estimate-distance+info->length)/info->speed)*Time::sec+delay;
388         }
389
390         return Time::day;
391 }
392
393 bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
394 {
395         if(state==ARRIVED && !duration && info->has_duration)
396                 return false;
397
398         OccupiedTrack *occ = occupied_tracks;
399         for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
400                 if(occ->track==&trk)
401                         return true;
402         return false;
403 }
404
405 bool TrainRoutePlanner::TrainRoutingState::check_arrival()
406 {
407         TrackIter next_track = track.next(path);
408
409         // Check if we're about the exit the current waypoint's tracks.
410         const TrainRouter::Waypoint &wp = info->waypoints[waypoint];
411         if(wp.chain->has_track(*track) && !wp.chain->has_track(*next_track))
412                 if(wp.direction==TrackChain::UNSPECIFIED || track==wp.chain->iter_for(*track, wp.direction))
413                 {
414                         if(waypoint+1<info->waypoints.size())
415                                 ++waypoint;
416                         else
417                         {
418                                 state = ARRIVED;
419                                 return true;
420                         }
421                 }
422
423         // If we're entering the first non-critical block, clear the critical flag.
424         if(info->first_noncritical->has_track(*next_track))
425                 critical = false;
426
427         return false;
428 }
429
430 void TrainRoutePlanner::TrainRoutingState::advance(float distance)
431 {
432         offset += distance;
433         back_offset += distance;
434
435         // See if the tail end of the train has passed any sensors.
436         unsigned count_to_free = 0;
437         unsigned last_sensor_addr = 0;
438         float distance_after_sensor = 0;
439         OccupiedTrack *occ = occupied_tracks;
440         for(unsigned n=occupied_tracks->n_tracks; n>0; --n)
441         {
442                 if(unsigned saddr = occ->track->get_sensor_address())
443                 {
444                         if(saddr!=last_sensor_addr)
445                         {
446                                 count_to_free = 0;
447                                 distance_after_sensor = 0;
448                         }
449                         last_sensor_addr = saddr;
450                 }
451
452                 ++count_to_free;
453                 distance_after_sensor += occ->path_length;
454
455                 occ = occ->next;
456         }
457
458         // Free the last passed sensor and any tracks behind it.
459         if(count_to_free && back_offset>distance_after_sensor)
460         {
461                 back_offset -= distance_after_sensor;
462                 if(occupied_tracks->refcount>1)
463                 {
464                         --occupied_tracks->refcount;
465                         occupied_tracks = new OccupiedTrack(*occupied_tracks);
466                 }
467                 occupied_tracks->n_tracks -= count_to_free;
468         }
469
470         distance_traveled += distance*travel_multiplier;
471         remaining_estimate -= distance*travel_multiplier;
472 }
473
474 void TrainRoutePlanner::TrainRoutingState::advance(const Time::TimeDelta &dt)
475 {
476         if(delay>=dt)
477         {
478                 delay -= dt;
479                 return;
480         }
481
482         float secs = dt/Time::sec;
483         // There may be some delay remaining.
484         if(delay)
485         {
486                 secs -= delay/Time::sec;
487                 delay = Time::zero;
488         }
489
490         if(duration)
491                 duration = max(duration-secs*Time::sec, Time::zero);
492
493         if(estimated_wait)
494                 estimated_wait = max(estimated_wait-secs*Time::sec, Time::zero);
495
496         float distance = info->speed*secs;
497         float remaining_on_track = occupied_tracks->path_length-offset;
498         if(state==MOVING || distance<remaining_on_track)
499                 advance(info->speed*secs);
500         else if(state!=ARRIVED)
501         {
502                 if(remaining_on_track>0)
503                 {
504                         advance(remaining_on_track);
505                         wait_time += (secs-remaining_on_track/info->speed)*Time::sec;
506                 }
507                 else
508                         wait_time += secs*Time::sec;
509         }
510 }
511
512 void TrainRoutePlanner::TrainRoutingState::advance_track(unsigned next_path)
513 {
514         float distance = occupied_tracks->path_length-offset;
515
516         track = track.next(path);
517         path = next_path;
518         occupied_tracks = new OccupiedTrack(*track, path, occupied_tracks);
519
520         advance(distance);
521         offset = 0;
522         travel_multiplier = info->metrics[waypoint]->get_travel_multiplier(*track, track.reverse(path).entry());
523 }
524
525 void TrainRoutePlanner::TrainRoutingState::set_path(unsigned p)
526 {
527         path = p;
528         OccupiedTrack *next_occ = occupied_tracks->next;
529         if(!--occupied_tracks->refcount)
530                 delete occupied_tracks;
531         occupied_tracks = new OccupiedTrack(*track, path, next_occ);
532         update_estimate();
533 }
534
535 void TrainRoutePlanner::TrainRoutingState::update_estimate()
536 {
537         TrackIter iter = track.reverse(path);
538         const TrainRouteMetric *metric = info->metrics[waypoint];
539         remaining_estimate = metric->get_distance_from(*iter, iter.entry());
540         travel_multiplier = metric->get_travel_multiplier(*iter, iter.entry());
541         if(remaining_estimate>=0)
542                 remaining_estimate += (occupied_tracks->path_length-offset)*travel_multiplier;
543 }
544
545 bool TrainRoutePlanner::TrainRoutingState::is_viable() const
546 {
547         if(remaining_estimate<0)
548                 return false;
549         if(critical && state==BLOCKED)
550                 return false;
551         return true;
552 }
553
554
555 TrainRoutePlanner::RoutingStep::RoutingStep():
556         preferred(false),
557         prev(0)
558 { }
559
560 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
561         time(p->time),
562         cost_estimate(p->cost_estimate),
563         preferred(false),
564         trains(p->trains),
565         prev(p)
566 { }
567
568 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
569 {
570         RoutingStep next(this);
571         if(next.update_states() && next.check_deadlocks())
572                 return;
573
574         int train_index = next.find_next_train();
575         if(train_index<0)
576                 return;
577
578         TrainRoutingState &train = next.trains[train_index];
579
580         Time::TimeDelta dt = train.get_time_to_next_track();
581         next.advance(dt);
582
583         /* Check arrival after the train has advanced to the end of its current track
584         so travel time and occupied tracks will be correct. */
585         if(train.check_arrival())
586         {
587                 new_steps.push_back(next);
588                 return;
589         }
590
591         if(train.state==MOVING)
592                 train.advance_track(0);
593         else
594         {
595                 new_steps.push_back(next);
596                 return;
597         }
598
599         const TrackType::Endpoint &entry_ep = train.track.endpoint();
600         if(train.critical)
601         {
602                 /* Only create a successor step matching the currently set path for a
603                 critical track. */
604                 unsigned critical_path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
605                 create_successor(next, train_index, critical_path, new_steps);
606         }
607         else
608         {
609                 // Create successor steps for all possible paths through the new track.
610                 for(unsigned i=0; entry_ep.paths>>i; ++i)
611                         if(entry_ep.has_path(i))
612                                 create_successor(next, train_index, i, new_steps);
613         }
614
615         if(entry_ep.paths!=train.track->get_type().get_paths() && !train.critical)
616         {
617                 /* Create a waiting state before the track if there's at least one path
618                 that doesn't pass through the entry endpoint. */
619                 RoutingStep wait(this);
620                 wait.advance(dt);
621                 wait.trains[train_index].state = WAITING;
622
623                 Time::TimeDelta estimated_wait = Time::day;
624                 for(unsigned i=0; i<wait.trains.size(); ++i)
625                         if(i!=static_cast<unsigned>(train_index) && wait.trains[i].state!=ARRIVED)
626                         {
627                                 Time::TimeDelta ttp = wait.trains[i].get_time_to_pass(*train.track);
628                                 estimated_wait = min(estimated_wait, ttp);
629                         }
630                 wait.trains[train_index].estimated_wait = estimated_wait;
631
632                 wait.update_estimate();
633                 if(wait.is_viable())
634                         new_steps.push_back(wait);
635         }
636 }
637
638 void TrainRoutePlanner::RoutingStep::create_successor(RoutingStep &next, unsigned train_index, unsigned path, list<RoutingStep> &new_steps)
639 {
640         TrainRoutingState &train = next.trains[train_index];
641
642         train.set_path(path);
643         next.update_estimate();
644         if(next.is_viable())
645                 new_steps.push_back(next);
646 }
647
648 bool TrainRoutePlanner::RoutingStep::update_states()
649 {
650         bool changes = false;
651         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
652         {
653                 if(i->state==ARRIVED)
654                         continue;
655
656                 TrainState old_state = i->state;
657
658                 TrackIter next_track = i->track.next(i->path);
659                 if(next_track)
660                 {
661                         i->blocked_by = get_occupant(*next_track);
662                         if(i->blocked_by>=0)
663                         {
664                                 /* If the train is still traversing its last critical track, the
665                                 flag needs to be cleared here to pass viability test. */
666                                 if(i->info->first_noncritical->has_track(*next_track))
667                                         i->critical = false;
668
669                                 if(i->state!=BLOCKED)
670                                         i->estimated_wait = trains[i->blocked_by].get_time_to_pass(*next_track);
671
672                                 /* Trains in the WAITING state will also transition to BLOCKED and
673                                 then to MOVING when the other train has passed. */
674                                 i->state = BLOCKED;
675                         }
676                         else if(i->state==BLOCKED)
677                         {
678                                 i->estimated_wait = Time::zero;
679                                 i->state = MOVING;
680                         }
681                 }
682                 else
683                         i->state = BLOCKED;
684
685                 if(i->state!=old_state)
686                         changes = true;
687         }
688
689         return changes;
690 }
691
692 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
693 {
694         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
695         {
696                 if(i->state!=BLOCKED)
697                         continue;
698
699                 // A train blocked by end of track is always considered a deadlock.
700                 if(i->blocked_by<0)
701                         return true;
702
703                 /* Use the tortoise and hare algorithm to check if trains are blocked
704                 cyclically (A blocks B, which blocks ..., which blocks A). */
705                 int slow = i->blocked_by;
706                 int fast = trains[slow].blocked_by;
707                 while(fast>=0 && trains[fast].blocked_by>=0)
708                 {
709                         if(fast==slow)
710                                 return true;
711
712                         slow = trains[slow].blocked_by;
713                         fast = trains[trains[fast].blocked_by].blocked_by;
714                 }
715         }
716
717         return false;
718 }
719
720 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
721 {
722         for(unsigned i=0; i<trains.size(); ++i)
723                 if(trains[i].is_occupying(track))
724                         return i;
725
726         return -1;
727 }
728
729 int TrainRoutePlanner::RoutingStep::find_next_train() const
730 {
731         /* Pick a moving train with the lowest time to next track.  A train that
732         just became blocked can still travel until the end of its current track,
733         so consider those too. */
734         Time::TimeDelta min_dt;
735         int next_train = -1;
736         for(unsigned i=0; i<trains.size(); ++i)
737                 if(trains[i].state==MOVING || (trains[i].state==BLOCKED && prev && prev->trains[i].state==MOVING))
738                 {
739                         Time::TimeDelta dt = trains[i].get_time_to_next_track();
740                         if(dt<min_dt || next_train<0)
741                         {
742                                 min_dt = dt;
743                                 next_train = i;
744                         }
745                 }
746
747         return next_train;
748 }
749
750 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
751 {
752         time += dt;
753         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
754                 i->advance(dt);
755 }
756
757 void TrainRoutePlanner::RoutingStep::update_estimate()
758 {
759         cost_estimate = Time::zero;
760         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
761                 if(i->remaining_estimate>=0)
762                         cost_estimate += i->wait_time+i->estimated_wait+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
763 }
764
765 bool TrainRoutePlanner::RoutingStep::is_viable() const
766 {
767         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
768                 if(!i->is_viable())
769                         return false;
770
771         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
772                 if(i->state==MOVING)
773                         return true;
774
775         return false;
776 }
777
778 bool TrainRoutePlanner::RoutingStep::is_goal() const
779 {
780         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
781                 if(i->state!=ARRIVED)
782                         return false;
783         return true;
784 }
785
786 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
787 {
788         if(preferred!=other.preferred)
789                 return preferred>other.preferred;
790         return cost_estimate<other.cost_estimate;
791 }
792
793
794 TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
795         planner(p)
796 {
797         launch();
798 }
799
800 void TrainRoutePlanner::PlanningThread::main()
801 {
802         planner.create_plan();
803 }
804
805 } // namespace R2C2