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