]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouteplanner.cpp
9bed406f102576c893a6f3b890ad031d36329840
[r2c2.git] / source / libr2c2 / trainrouteplanner.cpp
1 #include <msp/core/maputils.h>
2 #include "catalogue.h"
3 #include "layout.h"
4 #include "route.h"
5 #include "train.h"
6 #include "trainroutemetric.h"
7 #include "trainrouteplanner.h"
8 #include "trainrouter.h"
9 #include "vehicle.h"
10
11 using namespace std;
12 using namespace Msp;
13
14 namespace R2C2 {
15
16 TrainRoutePlanner::TrainRoutePlanner(Layout &layout):
17         goal(0),
18         result(PENDING),
19         thread(0)
20 {
21         const map<unsigned, Train *> &trains = layout.get_trains();
22         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
23         {
24                 TrainRoutingInfo info(*i->second);
25                 if(!info.waypoints.empty())
26                         routed_trains.push_back(info);
27         }
28 }
29
30 TrainRoutePlanner::~TrainRoutePlanner()
31 {
32         if(thread)
33         {
34                 thread->join();
35                 delete thread;
36         }
37 }
38
39 TrainRoutePlanner::Result TrainRoutePlanner::plan()
40 {
41         prepare_plan();
42         create_plan();
43         if(result==PENDING)
44                 finalize_plan();
45
46         return result;
47 }
48
49 void TrainRoutePlanner::plan_async()
50 {
51         if(thread)
52                 throw logic_error("already planning");
53
54         prepare_plan();
55         thread = new PlanningThread(*this);
56 }
57
58 TrainRoutePlanner::Result TrainRoutePlanner::check()
59 {
60         if(result==PENDING && goal)
61         {
62                 if(thread)
63                 {
64                         thread->join();
65                         delete thread;
66                         thread = 0;
67                 }
68                 finalize_plan();
69         }
70
71         return result;
72 }
73
74 const list<Route *> &TrainRoutePlanner::get_routes_for(const Train &train) const
75 {
76         return get_train_info(train).routes;
77 }
78
79 const list<TrainRouter::SequencePoint> &TrainRoutePlanner::get_sequence_for(const Train &train) const
80 {
81         return get_train_info(train).sequence;
82 }
83
84 const TrainRoutePlanner::TrainRoutingInfo &TrainRoutePlanner::get_train_info(const Train &train) const
85 {
86         for(vector<TrainRoutingInfo>::const_iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
87                 if(i->train==&train)
88                         return *i;
89
90         throw key_error(train.get_name());
91 }
92
93 const TrainRoutePlanner::RoutingStep &TrainRoutePlanner::get_step()
94 {
95         steps.splice(steps.end(), queue, queue.begin());
96         return steps.back();
97 }
98
99 void TrainRoutePlanner::prepare_plan()
100 {
101         steps.clear();
102         queue.clear();
103         goal = 0;
104         result = PENDING;
105
106         queue.push_back(RoutingStep());
107         RoutingStep &start = queue.back();
108         for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
109                 start.trains.push_back(TrainRoutingState(*i));
110         start.update_estimate();
111 }
112
113 void TrainRoutePlanner::create_plan()
114 {
115         while(!queue.empty())
116         {
117                 const RoutingStep &step = get_step();
118                 if(step.is_goal())
119                 {
120                         goal = &step;
121                         return;
122                 }
123
124                 add_steps(step);
125         }
126
127         result = FAILED;
128 }
129
130 void TrainRoutePlanner::add_steps(const RoutingStep &step)
131 {
132         list<RoutingStep> new_steps;
133         step.create_successors(new_steps);
134         new_steps.sort();
135         queue.merge(new_steps);
136 }
137
138 void TrainRoutePlanner::finalize_plan()
139 {
140         for(vector<TrainRoutingInfo>::iterator i=routed_trains.begin(); i!=routed_trains.end(); ++i)
141         {
142                 i->routes.clear();
143                 i->sequence.clear();
144                 for(unsigned j=0; j<2; ++j)
145                         i->track_history[j] = 0;
146         }
147
148         map<Track *, TrainRouter::SequencePoint *> sequenced_tracks;
149         unsigned sequence = steps.size();
150         for(const RoutingStep *i=goal; i; i=i->prev)
151                 for(vector<TrainRoutingState>::const_iterator j=i->trains.begin(); j!=i->trains.end(); ++j)
152                 {
153                         Track **history = j->info->track_history;
154                         if(j->track.track()==history[0])
155                                 continue;
156
157                         Route *route = 0;
158                         bool start_new_route = true;
159                         if(!j->info->routes.empty())
160                         {
161                                 route = j->info->routes.front();
162                                 start_new_route = route->has_track(*j->track);
163                                 if(!start_new_route)
164                                 {
165                                         unsigned nls = j->track->get_n_link_slots();
166                                         for(unsigned k=0; (!start_new_route && k<nls); ++k)
167                                         {
168                                                 Track *link = j->track->get_link(k);
169                                                 start_new_route = (link && link!=history[0] && route->has_track(*link));
170                                         }
171                                 }
172                         }
173
174                         if(start_new_route)
175                         {
176                                 route = new Route(j->info->train->get_layout());
177                                 route->set_name("Router");
178                                 route->set_temporary(true);
179                                 for(unsigned k=0; (k<2 && history[k]); ++k)
180                                         route->add_track(*history[k]);
181                                 j->info->routes.push_front(route);
182                         }
183
184                         route->add_track(*j->track.track());
185                         history[1] = history[0];
186                         history[0] = j->track.track();
187
188                         bool waitable = j->track.endpoint().paths!=j->track->get_type().get_paths();
189                         map<Track *, TrainRouter::SequencePoint *>::iterator k = sequenced_tracks.find(j->track.track());
190                         if(k!=sequenced_tracks.end())
191                         {
192                                 if(!k->second->preceding_train)
193                                 {
194                                         k->second->preceding_train = j->info->train;
195                                         k->second->sequence_in = sequence;
196                                 }
197                                 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
198                                 if(waitable)
199                                         k->second = &j->info->sequence.front();
200                                 --sequence;
201                         }
202                         else if(waitable)
203                         {
204                                 j->info->sequence.push_front(TrainRouter::SequencePoint(j->track->get_block(), sequence));
205                                 sequenced_tracks[j->track.track()] = &j->info->sequence.front();
206                                 --sequence;
207                         }
208                 }
209
210         result = COMPLETE;
211 }
212
213
214 TrainRoutePlanner::TrainRoutingInfo::TrainRoutingInfo(Train &t):
215         train(&t),
216         speed(train->get_maximum_speed()),
217         first_noncritical(train->get_first_noncritical_block().block()),
218         router(train->get_ai_of_type<TrainRouter>()),
219         waypoints(router ? router->get_n_waypoints() : 0),
220         has_duration(false)
221 {
222         if(!waypoints.empty())
223         {
224                 metrics.resize(waypoints.size());
225                 for(unsigned i=0; i<waypoints.size(); ++i)
226                 {
227                         waypoints[i] = &router->get_waypoint(i);
228                         metrics[i] = &router->get_metric(i);
229                 }
230                 has_duration = router->get_trip_duration();
231         }
232
233         // If no maximum speed is specified, use a sensible default
234         if(!speed)
235                 speed = 20*train->get_layout().get_catalogue().get_scale();
236 }
237
238
239 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(Track &t, unsigned p, OccupiedTrack *n):
240         track(&t),
241         path_length(track->get_type().get_path_length(p)),
242         next(n),
243         n_tracks(next ? next->n_tracks+1 : 1),
244         refcount(1)
245 {
246         if(next)
247                 ++next->refcount;
248 }
249
250 TrainRoutePlanner::OccupiedTrack::OccupiedTrack(const OccupiedTrack &other):
251         track(other.track),
252         path_length(other.path_length),
253         next(other.next),
254         n_tracks(other.n_tracks),
255         refcount(1)
256 {
257         if(next)
258                 ++next->refcount;
259 }
260
261 TrainRoutePlanner::OccupiedTrack::~OccupiedTrack()
262 {
263         if(next && !--next->refcount)
264                 delete next;
265 }
266
267
268 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(TrainRoutingInfo &inf):
269         info(&inf),
270         critical(true),
271         occupied_tracks(0),
272         state(MOVING),
273         delay(info->router->get_departure_delay()),
274         duration(info->router->get_trip_duration()),
275         waypoint(0),
276         blocked_by(-1)
277 {
278         const Vehicle *veh = &info->train->get_vehicle(0);
279         // TODO margins
280         TrackOffsetIter track_and_offs = veh->get_placement().get_position(VehiclePlacement::FRONT_BUFFER);
281         track = track_and_offs.track_iter();
282         offset = track_and_offs.offset();
283         path = track->get_active_path();
284
285         while(Vehicle *next = veh->get_link(1))
286                 veh = next;
287         track_and_offs = veh->get_placement().get_position(VehiclePlacement::BACK_BUFFER);
288         back_offset = track_and_offs.offset();
289
290         TrackIter iter = track_and_offs.track_iter();
291         while(1)
292         {
293                 occupied_tracks = new OccupiedTrack(*iter, iter->get_active_path(), occupied_tracks);
294                 if(iter.track()==track.track())
295                         break;
296                 iter = iter.next();
297         }
298
299         update_estimate();
300 }
301
302 TrainRoutePlanner::TrainRoutingState::TrainRoutingState(const TrainRoutingState &other):
303         info(other.info),
304         track(other.track),
305         path(other.path),
306         critical(other.critical),
307         occupied_tracks(other.occupied_tracks),
308         offset(other.offset),
309         back_offset(other.back_offset),
310         state(other.state),
311         delay(other.delay),
312         duration(other.duration),
313         waypoint(other.waypoint),
314         distance_traveled(other.distance_traveled),
315         remaining_estimate(other.remaining_estimate),
316         wait_time(other.wait_time),
317         blocked_by(other.blocked_by)
318 {
319         ++occupied_tracks->refcount;
320 }
321
322 TrainRoutePlanner::TrainRoutingState::~TrainRoutingState()
323 {
324         if(occupied_tracks && !--occupied_tracks->refcount)
325                 delete occupied_tracks;
326 }
327
328 Time::TimeDelta TrainRoutePlanner::TrainRoutingState::get_time_to_next_track() const
329 {
330         return ((track->get_type().get_path_length(path)-offset)/info->speed)*Time::sec+delay;
331 }
332
333 bool TrainRoutePlanner::TrainRoutingState::is_occupying(Track &trk) const
334 {
335         if(state==ARRIVED && !duration && info->has_duration)
336                 return false;
337
338         OccupiedTrack *occ = occupied_tracks;
339         for(unsigned n=occ->n_tracks; n>0; --n, occ=occ->next)
340                 if(occ->track==&trk)
341                         return true;
342         return false;
343 }
344
345 bool TrainRoutePlanner::TrainRoutingState::check_arrival()
346 {
347         TrackIter next_track = track.next(path);
348
349         const TrackChain *wp_chain = info->waypoints[waypoint];
350         if(wp_chain->has_track(*track) && !wp_chain->has_track(*next_track))
351         {
352                 if(waypoint+1<info->waypoints.size())
353                         ++waypoint;
354                 else
355                 {
356                         state = ARRIVED;
357                         return true;
358                 }
359         }
360
361         if(info->first_noncritical->has_track(*track))
362                 critical = false;
363
364         return false;
365 }
366
367 void TrainRoutePlanner::TrainRoutingState::advance(float distance)
368 {
369         offset += distance;
370         back_offset += distance;
371
372         unsigned count_to_free = 0;
373         unsigned last_sensor_addr = 0;
374         float distance_after_sensor = 0;
375         OccupiedTrack *occ = occupied_tracks;
376         for(unsigned n=occupied_tracks->n_tracks; n>0; --n)
377         {
378                 if(unsigned saddr = occ->track->get_sensor_address())
379                 {
380                         if(saddr!=last_sensor_addr)
381                         {
382                                 count_to_free = 0;
383                                 distance_after_sensor = 0;
384                         }
385                         last_sensor_addr = saddr;
386                 }
387
388                 ++count_to_free;
389                 distance_after_sensor += occ->path_length;
390
391                 occ = occ->next;
392         }
393
394         if(count_to_free && back_offset>distance_after_sensor)
395         {
396                 back_offset -= distance_after_sensor;
397                 if(occupied_tracks->refcount>1)
398                 {
399                         --occupied_tracks->refcount;
400                         occupied_tracks = new OccupiedTrack(*occupied_tracks);
401                 }
402                 occupied_tracks->n_tracks -= count_to_free;
403         }
404
405         distance_traveled += distance;
406         remaining_estimate -= distance;
407 }
408
409 void TrainRoutePlanner::TrainRoutingState::advance(const Time::TimeDelta &dt)
410 {
411         if(delay>=dt)
412         {
413                 delay -= dt;
414                 return;
415         }
416
417         float secs = dt/Time::sec;
418         if(delay)
419         {
420                 secs -= delay/Time::sec;
421                 delay = Time::zero;
422         }
423
424         if(duration)
425                 duration = max(duration-secs*Time::sec, Time::zero);
426
427         if(state==MOVING)
428                 advance(info->speed*secs);
429         else if(state!=ARRIVED)
430                 wait_time += secs*Time::sec;
431 }
432
433 void TrainRoutePlanner::TrainRoutingState::advance_track(unsigned next_path)
434 {
435         float distance = occupied_tracks->path_length-offset;
436         track = track.next(path);
437         path = next_path;
438         occupied_tracks = new OccupiedTrack(*track, path, occupied_tracks);
439         advance(distance);
440         offset = 0;
441 }
442
443 void TrainRoutePlanner::TrainRoutingState::update_estimate()
444 {
445         TrackIter iter = track.reverse(path);
446         float distance = info->metrics[waypoint]->get_distance_from(*iter.track(), iter.entry());
447         distance += track->get_type().get_path_length(path)-offset;
448         remaining_estimate = distance;
449 }
450
451 bool TrainRoutePlanner::TrainRoutingState::is_viable() const
452 {
453         if(remaining_estimate<0)
454                 return false;
455         if(critical && state==BLOCKED)
456                 return false;
457         return true;
458 }
459
460
461 TrainRoutePlanner::RoutingStep::RoutingStep():
462         prev(0)
463 { }
464
465 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
466         time(p->time),
467         penalty(p->penalty),
468         cost_estimate(p->cost_estimate),
469         trains(p->trains),
470         prev(p)
471 { }
472
473 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
474 {
475         RoutingStep next(this);
476         if(next.update_states())
477         {
478                 if(next.check_deadlocks())
479                         return;
480
481                 new_steps.push_back(next);
482                 return;
483         }
484
485         int train_index = find_next_train();
486         if(train_index<0)
487                 return;
488
489         TrainRoutingState &train = next.trains[train_index];
490
491         Time::TimeDelta dt = train.get_time_to_next_track();
492         next.advance(dt);
493
494         if(train.check_arrival())
495         {
496                 new_steps.push_back(next);
497                 return;
498         }
499
500         train.advance_track(0);
501
502         const TrackType::Endpoint &entry_ep = train.track.endpoint();
503         if(train.critical)
504         {
505                 train.path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
506                 train.update_estimate();
507                 next.update_estimate();
508                 if(next.is_viable())
509                         new_steps.push_back(next);
510         }
511         else
512         {
513                 for(unsigned i=0; entry_ep.paths>>i; ++i)
514                         if(entry_ep.has_path(i))
515                         {
516                                 train.path = i;
517                                 train.update_estimate();
518                                 next.update_estimate();
519                                 if(next.is_viable())
520                                         new_steps.push_back(next);
521                         }
522         }
523
524         new_steps.sort();
525         for(list<RoutingStep>::iterator i=new_steps.begin(); ++i!=new_steps.end(); )
526         {
527                 i->penalty += 5*Time::sec;
528                 i->update_estimate();
529         }
530
531         if(entry_ep.paths!=train.track->get_type().get_paths() && !train.critical)
532         {
533                 RoutingStep wait(this);
534                 wait.advance(dt);
535                 wait.trains[train_index].state = WAITING;
536                 wait.penalty += 15*Time::sec;
537                 wait.update_estimate();
538                 if(wait.is_viable())
539                         new_steps.push_back(wait);
540         }
541 }
542
543 bool TrainRoutePlanner::RoutingStep::update_states()
544 {
545         bool changes = false;
546         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
547         {
548                 if(i->state==ARRIVED)
549                         continue;
550
551                 TrainState old_state = i->state;
552
553                 TrackIter next_track = i->track.next(i->path);
554                 if(next_track)
555                 {
556                         i->blocked_by = get_occupant(*next_track);
557                         if(i->blocked_by>=0)
558                         {
559                                 if(i->info->first_noncritical->has_track(*next_track))
560                                         i->critical = false;
561                                 i->state = BLOCKED;
562                         }
563                         else if(i->state==BLOCKED)
564                                 i->state = MOVING;
565                 }
566                 else
567                         i->state = BLOCKED;
568
569                 if(i->state!=old_state)
570                         changes = true;
571         }
572
573         return changes;
574 }
575
576 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
577 {
578         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
579         {
580                 if(i->state!=BLOCKED)
581                         continue;
582
583                 if(i->blocked_by<0)
584                         return true;
585
586                 int slow = i->blocked_by;
587                 int fast = trains[slow].blocked_by;
588                 while(fast>=0 && trains[fast].blocked_by>=0)
589                 {
590                         if(fast==slow)
591                                 return true;
592
593                         slow = trains[slow].blocked_by;
594                         fast = trains[trains[fast].blocked_by].blocked_by;
595                 }
596         }
597
598         return false;
599 }
600
601 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
602 {
603         for(unsigned i=0; i<trains.size(); ++i)
604                 if(trains[i].is_occupying(track))
605                         return i;
606
607         return -1;
608 }
609
610 int TrainRoutePlanner::RoutingStep::find_next_train() const
611 {
612         Time::TimeDelta min_dt;
613         int next_train = -1;
614         for(unsigned i=0; i<trains.size(); ++i)
615                 if(trains[i].state==MOVING)
616                 {
617                         Time::TimeDelta dt = trains[i].get_time_to_next_track();
618                         if(dt<min_dt || next_train<0)
619                         {
620                                 min_dt = dt;
621                                 next_train = i;
622                         }
623                 }
624
625         return next_train;
626 }
627
628 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
629 {
630         time += dt;
631         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
632                 i->advance(dt);
633 }
634
635 void TrainRoutePlanner::RoutingStep::update_estimate()
636 {
637         cost_estimate = penalty;
638         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
639                 if(i->remaining_estimate>=0)
640                         cost_estimate += i->wait_time+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
641 }
642
643 bool TrainRoutePlanner::RoutingStep::is_viable() const
644 {
645         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
646                 if(!i->is_viable())
647                         return false;
648
649         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
650                 if(i->state==MOVING)
651                         return true;
652
653         return false;
654 }
655
656 bool TrainRoutePlanner::RoutingStep::is_goal() const
657 {
658         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
659                 if(i->state!=ARRIVED)
660                         return false;
661         return true;
662 }
663
664 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
665 {
666         return cost_estimate<other.cost_estimate;
667 }
668
669
670 TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
671         planner(p)
672 {
673         launch();
674 }
675
676 void TrainRoutePlanner::PlanningThread::main()
677 {
678         planner.create_plan();
679 }
680
681 } // namespace R2C2