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),
39 current_speed_step(0),
40 speed_changing(false),
45 accurate_position(false),
48 if(!loco_type.is_locomotive())
49 throw invalid_argument("Train::Train");
51 unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
53 speed_quantizer = new SpeedQuantizer(speed_steps);
55 vehicles.push_back(new Vehicle(layout, loco_type));
57 layout.add_train(*this);
59 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.signal_sensor_state_changed.connect(sigc::mem_fun(this, &Train::sensor_state_changed));
65 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
67 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
73 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
75 layout.remove_train(*this);
78 void Train::set_name(const string &n)
82 signal_name_changed.emit(name);
85 void Train::add_vehicle(const VehicleType &vt)
87 Vehicle *veh = new Vehicle(layout, vt);
88 vehicles.back()->attach_back(*veh);
89 vehicles.push_back(veh);
92 void Train::remove_vehicle(unsigned i)
94 if(i>=vehicles.size())
95 throw out_of_range("Train::remove_vehicle");
97 throw logic_error("can't remove locomotive");
99 vehicles.erase(vehicles.begin()+i);
100 if(i<vehicles.size())
101 vehicles[i-1]->attach_back(*vehicles[i]);
104 unsigned Train::get_n_vehicles() const
106 return vehicles.size();
109 Vehicle &Train::get_vehicle(unsigned i)
111 if(i>=vehicles.size())
112 throw out_of_range("Train::get_vehicle");
116 const Vehicle &Train::get_vehicle(unsigned i) const
118 if(i>=vehicles.size())
119 throw out_of_range("Train::get_vehicle");
123 void Train::set_control(const string &n, float v)
125 controller->set_control(n, v);
128 void Train::set_function(unsigned func, bool state)
130 if(!loco_type.get_functions().count(func))
131 throw invalid_argument("Train::set_function");
132 layout.get_driver().set_loco_function(address, func, state);
135 float Train::get_control(const string &ctrl) const
137 return controller->get_control(ctrl).value;
140 float Train::get_speed() const
142 return controller->get_speed();
145 float Train::get_quantized_speed() const
148 return speed_quantizer->quantize_speed(controller->get_speed());
150 return controller->get_speed();
153 bool Train::get_function(unsigned func) const
155 return (functions>>func)&1;
158 void Train::add_ai(TrainAI &ai)
161 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
164 void Train::remove_ai(TrainAI &ai)
166 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
171 void Train::ai_message(const TrainAI::Message &msg)
173 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
177 void Train::place(const BlockIter &block)
180 throw invalid_argument("Train::place");
181 if(controller->get_speed())
182 throw logic_error("moving");
184 allocator.start_from(block);
185 accurate_position = false;
188 vehicles.front()->place(block.reverse().track_iter(), 0, Vehicle::FRONT_BUFFER);
190 vehicles.back()->place(block.track_iter(), 0, Vehicle::BACK_BUFFER);
193 void Train::unplace()
195 if(controller->get_speed())
196 throw logic_error("moving");
199 accurate_position = false;
201 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
205 void Train::stop_at(Block *block)
207 allocator.stop_at(block);
210 bool Train::is_block_critical(const Block &block) const
212 return get_reserved_distance_until(&block)<controller->get_braking_distance()*1.3;
215 BlockIter Train::get_first_noncritical_block() const
217 if(allocator.empty())
220 BlockIter i = allocator.last_current().next();
222 if(controller->get_speed()==0)
225 float margin = 10*layout.get_catalogue().get_scale();
226 float min_dist = controller->get_braking_distance()*1.3+margin;
229 bool sensor_seen = false;
230 for(; i->get_train()==this; i=i.next())
232 if(dist>min_dist && sensor_seen)
235 dist += i->get_path_length(i.entry());
237 if(i->get_sensor_id())
244 void Train::refresh_blocks_from(Block &block)
246 if(is_block_critical(block))
247 allocator.rewind_to(*get_first_noncritical_block());
249 allocator.rewind_to(block);
252 float Train::get_reserved_distance() const
254 if(allocator.empty())
258 TrackIter next = allocator.last().next().track_iter();
259 if(next && next->get_type().is_turnout())
260 margin = 15*layout.get_catalogue().get_scale();
262 return max(get_reserved_distance_until(0)-margin, 0.0f);
265 void Train::tick(const Time::TimeDelta &dt)
270 if(stop_timeout<=Time::zero)
272 allocator.set_active(false);
273 stop_timeout = Time::TimeDelta();
279 Driver &driver = layout.get_driver();
281 bool intent_to_move = false;
282 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
285 if((*i)->has_intent_to_move())
286 intent_to_move = true;
289 controller->tick(dt);
290 float speed = controller->get_speed();
291 bool moving = speed>0;
293 if(controller->get_reverse()!=reverse)
295 reverse = controller->get_reverse();
297 if(loco_type.get_swap_direction())
299 driver.set_loco_reverse(address, r);
306 unsigned speed_step = speed_quantizer->find_speed_step(speed);
307 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
309 speed_changing = true;
310 driver.set_loco_speed(address, speed_step);
315 speed = speed_quantizer->get_speed(current_speed_step);
320 if(!allocator.is_active())
321 allocator.set_active(true);
323 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
325 float d = speed*(dt/Time::sec);
326 if(allocator.is_block_current(vehicle.get_track()->get_block()))
328 SetFlag setf(advancing);
329 vehicle.advance(reverse ? -d : d);
331 else if(accurate_position)
334 if(overshoot_dist>40*layout.get_catalogue().get_scale())
336 layout.emergency(name+" has not arrived at sensor");
337 accurate_position = false;
341 else if(allocator.is_active() && !intent_to_move && !stop_timeout)
342 stop_timeout = 2*Time::sec;
345 void Train::save(list<DataFile::Statement> &st) const
347 st.push_back((DataFile::Statement("name"), name));
349 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
350 if(i!=vehicles.begin())
351 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
355 DataFile::Statement ss("quantized_speed");
356 speed_quantizer->save(ss.sub);
361 DataFile::Statement ss("blocks");
362 allocator.save(ss.sub);
366 // XXX Need more generic way of saving AI state
367 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
369 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
371 DataFile::Statement ss("router");
372 router->save(ss.sub);
378 void Train::control_changed(const Controller::Control &ctrl)
380 signal_control_changed.emit(ctrl.name, ctrl.value);
383 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
387 current_speed_step = speed;
389 if(loco_type.get_swap_direction())
392 layout.get_driver().set_loco_reverse(address, r);
393 speed_changing = false;
398 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
403 functions |= 1<<func;
405 functions &= ~(1<<func);
407 signal_function_changed.emit(func, state);
411 void Train::sensor_state_changed(Sensor &sensor, Sensor::State state)
414 if(TrackCircuit *tc = dynamic_cast<TrackCircuit *>(&sensor))
415 block = &tc->get_block();
419 if(block->get_train()==this && state==Sensor::MAYBE_ACTIVE)
423 float travel_distance = -1;
424 if(pure_speed && speed_quantizer && current_speed_step>0)
427 for(BlockIter i=last_entry_block; &*i!=block; i=i.next())
429 if(i->get_sensor_id())
431 if(travel_distance>=0)
432 travel_distance += i->get_path_length(i.entry());
435 if(travel_distance>0)
437 float travel_time_secs = travel_time/Time::sec;
439 if(travel_time_secs>=2)
440 speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
444 last_entry_block = allocator.iter_for(*block);
445 travel_time = Time::zero;
447 accurate_position = true;
450 if(!advancing && vehicles.front()->get_track())
452 TrackIter track = last_entry_block.track_iter();
455 track = track.flip();
456 vehicles.back()->place(track, 0, Vehicle::BACK_AXLE);
459 vehicles.front()->place(track, 0, Vehicle::FRONT_AXLE);
464 void Train::halt_event(bool h)
467 accurate_position = false;
470 float Train::get_reserved_distance_until(const Block *until_block) const
472 if(allocator.empty())
475 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
477 TrackIter track = veh.get_track_iter();
478 if(!track) // XXX Probably unnecessary
481 BlockIter block = track.block_iter();
482 if(&*block==until_block)
485 // Account for the vehicle's offset on its current track
486 float result = veh.get_offset();
488 track = track.reverse();
490 result = track->get_type().get_path_length(track->get_active_path())-result;
491 result -= veh.get_type().get_length()/2;
493 // Count remaining distance in the vehicle's current block
494 for(track=track.next(); &track->get_block()==&*block; track=track.next())
495 result += track->get_type().get_path_length(track->get_active_path());
497 const BlockIter &last = allocator.last();
501 // Count any remaining blocks
502 for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
504 result += block->get_path_length(block.entry());
514 Train::Loader::Loader(Train &t):
515 DataFile::ObjectLoader<Train>(t),
519 add("blocks", &Loader::blocks);
520 add("name", &Loader::name);
521 add("quantized_speed", &Loader::quantized_speed);
522 add("router", &Loader::router);
523 add("vehicle", &Loader::vehicle);
526 void Train::Loader::finish()
528 if(!obj.allocator.empty())
530 TrackIter track = obj.allocator.first().track_iter();
531 float offset = 2*obj.layout.get_catalogue().get_scale();
532 obj.vehicles.back()->place(track, offset, Vehicle::BACK_BUFFER);
536 void Train::Loader::blocks()
538 load_sub(obj.allocator);
541 void Train::Loader::name(const string &n)
546 void Train::Loader::quantized_speed()
548 if(obj.speed_quantizer)
549 load_sub(*obj.speed_quantizer);
552 void Train::Loader::router()
554 TrainRouter *rtr = new TrainRouter(obj);
558 void Train::Loader::vehicle(ArticleNumber art_nr)
560 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
561 Vehicle *veh = new Vehicle(obj.layout, vtype);
562 obj.vehicles.back()->attach_back(*veh);
563 obj.vehicles.push_back(veh);