]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouter.cpp
Skip routes that are completely covered by the lead route
[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 bool TrainRouter::is_destination(Track &track) const
141 {
142         if(destination)
143                 return destination->has_track(track);
144         else
145                 return false;
146 }
147
148 void TrainRouter::add_waypoint(const TrackChain &wp)
149 {
150         waypoints.push_back(&wp);
151         destination_changed = true;
152         metrics_stale = true;
153 }
154
155 bool TrainRouter::is_waypoint(unsigned index, Track &track) const
156 {
157         if(index>=waypoints.size())
158                 throw out_of_range("TrainRouter::is_waypoint");
159
160         return waypoints[index]->has_track(track);
161 }
162
163 const TrainRouteMetric &TrainRouter::get_metric(int index) const
164 {
165         if(!destination)
166                 throw logic_error("no metrics");
167         else if(metrics_stale)
168                 throw logic_error("metrics are stale");
169
170         if(index<0)
171                 return *metrics.front();
172         else if(static_cast<unsigned>(index)>=waypoints.size())
173                 throw out_of_range("TrainRouter::get_metric");
174         else
175                 return *metrics[index+1];
176 }
177
178 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
179 {
180         delay = d;
181         destination_changed = true;
182 }
183
184 void TrainRouter::message(const Message &msg)
185 {
186         if(msg.type=="set-route")
187         {
188                 if(msg.value.check_type<Route *>())
189                         set_route(msg.value.value<Route *>());
190                 else
191                         set_route(msg.value.value<const Route *>());
192         }
193         else if(msg.type=="clear-route")
194                 set_route(0);
195         else if(msg.type=="set-destination")
196         {
197                 if(msg.value.check_type<TrackChain *>())
198                         set_destination(*msg.value.value<TrackChain *>());
199                 else
200                         set_destination(*msg.value.value<const TrackChain *>());
201         }
202         else if(msg.type=="add-waypoint")
203         {
204                 if(msg.value.check_type<TrackChain *>())
205                         add_waypoint(*msg.value.value<TrackChain *>());
206                 else
207                         add_waypoint(*msg.value.value<const TrackChain *>());
208         }
209         else if(msg.type=="set-departure-delay")
210                 set_departure_delay(msg.value.value<Time::TimeDelta>());
211 }
212
213 void TrainRouter::tick(const Time::TimeDelta &dt)
214 {
215         if(delay)
216         {
217                 delay -= dt;
218                 if(delay<=Time::zero)
219                         delay = Time::zero;
220         }
221
222         if(destination_changed && !planner)
223                 start_planning(train.get_layout());
224
225         if(planner && planner->get_result()!=TrainRoutePlanner::PENDING)
226         {
227                 destination_changed = false;
228                 if(planner->get_result()==TrainRoutePlanner::COMPLETE)
229                 {
230                         const list<Route *> &planned_routes = planner->get_routes_for(train);
231
232                         routes.clear();
233                         Route *lead = create_lead_route(0, planned_routes.front());
234                         routes.push_back(lead);
235
236                         list<Route *>::const_iterator begin = planned_routes.begin();
237                         for(; begin!=planned_routes.end(); ++begin)
238                         {
239                                 const Route::TrackSet &tracks = (*begin)->get_tracks();
240                                 bool eclipsed = true;
241                                 for(Route::TrackSet::const_iterator i=tracks.begin(); (eclipsed && i!=tracks.end()); ++i)
242                                         eclipsed = lead->has_track(**i);
243                                 if(!eclipsed)
244                                         break;
245                         }
246                         routes.insert(routes.end(), begin, planned_routes.end());
247
248                         sequence_points = planner->get_sequence_for(train);
249                         current_sequence = 0;
250                         sequence_check_pending = false;
251
252                         route_changed();
253                 }
254                 planner = 0;
255         }
256
257         if(sequence_check_pending)
258         {
259                 if(sequence_points.front().is_cleared())
260                         train.stop_at(0);
261                 sequence_check_pending = false;
262         }
263
264         if(arrival==RESERVED_TO_END && !train.get_speed())
265         {
266                 signal_arrived.emit(destination);
267                 signal_event.emit(Message("arrived", destination));
268                 arrival = ARRIVED;
269         }
270         else if(arrival==ARRIVED && !train.get_block_allocator().is_active())
271                 set_route(0);
272 }
273
274 void TrainRouter::save(list<DataFile::Statement> &st) const
275 {
276         st.push_back((DataFile::Statement("priority"), priority));
277
278         if(!routes.empty())
279         {
280                 RouteList::const_iterator i = routes.begin();
281                 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
282                 if(i!=routes.end())
283                         st.push_back((DataFile::Statement("route"), (*i)->get_name()));
284         }
285 }
286
287 void TrainRouter::block_reserved(Block &block, Train *t)
288 {
289         if(routes.empty())
290                 return;
291
292         if(t!=&train)
293         {
294                 if(!t)
295                         return;
296
297                 // Are we waiting for the other train to pass a sequence point?
298                 SequencePoint &sp = sequence_points.front();
299                 if(sp.preceding_train==t && sp.block==&block)
300                         /* The other train's router will advance its sequence on the same
301                         signal and may not have handled it yet. */
302                         sequence_check_pending = true;
303
304                 return;
305         }
306
307         // Did we reach our next sequence point?
308         if(!sequence_points.empty())
309         {
310                 SequencePoint &sp = sequence_points.front();
311                 if(sp.block==&block)
312                 {
313                         current_sequence = sp.sequence_out;
314                         sequence_points.pop_front();
315                 }
316         }
317
318         TrackIter track = train.get_block_allocator().iter_for(block).track_iter();
319
320         // Is the block a turnout?  If it is, set it to the correct path.
321         if(unsigned taddr = block.get_turnout_address())
322         {
323                 int path = (*reserving_route)->get_turnout(taddr);
324                 if(path>=0)
325                         track->set_active_path(path);
326         }
327
328         /* If the allocator has released blocks from the front, we may need to
329         resync reserving_route. */
330         if(reserving_route==routes.end() || !(*reserving_route)->has_track(*track))
331         {
332                 reserving_route = routes.begin();
333                 arrival = ON_THE_WAY;
334                 track = t->get_block_allocator().first().track_iter();
335                 for(; track; track=track.next())
336                 {
337                         if(!advance_to_track(reserving_route, *track))
338                                 throw logic_error("internal error (reservation outside of route)");
339                         else if(&track->get_block()==&block)
340                                 break;
341                 }
342         }
343
344         /* Keep reserving_route pointing to the route containing the block that is
345         expected to be allocated next. */
346         for(; track; track=track.next((*reserving_route)->get_path(*track)))
347         {
348                 if(!advance_to_track(reserving_route, *track))
349                 {
350                         // We've reached the end of the route.  Stop here.
351                         arrival = RESERVED_TO_END;
352                         train.stop_at(&block);
353                         return;
354                 }
355                 if(&track->get_block()!=&block)
356                         break;
357         }
358
359         // Do we need to wait for another train to pass?
360         if(!sequence_points.empty())
361         {
362                 SequencePoint &sp = sequence_points.front();
363                 if(sp.block==&track->get_block() && !sp.is_cleared())
364                         train.stop_at(&block);
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                                         waypoints.erase(waypoints.begin());
384                                         signal_waypoint_reached.emit(&wp);
385                                         signal_event.emit(Message("waypoint-reached", &wp));
386                                         break;
387                                 }
388                                 else if(!block.has_track(*t_iter))
389                                         break;
390                         }
391                 }
392         }
393 }
394
395 void TrainRouter::train_rear_advanced(Block &block)
396 {
397         Track &track = *train.get_block_allocator().iter_for(block).endpoint().track;
398
399         // Drop any routes that are now completely behind the train.
400         for(RouteList::iterator i=routes.begin(); i!=routes.end(); ++i)
401                 if((*i)->has_track(track))
402                 {
403                         if(i!=routes.begin())
404                         {
405                                 routes.erase(routes.begin(), i);
406                                 const Route *route = get_route();
407                                 signal_route_changed.emit(route);
408                                 signal_event.emit(Message("route-changed", route));
409                         }
410                         break;
411                 }
412 }
413
414 void TrainRouter::create_metrics()
415 {
416         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
417                 delete *i;
418         metrics.clear();
419
420         if(!destination)
421                 return;
422
423         metrics.push_back(new TrainRouteMetric(*destination));
424         for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
425                 metrics.push_back(new TrainRouteMetric(**i));
426
427         for(unsigned i=metrics.size(); --i>0; )
428                 metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
429 }
430
431 Route *TrainRouter::create_lead_route(Route *lead, const Route *target)
432 {
433         if(!lead)
434         {
435                 lead = new Route(train.get_layout());
436                 lead->set_name("Lead");
437                 lead->set_temporary(true);
438         }
439
440         bool target_reached = false;
441         for(TrackIter i=train.get_block_allocator().first().track_iter(); i; i=i.next())
442         {
443                 if(i->get_block().get_train()!=&train)
444                         break;
445                 if(target)
446                 {
447                         if(target->has_track(*i))
448                                 target_reached = true;
449                         else if(target_reached)
450                                 break;
451                 }
452                 lead->add_track(*i);
453         }
454
455         return lead;
456 }
457
458 bool TrainRouter::is_valid_for_track(const Route &route, Track &track) const
459 {
460         if(!route.has_track(track))
461                 return false;
462         if(track.get_type().is_turnout() && route.get_turnout(track.get_turnout_address())<0)
463                 return false;
464         return true;
465 }
466
467 bool TrainRouter::advance_to_track(RouteList::iterator &route, Track &track)
468 {
469         if(!is_valid_for_track(**route, track))
470         {
471                 ++route;
472                 if(route==routes.end())
473                         return false;
474                 if(!is_valid_for_track(**route, track))
475                         throw logic_error("internal error (routes are not continuous)");
476         }
477
478         return true;
479 }
480
481 void TrainRouter::start_planning(Layout &layout)
482 {
483         RefPtr<TrainRoutePlanner> planner = new TrainRoutePlanner(layout);
484
485         const map<unsigned, Train *> &trains = layout.get_trains();
486         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
487                 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
488                 {
489                         if(router->metrics_stale)
490                         {
491                                 router->create_metrics();
492                                 router->metrics_stale = false;
493                         }
494                         router->planner = planner;
495                 }
496
497         planner->plan();
498 }
499
500
501 TrainRouter::SequencePoint::SequencePoint(Block &b, unsigned o):
502         block(&b),
503         preceding_train(0),
504         sequence_in(0),
505         sequence_out(o)
506 { }
507
508 bool TrainRouter::SequencePoint::is_cleared() const
509 {
510         if(!preceding_train)
511                 return true;
512
513         TrainRouter *router = preceding_train->get_ai_of_type<TrainRouter>();
514         return router->get_current_sequence()>=sequence_in;
515 }
516
517
518 TrainRouter::Loader::Loader(TrainRouter &r):
519         DataFile::ObjectLoader<TrainRouter>(r)
520 {
521         add("priority", &TrainRouter::priority);
522         add("route",    &Loader::route);
523 }
524
525 void TrainRouter::Loader::route(const string &n)
526 {
527         obj.set_route(&obj.train.get_layout().get_route(n));
528 }
529
530 } // namespace R2C2