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>
10 #include "catalogue.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"
20 #include "trainrouter.h"
22 #include "vehicletype.h"
29 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
37 controller(new SimpleController),
38 current_speed_step(0),
39 speed_changing(false),
44 accurate_position(false),
47 if(!loco_type.is_locomotive())
48 throw invalid_argument("Train::Train");
50 unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
52 speed_quantizer = new SpeedQuantizer(speed_steps);
54 vehicles.push_back(new Vehicle(layout, loco_type));
55 vehicles.back()->set_train(this);
57 layout.add_train(*this);
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));
63 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
65 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
67 allocator.signal_advanced.connect(sigc::mem_fun(this, &Train::advanced));
68 allocator.signal_rear_advanced.connect(signal_rear_advanced);
74 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
76 layout.remove_train(*this);
79 void Train::set_name(const string &n)
83 signal_name_changed.emit(name);
86 void Train::add_vehicle(const VehicleType &vt)
88 Vehicle *veh = new Vehicle(layout, vt);
89 vehicles.back()->attach_back(*veh);
90 vehicles.push_back(veh);
92 signal_vehicle_added.emit(vehicles.size()-1, *veh);
95 void Train::remove_vehicle(unsigned i)
97 if(i>=vehicles.size())
98 throw out_of_range("Train::remove_vehicle");
100 throw logic_error("can't remove locomotive");
102 Vehicle *veh = vehicles[i];
103 vehicles.erase(vehicles.begin()+i);
105 if(i<vehicles.size())
108 vehicles[i-1]->attach_back(*vehicles[i]);
110 signal_vehicle_removed.emit(i, *veh);
114 unsigned Train::get_n_vehicles() const
116 return vehicles.size();
119 Vehicle &Train::get_vehicle(unsigned i)
121 if(i>=vehicles.size())
122 throw out_of_range("Train::get_vehicle");
126 const Vehicle &Train::get_vehicle(unsigned i) const
128 if(i>=vehicles.size())
129 throw out_of_range("Train::get_vehicle");
133 void Train::set_control(const string &n, float v)
135 controller->set_control(n, v);
138 void Train::set_function(unsigned func, bool state)
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);
145 float Train::get_control(const string &ctrl) const
147 return controller->get_control(ctrl).value;
150 float Train::get_speed() const
152 return controller->get_speed();
155 float Train::get_quantized_speed() const
158 return speed_quantizer->quantize_speed(controller->get_speed());
160 return controller->get_speed();
163 float Train::get_maximum_speed() const
166 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
168 float vms = (*i)->get_type().get_maximum_speed();
169 if(ms<=0 || (vms>0 && vms<ms))
175 bool Train::get_function(unsigned func) const
177 return (functions>>func)&1;
180 void Train::add_ai(TrainAI &ai)
183 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
186 void Train::remove_ai(TrainAI &ai)
188 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
193 void Train::ai_message(const TrainAI::Message &msg)
195 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
199 bool Train::place(const BlockIter &block)
202 throw invalid_argument("Train::place");
203 if(controller->get_speed())
204 throw logic_error("moving");
206 accurate_position = false;
207 last_entry_block = BlockIter();
209 if(allocator.start_from(block))
212 vehicles.front()->place(block.reverse().track_iter(), VehiclePlacement::FRONT_BUFFER);
214 vehicles.back()->place(block.track_iter(), VehiclePlacement::BACK_BUFFER);
224 void Train::unplace()
226 if(controller->get_speed())
227 throw logic_error("moving");
230 accurate_position = false;
231 last_entry_block = BlockIter();
233 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
237 void Train::stop_at(Block *block)
239 allocator.stop_at(block);
242 bool Train::is_block_critical(const Block &block) const
244 if(allocator.is_block_current(block))
247 BlockIter i = check_critical_blocks(&block);
248 return i.block()==█
251 BlockIter Train::get_last_critical_block() const
253 return check_critical_blocks(0);
256 BlockIter Train::check_critical_blocks(const Block *check) const
258 if(allocator.empty())
261 BlockIter i = allocator.last_current();
263 if(controller->get_speed()==0)
266 BlockIter last = allocator.last();
267 if(i.block()==last.block())
270 float margin = 10*layout.get_catalogue().get_scale();
271 float min_dist = controller->get_braking_distance()*1.3+margin;
274 bool sensor_seen = false;
276 while(i.block()!=last.block() && i.block()!=check)
278 dist += i->get_path_length(i.entry());
280 if(i->get_sensor_address())
283 if(dist>min_dist && sensor_seen)
286 BlockIter j = i.next();
287 if(j->get_train()!=this)
296 void Train::refresh_blocks_from(Block &block)
298 if(is_block_critical(block))
299 allocator.rewind_to(*get_last_critical_block().next());
301 allocator.rewind_to(block);
304 float Train::get_reserved_distance() const
306 if(allocator.empty())
310 TrackIter next = allocator.last().next().track_iter();
311 if(next && next->get_type().is_turnout())
312 margin = 15*layout.get_catalogue().get_scale();
314 return max(get_reserved_distance_until(0)-margin, 0.0f);
317 void Train::tick(const Time::TimeDelta &dt)
321 stop_timeout = max(stop_timeout-dt, Time::zero);
322 if(stop_timeout<=Time::zero)
323 allocator.set_active(false);
328 Driver &driver = layout.get_driver();
332 bool intent_to_move = false;
333 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
336 if((*i)->has_intent_to_move())
337 intent_to_move = true;
340 controller->tick(dt);
341 float speed = controller->get_speed();
342 bool moving = speed>0;
344 if(controller->get_reverse()!=reverse)
346 reverse = controller->get_reverse();
348 if(loco_type.get_swap_direction())
350 driver.set_loco_reverse(loco_id, r);
353 last_entry_block = BlockIter();
358 unsigned speed_step = speed_quantizer->find_speed_step(speed);
359 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
361 speed_changing = true;
362 driver.set_loco_speed(loco_id, speed_step);
367 speed = speed_quantizer->get_speed(current_speed_step);
372 if(!allocator.is_active())
373 allocator.set_active(true);
375 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
377 float d = speed*(dt/Time::sec);
378 Block &block = vehicle.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE)->get_block();
379 if(allocator.is_block_current(block))
381 SetFlag setf(advancing);
382 vehicle.advance(reverse ? -d : d);
384 else if(accurate_position)
387 if(overshoot_dist>40*layout.get_catalogue().get_scale())
389 layout.emergency(&block, name+" has not arrived at sensor");
390 accurate_position = false;
394 else if(intent_to_move && !allocator.is_active())
395 allocator.set_active(true);
396 else if(allocator.is_active() && !intent_to_move && !stop_timeout)
397 stop_timeout = 2*Time::sec;
400 void Train::save(list<DataFile::Statement> &st) const
402 st.push_back((DataFile::Statement("name"), name));
404 const Catalogue &cat = layout.get_catalogue();
405 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
406 if(i!=vehicles.begin())
407 st.push_back((DataFile::Statement("vehicle"), cat.get_name(&(*i)->get_type())));
411 DataFile::Statement ss("quantized_speed");
412 speed_quantizer->save(ss.sub);
417 DataFile::Statement ss("blocks");
418 allocator.save(ss.sub);
422 const VehicleType::FunctionMap &func_map = loco_type.get_functions();
423 for(VehicleType::FunctionMap::const_iterator i=func_map.begin(); i!=func_map.end(); ++i)
424 st.push_back((DataFile::Statement("function"), i->first, static_cast<bool>(functions&(1<<i->first))));
426 // XXX Need more generic way of saving AI state
427 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
429 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
431 DataFile::Statement ss("router");
432 router->save(ss.sub);
435 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
437 DataFile::Statement ss("timetable");
438 timetable->save(ss.sub);
444 void Train::control_changed(const Controller::Control &ctrl)
446 signal_control_changed.emit(ctrl.name, ctrl.value);
449 void Train::loco_speed_event(unsigned id, unsigned speed, bool rev)
453 current_speed_step = speed;
455 if(loco_type.get_swap_direction())
458 layout.get_driver().set_loco_reverse(loco_id, r);
459 speed_changing = false;
464 void Train::loco_func_event(unsigned id, unsigned func, bool state)
469 functions |= 1<<func;
471 functions &= ~(1<<func);
473 signal_function_changed.emit(func, state);
477 void Train::advanced(Block &block, Sensor *sensor)
479 if(!sensor || sensor==block.get_sensor())
480 signal_advanced.emit(block);
485 if(sensor==block.get_sensor())
487 if(last_entry_block && pure_speed && speed_quantizer)
489 float travel_distance = 0;
491 for(BlockIter i=last_entry_block; &*i!=█ i=i.next())
492 travel_distance += i->get_path_length(i.entry());
494 if(travel_distance>0)
496 float travel_time_secs = travel_time/Time::sec;
498 if(travel_time_secs>=2)
499 speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
503 last_entry_block = allocator.iter_for(block);
504 travel_time = Time::zero;
505 if(!layout.get_driver().is_halted())
508 accurate_position = true;
512 if(!advancing && vehicles.front()->is_placed())
514 TrackIter track = last_entry_block.track_iter();
517 track = track.flip();
518 vehicles.back()->place(track, VehiclePlacement::BACK_AXLE);
521 vehicles.front()->place(track, VehiclePlacement::FRONT_AXLE);
524 else if(BeamGate *gate = dynamic_cast<BeamGate *>(sensor))
526 if(!advancing && vehicles.front()->is_placed())
528 TrackIter track = allocator.iter_for(block).track_iter();
529 for(; (track && &track->get_block()==&block); track=track.next())
530 if(track.track()==gate->get_track())
533 track = track.reverse();
534 float offset = gate->get_offset_from_endpoint(track.entry());
536 vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
538 vehicles.front()->place(TrackOffsetIter(track, offset), VehiclePlacement::FRONT_BUFFER);
545 void Train::halt_event(bool h)
548 accurate_position = false;
551 float Train::get_reserved_distance_until(const Block *until_block) const
553 if(allocator.empty())
556 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
558 TrackOffsetIter track = veh.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE);
559 if(!track) // XXX Probably unnecessary
562 if(&track->get_block()==until_block)
565 // Account for the vehicle's offset on its current track
566 float result = track.offset();
568 track = track.reverse();
570 result = track->get_path_length()-result;
571 result -= veh.get_type().get_length()/2;
573 BlockIter block = track.block_iter();
575 // Count remaining distance in the vehicle's current block
576 for(track=track.next(); &track->get_block()==&*block; track=track.next())
577 result += track->get_path_length();
579 const BlockIter &last = allocator.last();
583 // Count any remaining blocks
584 for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
586 result += block->get_path_length(block.entry());
596 Train::Loader::Loader(Train &t):
597 DataFile::ObjectLoader<Train>(t),
601 add("blocks", &Loader::blocks);
602 add("function", &Loader::function);
603 add("name", &Loader::name);
604 add("quantized_speed", &Loader::quantized_speed);
605 add("router", &Loader::router);
606 add("timetable", &Loader::timetable);
607 add("vehicle", &Loader::vehicle);
610 void Train::Loader::finish()
612 if(!obj.allocator.empty())
614 TrackIter track = obj.allocator.first().track_iter();
615 float offset = 2*obj.layout.get_catalogue().get_scale();
616 obj.vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
620 void Train::Loader::blocks()
622 load_sub(obj.allocator);
625 void Train::Loader::function(unsigned f, bool s)
627 obj.set_function(f, s);
630 void Train::Loader::name(const string &n)
635 void Train::Loader::quantized_speed()
637 if(obj.speed_quantizer)
638 load_sub(*obj.speed_quantizer);
641 void Train::Loader::router()
643 TrainRouter *rtr = new TrainRouter(obj);
647 void Train::Loader::timetable()
649 Timetable *ttbl = new Timetable(obj);
650 load_sub(*ttbl, obj.layout);
653 void Train::Loader::vehicle(const string &n)
655 const VehicleType &vtype = obj.layout.get_catalogue().get<VehicleType>(n);
656 Vehicle *veh = new Vehicle(obj.layout, vtype);
657 obj.vehicles.back()->attach_back(*veh);
658 obj.vehicles.push_back(veh);
659 veh->set_train(&obj);