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