3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2010 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
9 #include <msp/strings/formatter.h>
10 #include <msp/time/units.h>
11 #include <msp/time/utils.h>
12 #include "aicontrol.h"
13 #include "catalogue.h"
17 #include "simplecontroller.h"
18 #include "timetable.h"
19 #include "tracktype.h"
22 #include "vehicletype.h"
29 Train::Train(Layout &l, const VehicleType &t, unsigned a):
35 controller(new AIControl(*this, new SimpleController)),
39 speed_changing(false),
49 accurate_position(false),
52 if(!loco_type.is_locomotive())
53 throw InvalidParameterValue("Initial vehicle must be a locomotive");
55 vehicles.push_back(new Vehicle(layout, loco_type));
57 layout.add_train(*this);
59 layout.get_driver().add_loco(address);
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_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
64 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
65 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
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));
76 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
78 layout.remove_train(*this);
81 void Train::set_name(const string &n)
85 signal_name_changed.emit(name);
88 void Train::set_priority(int p)
93 void Train::add_vehicle(const VehicleType &vt)
95 Vehicle *veh = new Vehicle(layout, vt);
96 vehicles.back()->attach_back(*veh);
97 vehicles.push_back(veh);
100 void Train::remove_vehicle(unsigned i)
102 if(i>=vehicles.size())
103 throw InvalidParameterValue("Vehicle index out of range");
105 throw InvalidParameterValue("Can't remove the locomotive");
107 vehicles.erase(vehicles.begin()+i);
108 if(i<vehicles.size())
109 vehicles[i-1]->attach_back(*vehicles[i]);
112 unsigned Train::get_n_vehicles() const
114 return vehicles.size();
117 Vehicle &Train::get_vehicle(unsigned i)
119 if(i>=vehicles.size())
120 throw InvalidParameterValue("Vehicle index out of range");
124 const Vehicle &Train::get_vehicle(unsigned i) const
126 if(i>=vehicles.size())
127 throw InvalidParameterValue("Vehicle index out of range");
131 void Train::set_control(const string &n, float v)
133 controller->set_control(n, v);
136 void Train::set_active(bool a)
140 if(!a && controller->get_speed())
141 throw InvalidState("Can't deactivate while moving");
146 stop_timeout = Time::TimeStamp();
151 stop_timeout = Time::now()+2*Time::sec;
152 set_status("Stopped");
156 void Train::set_function(unsigned func, bool state)
158 if(!loco_type.get_functions().count(func))
159 throw InvalidParameterValue("Invalid function");
161 layout.get_driver().set_loco_function(address, func, state);
163 layout.get_driver().set_loco_function(address+1, func-4, state);
166 float Train::get_control(const string &ctrl) const
168 return controller->get_control(ctrl).value;
171 float Train::get_speed() const
173 return controller->get_speed();
176 bool Train::get_function(unsigned func) const
178 return (functions>>func)&1;
181 void Train::set_timetable(Timetable *tt)
187 void Train::set_route(const Route *r)
189 if(!rsv_blocks.empty())
191 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
192 if(i->block->get_sensor_id())
194 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
201 end_of_route = false;
205 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
206 BlockRef next = last.next();
207 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
208 if(!route->get_tracks().count(ep.track))
211 route = Route::find(*ep.track, ep.track_ep, *next_route);
217 signal_route_changed.emit(route);
220 void Train::go_to(const Track &to)
222 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
223 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
225 signal_arrived.emit();
231 if(rsv_blocks.empty())
232 last = &cur_blocks.back();
235 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
236 if(i->block->get_sensor_id())
240 BlockRef next = last->next();
241 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
243 set_route(Route::find(*ep.track, ep.track_ep, to));
246 void Train::place(Block &block, unsigned entry)
248 if(controller->get_speed())
249 throw InvalidState("Must be stopped before placing");
251 release_blocks(rsv_blocks);
252 release_blocks(cur_blocks);
255 accurate_position = false;
257 if(!block.reserve(this))
259 set_status("Unplaced");
263 cur_blocks.push_back(BlockRef(&block, entry));
266 unsigned exit = block.traverse(entry);
267 const Block::Endpoint &bep = block.get_endpoints()[exit];
268 Track *track = bep.track->get_link(bep.track_ep);
269 unsigned ep = track->get_endpoint_by_link(*bep.track);
270 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
274 const Block::Endpoint &bep = block.get_endpoints()[entry];
275 vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
279 bool Train::free_block(Block &block)
282 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
288 release_blocks(rsv_blocks, i, rsv_blocks.end());
291 else if(i->block->get_sensor_id())
298 int Train::get_entry_to_block(Block &block) const
300 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
303 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
309 float Train::get_reserved_distance() const
311 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
312 const VehicleType &vtype = veh.get_type();
314 Track *track = veh.get_track();
317 unsigned entry = veh.get_entry();
319 float result = -vtype.get_length()/2;
322 entry = track->traverse(entry);
323 result += veh.get_offset();
326 result -= veh.get_offset();
329 list<BlockRef>::const_iterator block = cur_blocks.begin();
332 if(!first || !reverse)
333 result += track->get_type().get_path_length(track->get_active_path());
336 if(track->get_type().get_endpoints().size()<2)
339 unsigned exit = track->traverse(entry);
340 Track *next = track->get_link(exit);
342 while(!block->block->get_tracks().count(next))
345 if(block==cur_blocks.end())
346 block = rsv_blocks.begin();
347 if(block==rsv_blocks.end())
351 entry = next->get_endpoint_by_link(*track);
356 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
358 if(!active && stop_timeout && t>=stop_timeout)
360 release_blocks(rsv_blocks);
361 end_of_route = false;
362 stop_timeout = Time::TimeStamp();
365 Driver &driver = layout.get_driver();
369 controller->tick(dt);
370 float speed = controller->get_speed();
371 unsigned speed_notch = find_speed(speed);
373 if(controller->get_reverse()!=reverse)
375 reverse = controller->get_reverse();
376 driver.set_loco_reverse(address, reverse);
378 release_blocks(rsv_blocks);
379 reverse_blocks(cur_blocks);
383 if(speed_notch!=current_speed && !speed_changing && !driver.is_halted() && driver.get_power())
385 speed_changing = true;
386 driver.set_loco_speed(address, speed_notch);
391 set_status(format("Traveling %d kmh", get_travel_speed()));
393 set_status("Waiting");
401 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
402 Track *track = vehicle.get_track();
405 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
406 ok = i->block->get_tracks().count(track);
408 float d = get_real_speed(current_speed)*(dt/Time::sec);
410 vehicle.advance(reverse ? -d : d);
411 else if(accurate_position)
414 if(overshoot_dist>40*layout.get_catalogue().get_scale())
416 layout.emergency(name+" has not arrived at sensor");
417 accurate_position = false;
421 else if(end_of_route && rsv_blocks.empty())
423 signal_arrived.emit();
427 if(!cur_blocks.empty() && !cur_blocks.front().block->get_sensor_id())
429 Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
431 list<BlockRef>::iterator i = cur_blocks.begin();
432 const Block::Endpoint &bep = i->block->get_endpoints()[i->entry];
434 Track *track = bep.track;
435 unsigned entry = bep.track_ep;
438 float dist = veh.get_offset();
440 dist = veh.get_track()->get_type().get_path_length(veh.get_track()->get_active_path())-dist;
441 dist -= veh.get_type().get_length()/2;
444 if(track==veh.get_track())
450 if(i!=cur_blocks.begin())
452 float path_len = track->get_type().get_path_length(track->get_active_path());
456 unsigned exit = track->traverse(entry);
457 Track *next = track->get_link(exit);
458 entry = next->get_endpoint_by_link(*track);
461 if(!i->block->get_tracks().count(track))
464 if(i==cur_blocks.end())
469 if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
471 cur_blocks.front().block->reserve(0);
472 cur_blocks.erase(cur_blocks.begin());
477 void Train::save(list<DataFile::Statement> &st) const
479 st.push_back((DataFile::Statement("name"), name));
481 st.push_back((DataFile::Statement("priority"), priority));
483 for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
484 if(i!=vehicles.begin())
485 st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
487 for(unsigned i=0; i<=14; ++i)
488 if(real_speed[i].weight)
489 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
491 if(!cur_blocks.empty())
493 list<BlockRef> blocks = cur_blocks;
495 reverse_blocks(blocks);
497 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
498 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
500 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
501 st.push_back((DataFile::Statement("block"), i->block->get_id()));
506 if(!route->is_temporary())
507 st.push_back((DataFile::Statement("route"), route->get_name()));
508 else if(next_route && !next_route->is_temporary())
509 st.push_back((DataFile::Statement("route"), next_route->get_name()));
514 DataFile::Statement ss("timetable");
515 timetable->save(ss.sub);
520 void Train::control_changed(const Controller::Control &ctrl)
522 signal_control_changed.emit(ctrl.name, ctrl.value);
525 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
529 current_speed = speed;
530 speed_changing = false;
535 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
537 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
542 functions |= 1<<func;
544 functions &= ~(1<<func);
546 signal_function_changed.emit(func, state);
550 void Train::sensor_event(unsigned addr, bool state)
554 // Find the first sensor block from our reserved blocks that isn't this sensor
555 list<BlockRef>::iterator i;
557 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
558 if(i->block->get_sensor_id())
560 if(i->block->get_sensor_id()!=addr)
573 if(result==1 && i!=rsv_blocks.begin())
575 // Compute speed and update related state
576 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
582 RealSpeed &rs = real_speed[current_speed];
583 rs.add(travel_dist/travel_time_secs, travel_time_secs);
585 set_status(format("Traveling %d kmh", get_travel_speed()));
590 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
592 j->block->traverse(j->entry, &block_len);
593 travel_dist += block_len;
595 if(j->block->get_sensor_id()==addr)
597 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
600 Track *track = bep.track->get_link(bep.track_ep);
601 unsigned ep = track->get_endpoint_by_link(*bep.track);
602 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
605 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
608 last_entry_time = Time::now();
610 accurate_position = true;
613 // Check if we've reached the next route
616 const set<const Track *> &rtracks = next_route->get_tracks();
617 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
618 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
623 signal_route_changed.emit(route);
628 // Move blocks up to the next sensor to our current blocks
629 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
631 // Try to get more blocks if we're moving
636 layout.emergency("Sensor for "+name+" triggered out of order");
640 // Find the first sensor in our current blocks that's still active
641 list<BlockRef>::iterator end = cur_blocks.begin();
642 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
643 if(i->block->get_sensor_id())
645 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
654 if(end!=cur_blocks.begin())
655 // Free blocks up to the last inactive sensor
656 release_blocks(cur_blocks, cur_blocks.begin(), end);
660 void Train::turnout_event(unsigned addr, bool)
664 unsigned pending_addr = pending_block->get_turnout_id();
665 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
666 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
671 void Train::halt_event(bool h)
674 accurate_position = false;
677 void Train::block_reserved(const Block &block, const Train *train)
679 if(&block==pending_block && !train)
683 unsigned Train::reserve_more()
689 if(!rsv_blocks.empty())
690 last = &rsv_blocks.back();
691 else if(!cur_blocks.empty())
692 last = &cur_blocks.back();
698 // See how many sensor blocks we already have
700 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
701 if(i->block->get_sensor_id())
707 const Route *cur_route = 0;
710 const set<Track *> &tracks = last->block->get_tracks();
711 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
713 if(route->get_tracks().count(*i))
715 else if(next_route && next_route->get_tracks().count(*i))
716 cur_route = next_route;
720 bool got_more = false;
721 BlockRef *good = last;
722 unsigned good_sens = nsens;
725 // Traverse to the next block
726 unsigned exit = last->block->traverse(last->entry);
727 Block *link = last->block->get_link(exit);
731 int entry = link->get_endpoint_by_link(*last->block);
733 throw LogicError("Block links are inconsistent!");
735 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
739 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
740 cur_route = next_route;
741 else if(!cur_route->get_tracks().count(entry_ep.track))
743 // Keep the blocks if we arrived at the end of the route
750 else if(route && route->get_tracks().count(entry_ep.track))
753 if(link->get_endpoints().size()<2)
760 bool reserved = link->reserve(this);
763 // Ask a lesser priority train to free the block for us
764 if(link->get_train()->get_priority()<priority)
765 if(link->get_train()->free_block(*link))
766 reserved = link->reserve(this);
770 // If we found another train and it's not headed straight for us, we can keep the blocks we got
771 int other_entry = link->get_train()->get_entry_to_block(*link);
773 throw LogicError("Block reservation inconsistency");
774 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
779 pending_block = link;
784 if(link->get_turnout_id())
786 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
788 // Keep the blocks reserved so far, as either us or the other train can diverge
792 // Figure out what path we'd like to take on the turnout
795 path = cur_route->get_turnout(link->get_turnout_id());
797 path = entry_ep.track->get_active_path();
798 if(!((track_ep.paths>>path)&1))
800 for(unsigned i=0; track_ep.paths>>i; ++i)
801 if((track_ep.paths>>i)&1)
805 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
807 // The turnout is set to wrong path - switch and wait for it
809 pending_block = link;
810 entry_ep.track->set_active_path(path);
815 rsv_blocks.push_back(BlockRef(link, entry));
816 last = &rsv_blocks.back();
817 if(last->block->get_sensor_id())
824 // Unreserve blocks that were not good
825 while(!rsv_blocks.empty() && last!=good)
827 last->block->reserve(0);
828 rsv_blocks.erase(--rsv_blocks.end());
829 if(!rsv_blocks.empty())
830 last = &rsv_blocks.back();
833 // Make any sensorless blocks at the beginning immediately current
834 list<BlockRef>::iterator i;
835 for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
836 if(i!=rsv_blocks.begin())
837 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
842 float Train::get_real_speed(unsigned i) const
844 if(real_speed[i].weight)
845 return real_speed[i].speed;
849 for(low=i; low>0; --low)
850 if(real_speed[low].weight)
852 for(high=i; high<14; ++high)
853 if(real_speed[high].weight)
856 if(real_speed[high].weight)
858 if(real_speed[low].weight)
860 float f = float(i-low)/(high-low);
861 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
864 return real_speed[high].speed*float(i)/high;
866 else if(real_speed[low].weight)
867 return real_speed[low].speed*float(i)/low;
872 unsigned Train::find_speed(float real) const
874 if(real<=real_speed[0].speed)
879 for(unsigned i=0; (!high && i<=14); ++i)
880 if(real_speed[i].weight)
882 if(real_speed[i].speed<real)
896 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
899 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
900 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
903 float Train::get_travel_speed() const
905 float speed = get_real_speed(current_speed);
906 float scale = layout.get_catalogue().get_scale();
907 return static_cast<int>(round(speed/scale*3.6/5))*5;
910 void Train::set_status(const string &s)
913 signal_status_changed.emit(s);
916 void Train::release_blocks(list<BlockRef> &blocks)
918 release_blocks(blocks, blocks.begin(), blocks.end());
921 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
925 Block *block = begin->block;
926 blocks.erase(begin++);
931 void Train::reverse_blocks(list<BlockRef> &blocks) const
934 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
935 i->entry = i->block->traverse(i->entry);
939 Train::BlockRef::BlockRef(Block *b, unsigned e):
944 Train::BlockRef Train::BlockRef::next() const
946 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
948 throw InvalidState("At end of line");
950 int ep = blk->get_endpoint_by_link(*block);
952 throw LogicError("Block links are inconsistent");
954 return BlockRef(blk, ep);
958 Train::RealSpeed::RealSpeed():
963 void Train::RealSpeed::add(float s, float w)
965 speed = (speed*weight+s*w)/(weight+w);
966 weight = min(weight+w, 300.0f);
970 Train::Loader::Loader(Train &t):
971 DataFile::BasicLoader<Train>(t),
975 add("block", &Loader::block);
976 add("block_hint", &Loader::block_hint);
977 add("name", &Loader::name);
978 add("priority", &Train::priority);
979 add("real_speed", &Loader::real_speed);
980 add("route", &Loader::route);
981 add("timetable", &Loader::timetable);
982 add("vehicle", &Loader::vehicle);
985 void Train::Loader::finish()
987 if(!obj.cur_blocks.empty())
989 const BlockRef &blkref = obj.cur_blocks.front();
990 const Block::Endpoint &bep = blkref.block->get_endpoints()[blkref.entry];
991 obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
993 obj.set_status("Stopped");
997 void Train::Loader::block(unsigned id)
1005 blk = &obj.layout.get_block(id);
1007 catch(const KeyError &)
1009 blocks_valid = false;
1015 entry = blk->get_endpoint_by_link(*prev_block);
1020 obj.cur_blocks.push_back(BlockRef(blk, entry));
1022 if(blk->get_sensor_id())
1023 obj.layout.get_driver().set_sensor(blk->get_sensor_id(), true);
1028 void Train::Loader::block_hint(unsigned id)
1032 prev_block = &obj.layout.get_block(id);
1034 catch(const KeyError &)
1036 blocks_valid = false;
1040 void Train::Loader::name(const string &n)
1045 void Train::Loader::real_speed(unsigned i, float speed, float weight)
1047 obj.real_speed[i].speed = speed;
1048 obj.real_speed[i].weight = weight;
1051 void Train::Loader::route(const string &n)
1053 obj.set_route(&obj.layout.get_route(n));
1056 void Train::Loader::timetable()
1059 throw InvalidState("A timetable has already been loaded");
1061 obj.timetable = new Timetable(obj);
1062 load_sub(*obj.timetable);
1065 void Train::Loader::vehicle(unsigned n)
1067 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
1068 Vehicle *veh = new Vehicle(obj.layout, vtype);
1069 obj.vehicles.back()->attach_back(*veh);
1070 obj.vehicles.push_back(veh);
1073 } // namespace Marklin