]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouter.cpp
Store routing information in TrainRoutePlanner to avoid threading problems
[r2c2.git] / source / libr2c2 / trainrouter.cpp
1 #include "layout.h"
2 #include "route.h"
3 #include "trackiter.h"
4 #include "train.h"
5 #include "trackchain.h"
6 #include "trainroutemetric.h"
7 #include "trainrouteplanner.h"
8 #include "trainrouter.h"
9
10 using namespace std;
11 using namespace Msp;
12
13 namespace R2C2 {
14
15 TrainRouter::TrainRouter(Train &t):
16         TrainAI(t),
17         priority(0),
18         arrival(ON_THE_WAY),
19         destination(0),
20         destination_changed(false),
21         metrics_stale(false),
22         current_sequence(0),
23         sequence_check_pending(false)
24 {
25         train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
26         train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
27         train.signal_rear_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_rear_advanced));
28 }
29
30 TrainRouter::~TrainRouter()
31 {
32         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
33                 delete *i;
34 }
35
36 void TrainRouter::set_priority(int p)
37 {
38         priority = p;
39 }
40
41 bool TrainRouter::set_route(const Route *r)
42 {
43         BlockIter fncb = train.get_first_noncritical_block();
44
45         Route *lead = 0;
46         if(r && train.is_placed())
47         {
48                 const BlockAllocator &allocator = train.get_block_allocator();
49                 TrackIter first = allocator.first().track_iter();
50                 TrackIter next = fncb.track_iter();
51                 if(!r->has_track(*next))
52                 {
53                         lead = Route::find(next, *r);
54                         if(!lead)
55                                 return false;
56                         create_lead_route(lead, lead);
57                 }
58                 else if(!r->has_track(*first))
59                         lead = create_lead_route(0, r);
60         }
61
62         routes.clear();
63         if(lead)
64                 routes.push_back(lead);
65         // TODO Check if eclipsed by lead route
66         if(r)
67                 routes.push_back(r);
68
69         destination = 0;
70         waypoints.clear();
71         sequence_points.clear();
72         current_sequence = 0;
73         sequence_check_pending = false;
74
75         route_changed();
76
77         return true;
78 }
79
80 const Route *TrainRouter::get_route() const
81 {
82         if(routes.empty())
83                 return 0;
84         return routes.front();
85 }
86
87 void TrainRouter::route_changed()
88 {
89         BlockIter fncb = train.get_first_noncritical_block();
90
91         reserving_route = routes.begin();
92         bool already_at_end = false;
93         if(!routes.empty())
94         {
95                 /* Find the route that should be used for the next allocated block.  We
96                 can't rely on the resync code in block_reserved since we may need to
97                 clear the stop marker to continue allocation. */
98                 TrackIter track = train.get_block_allocator().first().track_iter();
99                 for(; track; track=track.next())
100                 {
101                         if(!advance_to_track(reserving_route, *track))
102                         {
103                                 already_at_end = true;
104                                 break;
105                         }
106                         if(&track->get_block()==fncb.block())
107                                 break;
108                 }
109         }
110
111         if(!already_at_end)
112         {
113                 // We are not at the end of the route now, but might have been before.
114                 arrival = ON_THE_WAY;
115                 train.refresh_blocks_from(*fncb);
116                 if(!arrival)
117                         train.stop_at(0);
118         }
119         else if(!arrival)
120         {
121                 /* If arrival wasn't set before (perhaps because we weren't on a route),
122                 set it now. */
123                 arrival = RESERVED_TO_END;
124                 train.stop_at(&*fncb.flip());
125                 train.refresh_blocks_from(*fncb);
126         }
127
128         const Route *route = get_route();
129         signal_route_changed.emit(route);
130         signal_event.emit(Message("route-changed", route));
131 }
132
133 void TrainRouter::set_destination(const TrackChain &d)
134 {
135         destination = &d;
136         destination_changed = true;
137         metrics_stale = true;
138 }
139
140 void TrainRouter::add_waypoint(const TrackChain &wp)
141 {
142         waypoints.push_back(&wp);
143         destination_changed = true;
144         metrics_stale = true;
145 }
146
147 const TrackChain &TrainRouter::get_waypoint(unsigned index) const
148 {
149         if(index>=waypoints.size())
150                 throw out_of_range("TrainRouter::is_waypoint");
151
152         return *waypoints[index];
153 }
154
155 const TrainRouteMetric &TrainRouter::get_metric(int index) const
156 {
157         if(!destination)
158                 throw logic_error("no metrics");
159         else if(metrics_stale)
160                 throw logic_error("metrics are stale");
161
162         if(index<0)
163                 return *metrics.front();
164         else if(static_cast<unsigned>(index)>=waypoints.size())
165                 throw out_of_range("TrainRouter::get_metric");
166         else
167                 return *metrics[index+1];
168 }
169
170 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
171 {
172         delay = d;
173         destination_changed = true;
174 }
175
176 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
177 {
178         duration = d;
179 }
180
181 void TrainRouter::message(const Message &msg)
182 {
183         if(msg.type=="set-route")
184         {
185                 if(msg.value.check_type<Route *>())
186                         set_route(msg.value.value<Route *>());
187                 else
188                         set_route(msg.value.value<const Route *>());
189         }
190         else if(msg.type=="clear-route")
191                 set_route(0);
192         else if(msg.type=="set-destination")
193         {
194                 if(msg.value.check_type<TrackChain *>())
195                         set_destination(*msg.value.value<TrackChain *>());
196                 else
197                         set_destination(*msg.value.value<const TrackChain *>());
198         }
199         else if(msg.type=="add-waypoint")
200         {
201                 if(msg.value.check_type<TrackChain *>())
202                         add_waypoint(*msg.value.value<TrackChain *>());
203                 else
204                         add_waypoint(*msg.value.value<const TrackChain *>());
205         }
206         else if(msg.type=="set-departure-delay")
207                 set_departure_delay(msg.value.value<Time::TimeDelta>());
208         else if(msg.type=="set-trip-duration")
209                 set_trip_duration(msg.value.value<Time::TimeDelta>());
210 }
211
212 void TrainRouter::tick(const Time::TimeDelta &dt)
213 {
214         if(delay)
215         {
216                 delay -= dt;
217                 if(delay<Time::zero)
218                 {
219                         duration = max(duration+delay, Time::zero);
220                         delay = Time::zero;
221                 }
222         }
223         else if(duration)
224                 duration = max(duration-dt, Time::zero);
225
226         if(destination_changed && !planner)
227                 start_planning(train.get_layout());
228
229         if(planner && planner->check()!=TrainRoutePlanner::PENDING)
230         {
231                 destination_changed = false;
232                 if(planner->get_result()==TrainRoutePlanner::COMPLETE)
233                 {
234                         const list<Route *> &planned_routes = planner->get_routes_for(train);
235
236                         routes.clear();
237                         Route *lead = create_lead_route(0, planned_routes.front());
238                         routes.push_back(lead);
239
240                         list<Route *>::const_iterator begin = planned_routes.begin();
241                         for(; begin!=planned_routes.end(); ++begin)
242                         {
243                                 const Route::TrackSet &tracks = (*begin)->get_tracks();
244                                 bool eclipsed = true;
245                                 for(Route::TrackSet::const_iterator i=tracks.begin(); (eclipsed && i!=tracks.end()); ++i)
246                                         eclipsed = lead->has_track(**i);
247                                 if(!eclipsed)
248                                         break;
249                         }
250                         routes.insert(routes.end(), begin, planned_routes.end());
251
252                         sequence_points = planner->get_sequence_for(train);
253                         current_sequence = 0;
254                         sequence_check_pending = false;
255
256                         route_changed();
257                 }
258                 planner = 0;
259         }
260
261         if(sequence_check_pending)
262         {
263                 if(sequence_points.front().is_cleared())
264                         train.stop_at(0);
265                 sequence_check_pending = false;
266         }
267
268         if(arrival==RESERVED_TO_END && !train.get_speed())
269         {
270                 signal_arrived.emit(destination);
271                 signal_event.emit(Message("arrived", destination));
272                 arrival = ARRIVED;
273         }
274         else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
275                 set_route(0);
276 }
277
278 void TrainRouter::save(list<DataFile::Statement> &st) const
279 {
280         st.push_back((DataFile::Statement("priority"), priority));
281
282         if(!routes.empty())
283         {
284                 RouteList::const_iterator i = routes.begin();
285                 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
286                 if(i!=routes.end())
287                         st.push_back((DataFile::Statement("route"), (*i)->get_name()));
288         }
289 }
290
291 void TrainRouter::block_reserved(Block &block, Train *t)
292 {
293         if(routes.empty())
294                 return;
295
296         if(t!=&train)
297         {
298                 if(!t)
299                         return;
300
301                 // Are we waiting for the other train to pass a sequence point?
302                 SequencePoint &sp = sequence_points.front();
303                 if(sp.preceding_train==t && sp.block==&block)
304                         /* The other train's router will advance its sequence on the same
305                         signal and may not have handled it yet. */
306                         sequence_check_pending = true;
307
308                 return;
309         }
310
311         // Did we reach our next sequence point?
312         if(!sequence_points.empty())
313         {
314                 SequencePoint &sp = sequence_points.front();
315                 if(sp.block==&block)
316                 {
317                         current_sequence = sp.sequence_out;
318                         sequence_points.pop_front();
319                 }
320         }
321
322         TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
323
324         // Is the block a turnout?  If it is, set it to the correct path.
325         if(unsigned taddr = block.get_turnout_address())
326         {
327                 int path = (*reserving_route)->get_turnout(taddr);
328                 if(path>=0)
329                         track->set_active_path(path);
330         }
331
332         /* If the allocator has released blocks from the front, we may need to
333         resync reserving_route. */
334         if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
335         {
336                 reserving_route = routes.begin();
337                 arrival = ON_THE_WAY;
338                 track = t->get_block_allocator().first().track_iter();
339                 for(; track; track=track.next())
340                 {
341                         if(!advance_to_track(reserving_route, *track))
342                                 throw logic_error("internal error (reservation outside of route)");
343                         else if(&track->get_block()==&block)
344                                 break;
345                 }
346         }
347
348         /* Keep reserving_route pointing to the route containing the block that is
349         expected to be allocated next. */
350         for(; track; track=track.next((*reserving_route)->get_path(*track)))
351         {
352                 if(!advance_to_track(reserving_route, *track))
353                 {
354                         // We've reached the end of the route.  Stop here.
355                         arrival = RESERVED_TO_END;
356                         train.stop_at(&block);
357                         return;
358                 }
359                 if(&track->get_block()!=&block)
360                         break;
361         }
362
363         // Do we need to wait for another train to pass?
364         if(!sequence_points.empty())
365         {
366                 SequencePoint &sp = sequence_points.front();
367                 if(sp.block==&track->get_block() && !sp.is_cleared())
368                         train.stop_at(&block);
369         }
370 }
371
372 void TrainRouter::train_advanced(Block &block)
373 {
374         BlockIter b_iter = train.get_block_allocator().iter_for(block);
375
376         if(!waypoints.empty())
377         {
378                 // A waypoint is considered reached when the train has advanced through it.
379                 const TrackChain &wp = *waypoints.front();
380                 TrackIter t_iter = b_iter.track_iter();
381                 if(wp.has_track(*t_iter))
382                 {
383                         for(; t_iter; t_iter=t_iter.next())
384                         {
385                                 if(!wp.has_track(*t_iter))
386                                 {
387                                         waypoints.erase(waypoints.begin());
388                                         signal_waypoint_reached.emit(&wp);
389                                         signal_event.emit(Message("waypoint-reached", &wp));
390                                         break;
391                                 }
392                                 else if(!block.has_track(*t_iter))
393                                         break;
394                         }
395                 }
396         }
397 }
398
399 void TrainRouter::train_rear_advanced(Block &block)
400 {
401         Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
402
403         // Drop any routes that are now completely behind the train.
404         for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
405                 if((*i)->has_track(track))
406                 {
407                         if(i!=routes.begin())
408                         {
409                                 routes.erase(routes.begin(), i);
410                                 const Route *route = get_route();
411                                 signal_route_changed.emit(route);
412                                 signal_event.emit(Message("route-changed", route));
413                         }
414                         break;
415                 }
416 }
417
418 void TrainRouter::create_metrics()
419 {
420         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
421                 delete *i;
422         metrics.clear();
423
424         if(!destination)
425                 return;
426
427         metrics.push_back(new TrainRouteMetric(*destination));
428         for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
429                 metrics.push_back(new TrainRouteMetric(**i));
430
431         for(unsigned i=metrics.size(); --i>0; )
432                 metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
433
434         metrics_stale = false;
435 }
436
437 Route *TrainRouter::create_lead_route(Route *lead, const Route *target)
438 {
439         if(!lead)
440         {
441                 lead = new Route(train.get_layout());
442                 lead->set_name("Lead");
443                 lead->set_temporary(true);
444         }
445
446         bool target_tracks = 0;
447         for(TrackIter i=train.get_block_allocator().first().track_iter(); (target_tracks<2 && i); i=i.next())
448         {
449                 if(i->get_block().get_train()!=&train)
450                         break;
451                 if(target)
452                 {
453                         if(target->has_track(*i))
454                                 ++target_tracks;
455                         else if(target_tracks>0)
456                                 break;
457                 }
458                 lead->add_track(*i);
459         }
460
461         return lead;
462 }
463
464 bool TrainRouter::is_valid_for_track(const Route &route, Track &track) const
465 {
466         if(!route.has_track(track))
467                 return false;
468         if(track.get_type().is_turnout() && route.get_turnout(track.get_turnout_address())<0)
469                 return false;
470         return true;
471 }
472
473 bool TrainRouter::advance_to_track(RouteList::iterator &route, Track &track)
474 {
475         if(!is_valid_for_track(**route, track))
476         {
477                 ++route;
478                 if(route==routes.end())
479                         return false;
480                 if(!is_valid_for_track(**route, track))
481                         throw logic_error("internal error (routes are not continuous)");
482         }
483
484         return true;
485 }
486
487 void TrainRouter::start_planning(Layout &layout)
488 {
489         vector<TrainRouter *> routers;
490         const map<unsigned, Train *> &trains = layout.get_trains();
491         routers.reserve(trains.size());
492         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
493                 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
494                         routers.push_back(router);
495
496         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
497                 if((*i)->metrics_stale)
498                         (*i)->create_metrics();
499
500         RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
501         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
502                 (*i)->planner = planner;
503
504         planner->plan_async();
505 }
506
507
508 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
509         block(&b),
510         preceding_train(0),
511         sequence_in(0),
512         sequence_out(o)
513 { }
514
515 bool TrainRouter::SequencePoint::is_cleared() const
516 {
517         if(!preceding_train)
518                 return true;
519
520         TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
521         return router->get_current_sequence()>=sequence_in;
522 }
523
524
525 TrainRouter::Loader::Loader(TrainRouter &r):
526         DataFile::ObjectLoader<TrainRouter>(r)
527 {
528         add("priority", &TrainRouter::priority);
529         add("route",    &Loader::route);
530 }
531
532 void TrainRouter::Loader::route(const string &n)
533 {
534         obj.set_route(&obj.train.get_layout().get_route(n));
535 }
536
537 } // namespace R2C2