]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouter.cpp
Set delay to zero before emitting signal_departed
[r2c2.git] / source / libr2c2 / trainrouter.cpp
1 #include "driver.h"
2 #include "layout.h"
3 #include "route.h"
4 #include "trackiter.h"
5 #include "train.h"
6 #include "trackchain.h"
7 #include "trainroutemetric.h"
8 #include "trainrouteplanner.h"
9 #include "trainrouter.h"
10
11 using namespace std;
12 using namespace Msp;
13
14 namespace R2C2 {
15
16 TrainRouter::TrainRouter(Train &t):
17         TrainAI(t),
18         priority(0),
19         state(ON_THE_WAY),
20         waypoints_changed(false),
21         metrics_stale(false),
22         current_sequence(0)
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
52         route_changed();
53
54         return true;
55 }
56
57 const Route *TrainRouter::get_route() const
58 {
59         if(routes.empty())
60                 return 0;
61         return routes.front();
62 }
63
64 void TrainRouter::use_planned_route()
65 {
66         if(!planner || planner->get_result()!=TrainRoutePlanner::COMPLETE)
67                 return;
68         if(waypoints.empty())
69                 return;
70
71         const list<Route *> &planned_routes = planner->get_routes_for(train);
72
73         routes.clear();
74         routes.insert(routes.end(), planned_routes.begin(), planned_routes.end());
75         create_lead_route();
76
77         sequence_points = planner->get_sequence_for(train);
78         current_sequence = 0;
79
80         route_changed();
81 }
82
83 void TrainRouter::route_changed()
84 {
85         BlockIter fncb = train.get_last_critical_block().next();
86
87         state = ON_THE_WAY;
88         reserving_route = routes.begin();
89         if(!routes.empty())
90         {
91                 /* Find the route that should be used for the next allocated block.  We
92                 can't rely on the resync code in block_reserved since we may need to
93                 clear the stop marker to continue allocation. */
94                 const BlockAllocator &allocator = train.get_block_allocator();
95                 TrackIter track = allocator.first().track_iter();
96                 list<SequencePoint>::iterator seq_begin = sequence_points.begin();
97                 for(; track; track=track.next())
98                 {
99                         if(!advance_to_track(reserving_route, track))
100                         {
101                                 state = (allocator.is_block_current(track->get_block()) ? ADVANCED_TO_END : RESERVED_TO_END);
102                                 break;
103                         }
104                         if(&track->get_block()==fncb.block())
105                                 break;
106
107                         if(seq_begin!=sequence_points.end() && seq_begin->block==&track->get_block())
108                         {
109                                 // Assume any sequence points within critical blocks to be cleared
110                                 current_sequence = seq_begin->sequence_out;
111                                 ++seq_begin;
112                         }
113                 }
114
115                 sequence_points.erase(sequence_points.begin(), seq_begin);
116
117                 if(!sequence_points.empty())
118                 {
119                         const SequencePoint &sp = sequence_points.front();
120                         if(sp.block==fncb.block() && !sp.is_cleared())
121                                 state = SEQUENCE_CHECK_PENDING;
122                 }
123         }
124
125         /* Refresh from the first non-critical block to pick up any changes in the
126         route.  Set stop marker first in case a stopping state was set within the
127         critical blocks. */
128         if(state!=ON_THE_WAY)
129                 train.stop_at(&*fncb.flip());
130         train.refresh_blocks_from(*fncb);
131         // If we don't need to stop, clear a possible previous stop marker.
132         if(state==ON_THE_WAY)
133                 train.stop_at(0);
134
135         const Route *route = get_route();
136         signal_route_changed.emit(route);
137         signal_event.emit(Message("route-changed", route));
138 }
139
140 void TrainRouter::set_destination(const TrackChain &d)
141 {
142         if(waypoints.empty())
143                 waypoints.push_back(Waypoint(d));
144         else
145                 waypoints.back() = Waypoint(d);
146         waypoints_changed = true;
147         metrics_stale = true;
148 }
149
150 void TrainRouter::add_waypoint(const TrackChain &chain, TrackChain::Direction dir)
151 {
152         waypoints.push_back(Waypoint(chain, dir));
153         waypoints_changed = true;
154         metrics_stale = true;
155 }
156
157 const TrainRouter::Waypoint &TrainRouter::get_waypoint(unsigned index) const
158 {
159         if(index>=waypoints.size())
160                 throw out_of_range("TrainRouter::is_waypoint");
161
162         return waypoints[index];
163 }
164
165 const TrainRouteMetric &TrainRouter::get_metric(int index) const
166 {
167         if(waypoints.empty())
168                 throw logic_error("no metrics");
169         else if(metrics_stale)
170                 throw logic_error("metrics are stale");
171
172         if(index<0)
173                 return *metrics.back();
174         else if(static_cast<unsigned>(index)>=waypoints.size())
175                 throw out_of_range("TrainRouter::get_metric");
176         else
177                 return *metrics[index];
178 }
179
180 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
181 {
182         delay = d;
183         waypoints_changed = true;
184 }
185
186 void TrainRouter::set_trip_duration(const Time::TimeDelta &d)
187 {
188         duration = d;
189 }
190
191 void TrainRouter::message(const Message &msg)
192 {
193         if(msg.type=="set-route")
194         {
195                 if(msg.value.check_type<Route *>())
196                         set_route(msg.value.value<Route *>());
197                 else
198                         set_route(msg.value.value<const Route *>());
199         }
200         else if(msg.type=="clear-route")
201                 set_route(0);
202         else if(msg.type=="set-destination")
203         {
204                 if(msg.value.check_type<TrackChain *>())
205                         set_destination(*msg.value.value<TrackChain *>());
206                 else
207                         set_destination(*msg.value.value<const TrackChain *>());
208         }
209         else if(msg.type=="add-waypoint")
210         {
211                 if(msg.value.check_type<Waypoint>())
212                 {
213                         Waypoint wp = msg.value.value<Waypoint>();
214                         add_waypoint(*wp.chain, wp.direction);
215                 }
216                 else if(msg.value.check_type<TrackChain *>())
217                         add_waypoint(*msg.value.value<TrackChain *>());
218                 else
219                         add_waypoint(*msg.value.value<const TrackChain *>());
220         }
221         else if(msg.type=="set-departure-delay")
222                 set_departure_delay(msg.value.value<Time::TimeDelta>());
223         else if(msg.type=="set-trip-duration")
224                 set_trip_duration(msg.value.value<Time::TimeDelta>());
225 }
226
227 void TrainRouter::tick(const Time::TimeDelta &dt)
228 {
229         if(waypoints_changed && !planner)
230                 start_planning(train.get_layout());
231
232         if(planner && planner->check()!=TrainRoutePlanner::PENDING)
233                 apply_plan(train.get_layout(), *planner);
234
235         Layout &layout = train.get_layout();
236         if(!layout.get_driver().is_halted() && !layout.get_clock().is_stopped())
237         {
238                 if(delay)
239                 {
240                         delay -= dt;
241                         if(delay<Time::zero)
242                         {
243                                 duration = max(duration+delay, Time::zero);
244                                 delay = Time::zero;
245                                 train.ai_message(Message("set-target-speed", train.get_maximum_speed()));
246                                 signal_departed.emit();
247                                 signal_event.emit(Message("departed"));
248                         }
249                 }
250                 else if(duration)
251                         duration = max(duration-dt, Time::zero);
252         }
253
254         if(state==SEQUENCE_CHECK_PENDING)
255         {
256                 if(sequence_points.front().is_cleared())
257                 {
258                         state = ON_THE_WAY;
259                         train.stop_at(0);
260                 }
261                 else
262                         state = WAITING_FOR_SEQUENCE;
263         }
264
265         if(state==ADVANCED_TO_END && !train.get_speed())
266         {
267                 signal_arrived.emit(waypoints.back().chain);
268                 signal_event.emit(Message("arrived", waypoints.back().chain));
269                 state = ARRIVED;
270         }
271         else if(state==ARRIVED && !train.get_block_allocator().is_active())
272                 set_route(0);
273 }
274
275 void TrainRouter::save(list<DataFile::Statement> &st) const
276 {
277         st.push_back((DataFile::Statement("priority"), priority));
278
279         if(!routes.empty())
280         {
281                 RouteList::const_iterator i = routes.begin();
282                 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
283                 if(i!=routes.end())
284                         st.push_back((DataFile::Statement("route"), (*i)->get_name()));
285         }
286 }
287
288 void TrainRouter::block_reserved(Block &block, Train *t)
289 {
290         if(routes.empty())
291                 return;
292
293         if(t!=&train)
294         {
295                 if(!t)
296                         return;
297
298                 // Are we waiting for the other train to pass a sequence point?
299                 if(state==WAITING_FOR_SEQUENCE)
300                 {
301                         SequencePoint &sp = sequence_points.front();
302                         if(sp.preceding_train==t && sp.block==&block)
303                                 /* The other train's router will advance its sequence on the same
304                                 signal and may not have handled it yet. */
305                                 state = SEQUENCE_CHECK_PENDING;
306                 }
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                 state = 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                         state = 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                 {
369                         state = SEQUENCE_CHECK_PENDING;
370                         train.stop_at(&block);
371                 }
372         }
373 }
374
375 void TrainRouter::train_advanced(Block &block)
376 {
377         if(!waypoints.empty())
378         {
379                 // A waypoint is considered reached when the train has advanced through it.
380                 BlockIter b_iter = train.get_block_allocator().iter_for(block);
381                 const Waypoint &wp = waypoints.front();
382                 TrackIter t_iter = b_iter.track_iter();
383                 if(wp.chain->has_track(*t_iter))
384                 {
385                         while(1)
386                         {
387                                 TrackIter next = t_iter.next();
388                                 if(!next)
389                                         break;
390
391                                 if(!wp.chain->has_track(*next))
392                                 {
393                                         if(wp.direction!=TrackChain::UNSPECIFIED)
394                                                 if(t_iter!=wp.chain->iter_for(*t_iter, wp.direction))
395                                                         break;
396
397                                         if(waypoints.size()==1)
398                                         {
399                                                 if(state==RESERVED_TO_END)
400                                                         state = ADVANCED_TO_END;
401                                         }
402                                         else
403                                         {
404                                                 const TrackChain *chain = wp.chain;
405                                                 waypoints.erase(waypoints.begin());
406                                                 metrics_stale = true;
407                                                 signal_waypoint_reached.emit(chain);
408                                                 signal_event.emit(Message("waypoint-reached", chain));
409                                         }
410                                         break;
411                                 }
412                                 else if(!block.has_track(*next))
413                                         break;
414
415                                 t_iter = next;
416                         }
417                 }
418         }
419 }
420
421 void TrainRouter::train_rear_advanced(Block &block)
422 {
423         Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
424
425         // Drop any routes that are now completely behind the train.
426         for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
427                 if((*i)->has_track(track))
428                 {
429                         if(i!=routes.begin())
430                         {
431                                 routes.erase(routes.begin(), i);
432                                 const Route *route = get_route();
433                                 signal_route_changed.emit(route);
434                                 signal_event.emit(Message("route-changed", route));
435                         }
436                         break;
437                 }
438 }
439
440 void TrainRouter::create_metrics()
441 {
442         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
443                 delete *i;
444         metrics.clear();
445
446         metrics_stale = false;
447
448         if(waypoints.empty())
449                 return;
450
451         for(vector<Waypoint>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
452                 metrics.push_back(new TrainRouteMetric(*i->chain, i->direction));
453
454         for(unsigned i=metrics.size()-1; i-->0; )
455                 metrics[i]->chain_to(*metrics[i+1]);
456 }
457
458 bool TrainRouter::create_lead_route()
459 {
460         if(routes.empty() || !train.is_placed())
461                 return false;
462
463         BlockIter lcb = train.get_last_critical_block();
464         TrackIter last_track_rev = lcb.reverse().track_iter();
465
466         unsigned count = 0;
467         for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
468         {
469                 if(routes.front()->has_track(*i))
470                         ++count;
471                 else if(count>0)
472                 {
473                         if(count==routes.front()->get_tracks().size())
474                                 last_track_rev = i;
475                         break;
476                 }
477         }
478
479         TrackIter next_track = last_track_rev.flip();
480         if(!routes.front()->has_track(*last_track_rev) && !routes.front()->has_track(*next_track))
481         {
482                 Route *pf = Route::find(next_track, *routes.front());
483                 if(!pf)
484                         return false;
485
486                 routes.push_front(pf);
487         }
488
489         Route *lead = 0;
490         for(TrackIter i=last_track_rev; (i && i->get_block().get_train()==&train); i=i.next())
491         {
492                 if(!lead && !routes.front()->has_track(*i))
493                 {
494                         lead = new Route(train.get_layout());
495                         lead->set_name("Lead");
496                         lead->set_temporary(true);
497                         routes.push_front(lead);
498
499                         TrackIter j = i.flip();
500                         lead->add_track(*j);
501                         lead->add_track(*j.next());
502                 }
503
504                 if(lead)
505                         lead->add_track(*i);
506         }
507
508         return true;
509 }
510
511 bool TrainRouter::advance_to_track(RouteList::iterator &route, const TrackIter &track)
512 {
513         Track &prev_track = *track.flip();
514         unsigned taddr = (track->get_type().is_turnout() ? track->get_turnout_address() : 0);
515         for(unsigned i=0; route!=routes.end(); ++i)
516         {
517                 bool in_route = (*route)->has_track(*track);
518                 bool prev_in_route = (*route)->has_track(prev_track);
519                 bool known_path = (!taddr || (*route)->get_turnout(taddr)>=0);
520
521                 if(in_route && (known_path || !prev_in_route))
522                         return true;
523                 else if(i==0 || prev_in_route)
524                         ++route;
525                 else
526                         throw logic_error("internal error (routes are not continuous)");
527         }
528
529         return false;
530 }
531
532 void TrainRouter::get_routers(Layout &layout, vector<TrainRouter *> &routers, TrainRoutePlanner *planner)
533 {
534         const map<unsigned, Train *> &trains = layout.get_trains();
535         routers.reserve(trains.size());
536         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
537                 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
538                         if(!planner || router->planner.get()==planner)
539                                 routers.push_back(router);
540 }
541
542 void TrainRouter::start_planning(Layout &layout)
543 {
544         vector<TrainRouter *> routers;
545         get_routers(layout, routers);
546
547         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
548                 if((*i)->metrics_stale)
549                         (*i)->create_metrics();
550
551         RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
552         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
553         {
554                 (*i)->waypoints_changed = false;
555                 (*i)->planner = planner;
556         }
557
558         planner->plan_async();
559 }
560
561 void TrainRouter::apply_plan(Layout &layout, TrainRoutePlanner &planner)
562 {
563         if(planner.get_result()==TrainRoutePlanner::FAILED)
564                 layout.emergency(0, "Route planning failed");
565
566         vector<TrainRouter *> routers;
567         get_routers(layout, routers, &planner);
568
569         /* Clear sequence counters first to avoid inconsistent state while applying
570         the plan. */
571         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
572                 (*i)->current_sequence = 0;
573
574         for(vector<TrainRouter *>::const_iterator i=routers.begin(); i!=routers.end(); ++i)
575         {
576                 (*i)->use_planned_route();
577                 (*i)->planner = 0;
578         }
579 }
580
581
582 TrainRouter::Waypoint::Waypoint(const TrackChain &c, TrackChain::Direction d):
583         chain(&c),
584         direction(d)
585 { }
586
587
588 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
589         block(&b),
590         preceding_train(0),
591         sequence_in(0),
592         sequence_out(o)
593 { }
594
595 bool TrainRouter::SequencePoint::is_cleared() const
596 {
597         if(!preceding_train)
598                 return true;
599
600         TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
601         return router->get_current_sequence()>=sequence_in;
602 }
603
604
605 TrainRouter::Loader::Loader(TrainRouter &r):
606         DataFile::ObjectLoader<TrainRouter>(r)
607 {
608         add("priority", &TrainRouter::priority);
609         add("route",    &Loader::route);
610 }
611
612 void TrainRouter::Loader::route(const string &n)
613 {
614         obj.set_route(&obj.train.get_layout().get_route(n));
615 }
616
617 } // namespace R2C2