3 #include <msp/core/maputils.h>
4 #include <msp/strings/format.h>
5 #include <msp/time/units.h>
6 #include <msp/time/utils.h>
12 #include "simplecontroller.h"
13 #include "speedquantizer.h"
14 #include "timetable.h"
15 #include "trackiter.h"
16 #include "tracktype.h"
18 #include "trainrouter.h"
20 #include "vehicletype.h"
32 SetFlag(bool &f): flag(f) { flag = true; }
33 ~SetFlag() { flag = false; }
41 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
47 cur_blocks_end(blocks.end()),
51 controller(new SimpleController),
53 current_speed_step(0),
54 speed_changing(false),
60 accurate_position(false),
63 if(!loco_type.is_locomotive())
64 throw invalid_argument("Train::Train");
66 unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
68 speed_quantizer = new SpeedQuantizer(speed_steps);
70 vehicles.push_back(new Vehicle(layout, loco_type));
72 layout.add_train(*this);
74 layout.get_driver().add_loco(address, protocol, loco_type);
75 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
76 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
78 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
79 layout.signal_block_state_changed.connect(sigc::mem_fun(this, &Train::block_state_changed));
81 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
83 const set<Track *> &tracks = layout.get_tracks();
84 for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
85 if((*i)->get_turnout_id())
86 (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &Train::turnout_path_changed), sigc::ref(**i))));
88 controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
94 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
96 layout.remove_train(*this);
99 void Train::set_name(const string &n)
103 signal_name_changed.emit(name);
106 void Train::add_vehicle(const VehicleType &vt)
108 Vehicle *veh = new Vehicle(layout, vt);
109 vehicles.back()->attach_back(*veh);
110 vehicles.push_back(veh);
113 void Train::remove_vehicle(unsigned i)
115 if(i>=vehicles.size())
116 throw out_of_range("Train::remove_vehicle");
118 throw logic_error("can't remove locomotive");
120 vehicles.erase(vehicles.begin()+i);
121 if(i<vehicles.size())
122 vehicles[i-1]->attach_back(*vehicles[i]);
125 unsigned Train::get_n_vehicles() const
127 return vehicles.size();
130 Vehicle &Train::get_vehicle(unsigned i)
132 if(i>=vehicles.size())
133 throw out_of_range("Train::get_vehicle");
137 const Vehicle &Train::get_vehicle(unsigned i) const
139 if(i>=vehicles.size())
140 throw out_of_range("Train::get_vehicle");
144 void Train::set_control(const string &n, float v)
146 controller->set_control(n, v);
149 void Train::set_active(bool a)
153 if(!a && controller->get_speed())
154 throw logic_error("moving");
159 stop_timeout = Time::TimeStamp();
163 stop_timeout = Time::now()+2*Time::sec;
166 void Train::set_function(unsigned func, bool state)
168 if(!loco_type.get_functions().count(func))
169 throw invalid_argument("Train::set_function");
170 layout.get_driver().set_loco_function(address, func, state);
173 float Train::get_control(const string &ctrl) const
175 return controller->get_control(ctrl).value;
178 float Train::get_speed() const
180 return controller->get_speed();
183 float Train::get_quantized_speed() const
186 return speed_quantizer->quantize_speed(controller->get_speed());
188 return controller->get_speed();
191 bool Train::get_function(unsigned func) const
193 return (functions>>func)&1;
196 void Train::add_ai(TrainAI &ai)
199 ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
202 void Train::remove_ai(TrainAI &ai)
204 list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
209 TrainAI *Train::get_tagged_ai(const string &tag) const
211 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
212 if((*i)->get_tag()==tag)
218 void Train::ai_message(const TrainAI::Message &msg)
220 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
224 void Train::place(Block &block, unsigned entry)
226 if(controller->get_speed())
227 throw logic_error("moving");
232 accurate_position = false;
234 blocks.push_back(BlockIter(&block, entry));
235 if(!block.reserve(this))
243 TrackIter track = BlockIter(&block, entry).reverse().track_iter();
244 vehicles.front()->place(*track, track.entry(), 0, Vehicle::FRONT_BUFFER);
248 const Block::Endpoint &bep = block.get_endpoint(entry);
249 vehicles.back()->place(*bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
253 void Train::unplace()
255 if(controller->get_speed())
256 throw logic_error("moving");
261 accurate_position = false;
263 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
267 void Train::stop_at(Block *block)
269 stop_at_block = block;
272 bool Train::free_block(Block &block)
274 if(get_reserved_distance_until(&block, false)<controller->get_braking_distance()*1.3)
278 for(BlockList::iterator i=cur_blocks_end; i!=blocks.end(); ++i)
280 if(i->block()==&block)
284 release_blocks(i, blocks.end());
287 else if((*i)->get_sensor_id())
294 void Train::free_noncritical_blocks()
299 if(controller->get_speed()==0)
301 release_blocks(cur_blocks_end, blocks.end());
305 float margin = 10*layout.get_catalogue().get_scale();
306 float min_dist = controller->get_braking_distance()*1.3+margin;
308 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
310 TrackIter track(veh.get_track(), veh.get_entry());
311 BlockList::iterator block = blocks.begin();
313 while(block!=blocks.end() && !(*block)->has_track(*track))
316 if(block==cur_blocks_end)
320 float dist = veh.get_offset();
324 dist = track->get_type().get_path_length(track->get_active_path())-dist;
325 dist -= veh.get_type().get_length()/2;
330 track = track.next();
332 if(!(*block)->has_track(*track))
335 if(block==cur_blocks_end)
337 if(block==blocks.end())
340 if(dist>min_dist && nsens>0)
342 release_blocks(block, blocks.end());
346 if(in_rsv && (*block)->get_sensor_id())
350 dist += track->get_type().get_path_length(track->get_active_path());
354 const BlockIter &Train::get_head_block() const
357 throw logic_error("no blocks");
358 return blocks.back();
361 const BlockIter &Train::get_tail_block() const
364 throw logic_error("no blocks");
365 return blocks.front();
368 int Train::get_entry_to_block(const Block &block) const
370 for(BlockList::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
371 if(i->block()==&block)
376 float Train::get_reserved_distance() const
382 TrackIter next = blocks.back().next().track_iter();
383 if(next && next->get_type().is_turnout())
384 margin = 15*layout.get_catalogue().get_scale();
386 return max(get_reserved_distance_until(pending_block, false)-margin, 0.0f);
389 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
391 if(!active && stop_timeout && t>=stop_timeout)
393 release_blocks(cur_blocks_end, blocks.end());
394 stop_timeout = Time::TimeStamp();
397 Driver &driver = layout.get_driver();
399 for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
401 controller->tick(dt);
402 float speed = controller->get_speed();
403 bool moving = speed>0;
405 if(controller->get_reverse()!=reverse)
407 reverse = controller->get_reverse();
409 if(loco_type.get_swap_direction())
411 driver.set_loco_reverse(address, r);
413 release_blocks(cur_blocks_end, blocks.end());
414 reverse_blocks(blocks);
421 unsigned speed_step = speed_quantizer->find_speed_step(speed);
422 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
424 speed_changing = true;
425 driver.set_loco_speed(address, speed_step);
430 speed = speed_quantizer->get_speed(current_speed_step);
438 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
439 Track *track = vehicle.get_track();
442 for(BlockList::const_iterator i=blocks.begin(); (!ok && i!=cur_blocks_end); ++i)
443 ok = (*i)->has_track(*track);
445 float d = speed*(dt/Time::sec);
448 SetFlag setf(advancing);
449 vehicle.advance(reverse ? -d : d);
451 else if(accurate_position)
454 if(overshoot_dist>40*layout.get_catalogue().get_scale())
456 layout.emergency(name+" has not arrived at sensor");
457 accurate_position = false;
462 if(!blocks.empty() && !blocks.front()->get_sensor_id())
464 float dist = get_reserved_distance_until(&*blocks.front(), true);
466 if(dist>10*layout.get_catalogue().get_scale())
468 Block &block = *blocks.front();
475 void Train::save(list<DataFile::Statement> &st) const
477 st.push_back((DataFile::Statement("name"), name));
479 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
480 if(i!=vehicles.begin())
481 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
485 DataFile::Statement ss("quantized_speed");
486 speed_quantizer->save(ss.sub);
490 if(!blocks.empty() && cur_blocks_end!=blocks.begin())
492 BlockList blks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
494 reverse_blocks(blks);
496 BlockIter prev = blks.front().flip();
497 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
499 for(BlockList::const_iterator i=blks.begin(); i!=blks.end(); ++i)
500 st.push_back((DataFile::Statement("block"), (*i)->get_id()));
503 // XXX Need more generic way of saving AI state
504 for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
506 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
508 DataFile::Statement ss("router");
509 router->save(ss.sub);
512 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
514 DataFile::Statement ss("timetable");
515 timetable->save(ss.sub);
521 void Train::control_changed(const Controller::Control &ctrl)
523 signal_control_changed.emit(ctrl.name, ctrl.value);
526 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
530 current_speed_step = speed;
532 if(loco_type.get_swap_direction())
535 layout.get_driver().set_loco_reverse(address, r);
536 speed_changing = false;
541 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
546 functions |= 1<<func;
548 functions &= ~(1<<func);
550 signal_function_changed.emit(func, state);
554 void Train::block_state_changed(Block &block, Block::State state)
556 if(state==Block::MAYBE_ACTIVE)
558 // Find the first sensor block from our reserved blocks that isn't this sensor
559 BlockList::iterator end;
561 for(end=cur_blocks_end; end!=blocks.end(); ++end)
562 if((*end)->get_sensor_id())
579 // Compute speed and update related state
580 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
582 if(pure_speed && speed_quantizer && current_speed_step>0 && travel_time_secs>=2)
583 speed_quantizer->learn(current_speed_step, travel_dist/travel_time_secs, travel_time_secs);
586 for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
588 travel_dist += (*j)->get_path_length(j->entry());
590 if(&**j==&block && !advancing)
592 TrackIter track = j->track_iter();
595 track = track.flip();
596 vehicles.back()->place(*track, track.entry(), 0, Vehicle::BACK_AXLE);
599 vehicles.front()->place(*track, track.entry(), 0, Vehicle::FRONT_AXLE);
602 last_entry_time = Time::now();
604 accurate_position = true;
607 // Move blocks up to the next sensor to our current blocks
608 for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
609 signal_advanced.emit(**j);
610 cur_blocks_end = end;
612 // Try to get more blocks if we're moving
617 layout.emergency("Sensor for "+name+" triggered out of order");
619 else if(state==Block::INACTIVE)
621 const Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
623 // Find the first sensor in our current blocks that's still active
624 BlockList::iterator end = blocks.begin();
625 for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
627 if((*i)->has_track(*veh.get_track()))
629 if((*i)->get_sensor_id())
631 if(layout.get_driver().get_sensor((*i)->get_sensor_id()))
641 if(end!=blocks.begin() && end!=cur_blocks_end)
642 // Free blocks up to the last inactive sensor
643 release_blocks(blocks.begin(), end);
647 void Train::turnout_path_changed(Track &track)
649 for(list<BlockIter>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
650 if((*i)->get_turnout_id()==track.get_turnout_id() && !reserving && &**i==pending_block)
654 void Train::halt_event(bool h)
657 accurate_position = false;
660 void Train::block_reserved(const Block &block, const Train *train)
662 if(&block==pending_block && !train && !reserving)
666 void Train::reserve_more()
668 if(!active || blocks.empty())
671 BlockIter start = blocks.back();
672 if(&*start==stop_at_block)
674 else if(&*start==pending_block)
676 TrackIter track = start.track_iter();
677 if(!track.endpoint().has_path(track->get_active_path()))
684 // See how many sensor blocks and how much track we already have
687 for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i)
689 if((*i)->get_sensor_id())
692 dist += (*i)->get_path_length(i->entry());
695 float approach_margin = 50*layout.get_catalogue().get_scale();
696 float min_dist = controller->get_braking_distance()*1.3+approach_margin*2;
698 BlockIter block = start;
700 SetFlag setf(reserving);
704 BlockIter last = block;
705 block = block.next();
706 if(!block || block->get_endpoints().size()<2)
707 // The track ends here
710 if(block->get_turnout_id() && !last->get_turnout_id())
712 /* We are arriving at a turnout. See if we have enough blocks and
713 distance reserved. */
714 if(nsens>=3 && dist>=min_dist)
718 blocks.push_back(block);
719 if(!block->reserve(this))
722 pending_block = &*block;
726 if(cur_blocks_end==blocks.end())
729 TrackIter track = block.track_iter();
730 if(track->is_path_changing())
732 pending_block = &*block;
737 const TrackType::Endpoint &entry_ep = track.endpoint();
738 unsigned path = track->get_active_path();
739 if(!entry_ep.has_path(path))
741 const TrackType::Endpoint &exit_ep = track.reverse().endpoint();
742 if(entry_ep.has_common_paths(exit_ep))
744 unsigned mask = entry_ep.paths&exit_ep.paths;
745 for(path=0; mask>1; ++path, mask>>=1) ;
747 track->set_active_path(path);
748 if(track->is_path_changing())
750 pending_block = &*block;
755 // XXX Do something here
760 if(&*block==stop_at_block)
763 if(block->get_sensor_id())
766 dist += block->get_path_length(block.entry());
769 // Make any sensorless blocks at the beginning immediately current
770 while(cur_blocks_end!=blocks.end() && !(*cur_blocks_end)->get_sensor_id())
774 float Train::get_reserved_distance_until(const Block *until_block, bool back) const
779 Vehicle &veh = *(reverse!=back ? vehicles.back() : vehicles.front());
780 const VehicleType &vtype = veh.get_type();
782 TrackIter track(veh.get_track(), veh.get_entry());
783 if(!track) // XXX Probably unnecessary
786 BlockList::const_iterator block = blocks.begin();
787 while(block!=blocks.end() && !(*block)->has_track(*track))
789 if(block==blocks.end() || &**block==until_block)
792 float result = veh.get_offset();
794 track = track.reverse();
796 result = track->get_type().get_path_length(track->get_active_path())-result;
797 result -= vtype.get_length()/2;
801 track = track.next();
805 if(!(*block)->has_track(*track))
809 if(block==blocks.begin())
816 if(block==blocks.end())
820 if(&**block==until_block)
824 result += track->get_type().get_path_length(track->get_active_path());
830 void Train::release_blocks()
832 release_blocks(blocks.begin(), blocks.end());
835 void Train::release_blocks(BlockList::iterator begin, BlockList::iterator end)
839 if(begin==cur_blocks_end)
840 cur_blocks_end = end;
842 Block &block = **begin;
843 blocks.erase(begin++);
848 void Train::reverse_blocks(BlockList &blks) const
851 for(BlockList::iterator i=blks.begin(); i!=blks.end(); ++i)
856 Train::Loader::Loader(Train &t):
857 DataFile::ObjectLoader<Train>(t),
861 add("block", &Loader::block);
862 add("block_hint", &Loader::block_hint);
863 add("name", &Loader::name);
864 add("quantized_speed", &Loader::quantized_speed);
865 add("router", &Loader::router);
866 add("timetable", &Loader::timetable);
867 add("vehicle", &Loader::vehicle);
870 void Train::Loader::finish()
872 if(!obj.blocks.empty())
874 TrackIter track = obj.blocks.front().track_iter();
875 float offset = 2*obj.layout.get_catalogue().get_scale();
876 obj.vehicles.back()->place(*track, track.entry(), offset, Vehicle::BACK_BUFFER);
880 void Train::Loader::block(unsigned id)
888 blk = &obj.layout.get_block(id);
890 catch(const key_error &)
892 blocks_valid = false;
898 entry = blk->get_endpoint_by_link(*prev_block);
902 obj.blocks.push_back(BlockIter(blk, entry));
905 if(blk->get_sensor_id())
906 obj.layout.get_driver().set_sensor(blk->get_sensor_id(), true);
911 void Train::Loader::block_hint(unsigned id)
915 prev_block = &obj.layout.get_block(id);
917 catch(const key_error &)
919 blocks_valid = false;
923 void Train::Loader::name(const string &n)
928 void Train::Loader::quantized_speed()
930 if(obj.speed_quantizer)
931 load_sub(*obj.speed_quantizer);
934 void Train::Loader::router()
936 TrainRouter *rtr = new TrainRouter(obj);
940 void Train::Loader::timetable()
942 Timetable *ttbl = new Timetable(obj);
946 void Train::Loader::vehicle(ArticleNumber art_nr)
948 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
949 Vehicle *veh = new Vehicle(obj.layout, vtype);
950 obj.vehicles.back()->attach_back(*veh);
951 obj.vehicles.push_back(veh);