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