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"
14 #include "simplecontroller.h"
15 #include "speedquantizer.h"
16 #include "trackcircuit.h"
17 #include "trackiter.h"
18 #include "tracktype.h"
20 #include "trainrouter.h"
22 #include "vehicletype.h"
30 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
38 controller(new SimpleController),
40 current_speed_step(0),
41 speed_changing(false),
46 accurate_position(false),
49 if(!loco_type.is_locomotive())
50 throw invalid_argument("Train::Train");
52 unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
54 speed_quantizer = new SpeedQuantizer(speed_steps);
56 vehicles.push_back(new Vehicle(layout, loco_type));
58 layout.add_train(*this);
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));
64 layout.signal_sensor_state_changed.connect(sigc::mem_fun(this, &Train::sensor_state_changed));
66 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
68 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
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);
93 void Train::remove_vehicle(unsigned i)
95 if(i>=vehicles.size())
96 throw out_of_range("Train::remove_vehicle");
98 throw logic_error("can't remove locomotive");
100 vehicles.erase(vehicles.begin()+i);
101 if(i<vehicles.size())
102 vehicles[i-1]->attach_back(*vehicles[i]);
105 unsigned Train::get_n_vehicles() const
107 return vehicles.size();
110 Vehicle &Train::get_vehicle(unsigned i)
112 if(i>=vehicles.size())
113 throw out_of_range("Train::get_vehicle");
117 const Vehicle &Train::get_vehicle(unsigned i) const
119 if(i>=vehicles.size())
120 throw out_of_range("Train::get_vehicle");
124 void Train::set_control(const string &n, float v)
126 controller->set_control(n, v);
129 void Train::set_active(bool a)
133 if(!a && controller->get_speed())
134 throw logic_error("moving");
139 stop_timeout = Time::zero;
140 allocator.reserve_more();
143 stop_timeout = 2*Time::sec;
146 void Train::set_function(unsigned func, bool state)
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);
153 float Train::get_control(const string &ctrl) const
155 return controller->get_control(ctrl).value;
158 float Train::get_speed() const
160 return controller->get_speed();
163 float Train::get_quantized_speed() const
166 return speed_quantizer->quantize_speed(controller->get_speed());
168 return controller->get_speed();
171 bool Train::get_function(unsigned func) const
173 return (functions>>func)&1;
176 void Train::add_ai(TrainAI &ai)
179 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
182 void Train::remove_ai(TrainAI &ai)
184 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
189 void Train::ai_message(const TrainAI::Message &msg)
191 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
195 void Train::place(const BlockIter &block)
198 throw invalid_argument("Train::place");
199 if(controller->get_speed())
200 throw logic_error("moving");
203 accurate_position = false;
205 allocator.start_from(block);
208 vehicles.front()->place(block.reverse().track_iter(), 0, Vehicle::FRONT_BUFFER);
210 vehicles.back()->place(block.track_iter(), 0, Vehicle::BACK_BUFFER);
213 void Train::unplace()
215 if(controller->get_speed())
216 throw logic_error("moving");
221 accurate_position = false;
223 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
227 void Train::stop_at(Block *block)
229 allocator.stop_at(block);
231 allocator.reserve_more();
234 bool Train::free_block(Block &block)
236 if(get_reserved_distance_until(&block)<controller->get_braking_distance()*1.3)
239 return allocator.release_from(block);
242 void Train::free_noncritical_blocks()
244 if(allocator.empty())
247 if(controller->get_speed()==0)
249 allocator.release_noncurrent();
253 float margin = 10*layout.get_catalogue().get_scale();
254 float min_dist = controller->get_braking_distance()*1.3+margin;
256 BlockIter i = allocator.last_current().next();
258 bool sensor_seen = false;
259 for(; i->get_train()==this; i=i.next())
261 if(dist>min_dist && sensor_seen)
263 allocator.release_from(*i);
267 dist += i->get_path_length(i.entry());
269 if(i->get_sensor_id())
274 float Train::get_reserved_distance() const
276 if(allocator.empty())
280 TrackIter next = allocator.last().next().track_iter();
281 if(next && next->get_type().is_turnout())
282 margin = 15*layout.get_catalogue().get_scale();
284 return max(get_reserved_distance_until(0)-margin, 0.0f);
287 void Train::reserve_more()
289 allocator.reserve_more();
292 void Train::tick(const Time::TimeDelta &dt)
294 if(!active && stop_timeout)
297 if(stop_timeout<=Time::zero)
299 allocator.release_noncurrent();
300 stop_timeout = Time::TimeDelta();
306 Driver &driver = layout.get_driver();
308 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
310 controller->tick(dt);
311 float speed = controller->get_speed();
312 bool moving = speed>0;
314 if(controller->get_reverse()!=reverse)
316 reverse = controller->get_reverse();
318 if(loco_type.get_swap_direction())
320 driver.set_loco_reverse(address, r);
324 allocator.reserve_more();
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())
332 speed_changing = true;
333 driver.set_loco_speed(address, speed_step);
338 speed = speed_quantizer->get_speed(current_speed_step);
346 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
348 float d = speed*(dt/Time::sec);
349 if(allocator.is_block_current(vehicle.get_track()->get_block()))
351 SetFlag setf(advancing);
352 vehicle.advance(reverse ? -d : d);
354 else if(accurate_position)
357 if(overshoot_dist>40*layout.get_catalogue().get_scale())
359 layout.emergency(name+" has not arrived at sensor");
360 accurate_position = false;
366 void Train::save(list<DataFile::Statement> &st) const
368 st.push_back((DataFile::Statement("name"), name));
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()));
376 DataFile::Statement ss("quantized_speed");
377 speed_quantizer->save(ss.sub);
382 DataFile::Statement ss("blocks");
383 allocator.save(ss.sub);
387 // XXX Need more generic way of saving AI state
388 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
390 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
392 DataFile::Statement ss("router");
393 router->save(ss.sub);
399 void Train::control_changed(const Controller::Control &ctrl)
401 signal_control_changed.emit(ctrl.name, ctrl.value);
404 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
408 current_speed_step = speed;
410 if(loco_type.get_swap_direction())
413 layout.get_driver().set_loco_reverse(address, r);
414 speed_changing = false;
419 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
424 functions |= 1<<func;
426 functions &= ~(1<<func);
428 signal_function_changed.emit(func, state);
432 void Train::sensor_state_changed(Sensor &sensor, Sensor::State state)
435 if(TrackCircuit *tc = dynamic_cast<TrackCircuit *>(&sensor))
436 block = &tc->get_block();
440 if(block->get_train()==this && state==Sensor::MAYBE_ACTIVE)
444 float travel_distance = -1;
445 if(pure_speed && speed_quantizer && current_speed_step>0)
448 for(BlockIter i=last_entry_block; &*i!=block; i=i.next())
450 if(i->get_sensor_id())
452 if(travel_distance>=0)
453 travel_distance += i->get_path_length(i.entry());
456 if(travel_distance>0)
458 float travel_time_secs = travel_time/Time::sec;
460 if(travel_time_secs>=2)
461 speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
465 last_entry_block = allocator.iter_for(*block);
466 travel_time = Time::zero;
468 accurate_position = true;
471 if(!advancing && vehicles.front()->get_track())
473 TrackIter track = last_entry_block.track_iter();
476 track = track.flip();
477 vehicles.back()->place(track, 0, Vehicle::BACK_AXLE);
480 vehicles.front()->place(track, 0, Vehicle::FRONT_AXLE);
485 void Train::halt_event(bool h)
488 accurate_position = false;
491 float Train::get_reserved_distance_until(const Block *until_block) const
493 if(allocator.empty())
496 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
498 TrackIter track = veh.get_track_iter();
499 if(!track) // XXX Probably unnecessary
502 BlockIter block = track.block_iter();
503 if(&*block==until_block)
506 // Account for the vehicle's offset on its current track
507 float result = veh.get_offset();
509 track = track.reverse();
511 result = track->get_type().get_path_length(track->get_active_path())-result;
512 result -= veh.get_type().get_length()/2;
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());
518 const BlockIter &last = allocator.last();
522 // Count any remaining blocks
523 for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
525 result += block->get_path_length(block.entry());
535 Train::Loader::Loader(Train &t):
536 DataFile::ObjectLoader<Train>(t),
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);
547 void Train::Loader::finish()
549 if(!obj.allocator.empty())
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);
557 void Train::Loader::blocks()
559 load_sub(obj.allocator);
562 void Train::Loader::name(const string &n)
567 void Train::Loader::quantized_speed()
569 if(obj.speed_quantizer)
570 load_sub(*obj.speed_quantizer);
573 void Train::Loader::router()
575 TrainRouter *rtr = new TrainRouter(obj);
579 void Train::Loader::vehicle(ArticleNumber art_nr)
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);