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>
11 #include "catalogue.h"
15 #include "simplecontroller.h"
16 #include "speedquantizer.h"
17 #include "trackcircuit.h"
18 #include "trackiter.h"
19 #include "tracktype.h"
21 #include "trainrouter.h"
23 #include "vehicletype.h"
31 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
39 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));
57 vehicles.back()->set_train(this);
59 layout.add_train(*this);
61 loco_id = layout.get_driver().add_loco(address, protocol, loco_type);
62 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
63 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
65 layout.signal_sensor_state_changed.connect(sigc::mem_fun(this, &Train::sensor_state_changed));
67 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
69 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
75 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
77 layout.remove_train(*this);
80 void Train::set_name(const string &n)
84 signal_name_changed.emit(name);
87 void Train::add_vehicle(const VehicleType &vt)
89 Vehicle *veh = new Vehicle(layout, vt);
90 vehicles.back()->attach_back(*veh);
91 vehicles.push_back(veh);
93 signal_vehicle_added.emit(vehicles.size()-1, *veh);
96 void Train::remove_vehicle(unsigned i)
98 if(i>=vehicles.size())
99 throw out_of_range("Train::remove_vehicle");
101 throw logic_error("can't remove locomotive");
103 Vehicle *veh = vehicles[i];
104 vehicles.erase(vehicles.begin()+i);
106 if(i<vehicles.size())
109 vehicles[i-1]->attach_back(*vehicles[i]);
111 signal_vehicle_removed.emit(i, *veh);
115 unsigned Train::get_n_vehicles() const
117 return vehicles.size();
120 Vehicle &Train::get_vehicle(unsigned i)
122 if(i>=vehicles.size())
123 throw out_of_range("Train::get_vehicle");
127 const Vehicle &Train::get_vehicle(unsigned i) const
129 if(i>=vehicles.size())
130 throw out_of_range("Train::get_vehicle");
134 void Train::set_control(const string &n, float v)
136 controller->set_control(n, v);
139 void Train::set_function(unsigned func, bool state)
141 if(!loco_type.get_functions().count(func))
142 throw invalid_argument("Train::set_function");
143 layout.get_driver().set_loco_function(loco_id, func, state);
146 float Train::get_control(const string &ctrl) const
148 return controller->get_control(ctrl).value;
151 float Train::get_speed() const
153 return controller->get_speed();
156 float Train::get_quantized_speed() const
159 return speed_quantizer->quantize_speed(controller->get_speed());
161 return controller->get_speed();
164 float Train::get_maximum_speed() const
167 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
169 float vms = (*i)->get_type().get_maximum_speed();
170 if(ms<=0 || (vms>0 && vms<ms))
176 bool Train::get_function(unsigned func) const
178 return (functions>>func)&1;
181 void Train::add_ai(TrainAI &ai)
184 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
187 void Train::remove_ai(TrainAI &ai)
189 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
194 void Train::ai_message(const TrainAI::Message &msg)
196 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
200 bool Train::place(const BlockIter &block)
203 throw invalid_argument("Train::place");
204 if(controller->get_speed())
205 throw logic_error("moving");
207 accurate_position = false;
208 last_entry_block = BlockIter();
210 if(allocator.start_from(block))
213 vehicles.front()->place(block.reverse().track_iter(), VehiclePlacement::FRONT_BUFFER);
215 vehicles.back()->place(block.track_iter(), VehiclePlacement::BACK_BUFFER);
225 void Train::unplace()
227 if(controller->get_speed())
228 throw logic_error("moving");
231 accurate_position = false;
232 last_entry_block = BlockIter();
234 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
238 void Train::stop_at(Block *block)
240 allocator.stop_at(block);
243 bool Train::is_block_critical(const Block &block) const
245 return get_reserved_distance_until(&block)<=controller->get_braking_distance()*1.3;
248 BlockIter Train::get_first_noncritical_block() const
250 if(allocator.empty())
253 BlockIter i = allocator.last_current().next();
255 if(controller->get_speed()==0)
258 float margin = 10*layout.get_catalogue().get_scale();
259 float min_dist = controller->get_braking_distance()*1.3+margin;
262 bool sensor_seen = false;
263 for(; i->get_train()==this; i=i.next())
265 if(dist>min_dist && sensor_seen)
268 dist += i->get_path_length(i.entry());
270 if(i->get_sensor_address())
277 void Train::refresh_blocks_from(Block &block)
279 if(is_block_critical(block))
280 allocator.rewind_to(*get_first_noncritical_block());
282 allocator.rewind_to(block);
285 float Train::get_reserved_distance() const
287 if(allocator.empty())
291 TrackIter next = allocator.last().next().track_iter();
292 if(next && next->get_type().is_turnout())
293 margin = 15*layout.get_catalogue().get_scale();
295 return max(get_reserved_distance_until(0)-margin, 0.0f);
298 void Train::tick(const Time::TimeDelta &dt)
303 if(stop_timeout<=Time::zero)
305 allocator.set_active(false);
306 stop_timeout = Time::TimeDelta();
312 Driver &driver = layout.get_driver();
314 bool intent_to_move = false;
315 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
318 if((*i)->has_intent_to_move())
319 intent_to_move = true;
322 controller->tick(dt);
323 float speed = controller->get_speed();
324 bool moving = speed>0;
326 if(controller->get_reverse()!=reverse)
328 reverse = controller->get_reverse();
330 if(loco_type.get_swap_direction())
332 driver.set_loco_reverse(loco_id, r);
335 last_entry_block = BlockIter();
340 unsigned speed_step = speed_quantizer->find_speed_step(speed);
341 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
343 speed_changing = true;
344 driver.set_loco_speed(loco_id, speed_step);
349 speed = speed_quantizer->get_speed(current_speed_step);
354 if(!allocator.is_active())
355 allocator.set_active(true);
357 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
359 float d = speed*(dt/Time::sec);
360 if(allocator.is_block_current(vehicle.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE)->get_block()))
362 SetFlag setf(advancing);
363 vehicle.advance(reverse ? -d : d);
365 else if(accurate_position)
368 if(overshoot_dist>40*layout.get_catalogue().get_scale())
370 layout.emergency(name+" has not arrived at sensor");
371 accurate_position = false;
375 else if(intent_to_move && !allocator.is_active())
376 allocator.set_active(true);
377 else if(allocator.is_active() && !intent_to_move && !stop_timeout)
378 stop_timeout = 2*Time::sec;
381 void Train::save(list<DataFile::Statement> &st) const
383 st.push_back((DataFile::Statement("name"), name));
385 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
386 if(i!=vehicles.begin())
387 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
391 DataFile::Statement ss("quantized_speed");
392 speed_quantizer->save(ss.sub);
397 DataFile::Statement ss("blocks");
398 allocator.save(ss.sub);
402 // XXX Need more generic way of saving AI state
403 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
405 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
407 DataFile::Statement ss("router");
408 router->save(ss.sub);
414 void Train::control_changed(const Controller::Control &ctrl)
416 signal_control_changed.emit(ctrl.name, ctrl.value);
419 void Train::loco_speed_event(unsigned id, unsigned speed, bool rev)
423 current_speed_step = speed;
425 if(loco_type.get_swap_direction())
428 layout.get_driver().set_loco_reverse(loco_id, r);
429 speed_changing = false;
434 void Train::loco_func_event(unsigned id, unsigned func, bool state)
439 functions |= 1<<func;
441 functions &= ~(1<<func);
443 signal_function_changed.emit(func, state);
447 void Train::sensor_state_changed(Sensor &sensor, Sensor::State state)
449 if(!current_speed_step || state!=Sensor::MAYBE_ACTIVE)
452 Block *block = sensor.get_block();
453 if(!block || block->get_train()!=this)
456 if(last_entry_block && &*last_entry_block!=block)
458 for(BlockIter i=last_entry_block.next(); (i && &*i!=block); i=i.next())
459 if(i->get_train()!=this || i->get_sensor_address())
463 if(dynamic_cast<TrackCircuit *>(&sensor))
465 if(last_entry_block && pure_speed && speed_quantizer)
467 float travel_distance = 0;
469 for(BlockIter i=last_entry_block; &*i!=block; i=i.next())
470 travel_distance += i->get_path_length(i.entry());
472 if(travel_distance>0)
474 float travel_time_secs = travel_time/Time::sec;
476 if(travel_time_secs>=2)
477 speed_quantizer->learn(current_speed_step, travel_distance/travel_time_secs, travel_time_secs);
481 last_entry_block = allocator.iter_for(*block);
482 travel_time = Time::zero;
484 accurate_position = true;
487 if(!advancing && vehicles.front()->is_placed())
489 TrackIter track = last_entry_block.track_iter();
492 track = track.flip();
493 vehicles.back()->place(track, VehiclePlacement::BACK_AXLE);
496 vehicles.front()->place(track, VehiclePlacement::FRONT_AXLE);
499 else if(BeamGate *gate = dynamic_cast<BeamGate *>(&sensor))
501 if(!advancing && vehicles.front()->is_placed())
503 TrackIter track = allocator.iter_for(*block).track_iter();
504 for(; (track && &track->get_block()==block); track=track.next())
505 if(track.track()==gate->get_track())
508 track = track.reverse();
509 float offset = gate->get_offset_from_endpoint(track.entry());
511 vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
513 vehicles.front()->place(TrackOffsetIter(track, offset), VehiclePlacement::FRONT_BUFFER);
520 void Train::halt_event(bool h)
523 accurate_position = false;
526 float Train::get_reserved_distance_until(const Block *until_block) const
528 if(allocator.empty())
531 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
533 TrackOffsetIter track = veh.get_placement().get_position(reverse ? VehiclePlacement::BACK_AXLE : VehiclePlacement::FRONT_AXLE);
534 if(!track) // XXX Probably unnecessary
537 if(&track->get_block()==until_block)
540 // Account for the vehicle's offset on its current track
541 float result = track.offset();
543 track = track.reverse();
545 result = track->get_path_length()-result;
546 result -= veh.get_type().get_length()/2;
548 BlockIter block = track.block_iter();
550 // Count remaining distance in the vehicle's current block
551 for(track=track.next(); &track->get_block()==&*block; track=track.next())
552 result += track->get_path_length();
554 const BlockIter &last = allocator.last();
558 // Count any remaining blocks
559 for(block=block.next(); (&*block!=until_block && block->get_train()==this); block=block.next())
561 result += block->get_path_length(block.entry());
571 Train::Loader::Loader(Train &t):
572 DataFile::ObjectLoader<Train>(t),
576 add("blocks", &Loader::blocks);
577 add("name", &Loader::name);
578 add("quantized_speed", &Loader::quantized_speed);
579 add("router", &Loader::router);
580 add("vehicle", &Loader::vehicle);
583 void Train::Loader::finish()
585 if(!obj.allocator.empty())
587 TrackIter track = obj.allocator.first().track_iter();
588 float offset = 2*obj.layout.get_catalogue().get_scale();
589 obj.vehicles.back()->place(TrackOffsetIter(track, offset), VehiclePlacement::BACK_BUFFER);
593 void Train::Loader::blocks()
595 load_sub(obj.allocator);
598 void Train::Loader::name(const string &n)
603 void Train::Loader::quantized_speed()
605 if(obj.speed_quantizer)
606 load_sub(*obj.speed_quantizer);
609 void Train::Loader::router()
611 TrainRouter *rtr = new TrainRouter(obj);
615 void Train::Loader::vehicle(ArticleNumber art_nr)
617 const VehicleType &vtype = obj.layout.get_catalogue().get<VehicleType>(art_nr);
618 Vehicle *veh = new Vehicle(obj.layout, vtype);
619 obj.vehicles.back()->attach_back(*veh);
620 obj.vehicles.push_back(veh);
621 veh->set_train(&obj);