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