]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/train.cpp
Add a utility function to get path length from Track
[r2c2.git] / source / libr2c2 / train.cpp
1 #include <algorithm>
2 #include <cmath>
3 #include <msp/core/maputils.h>
4 #include <msp/core/raii.h>
5 #include <msp/strings/format.h>
6 #include <msp/time/units.h>
7 #include <msp/time/utils.h>
8 #include "aicontrol.h"
9 #include "beamgate.h"
10 #include "block.h"
11 #include "catalogue.h"
12 #include "driver.h"
13 #include "layout.h"
14 #include "route.h"
15 #include "simplecontroller.h"
16 #include "speedquantizer.h"
17 #include "trackcircuit.h"
18 #include "trackiter.h"
19 #include "tracktype.h"
20 #include "train.h"
21 #include "trainrouter.h"
22 #include "vehicle.h"
23 #include "vehicletype.h"
24 #include "zone.h"
25
26 using namespace std;
27 using namespace Msp;
28
29 namespace R2C2 {
30
31 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
32         layout(l),
33         loco_type(t),
34         address(a),
35         protocol(p),
36         preceding_train(0),
37         allocator(*this),
38         advancing(false),
39         controller(new SimpleController),
40         current_speed_step(0),
41         speed_changing(false),
42         reverse(false),
43         functions(0),
44         pure_speed(false),
45         speed_quantizer(0),
46         accurate_position(false),
47         overshoot_dist(false)
48 {
49         if(!loco_type.is_locomotive())
50                 throw invalid_argument("Train::Train");
51
52         unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
53         if(speed_steps)
54                 speed_quantizer = new SpeedQuantizer(speed_steps);
55
56         vehicles.push_back(new Vehicle(layout, loco_type));
57         vehicles.back()->set_train(this);
58
59         layout.add_train(*this);
60
61         layout.get_driver().add_loco(address, protocol, loco_type);
62         layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
63         layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
64
65         layout.signal_sensor_state_changed.connect(sigc::mem_fun(this, &Train::sensor_state_changed));
66
67         layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
68
69         controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
70 }
71
72 Train::~Train()
73 {
74         delete controller;
75         for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
76                 delete *i;
77         layout.remove_train(*this);
78 }
79
80 void Train::set_name(const string &n)
81 {
82         name = n;
83
84         signal_name_changed.emit(name);
85 }
86
87 void Train::add_vehicle(const VehicleType &vt)
88 {
89         Vehicle *veh = new Vehicle(layout, vt);
90         vehicles.back()->attach_back(*veh);
91         vehicles.push_back(veh);
92         veh->set_train(this);
93         signal_vehicle_added.emit(vehicles.size()-1, *veh);
94 }
95
96 void Train::remove_vehicle(unsigned i)
97 {
98         if(i>=vehicles.size())
99                 throw out_of_range("Train::remove_vehicle");
100         if(i==0)
101                 throw logic_error("can't remove locomotive");
102
103         Vehicle *veh = vehicles[i];
104         vehicles.erase(vehicles.begin()+i);
105         veh->detach_front();
106         if(i<vehicles.size())
107         {
108                 veh->detach_back();
109                 vehicles[i-1]->attach_back(*vehicles[i]);
110         }
111         signal_vehicle_removed.emit(i, *veh);
112         delete veh;
113 }
114
115 unsigned Train::get_n_vehicles() const
116 {
117         return vehicles.size();
118 }
119
120 Vehicle &Train::get_vehicle(unsigned i)
121 {
122         if(i>=vehicles.size())
123                 throw out_of_range("Train::get_vehicle");
124         return *vehicles[i];
125 }
126
127 const Vehicle &Train::get_vehicle(unsigned i) const
128 {
129         if(i>=vehicles.size())
130                 throw out_of_range("Train::get_vehicle");
131         return *vehicles[i];
132 }
133
134 void Train::set_control(const string &n, float v)
135 {
136         controller->set_control(n, v);
137 }
138
139 void Train::set_function(unsigned func, bool state)
140 {
141         if(!loco_type.get_functions().count(func))
142                 throw invalid_argument("Train::set_function");
143         layout.get_driver().set_loco_function(address, func, state);
144 }
145
146 float Train::get_control(const string &ctrl) const
147 {
148         return controller->get_control(ctrl).value;
149 }
150
151 float Train::get_speed() const
152 {
153         return controller->get_speed();
154 }
155
156 float Train::get_quantized_speed() const
157 {
158         if(speed_quantizer)
159                 return speed_quantizer->quantize_speed(controller->get_speed());
160         else
161                 return controller->get_speed();
162 }
163
164 bool Train::get_function(unsigned func) const
165 {
166         return (functions>>func)&1;
167 }
168
169 void Train::add_ai(TrainAI &ai)
170 {
171         ais.push_back(&ai);
172         ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
173 }
174
175 void Train::remove_ai(TrainAI &ai)
176 {
177         list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
178         if(i!=ais.end())
179                 ais.erase(i);
180 }
181
182 void Train::ai_message(const TrainAI::Message &msg)
183 {
184         for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
185                 (*i)->message(msg);
186 }
187
188 bool Train::place(const BlockIter &block)
189 {
190         if(!block)
191                 throw invalid_argument("Train::place");
192         if(controller->get_speed())
193                 throw logic_error("moving");
194
195         accurate_position = false;
196         last_entry_block = BlockIter();
197
198         if(allocator.start_from(block))
199         {
200                 if(reverse)
201                         vehicles.front()->place(block.reverse().track_iter(), VehiclePlacement::FRONT_BUFFER);
202                 else
203                         vehicles.back()->place(block.track_iter(), VehiclePlacement::BACK_BUFFER);
204                 return true;
205         }
206         else
207         {
208                 unplace();
209                 return false;
210         }
211 }
212
213 void Train::unplace()
214 {
215         if(controller->get_speed())
216                 throw logic_error("moving");
217
218         allocator.clear();
219         accurate_position = false;
220         last_entry_block = BlockIter();
221
222         for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
223                 (*i)->unplace();
224 }
225
226 void Train::stop_at(Block *block)
227 {
228         allocator.stop_at(block);
229 }
230
231 bool Train::is_block_critical(const Block &block) const
232 {
233         return get_reserved_distance_until(&block)<=controller->get_braking_distance()*1.3;
234 }
235
236 BlockIter Train::get_first_noncritical_block() const
237 {
238         if(allocator.empty())
239                 return BlockIter();
240
241         BlockIter i = allocator.last_current().next();
242
243         if(controller->get_speed()==0)
244                 return i;
245
246         float margin = 10*layout.get_catalogue().get_scale();
247         float min_dist = controller->get_braking_distance()*1.3+margin;
248
249         float dist = 0;
250         bool sensor_seen = false;
251         for(; i->get_train()==this; i=i.next())
252         {
253                 if(dist>min_dist && sensor_seen)
254                         return i;
255
256                 dist += i->get_path_length(i.entry());
257
258                 if(i->get_sensor_id())
259                         sensor_seen = true;
260         }
261
262         return i;
263 }
264
265 void Train::refresh_blocks_from(Block &block)
266 {
267         if(is_block_critical(block))
268                 allocator.rewind_to(*get_first_noncritical_block());
269         else
270                 allocator.rewind_to(block);
271 }
272
273 float Train::get_reserved_distance() const
274 {
275         if(allocator.empty())
276                 return 0;
277
278         float margin = 0;
279         TrackIter next = allocator.last().next().track_iter();
280         if(next && next->get_type().is_turnout())
281                 margin = 15*layout.get_catalogue().get_scale();
282
283         return max(get_reserved_distance_until(0)-margin, 0.0f);
284 }
285
286 void Train::tick(const Time::TimeDelta &dt)
287 {
288         if(stop_timeout)
289         {
290                 stop_timeout -= dt;
291                 if(stop_timeout<=Time::zero)
292                 {
293                         allocator.set_active(false);
294                         stop_timeout = Time::TimeDelta();
295                 }
296         }
297
298         travel_time += dt;
299
300         Driver &driver = layout.get_driver();
301
302         bool intent_to_move = false;
303         for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
304         {
305                 (*i)->tick(dt);
306                 if((*i)->has_intent_to_move())
307                         intent_to_move = true;
308         }
309
310         controller->tick(dt);
311         float speed = controller->get_speed();
312         bool moving = speed>0;
313
314         if(controller->get_reverse()!=reverse)
315         {
316                 reverse = controller->get_reverse();
317                 bool r = reverse;
318                 if(loco_type.get_swap_direction())
319                         r = !r;
320                 driver.set_loco_reverse(address, r);
321
322                 allocator.reverse();
323                 last_entry_block = BlockIter();
324         }
325
326         if(speed_quantizer)
327         {
328                 unsigned speed_step = speed_quantizer->find_speed_step(speed);
329                 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
330                 {
331                         speed_changing = true;
332                         driver.set_loco_speed(address, speed_step);
333
334                         pure_speed = false;
335                 }
336
337                 speed = speed_quantizer->get_speed(current_speed_step);
338         }
339
340         if(moving)
341         {
342                 if(!allocator.is_active())
343                         allocator.set_active(true);
344
345                 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
346
347                 float d = speed*(dt/Time::sec);
348                 if(allocator.is_block_current(vehicle.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE)->get_block()))
349                 {
350                         SetFlag setf(advancing);
351                         vehicle.advance(reverse ? -d : d);
352                 }
353                 else if(accurate_position)
354                 {
355                         overshoot_dist += d;
356                         if(overshoot_dist>40*layout.get_catalogue().get_scale())
357                         {
358                                 layout.emergency(name+" has not arrived at sensor");
359                                 accurate_position = false;
360                         }
361                 }
362         }
363         else if(intent_to_move && !allocator.is_active())
364                 allocator.set_active(true);
365         else if(allocator.is_active() && !intent_to_move && !stop_timeout)
366                 stop_timeout = 2*Time::sec;
367 }
368
369 void Train::save(list<DataFile::Statement> &st) const
370 {
371         st.push_back((DataFile::Statement("name"), name));
372
373         for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
374                 if(i!=vehicles.begin())
375                         st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
376
377         if(speed_quantizer)
378         {
379                 DataFile::Statement ss("quantized_speed");
380                 speed_quantizer->save(ss.sub);
381                 st.push_back(ss);
382         }
383
384         {
385                 DataFile::Statement ss("blocks");
386                 allocator.save(ss.sub);
387                 st.push_back(ss);
388         }
389
390         // XXX Need more generic way of saving AI state
391         for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
392         {
393                 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
394                 {
395                         DataFile::Statement ss("router");
396                         router->save(ss.sub);
397                         st.push_back(ss);
398                 }
399         }
400 }
401
402 void Train::control_changed(const Controller::Control &ctrl)
403 {
404         signal_control_changed.emit(ctrl.name, ctrl.value);
405 }
406
407 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
408 {
409         if(addr==address)
410         {
411                 current_speed_step = speed;
412                 bool r = reverse;
413                 if(loco_type.get_swap_direction())
414                         r = !r;
415                 if(rev!=r)
416                         layout.get_driver().set_loco_reverse(address, r);
417                 speed_changing = false;
418                 pure_speed = false;
419         }
420 }
421
422 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
423 {
424         if(addr==address)
425         {
426                 if(state)
427                         functions |= 1<<func;
428                 else
429                         functions &= ~(1<<func);
430
431                 signal_function_changed.emit(func, state);
432         }
433 }
434
435 void Train::sensor_state_changed(Sensor &sensor, Sensor::State state)
436 {
437         if(!current_speed_step || state!=Sensor::MAYBE_ACTIVE)
438                 return;
439
440         Block *block = sensor.get_block();
441         if(!block || block->get_train()!=this)
442                 return;
443
444         if(last_entry_block && &*last_entry_block!=block)
445         {
446                 for(BlockIter i=last_entry_block.next(); (i && &*i!=block); i=i.next())
447                         if(i->get_train()!=this || i->get_sensor_id())
448                                 return;
449         }
450
451         if(dynamic_cast<TrackCircuit *>(&sensor))
452         {
453                 if(last_entry_block && pure_speed && speed_quantizer)
454                 {
455                         float travel_distance = 0;
456
457                         for(BlockIter i=last_entry_block; &*i!=block; i=i.next())
458                                 travel_distance += i->get_path_length(i.entry());
459
460                         if(travel_distance>0)
461                         {
462                                 float travel_time_secs = travel_time/Time::sec;
463
464                                 if(travel_time_secs>=2)
465                                         speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
466                         }
467                 }
468
469                 last_entry_block = allocator.iter_for(*block);
470                 travel_time = Time::zero;
471                 pure_speed = true;
472                 accurate_position = true;
473                 overshoot_dist = 0;
474
475                 if(!advancing && vehicles.front()->is_placed())
476                 {
477                         TrackIter track = last_entry_block.track_iter();
478                         if(reverse)
479                         {
480                                 track = track.flip();
481                                 vehicles.back()->place(track, VehiclePlacement::BACK_AXLE);
482                         }
483                         else
484                                 vehicles.front()->place(track, VehiclePlacement::FRONT_AXLE);
485                 }
486         }
487         else if(BeamGate *gate = dynamic_cast<BeamGate *>(&sensor))
488         {
489                 if(!advancing && vehicles.front()->is_placed())
490                 {
491                         TrackIter track = allocator.iter_for(*block).track_iter();
492                         for(; (track && &track->get_block()==block); track=track.next())
493                                 if(track.track()==gate->get_track())
494                                 {
495                                         if(reverse)
496                                                 track = track.reverse();
497                                         float offset = gate->get_offset_from_endpoint(track.entry());
498                                         if(reverse)
499                                                 vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
500                                         else
501                                                 vehicles.front()->place(TrackOffsetIter(track, offset), VehiclePlacement::FRONT_BUFFER);
502                                         break;
503                                 }
504                 }
505         }
506 }
507
508 void Train::halt_event(bool h)
509 {
510         if(h)
511                 accurate_position = false;
512 }
513
514 float Train::get_reserved_distance_until(const Block *until_block) const
515 {
516         if(allocator.empty())
517                 return 0;
518
519         Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
520
521         TrackOffsetIter track = veh.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE);
522         if(!track)  // XXX Probably unnecessary
523                 return 0;
524
525         if(&track->get_block()==until_block)
526                 return 0;
527
528         // Account for the vehicle's offset on its current track
529         float result = track.offset();
530         if(reverse)
531                 track = track.reverse();
532         else
533                 result = track->get_path_length()-result;
534         result -= veh.get_type().get_length()/2;
535
536         BlockIter block = track.block_iter();
537
538         // Count remaining distance in the vehicle's current block
539         for(track=track.next(); &track->get_block()==&*block; track=track.next())
540                 result += track->get_path_length();
541
542         const BlockIter &last = allocator.last();
543         if(&*block==&*last)
544                 return result;
545
546         // Count any remaining blocks
547         for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
548         {
549                 result += block->get_path_length(block.entry());
550
551                 if(&*block==&*last)
552                         break;
553         }
554
555         return result;
556 }
557
558
559 Train::Loader::Loader(Train &t):
560         DataFile::ObjectLoader<Train>(t),
561         prev_block(0),
562         blocks_valid(true)
563 {
564         add("blocks",      &Loader::blocks);
565         add("name",        &Loader::name);
566         add("quantized_speed",  &Loader::quantized_speed);
567         add("router",      &Loader::router);
568         add("vehicle",     &Loader::vehicle);
569 }
570
571 void Train::Loader::finish()
572 {
573         if(!obj.allocator.empty())
574         {
575                 TrackIter track = obj.allocator.first().track_iter();
576                 float offset = 2*obj.layout.get_catalogue().get_scale();
577                 obj.vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
578         }
579 }
580
581 void Train::Loader::blocks()
582 {
583         load_sub(obj.allocator);
584 }
585
586 void Train::Loader::name(const string &n)
587 {
588         obj.set_name(n);
589 }
590
591 void Train::Loader::quantized_speed()
592 {
593         if(obj.speed_quantizer)
594                 load_sub(*obj.speed_quantizer);
595 }
596
597 void Train::Loader::router()
598 {
599         TrainRouter *rtr = new TrainRouter(obj);
600         load_sub(*rtr);
601 }
602
603 void Train::Loader::vehicle(ArticleNumber art_nr)
604 {
605         const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
606         Vehicle *veh = new Vehicle(obj.layout, vtype);
607         obj.vehicles.back()->attach_back(*veh);
608         obj.vehicles.push_back(veh);
609         veh->set_train(&obj);
610 }
611
612 } // namespace R2C2