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