]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouteplanner.cpp
Move duplicated successor step creation code to a function
[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                         if(j->track.track()==history[0])
171                                 continue;
172
173                         Route *route = 0;
174                         bool start_new_route = true;
175                         if(!j->info->routes.empty())
176                         {
177                                 route = j->info->routes.front();
178                                 start_new_route = route->has_track(*j->track);
179                                 if(!start_new_route)
180                                 {
181                                         unsigned nls = j->track->get_n_link_slots();
182                                         for(unsigned k=0; (!start_new_route && k<nls); ++k)
183                                         {
184                                                 Track *link = j->track->get_link(k);
185                                                 start_new_route = (link && link!=history[0] && route->has_track(*link));
186                                         }
187                                 }
188                         }
189
190                         if(start_new_route)
191                         {
192                                 route = new Route(j->info->train->get_layout());
193                                 route->set_name("Router");
194                                 route->set_temporary(true);
195                                 for(unsigned k=0; (k<2 && history[k]); ++k)
196                                         route->add_track(*history[k]);
197                                 j->info->routes.push_front(route);
198                         }
199
200                         route->add_track(*j->track.track());
201                         history[1] = history[0];
202                         history[0] = j->track.track();
203
204                         bool waitable = j->track.endpoint().paths!=j->track->get_type().get_paths();
205                         map<Track *, TrainRouter::SequencePoint *>::iterator k = sequenced_tracks.find(j->track.track());
206                         if(k!=sequenced_tracks.end())
207                         {
208                                 if(!k->second->preceding_train)
209                                 {
210                                         k->second->preceding_train = j->info->train;
211                                         k->second->sequence_in = sequence;
212                                 }
213                                 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
214                                 if(waitable)
215                                         k->second = &j->info->sequence.front();
216                                 --sequence;
217                         }
218                         else if(waitable)
219                         {
220                                 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
221                                 sequenced_tracks[j->track.track()] = &j->info->sequence.front();
222                                 --sequence;
223                         }
224                 }
225
226         result = COMPLETE;
227 }
228
229
230 TrainRoutePlanner::TrainRoutingInfo::TrainRoutingInfo(Train &t):
231         train(&t),
232         speed(train->get_maximum_speed()),
233         first_noncritical(train->get_last_critical_block().next().block()),
234         router(train->get_ai_of_type<TrainRouter>()),
235         has_duration(false)
236 {
237         if(unsigned n_wps = router->get_n_waypoints())
238         {
239                 waypoints.reserve(n_wps),
240                 metrics.reserve(n_wps);
241                 for(unsigned i=0; i<n_wps; ++i)
242                 {
243                         waypoints.push_back(router->get_waypoint(i));
244                         metrics.push_back(&router->get_metric(i));
245                 }
246                 has_duration = router->get_trip_duration();
247         }
248
249         // If no maximum speed is specified, use a sensible default
250         if(!speed)
251                 speed = 20*train->get_layout().get_catalogue().get_scale();
252 }
253
254
255 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(Track &t, unsigned p, OccupiedTrack *n):
256         track(&t),
257         path_length(track->get_type().get_path_length(p)),
258         next(n),
259         n_tracks(next ? next->n_tracks+1 : 1),
260         refcount(1)
261 {
262         if(next)
263                 ++next->refcount;
264 }
265
266 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(const OccupiedTrack &other):
267         track(other.track),
268         path_length(other.path_length),
269         next(other.next),
270         n_tracks(other.n_tracks),
271         refcount(1)
272 {
273         if(next)
274                 ++next->refcount;
275 }
276
277 TrainRoutePlanner::OccupiedTrack::~OccupiedTrack()
278 {
279         if(next && !--next->refcount)
280                 delete next;
281 }
282
283
284 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
285         info(&inf),
286         critical(true),
287         occupied_tracks(0),
288         state(MOVING),
289         delay(info->router->get_departure_delay()),
290         duration(info->router->get_trip_duration()),
291         waypoint(0),
292         blocked_by(-1)
293 {
294         const Vehicle *veh = &info->train->get_vehicle(0);
295         // TODO margins
296         TrackOffsetIter track_and_offs = veh->get_placement().get_position(VehiclePlacement::FRONT_BUFFER);
297         track = track_and_offs.track_iter();
298         offset = track_and_offs.offset();
299         path = track->get_active_path();
300
301         while(Vehicle *next = veh->get_link(1))
302                 veh = next;
303         track_and_offs = veh->get_placement().get_position(VehiclePlacement::BACK_BUFFER);
304         back_offset = track_and_offs.offset();
305
306         TrackIter iter = track_and_offs.track_iter();
307         while(1)
308         {
309                 occupied_tracks = new OccupiedTrack(*iter, iter->get_active_path(), occupied_tracks);
310                 if(iter.track()==track.track())
311                         break;
312                 iter = iter.next();
313         }
314
315         update_estimate();
316 }
317
318 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(const TrainRoutingState &other):
319         info(other.info),
320         track(other.track),
321         path(other.path),
322         critical(other.critical),
323         occupied_tracks(other.occupied_tracks),
324         offset(other.offset),
325         back_offset(other.back_offset),
326         state(other.state),
327         delay(other.delay),
328         duration(other.duration),
329         waypoint(other.waypoint),
330         distance_traveled(other.distance_traveled),
331         remaining_estimate(other.remaining_estimate),
332         wait_time(other.wait_time),
333         blocked_by(other.blocked_by)
334 {
335         ++occupied_tracks->refcount;
336 }
337
338 TrainRoutePlanner::TrainRoutingState::~TrainRoutingState()
339 {
340         if(occupied_tracks && !--occupied_tracks->refcount)
341                 delete occupied_tracks;
342 }
343
344 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_next_track() const
345 {
346         return ((track->get_type().get_path_length(path)-offset)/info->speed)*Time::sec+delay;
347 }
348
349 bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
350 {
351         if(state==ARRIVED && !duration && info->has_duration)
352                 return false;
353
354         OccupiedTrack *occ = occupied_tracks;
355         for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
356                 if(occ->track==&trk)
357                         return true;
358         return false;
359 }
360
361 bool TrainRoutePlanner::TrainRoutingState::check_arrival()
362 {
363         TrackIter next_track = track.next(path);
364
365         const TrainRouter::Waypoint &wp = info->waypoints[waypoint];
366         if(wp.chain->has_track(*track) && !wp.chain->has_track(*next_track))
367                 if(wp.direction==TrackChain::UNSPECIFIED || track==wp.chain->iter_for(*track, wp.direction))
368                 {
369                         if(waypoint+1<info->waypoints.size())
370                                 ++waypoint;
371                         else
372                         {
373                                 state = ARRIVED;
374                                 return true;
375                         }
376                 }
377
378         if(info->first_noncritical->has_track(*track))
379                 critical = false;
380
381         return false;
382 }
383
384 void TrainRoutePlanner::TrainRoutingState::advance(float distance)
385 {
386         offset += distance;
387         back_offset += distance;
388
389         unsigned count_to_free = 0;
390         unsigned last_sensor_addr = 0;
391         float distance_after_sensor = 0;
392         OccupiedTrack *occ = occupied_tracks;
393         for(unsigned n=occupied_tracks->n_tracks; n>0; --n)
394         {
395                 if(unsigned saddr = occ->track->get_sensor_address())
396                 {
397                         if(saddr!=last_sensor_addr)
398                         {
399                                 count_to_free = 0;
400                                 distance_after_sensor = 0;
401                         }
402                         last_sensor_addr = saddr;
403                 }
404
405                 ++count_to_free;
406                 distance_after_sensor += occ->path_length;
407
408                 occ = occ->next;
409         }
410
411         if(count_to_free && back_offset>distance_after_sensor)
412         {
413                 back_offset -= distance_after_sensor;
414                 if(occupied_tracks->refcount>1)
415                 {
416                         --occupied_tracks->refcount;
417                         occupied_tracks = new OccupiedTrack(*occupied_tracks);
418                 }
419                 occupied_tracks->n_tracks -= count_to_free;
420         }
421
422         distance_traveled += distance;
423         remaining_estimate -= distance;
424 }
425
426 void TrainRoutePlanner::TrainRoutingState::advance(const Time::TimeDelta &dt)
427 {
428         if(delay>=dt)
429         {
430                 delay -= dt;
431                 return;
432         }
433
434         float secs = dt/Time::sec;
435         if(delay)
436         {
437                 secs -= delay/Time::sec;
438                 delay = Time::zero;
439         }
440
441         if(duration)
442                 duration = max(duration-secs*Time::sec, Time::zero);
443
444         if(state==MOVING)
445                 advance(info->speed*secs);
446         else if(state!=ARRIVED)
447                 wait_time += secs*Time::sec;
448 }
449
450 void TrainRoutePlanner::TrainRoutingState::advance_track(unsigned next_path)
451 {
452         float distance = occupied_tracks->path_length-offset;
453         track = track.next(path);
454         path = next_path;
455         occupied_tracks = new OccupiedTrack(*track, path, occupied_tracks);
456         advance(distance);
457         offset = 0;
458 }
459
460 void TrainRoutePlanner::TrainRoutingState::update_estimate()
461 {
462         TrackIter iter = track.reverse(path);
463         remaining_estimate = info->metrics[waypoint]->get_distance_from(*iter.track(), iter.entry());
464         if(remaining_estimate>=0)
465                 remaining_estimate += track->get_type().get_path_length(path)-offset;
466 }
467
468 bool TrainRoutePlanner::TrainRoutingState::is_viable() const
469 {
470         if(remaining_estimate<0)
471                 return false;
472         if(critical && state==BLOCKED)
473                 return false;
474         return true;
475 }
476
477
478 TrainRoutePlanner::RoutingStep::RoutingStep():
479         prev(0)
480 { }
481
482 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
483         time(p->time),
484         penalty(p->penalty),
485         cost_estimate(p->cost_estimate),
486         trains(p->trains),
487         prev(p)
488 { }
489
490 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
491 {
492         RoutingStep next(this);
493         if(next.update_states())
494         {
495                 if(next.check_deadlocks())
496                         return;
497
498                 new_steps.push_back(next);
499                 return;
500         }
501
502         int train_index = find_next_train();
503         if(train_index<0)
504                 return;
505
506         TrainRoutingState &train = next.trains[train_index];
507
508         Time::TimeDelta dt = train.get_time_to_next_track();
509         next.advance(dt);
510
511         if(train.check_arrival())
512         {
513                 new_steps.push_back(next);
514                 return;
515         }
516
517         train.advance_track(0);
518
519         const TrackType::Endpoint &entry_ep = train.track.endpoint();
520         if(train.critical)
521         {
522                 unsigned critical_path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
523                 create_successor(next, train_index, critical_path, new_steps);
524         }
525         else
526         {
527                 for(unsigned i=0; entry_ep.paths>>i; ++i)
528                         if(entry_ep.has_path(i))
529                                 create_successor(next, train_index, i, new_steps);
530         }
531
532         new_steps.sort();
533         for(list<RoutingStep>::iterator i=new_steps.begin(); ++i!=new_steps.end(); )
534         {
535                 i->penalty += 5*Time::sec;
536                 i->update_estimate();
537         }
538
539         if(entry_ep.paths!=train.track->get_type().get_paths() && !train.critical)
540         {
541                 RoutingStep wait(this);
542                 wait.advance(dt);
543                 wait.trains[train_index].state = WAITING;
544                 wait.penalty += 15*Time::sec;
545                 wait.update_estimate();
546                 if(wait.is_viable())
547                         new_steps.push_back(wait);
548         }
549 }
550
551 void TrainRoutePlanner::RoutingStep::create_successor(RoutingStep &next, unsigned train_index, unsigned path, list<RoutingStep> &new_steps)
552 {
553         TrainRoutingState &train = next.trains[train_index];
554
555         train.path = path;
556         train.update_estimate();
557         next.update_estimate();
558         if(next.is_viable())
559                 new_steps.push_back(next);
560 }
561
562 bool TrainRoutePlanner::RoutingStep::update_states()
563 {
564         bool changes = false;
565         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
566         {
567                 if(i->state==ARRIVED)
568                         continue;
569
570                 TrainState old_state = i->state;
571
572                 TrackIter next_track = i->track.next(i->path);
573                 if(next_track)
574                 {
575                         i->blocked_by = get_occupant(*next_track);
576                         if(i->blocked_by>=0)
577                         {
578                                 if(i->info->first_noncritical->has_track(*next_track))
579                                         i->critical = false;
580                                 i->state = BLOCKED;
581                         }
582                         else if(i->state==BLOCKED)
583                                 i->state = MOVING;
584                 }
585                 else
586                         i->state = BLOCKED;
587
588                 if(i->state!=old_state)
589                         changes = true;
590         }
591
592         return changes;
593 }
594
595 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
596 {
597         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
598         {
599                 if(i->state!=BLOCKED)
600                         continue;
601
602                 if(i->blocked_by<0)
603                         return true;
604
605                 int slow = i->blocked_by;
606                 int fast = trains[slow].blocked_by;
607                 while(fast>=0 && trains[fast].blocked_by>=0)
608                 {
609                         if(fast==slow)
610                                 return true;
611
612                         slow = trains[slow].blocked_by;
613                         fast = trains[trains[fast].blocked_by].blocked_by;
614                 }
615         }
616
617         return false;
618 }
619
620 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
621 {
622         for(unsigned i=0; i<trains.size(); ++i)
623                 if(trains[i].is_occupying(track))
624                         return i;
625
626         return -1;
627 }
628
629 int TrainRoutePlanner::RoutingStep::find_next_train() const
630 {
631         Time::TimeDelta min_dt;
632         int next_train = -1;
633         for(unsigned i=0; i<trains.size(); ++i)
634                 if(trains[i].state==MOVING)
635                 {
636                         Time::TimeDelta dt = trains[i].get_time_to_next_track();
637                         if(dt<min_dt || next_train<0)
638                         {
639                                 min_dt = dt;
640                                 next_train = i;
641                         }
642                 }
643
644         return next_train;
645 }
646
647 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
648 {
649         time += dt;
650         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
651                 i->advance(dt);
652 }
653
654 void TrainRoutePlanner::RoutingStep::update_estimate()
655 {
656         cost_estimate = penalty;
657         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
658                 if(i->remaining_estimate>=0)
659                         cost_estimate += i->wait_time+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
660 }
661
662 bool TrainRoutePlanner::RoutingStep::is_viable() const
663 {
664         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
665                 if(!i->is_viable())
666                         return false;
667
668         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
669                 if(i->state==MOVING)
670                         return true;
671
672         return false;
673 }
674
675 bool TrainRoutePlanner::RoutingStep::is_goal() const
676 {
677         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
678                 if(i->state!=ARRIVED)
679                         return false;
680         return true;
681 }
682
683 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
684 {
685         return cost_estimate<other.cost_estimate;
686 }
687
688
689 TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
690         planner(p)
691 {
692         launch();
693 }
694
695 void TrainRoutePlanner::PlanningThread::main()
696 {
697         planner.create_plan();
698 }
699
700 } // namespace R2C2