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