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