]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/train.cpp
Remove the scripting-based timetable
[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::TimeStamp();
140                 allocator.reserve_more();
141         }
142         else
143                 stop_timeout = Time::now()+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::TimeStamp &t, const Time::TimeDelta &dt)
293 {
294         if(!active && stop_timeout && t>=stop_timeout)
295         {
296                 allocator.release_noncurrent();
297                 stop_timeout = Time::TimeStamp();
298         }
299
300         Driver &driver = layout.get_driver();
301
302         for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
303                 (*i)->tick(t, dt);
304         controller->tick(dt);
305         float speed = controller->get_speed();
306         bool moving = speed>0;
307
308         if(controller->get_reverse()!=reverse)
309         {
310                 reverse = controller->get_reverse();
311                 bool r = reverse;
312                 if(loco_type.get_swap_direction())
313                         r = !r;
314                 driver.set_loco_reverse(address, r);
315
316                 allocator.reverse();
317                 if(active)
318                         allocator.reserve_more();
319         }
320
321         if(speed_quantizer)
322         {
323                 unsigned speed_step = speed_quantizer->find_speed_step(speed);
324                 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
325                 {
326                         speed_changing = true;
327                         driver.set_loco_speed(address, speed_step);
328
329                         pure_speed = false;
330                 }
331
332                 speed = speed_quantizer->get_speed(current_speed_step);
333         }
334
335         if(moving)
336         {
337                 if(!active)
338                         set_active(true);
339
340                 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
341
342                 float d = speed*(dt/Time::sec);
343                 if(allocator.is_block_current(vehicle.get_track()->get_block()))
344                 {
345                         SetFlag setf(advancing);
346                         vehicle.advance(reverse ? -d : d);
347                 }
348                 else if(accurate_position)
349                 {
350                         overshoot_dist += d;
351                         if(overshoot_dist>40*layout.get_catalogue().get_scale())
352                         {
353                                 layout.emergency(name+" has not arrived at sensor");
354                                 accurate_position = false;
355                         }
356                 }
357         }
358 }
359
360 void Train::save(list<DataFile::Statement> &st) const
361 {
362         st.push_back((DataFile::Statement("name"), name));
363
364         for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
365                 if(i!=vehicles.begin())
366                         st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
367
368         if(speed_quantizer)
369         {
370                 DataFile::Statement ss("quantized_speed");
371                 speed_quantizer->save(ss.sub);
372                 st.push_back(ss);
373         }
374
375         {
376                 DataFile::Statement ss("blocks");
377                 allocator.save(ss.sub);
378                 st.push_back(ss);
379         }
380
381         // XXX Need more generic way of saving AI state
382         for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
383         {
384                 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
385                 {
386                         DataFile::Statement ss("router");
387                         router->save(ss.sub);
388                         st.push_back(ss);
389                 }
390         }
391 }
392
393 void Train::control_changed(const Controller::Control &ctrl)
394 {
395         signal_control_changed.emit(ctrl.name, ctrl.value);
396 }
397
398 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
399 {
400         if(addr==address)
401         {
402                 current_speed_step = speed;
403                 bool r = reverse;
404                 if(loco_type.get_swap_direction())
405                         r = !r;
406                 if(rev!=r)
407                         layout.get_driver().set_loco_reverse(address, r);
408                 speed_changing = false;
409                 pure_speed = false;
410         }
411 }
412
413 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
414 {
415         if(addr==address)
416         {
417                 if(state)
418                         functions |= 1<<func;
419                 else
420                         functions &= ~(1<<func);
421
422                 signal_function_changed.emit(func, state);
423         }
424 }
425
426 void Train::sensor_state_changed(Sensor &sensor, Sensor::State state)
427 {
428         Block *block = 0;
429         if(TrackCircuit *tc = dynamic_cast<TrackCircuit *>(&sensor))
430                 block = &tc->get_block();
431         else
432                 return;
433
434         if(block->get_train()==this && state==Sensor::MAYBE_ACTIVE)
435         {
436                 if(last_entry_block)
437                 {
438                         float travel_distance = -1;
439                         if(pure_speed && speed_quantizer && current_speed_step>0)
440                                 travel_distance = 0;
441
442                         for(BlockIter i=last_entry_block; &*i!=block; i=i.next())
443                         {
444                                 if(i->get_sensor_id())
445                                         return;
446                                 if(travel_distance>=0)
447                                         travel_distance += i->get_path_length(i.entry());
448                         }
449
450                         if(travel_distance>0)
451                         {
452                                 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
453
454                                 if(travel_time_secs>=2)
455                                         speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
456                         }
457                 }
458
459                 last_entry_block = allocator.iter_for(*block);
460                 last_entry_time = Time::now();
461                 pure_speed = true;
462                 accurate_position = true;
463                 overshoot_dist = 0;
464
465                 if(!advancing && vehicles.front()->get_track())
466                 {
467                         TrackIter track = last_entry_block.track_iter();
468                         if(reverse)
469                         {
470                                 track = track.flip();
471                                 vehicles.back()->place(track, 0, Vehicle::BACK_AXLE);
472                         }
473                         else
474                                 vehicles.front()->place(track, 0, Vehicle::FRONT_AXLE);
475                 }
476         }
477 }
478
479 void Train::halt_event(bool h)
480 {
481         if(h)
482                 accurate_position = false;
483 }
484
485 float Train::get_reserved_distance_until(const Block *until_block) const
486 {
487         if(allocator.empty())
488                 return 0;
489
490         Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
491
492         TrackIter track = veh.get_track_iter();
493         if(!track)  // XXX Probably unnecessary
494                 return 0;
495
496         BlockIter block = track.block_iter();
497         if(&*block==until_block)
498                 return 0;
499
500         // Account for the vehicle's offset on its current track
501         float result = veh.get_offset();
502         if(reverse)
503                 track = track.reverse();
504         else
505                 result = track->get_type().get_path_length(track->get_active_path())-result;
506         result -= veh.get_type().get_length()/2;
507
508         // Count remaining distance in the vehicle's current block
509         for(track=track.next(); &track->get_block()==&*block; track=track.next())
510                 result += track->get_type().get_path_length(track->get_active_path());
511
512         const BlockIter &last = allocator.last();
513         if(&*block==&*last)
514                 return result;
515
516         // Count any remaining blocks
517         for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
518         {
519                 result += block->get_path_length(block.entry());
520
521                 if(&*block==&*last)
522                         break;
523         }
524
525         return result;
526 }
527
528
529 Train::Loader::Loader(Train &t):
530         DataFile::ObjectLoader<Train>(t),
531         prev_block(0),
532         blocks_valid(true)
533 {
534         add("blocks",      &Loader::blocks);
535         add("name",        &Loader::name);
536         add("quantized_speed",  &Loader::quantized_speed);
537         add("router",      &Loader::router);
538         add("vehicle",     &Loader::vehicle);
539 }
540
541 void Train::Loader::finish()
542 {
543         if(!obj.allocator.empty())
544         {
545                 TrackIter track = obj.allocator.first().track_iter();
546                 float offset = 2*obj.layout.get_catalogue().get_scale();
547                 obj.vehicles.back()->place(track, offset, Vehicle::BACK_BUFFER);
548         }
549 }
550
551 void Train::Loader::blocks()
552 {
553         load_sub(obj.allocator);
554 }
555
556 void Train::Loader::name(const string &n)
557 {
558         obj.set_name(n);
559 }
560
561 void Train::Loader::quantized_speed()
562 {
563         if(obj.speed_quantizer)
564                 load_sub(*obj.speed_quantizer);
565 }
566
567 void Train::Loader::router()
568 {
569         TrainRouter *rtr = new TrainRouter(obj);
570         load_sub(*rtr);
571 }
572
573 void Train::Loader::vehicle(ArticleNumber art_nr)
574 {
575         const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
576         Vehicle *veh = new Vehicle(obj.layout, vtype);
577         obj.vehicles.back()->attach_back(*veh);
578         obj.vehicles.push_back(veh);
579 }
580
581 } // namespace R2C2