]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/trainrouter.cpp
9a86263b9bec5922fa58d8201529731e79c01944
[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                 Track &track = *b_iter.endpoint().track;
270                 const Route *route = get_route();
271                 bool change_route = false;
272                 if(route->is_loop())
273                         change_route = (*++routes.begin())->has_track(track);
274                 else
275                         change_route = !route->has_track(track);
276
277                 if(change_route)
278                 {
279                         routes.pop_front();
280                         route = get_route();
281                         // XXX Exceptions?
282                         signal_route_changed.emit(route);
283                         signal_event.emit(Message("route-changed", route));
284                 }
285         }
286
287         if(!waypoints.empty())
288         {
289                 const TrackChain &wp = *waypoints.front();
290                 TrackIter t_iter = b_iter.track_iter();
291                 if(wp.has_track(*t_iter))
292                 {
293                         for(; t_iter; t_iter=t_iter.next())
294                         {
295                                 if(!wp.has_track(*t_iter))
296                                 {
297                                         waypoints.erase(waypoints.begin());
298                                         signal_waypoint_reached.emit(&wp);
299                                         signal_event.emit(Message("waypoint-reached", &wp));
300                                         break;
301                                 }
302                                 else if(!block.has_track(*t_iter))
303                                         break;
304                         }
305                 }
306         }
307
308         if(!routes.empty())
309         {
310                 b_iter = b_iter.next();
311                 if(b_iter && !is_on_route(*b_iter))
312                         arriving = 1;
313         }
314 }
315
316 const Route *TrainRouter::get_route_for_block(const Block &block) const
317 {
318         const set<Track *> &tracks = block.get_tracks();
319         for(RouteList::const_iterator i=routes.begin(); i!=routes.end(); ++i)
320                 for(set<Track *>::const_iterator j=tracks.begin(); j!=tracks.end(); ++j)
321                         if((*i)->has_track(**j))
322                                 return *i;
323
324         return 0;
325 }
326
327 void TrainRouter::create_metrics()
328 {
329         for(vector<TrainRouteMetric *>::iterator i=metrics.begin(); i!=metrics.end(); ++i)
330                 delete *i;
331         metrics.clear();
332
333         if(!destination)
334                 return;
335
336         metrics.push_back(new TrainRouteMetric(*destination));
337         for(vector<const TrackChain *>::const_iterator i=waypoints.begin(); i!=waypoints.end(); ++i)
338                 metrics.push_back(new TrainRouteMetric(**i));
339
340         for(unsigned i=metrics.size(); --i>0; )
341                 metrics[i]->chain_to(*metrics[(i+1)%metrics.size()]);
342 }
343
344 Route *TrainRouter::create_lead_route(Route *lead, const Route *target)
345 {
346         if(!lead)
347         {
348                 lead = new Route(train.get_layout());
349                 lead->set_name("Lead");
350                 lead->set_temporary(true);
351         }
352
353         bool target_reached = false;
354         for(TrackIter i=train.get_block_allocator().first().track_iter(); i; i=i.next())
355         {
356                 if(i->get_block().get_train()!=&train)
357                         break;
358                 if(target)
359                 {
360                         if(target->has_track(*i))
361                                 target_reached = true;
362                         else if(target_reached)
363                                 break;
364                 }
365                 lead->add_track(*i);
366         }
367
368         return lead;
369 }
370
371 bool TrainRouter::advance_route(RouteList::iterator &iter, const Block &block)
372 {
373         const set<Track *> &tracks = block.get_tracks();
374         unsigned turnout_addr = block.get_turnout_address();
375         for(; iter!=routes.end(); ++iter)
376         {
377                 if(turnout_addr && (*iter)->get_turnout(turnout_addr)<0)
378                         continue;
379                 for(set<Track *>::const_iterator j=tracks.begin(); j!=tracks.end(); ++j)
380                         if((*iter)->has_track(**j))
381                                 return true;
382         }
383
384         return false;
385 }
386
387 bool TrainRouter::is_on_route(const Block &block)
388 {
389         RouteList::iterator iter = routes.begin();
390         return advance_route(iter, block);
391 }
392
393 void TrainRouter::create_plans(Layout &layout)
394 {
395         const map<unsigned, Train *> &trains = layout.get_trains();
396         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
397                 if(TrainRouter *router = i->second->get_ai_of_type<TrainRouter>())
398                 {
399                         if(router->update_pending)
400                                 router->create_metrics();
401                         router->update_pending = false;
402                 }
403
404         TrainRoutePlanner planner(layout);
405         planner.plan();
406 }
407
408
409 TrainRouter::Wait::Wait():
410         block(0),
411         train(0)
412 { }
413
414
415 TrainRouter::Loader::Loader(TrainRouter &r):
416         DataFile::ObjectLoader<TrainRouter>(r)
417 {
418         add("priority", &TrainRouter::priority);
419         add("route",    &Loader::route);
420 }
421
422 void TrainRouter::Loader::route(const string &n)
423 {
424         obj.set_route(&obj.train.get_layout().get_route(n));
425 }
426
427 } // namespace R2C2