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