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