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