]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouter.cpp
Fix lead route generation
[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         arriving(0),
19         destination(0),
20         update_pending(false)
21 {
22         train.get_layout().signal_block_reserved.connect(sigc::mem_fun(this, &TrainRouter::block_reserved));
23         train.signal_advanced.connect(sigc::mem_fun(this, &TrainRouter::train_advanced));
24 }
25
26 TrainRouter::~TrainRouter()
27 {
28         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
29                 delete *i;
30 }
31
32 void TrainRouter::set_priority(int p)
33 {
34         priority = p;
35 }
36
37 bool TrainRouter::set_route(const Route *r)
38 {
39         BlockIter fncb = train.get_first_noncritical_block();
40
41         Route *lead = 0;
42         if(r && train.is_placed())
43         {
44                 const BlockAllocator &allocator = train.get_block_allocator();
45                 TrackIter first = allocator.first().track_iter();
46                 TrackIter next = fncb.track_iter();
47                 if(!r->has_track(*next))
48                 {
49                         lead = Route::find(next, *r);
50                         if(!lead)
51                                 return false;
52                         create_lead_route(lead, lead);
53                 }
54                 else if(!r->has_track(*first))
55                         lead = create_lead_route(0, r);
56         }
57
58         routes.clear();
59         if(lead)
60                 routes.push_back(lead);
61         if(r)
62                 routes.push_back(r);
63         train.stop_at(0);
64         arriving = 0;
65
66         /* TODO destination should also be cleared when manually setting a different
67         route, but not when the planner calls this. */
68         if(!r)
69         {
70                 destination = 0;
71                 waypoints.clear();
72         }
73
74         train.refresh_blocks_from(*fncb);
75
76         const Route *route = get_route();
77         signal_route_changed.emit(route);
78         signal_event.emit(Message("route-changed", route));
79
80         return true;
81 }
82
83 bool TrainRouter::add_route(const Route &r)
84 {
85         if(routes.empty())
86                 return set_route(&r);
87
88         // TODO Check that it can be reached from previous routes
89         routes.push_back(&r);
90
91         return true;
92 }
93
94 void TrainRouter::add_wait(Block &block, Train *tr)
95 {
96         Wait wait;
97         wait.block = &block;
98         wait.train = tr;
99         waits.push_back(wait);
100 }
101
102 const Route *TrainRouter::get_route() const
103 {
104         if(routes.empty())
105                 return 0;
106         return routes.front();
107 }
108
109 void TrainRouter::set_destination(const TrackChain &d)
110 {
111         destination = &d;
112         update_pending = true;
113 }
114
115 bool TrainRouter::is_destination(Track &track) const
116 {
117         if(destination)
118                 return destination->has_track(track);
119         else
120                 return false;
121 }
122
123 void TrainRouter::add_waypoint(const TrackChain &wp)
124 {
125         waypoints.push_back(&wp);
126         update_pending = true;
127 }
128
129 bool TrainRouter::is_waypoint(unsigned index, Track &track) const
130 {
131         if(index>=waypoints.size())
132                 throw out_of_range("TrainRouter::is_waypoint");
133
134         return waypoints[index]->has_track(track);
135 }
136
137 const TrainRouteMetric &TrainRouter::get_metric(int index) const
138 {
139         if(!destination)
140                 throw logic_error("no metrics");
141         else if(update_pending)
142                 throw logic_error("metrics are stale");
143
144         if(index<0)
145                 return *metrics.front();
146         else if(static_cast<unsigned>(index)>=waypoints.size())
147                 throw out_of_range("TrainRouter::get_metric");
148         else
149                 return *metrics[index+1];
150 }
151
152 void TrainRouter::set_departure_delay(const Time::TimeDelta &d)
153 {
154         delay = d;
155         update_pending = true;
156 }
157
158 void TrainRouter::message(const Message &msg)
159 {
160         if(msg.type=="set-route")
161         {
162                 if(msg.value.check_type<Route *>())
163                         set_route(msg.value.value<Route *>());
164                 else
165                         set_route(msg.value.value<const Route *>());
166         }
167         else if(msg.type=="clear-route")
168                 set_route(0);
169         else if(msg.type=="set-destination")
170         {
171                 if(msg.value.check_type<TrackChain *>())
172                         set_destination(*msg.value.value<TrackChain *>());
173                 else
174                         set_destination(*msg.value.value<const TrackChain *>());
175         }
176         else if(msg.type=="add-waypoint")
177         {
178                 if(msg.value.check_type<TrackChain *>())
179                         add_waypoint(*msg.value.value<TrackChain *>());
180                 else
181                         add_waypoint(*msg.value.value<const TrackChain *>());
182         }
183         else if(msg.type=="set-departure-delay")
184                 set_departure_delay(msg.value.value<Time::TimeDelta>());
185 }
186
187 void TrainRouter::tick(const Time::TimeDelta &dt)
188 {
189         if(delay)
190         {
191                 delay -= dt;
192                 if(delay<=Time::zero)
193                         delay = Time::zero;
194         }
195
196         if(update_pending)
197                 create_plans(train.get_layout());
198
199         if(arriving==1 && !train.get_speed())
200         {
201                 signal_arrived.emit(destination);
202                 signal_event.emit(Message("arrived", destination));
203                 arriving = 2;
204         }
205         else if(arriving==2 && !train.get_block_allocator().is_active())
206                 set_route(0);
207 }
208
209 void TrainRouter::save(list<DataFile::Statement> &st) const
210 {
211         st.push_back((DataFile::Statement("priority"), priority));
212
213         if(!routes.empty())
214         {
215                 RouteList::const_iterator i = routes.begin();
216                 for(; (i!=routes.end() && (*i)->is_temporary()); ++i) ;
217                 if(i!=routes.end())
218                         st.push_back((DataFile::Statement("route"), (*i)->get_name()));
219         }
220 }
221
222 void TrainRouter::block_reserved(Block &block, Train *t)
223 {
224         if(t!=&train)
225         {
226                 if(!waits.empty() && waits.front().block==&block)
227                 {
228                         train.stop_at(0);
229                         waits.pop_front();
230                 }
231                 return;
232         }
233
234         BlockIter b_iter = t->get_block_allocator().iter_for(block);
235
236         RouteList::iterator route = routes.begin();
237         if(advance_route(route, block))
238         {
239                 // Check if the block is a turnout and set it to proper path
240                 if(unsigned taddr = block.get_turnout_address())
241                 {
242                         int path = (*route)->get_turnout(taddr);
243                         if(path>=0)
244                                 b_iter.track_iter()->set_active_path(path);
245                 }
246
247                 // Check if the next block is still part of the designated route
248                 BlockIter b_iter_next = b_iter.next(*route);
249
250                 RouteList::iterator next_route = route;
251                 if(!advance_route(next_route, *b_iter_next))
252                 {
253                         train.stop_at(&block);
254                         return;
255                 }
256
257                 if(!waits.empty() && waits.front().block==b_iter_next.block())
258                         train.stop_at(&block);
259         }
260 }
261
262 void TrainRouter::train_advanced(Block &block)
263 {
264         BlockIter b_iter = train.get_block_allocator().iter_for(block);
265
266         // Check if we've reached the next route
267         if(routes.size()>1)
268         {
269                 const Route &route = **++routes.begin();
270                 if(route.has_track(*b_iter.endpoint().track))
271                 {
272                         routes.pop_front();
273                         const Route *r = get_route();
274                         // XXX Exceptions?
275                         signal_route_changed.emit(r);
276                         signal_event.emit(Message("route-changed", r));
277                 }
278         }
279
280         if(!waypoints.empty())
281         {
282                 const TrackChain &wp = *waypoints.front();
283                 TrackIter t_iter = b_iter.track_iter();
284                 if(wp.has_track(*t_iter))
285                 {
286                         for(; t_iter; t_iter=t_iter.next())
287                         {
288                                 if(!wp.has_track(*t_iter))
289                                 {
290                                         waypoints.erase(waypoints.begin());
291                                         signal_waypoint_reached.emit(&wp);
292                                         signal_event.emit(Message("waypoint-reached", &wp));
293                                         break;
294                                 }
295                                 else if(!block.has_track(*t_iter))
296                                         break;
297                         }
298                 }
299         }
300
301         if(!routes.empty())
302         {
303                 b_iter = b_iter.next();
304                 if(b_iter && !is_on_route(*b_iter))
305                         arriving = 1;
306         }
307 }
308
309 const Route *TrainRouter::get_route_for_block(const Block &block) const
310 {
311         const set<Track *> &tracks = block.get_tracks();
312         for(RouteList::const_iterator i=routes.begin(); i!=routes.end(); ++i)
313                 for(set<Track *>::const_iterator j=tracks.begin(); j!=tracks.end(); ++j)
314                         if((*i)->has_track(**j))
315                                 return *i;
316
317         return 0;
318 }
319
320 void TrainRouter::create_metrics()
321 {
322         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
323                 delete *i;
324         metrics.clear();
325
326         if(!destination)
327                 return;
328
329         metrics.push_back(new TrainRouteMetric(*destination));
330         for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
331                 metrics.push_back(new TrainRouteMetric(**i));
332
333         for(unsigned i=metrics.size(); --i>0; )
334                 metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
335 }
336
337 Route *TrainRouter::create_lead_route(Route *lead, const Route *target)
338 {
339         if(!lead)
340         {
341                 lead = new Route(train.get_layout());
342                 lead->set_name("Lead");
343                 lead->set_temporary(true);
344         }
345
346         bool target_reached = false;
347         for(TrackIter i=train.get_block_allocator().first().track_iter(); i; i=i.next())
348         {
349                 if(i->get_block().get_train()!=&train)
350                         break;
351                 if(target)
352                 {
353                         if(target->has_track(*i))
354                                 target_reached = true;
355                         else if(target_reached)
356                                 break;
357                 }
358                 lead->add_track(*i);
359         }
360
361         return lead;
362 }
363
364 bool TrainRouter::advance_route(RouteList::iterator &iter, const Block &block)
365 {
366         const set<Track *> &tracks = block.get_tracks();
367         for(; iter!=routes.end(); ++iter)
368                 for(set<Track *>::const_iterator j=tracks.begin(); j!=tracks.end(); ++j)
369                         if((*iter)->has_track(**j))
370                                 return true;
371
372         return false;
373 }
374
375 bool TrainRouter::is_on_route(const Block &block)
376 {
377         RouteList::iterator iter = routes.begin();
378         return advance_route(iter, block);
379 }
380
381 void TrainRouter::create_plans(Layout &layout)
382 {
383         const map<unsigned, Train *> &trains = layout.get_trains();
384         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
385                 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
386                 {
387                         if(router->update_pending)
388                                 router->create_metrics();
389                         router->update_pending = false;
390                 }
391
392         TrainRoutePlanner planner(layout);
393         planner.plan();
394 }
395
396
397 TrainRouter::Wait::Wait():
398         block(0),
399         train(0)
400 { }
401
402
403 TrainRouter::Loader::Loader(TrainRouter &r):
404         DataFile::ObjectLoader<TrainRouter>(r)
405 {
406         add("priority", &TrainRouter::priority);
407         add("route",    &Loader::route);
408 }
409
410 void TrainRouter::Loader::route(const string &n)
411 {
412         obj.set_route(&obj.train.get_layout().get_route(n));
413 }
414
415 } // namespace R2C2