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"
18 #include "simplephysics.h"
19 #include "timetable.h"
20 #include "tracktype.h"
29 Train::Train(Layout &l, const LocoType &t, unsigned a):
34 control(new AIControl(*this, new SimplePhysics)),
38 speed_changing(false),
49 vehicles.push_back(new Vehicle(layout, loco_type));
51 layout.add_train(*this);
53 layout.get_driver().add_loco(address);
54 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
55 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
57 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
58 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
59 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
61 control->signal_control_changed.connect(signal_control_changed);
66 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
68 layout.remove_train(*this);
71 void Train::set_name(const string &n)
75 signal_name_changed.emit(name);
78 Vehicle &Train::get_vehicle(unsigned i)
80 if(i>=vehicles.size())
81 throw InvalidParameterValue("Vehicle index out of range");
85 const Vehicle &Train::get_vehicle(unsigned i) const
87 if(i>=vehicles.size())
88 throw InvalidParameterValue("Vehicle index out of range");
92 void Train::set_control(const string &n, float v)
94 control->set_control(n, v);
97 void Train::set_active(bool a)
101 if(!a && control->get_speed())
102 throw InvalidState("Can't deactivate while moving");
107 stop_timeout = Time::TimeStamp();
112 stop_timeout = Time::now()+2*Time::sec;
113 set_status("Stopped");
117 void Train::set_function(unsigned func, bool state)
119 if(!loco_type.get_functions().count(func))
120 throw InvalidParameterValue("Invalid function");
122 layout.get_driver().set_loco_function(address, func, state);
124 layout.get_driver().set_loco_function(address+1, func-4, state);
127 bool Train::get_function(unsigned func) const
129 return (functions>>func)&1;
132 void Train::set_route(const Route *r)
134 if(!rsv_blocks.empty())
136 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
137 if(i->block->get_sensor_id())
139 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
146 end_of_route = false;
150 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
151 BlockRef next = last.next();
152 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
153 if(!route->get_tracks().count(ep.track))
156 route = Route::find(*ep.track, ep.track_ep, *next_route);
163 signal_route_changed.emit(route);
166 void Train::go_to(const Track &to)
168 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
169 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
171 signal_arrived.emit();
177 if(rsv_blocks.empty())
178 last = &cur_blocks.back();
181 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
182 if(i->block->get_sensor_id())
186 BlockRef next = last->next();
187 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
189 set_route(Route::find(*ep.track, ep.track_ep, to));
192 void Train::place(Block &block, unsigned entry)
194 if(control->get_speed())
195 throw InvalidState("Must be stopped before placing");
197 release_blocks(rsv_blocks);
198 release_blocks(cur_blocks);
202 if(!block.reserve(this))
204 set_status("Unplaced");
208 cur_blocks.push_back(BlockRef(&block, entry));
211 unsigned exit = block.traverse(entry);
212 const Block::Endpoint &bep = block.get_endpoints()[exit];
213 Track *track = bep.track->get_link(bep.track_ep);
214 unsigned ep = track->get_endpoint_by_link(*bep.track);
215 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
219 const Block::Endpoint &bep = block.get_endpoints()[entry];
220 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
224 bool Train::free_block(Block &block)
227 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
233 release_blocks(rsv_blocks, i, rsv_blocks.end());
236 else if(i->block->get_sensor_id())
243 int Train::get_entry_to_block(Block &block) const
245 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
248 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
254 float Train::get_reserved_distance() const
256 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
257 const VehicleType &vtype = veh.get_type();
259 Track *track = veh.get_track();
260 unsigned entry = veh.get_entry();
262 float result = -vtype.get_length()/2;
265 entry = track->traverse(entry);
266 result += veh.get_offset();
269 result -= veh.get_offset();
272 list<BlockRef>::const_iterator block = cur_blocks.begin();
275 if(!first || !reverse)
276 result += track->get_type().get_path_length(track->get_active_path());
279 unsigned exit = track->traverse(entry);
280 Track *next = track->get_link(exit);
282 while(!block->block->get_tracks().count(next))
285 if(block==cur_blocks.end())
286 block = rsv_blocks.begin();
287 if(block==rsv_blocks.end())
291 entry = next->get_endpoint_by_link(*track);
296 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
298 if(!active && stop_timeout && t>=stop_timeout)
300 release_blocks(rsv_blocks);
301 end_of_route = false;
302 stop_timeout = Time::TimeStamp();
308 float speed = control->get_speed();
309 unsigned speed_notch = find_speed(abs(speed));
311 if(speed && (speed<0)!=reverse)
313 layout.get_driver().set_loco_reverse(address, speed<0);
316 release_blocks(rsv_blocks);
317 reverse_blocks(cur_blocks);
321 if(speed_notch!=current_speed && !speed_changing)
323 speed_changing = true;
324 layout.get_driver().set_loco_speed(address, speed_notch);
329 set_status(format("Traveling %d kmh", get_travel_speed()));
331 set_status("Waiting");
339 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
340 Track *track = vehicle.get_track();
343 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
344 ok = i->block->get_tracks().count(track);
348 float d = get_real_speed(current_speed)*(dt/Time::sec);
349 vehicle.advance(reverse ? -d : d);
352 else if(end_of_route)
356 void Train::save(list<DataFile::Statement> &st) const
358 st.push_back((DataFile::Statement("name"), name));
359 for(unsigned i=0; i<=14; ++i)
360 if(real_speed[i].weight)
361 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
363 if(!cur_blocks.empty())
365 list<BlockRef> blocks = cur_blocks;
367 reverse_blocks(blocks);
369 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
370 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
372 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
373 st.push_back((DataFile::Statement("block"), i->block->get_id()));
377 st.push_back((DataFile::Statement("route"), route->get_name()));
381 DataFile::Statement ss("timetable");
382 timetable->save(ss.sub);
387 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
391 current_speed = speed;
392 speed_changing = false;
396 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
398 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
403 functions |= 1<<func;
405 functions &= ~(1<<func);
407 signal_function_changed.emit(func, state);
411 void Train::sensor_event(unsigned addr, bool state)
415 // Find the first sensor block from our reserved blocks that isn't this sensor
416 list<BlockRef>::iterator i;
417 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
418 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
421 if(i!=rsv_blocks.begin())
423 // Compute speed and update related state
424 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
428 RealSpeed &rs = real_speed[current_speed];
429 rs.add(travel_dist/travel_time_secs, travel_time_secs);
430 set_status(format("Traveling %d kmh", get_travel_speed()));
435 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
437 j->block->traverse(j->entry, &block_len);
438 travel_dist += block_len;
440 if(j->block->get_sensor_id()==addr)
442 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
445 Track *track = bep.track->get_link(bep.track_ep);
446 unsigned ep = track->get_endpoint_by_link(*bep.track);
447 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
450 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
453 last_entry_time = Time::now();
456 // Check if we've reached the next route
459 const set<const Track *> &rtracks = next_route->get_tracks();
460 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
461 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
466 signal_route_changed.emit(route);
471 // Move blocks up to the next sensor to our current blocks
472 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
474 // Try to get more blocks if we're moving
477 unsigned nsens = reserve_more();
478 if(!nsens && end_of_route)
479 signal_arrived.emit();
485 // Find the first sensor in our current blocks that's still active
486 list<BlockRef>::iterator end = cur_blocks.begin();
487 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
488 if(i->block->get_sensor_id())
490 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
496 if(end!=cur_blocks.begin())
498 // Free blocks up to the last inactive sensor
500 release_blocks(cur_blocks, cur_blocks.begin(), end);
505 void Train::turnout_event(unsigned addr, bool)
509 unsigned pending_addr = pending_block->get_turnout_id();
510 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
511 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
516 void Train::block_reserved(const Block &block, const Train *train)
518 if(&block==pending_block && !train)
522 unsigned Train::reserve_more()
525 if(!rsv_blocks.empty())
526 last = &rsv_blocks.back();
527 else if(!cur_blocks.empty())
528 last = &cur_blocks.back();
534 // See how many sensor blocks we already have
536 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
537 if(i->block->get_sensor_id())
543 const Route *cur_route = 0;
546 const set<Track *> &tracks = last->block->get_tracks();
547 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
549 if(route->get_tracks().count(*i))
551 else if(next_route && next_route->get_tracks().count(*i))
552 cur_route = next_route;
556 bool got_more = false;
557 BlockRef *good = last;
558 unsigned good_sens = nsens;
561 // Traverse to the next block
562 unsigned exit = last->block->traverse(last->entry);
563 Block *link = last->block->get_link(exit);
567 int entry = link->get_endpoint_by_link(*last->block);
569 throw LogicError("Block links are inconsistent!");
571 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
575 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
576 cur_route = next_route;
577 else if(!cur_route->get_tracks().count(entry_ep.track))
579 // Keep the blocks if we arrived at the end of the route
586 else if(route && route->get_tracks().count(entry_ep.track))
589 if(!link->reserve(this))
591 // If we found another train and it's not headed straight for us, we can keep the blocks we got
592 int other_entry = link->get_train()->get_entry_to_block(*link);
594 throw LogicError("Block reservation inconsistency");
595 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
600 pending_block = link;
604 if(link->get_turnout_id())
606 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
608 // Keep the blocks reserved so far, as either us or the other train can diverge
612 // Figure out what path we'd like to take on the turnout
615 path = cur_route->get_turnout(link->get_turnout_id());
617 path = entry_ep.track->get_active_path();
618 if(!((track_ep.paths>>path)&1))
620 for(unsigned i=0; track_ep.paths>>i; ++i)
621 if((track_ep.paths>>i)&1)
625 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
627 // The turnout is set to wrong path - switch and wait for it
629 pending_block = link;
630 entry_ep.track->set_active_path(path);
635 rsv_blocks.push_back(BlockRef(link, entry));
636 last = &rsv_blocks.back();
637 if(last->block->get_sensor_id())
644 // Unreserve blocks that were not good
645 while(!rsv_blocks.empty() && last!=good)
647 last->block->reserve(0);
648 rsv_blocks.erase(--rsv_blocks.end());
649 if(!rsv_blocks.empty())
650 last = &rsv_blocks.back();
656 float Train::get_real_speed(unsigned i) const
658 if(real_speed[i].weight)
659 return real_speed[i].speed;
663 for(low=i; low>0; --low)
664 if(real_speed[low].weight)
666 for(high=i; high<14; ++high)
667 if(real_speed[high].weight)
670 if(real_speed[high].weight)
672 if(real_speed[low].weight)
674 float f = float(i-low)/(high-low);
675 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
678 return real_speed[high].speed*float(i)/high;
680 else if(real_speed[low].weight)
681 return real_speed[low].speed*float(i)/low;
686 unsigned Train::find_speed(float real) const
688 if(real<=real_speed[0].speed)
693 for(unsigned i=0; (!high && i<=14); ++i)
694 if(real_speed[i].weight)
696 if(real_speed[i].speed<real)
705 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
708 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
709 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
712 float Train::get_travel_speed() const
714 float speed = get_real_speed(current_speed);
715 float scale = layout.get_catalogue().get_scale();
716 return static_cast<int>(round(speed/scale*3.6/5))*5;
719 void Train::set_status(const string &s)
722 signal_status_changed.emit(s);
725 void Train::release_blocks(list<BlockRef> &blocks)
727 release_blocks(blocks, blocks.begin(), blocks.end());
730 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
734 Block *block = begin->block;
735 blocks.erase(begin++);
740 void Train::reverse_blocks(list<BlockRef> &blocks) const
743 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
744 i->entry = i->block->traverse(i->entry);
748 Train::BlockRef::BlockRef(Block *b, unsigned e):
753 Train::BlockRef Train::BlockRef::next() const
755 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
757 throw InvalidState("At end of line");
759 int ep = blk->get_endpoint_by_link(*block);
761 throw LogicError("Block links are inconsistent");
763 return BlockRef(blk, ep);
767 Train::RealSpeed::RealSpeed():
772 void Train::RealSpeed::add(float s, float w)
774 speed = (speed*weight+s*w)/(weight+w);
775 weight = min(weight+w, 300.0f);
779 Train::Loader::Loader(Train &t):
780 DataFile::BasicLoader<Train>(t),
783 add("block", &Loader::block);
784 add("block_hint", &Loader::block_hint);
785 add("name", &Loader::name);
786 add("real_speed", &Loader::real_speed);
787 add("route", &Loader::route);
788 add("timetable", &Loader::timetable);
789 add("vehicle", &Loader::vehicle);
792 void Train::Loader::block(unsigned id)
794 Block &blk = obj.layout.get_block(id);
797 entry = blk.get_endpoint_by_link(*prev_block);
802 obj.cur_blocks.push_back(BlockRef(&blk, entry));
803 obj.set_status("Stopped");
804 const Block::Endpoint &bep = blk.get_endpoints()[entry];
805 obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
807 if(blk.get_sensor_id())
808 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
813 void Train::Loader::block_hint(unsigned id)
815 prev_block = &obj.layout.get_block(id);
818 void Train::Loader::name(const string &n)
823 void Train::Loader::real_speed(unsigned i, float speed, float weight)
825 obj.real_speed[i].speed = speed;
826 obj.real_speed[i].weight = weight;
829 void Train::Loader::route(const string &n)
831 obj.set_route(&obj.layout.get_route(n));
834 void Train::Loader::timetable()
837 throw InvalidState("A timetable has already been loaded");
839 obj.timetable = new Timetable(obj);
840 load_sub(*obj.timetable);
843 void Train::Loader::vehicle(unsigned n)
845 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
846 Vehicle *veh = new Vehicle(obj.layout, vtype);
847 obj.vehicles.back()->attach_back(*veh);
848 obj.vehicles.push_back(veh);
851 } // namespace Marklin