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