]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouteplanner.cpp
653cfda6d9f01fc1288722d8f1c6ca33e47634c6
[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
452 TrainRoutePlanner::RoutingStep::RoutingStep():
453         prev(0)
454 { }
455
456 TrainRoutePlanner::RoutingStep::RoutingStep(const RoutingStep *p):
457         time(p->time),
458         penalty(p->penalty),
459         cost_estimate(p->cost_estimate),
460         trains(p->trains),
461         prev(p)
462 { }
463
464 void TrainRoutePlanner::RoutingStep::create_successors(list<RoutingStep> &new_steps) const
465 {
466         RoutingStep next(this);
467         if(next.update_states())
468         {
469                 if(next.check_deadlocks())
470                         return;
471
472                 new_steps.push_back(next);
473                 return;
474         }
475
476         int train_index = find_next_train();
477         if(train_index<0)
478                 return;
479
480         TrainRoutingState &train = next.trains[train_index];
481
482         Time::TimeDelta dt = train.get_time_to_next_track();
483         next.advance(dt);
484
485         if(train.check_arrival())
486         {
487                 new_steps.push_back(next);
488                 return;
489         }
490
491         train.advance_track(0);
492
493         const TrackType::Endpoint &entry_ep = train.track.endpoint();
494         if(train.critical)
495         {
496                 train.path = train.track->get_type().coerce_path(train.track.entry(), train.track->get_active_path());
497                 train.update_estimate();
498                 next.update_estimate();
499                 if(next.is_viable())
500                         new_steps.push_back(next);
501         }
502         else
503         {
504                 for(unsigned i=0; entry_ep.paths>>i; ++i)
505                         if(entry_ep.has_path(i))
506                         {
507                                 train.path = i;
508                                 train.update_estimate();
509                                 next.update_estimate();
510                                 if(next.is_viable())
511                                         new_steps.push_back(next);
512                         }
513         }
514
515         new_steps.sort();
516         for(list<RoutingStep>::iterator i=new_steps.begin(); ++i!=new_steps.end(); )
517         {
518                 i->penalty += 5*Time::sec;
519                 i->update_estimate();
520         }
521
522         if(entry_ep.paths!=train.track->get_type().get_paths() && !train.critical)
523         {
524                 RoutingStep wait(this);
525                 wait.advance(dt);
526                 wait.trains[train_index].state = WAITING;
527                 wait.penalty += 15*Time::sec;
528                 wait.update_estimate();
529                 if(wait.is_viable())
530                         new_steps.push_back(wait);
531         }
532 }
533
534 bool TrainRoutePlanner::RoutingStep::update_states()
535 {
536         bool changes = false;
537         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
538         {
539                 if(i->state==ARRIVED)
540                         continue;
541
542                 TrainState old_state = i->state;
543
544                 TrackIter next_track = i->track.next(i->path);
545                 if(next_track)
546                 {
547                         i->blocked_by = get_occupant(*next_track);
548                         if(i->blocked_by>=0)
549                                 i->state = BLOCKED;
550                         else if(i->state==BLOCKED)
551                                 i->state = MOVING;
552                 }
553                 else
554                         i->state = BLOCKED;
555
556                 if(i->state!=old_state)
557                         changes = true;
558         }
559
560         return changes;
561 }
562
563 bool TrainRoutePlanner::RoutingStep::check_deadlocks() const
564 {
565         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
566         {
567                 if(i->state!=BLOCKED)
568                         continue;
569
570                 if(i->blocked_by<0)
571                         return true;
572
573                 int slow = i->blocked_by;
574                 int fast = trains[slow].blocked_by;
575                 while(fast>=0 && trains[fast].blocked_by>=0)
576                 {
577                         if(fast==slow)
578                                 return true;
579
580                         slow = trains[slow].blocked_by;
581                         fast = trains[trains[fast].blocked_by].blocked_by;
582                 }
583         }
584
585         return false;
586 }
587
588 int TrainRoutePlanner::RoutingStep::get_occupant(Track &track) const
589 {
590         for(unsigned i=0; i<trains.size(); ++i)
591                 if(trains[i].is_occupying(track))
592                         return i;
593
594         return -1;
595 }
596
597 int TrainRoutePlanner::RoutingStep::find_next_train() const
598 {
599         Time::TimeDelta min_dt;
600         int next_train = -1;
601         for(unsigned i=0; i<trains.size(); ++i)
602                 if(trains[i].state==MOVING)
603                 {
604                         Time::TimeDelta dt = trains[i].get_time_to_next_track();
605                         if(dt<min_dt || next_train<0)
606                         {
607                                 min_dt = dt;
608                                 next_train = i;
609                         }
610                 }
611
612         return next_train;
613 }
614
615 void TrainRoutePlanner::RoutingStep::advance(const Time::TimeDelta &dt)
616 {
617         time += dt;
618         for(vector<TrainRoutingState>::iterator i=trains.begin(); i!=trains.end(); ++i)
619                 i->advance(dt);
620 }
621
622 void TrainRoutePlanner::RoutingStep::update_estimate()
623 {
624         cost_estimate = penalty;
625         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
626                 if(i->remaining_estimate>=0)
627                         cost_estimate += i->wait_time+((i->distance_traveled+i->remaining_estimate)/i->info->speed)*Time::sec;
628 }
629
630 bool TrainRoutePlanner::RoutingStep::is_viable() const
631 {
632         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
633                 if(i->remaining_estimate<0)
634                         return false;
635
636         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
637                 if(i->state==MOVING)
638                         return true;
639
640         return false;
641 }
642
643 bool TrainRoutePlanner::RoutingStep::is_goal() const
644 {
645         for(vector<TrainRoutingState>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
646                 if(i->state!=ARRIVED)
647                         return false;
648         return true;
649 }
650
651 bool TrainRoutePlanner::RoutingStep::operator<(const RoutingStep &other) const
652 {
653         return cost_estimate<other.cost_estimate;
654 }
655
656
657 TrainRoutePlanner::PlanningThread::PlanningThread(TrainRoutePlanner &p):
658         planner(p)
659 {
660         launch();
661 }
662
663 void TrainRoutePlanner::PlanningThread::main()
664 {
665         planner.create_plan();
666 }
667
668 } // namespace R2C2