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