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);
68 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
70 layout.remove_train(*this);
73 void Train::set_name(const string &n)
77 signal_name_changed.emit(name);
80 Vehicle &Train::get_vehicle(unsigned i)
82 if(i>=vehicles.size())
83 throw InvalidParameterValue("Vehicle index out of range");
87 const Vehicle &Train::get_vehicle(unsigned i) const
89 if(i>=vehicles.size())
90 throw InvalidParameterValue("Vehicle index out of range");
94 void Train::set_control(const string &n, float v)
96 control->set_control(n, v);
99 void Train::set_active(bool a)
103 if(!a && control->get_speed())
104 throw InvalidState("Can't deactivate while moving");
109 stop_timeout = Time::TimeStamp();
114 stop_timeout = Time::now()+2*Time::sec;
115 set_status("Stopped");
119 void Train::set_function(unsigned func, bool state)
121 if(!loco_type.get_functions().count(func))
122 throw InvalidParameterValue("Invalid function");
124 layout.get_driver().set_loco_function(address, func, state);
126 layout.get_driver().set_loco_function(address+1, func-4, state);
129 bool Train::get_function(unsigned func) const
131 return (functions>>func)&1;
134 void Train::set_route(const Route *r)
136 if(!rsv_blocks.empty())
138 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
139 if(i->block->get_sensor_id())
141 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
148 end_of_route = false;
152 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
153 BlockRef next = last.next();
154 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
155 if(!route->get_tracks().count(ep.track))
158 route = Route::find(*ep.track, ep.track_ep, *next_route);
165 signal_route_changed.emit(route);
168 void Train::go_to(const Track &to)
170 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
171 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
173 signal_arrived.emit();
179 if(rsv_blocks.empty())
180 last = &cur_blocks.back();
183 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
184 if(i->block->get_sensor_id())
188 BlockRef next = last->next();
189 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
191 set_route(Route::find(*ep.track, ep.track_ep, to));
194 void Train::place(Block &block, unsigned entry)
196 if(control->get_speed())
197 throw InvalidState("Must be stopped before placing");
199 release_blocks(rsv_blocks);
200 release_blocks(cur_blocks);
204 if(!block.reserve(this))
206 set_status("Unplaced");
210 cur_blocks.push_back(BlockRef(&block, entry));
213 unsigned exit = block.traverse(entry);
214 const Block::Endpoint &bep = block.get_endpoints()[exit];
215 Track *track = bep.track->get_link(bep.track_ep);
216 unsigned ep = track->get_endpoint_by_link(*bep.track);
217 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
221 const Block::Endpoint &bep = block.get_endpoints()[entry];
222 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
226 bool Train::free_block(Block &block)
229 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
235 release_blocks(rsv_blocks, i, rsv_blocks.end());
238 else if(i->block->get_sensor_id())
245 int Train::get_entry_to_block(Block &block) const
247 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
250 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
256 float Train::get_reserved_distance() const
258 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
259 const VehicleType &vtype = veh.get_type();
261 Track *track = veh.get_track();
262 unsigned entry = veh.get_entry();
264 float result = -vtype.get_length()/2;
267 entry = track->traverse(entry);
268 result += veh.get_offset();
271 result -= veh.get_offset();
274 list<BlockRef>::const_iterator block = cur_blocks.begin();
277 if(!first || !reverse)
278 result += track->get_type().get_path_length(track->get_active_path());
281 unsigned exit = track->traverse(entry);
282 Track *next = track->get_link(exit);
284 while(!block->block->get_tracks().count(next))
287 if(block==cur_blocks.end())
288 block = rsv_blocks.begin();
289 if(block==rsv_blocks.end())
293 entry = next->get_endpoint_by_link(*track);
298 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
300 if(!active && stop_timeout && t>=stop_timeout)
302 release_blocks(rsv_blocks);
303 end_of_route = false;
304 stop_timeout = Time::TimeStamp();
310 float speed = control->get_speed();
311 unsigned speed_notch = find_speed(abs(speed));
313 if(speed && (speed<0)!=reverse)
315 layout.get_driver().set_loco_reverse(address, speed<0);
318 release_blocks(rsv_blocks);
319 reverse_blocks(cur_blocks);
323 if(speed_notch!=current_speed && !speed_changing)
325 speed_changing = true;
326 layout.get_driver().set_loco_speed(address, speed_notch);
331 set_status(format("Traveling %d kmh", get_travel_speed()));
333 set_status("Waiting");
341 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
342 Track *track = vehicle.get_track();
345 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
346 ok = i->block->get_tracks().count(track);
350 float d = get_real_speed(current_speed)*(dt/Time::sec);
351 vehicle.advance(reverse ? -d : d);
354 else if(end_of_route)
358 void Train::save(list<DataFile::Statement> &st) const
360 st.push_back((DataFile::Statement("name"), name));
361 for(unsigned i=0; i<=14; ++i)
362 if(real_speed[i].weight)
363 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
365 if(!cur_blocks.empty())
367 list<BlockRef> blocks = cur_blocks;
369 reverse_blocks(blocks);
371 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
372 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
374 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
375 st.push_back((DataFile::Statement("block"), i->block->get_id()));
379 st.push_back((DataFile::Statement("route"), route->get_name()));
383 DataFile::Statement ss("timetable");
384 timetable->save(ss.sub);
389 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
393 current_speed = speed;
394 speed_changing = false;
398 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
400 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
405 functions |= 1<<func;
407 functions &= ~(1<<func);
409 signal_function_changed.emit(func, state);
413 void Train::sensor_event(unsigned addr, bool state)
417 // Find the first sensor block from our reserved blocks that isn't this sensor
418 list<BlockRef>::iterator i;
419 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
420 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
423 if(i!=rsv_blocks.begin())
425 // Compute speed and update related state
426 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
430 RealSpeed &rs = real_speed[current_speed];
431 rs.add(travel_dist/travel_time_secs, travel_time_secs);
432 set_status(format("Traveling %d kmh", get_travel_speed()));
437 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
439 j->block->traverse(j->entry, &block_len);
440 travel_dist += block_len;
442 if(j->block->get_sensor_id()==addr)
444 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
447 Track *track = bep.track->get_link(bep.track_ep);
448 unsigned ep = track->get_endpoint_by_link(*bep.track);
449 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
452 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
455 last_entry_time = Time::now();
458 // Check if we've reached the next route
461 const set<const Track *> &rtracks = next_route->get_tracks();
462 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
463 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
468 signal_route_changed.emit(route);
473 // Move blocks up to the next sensor to our current blocks
474 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
476 // Try to get more blocks if we're moving
479 unsigned nsens = reserve_more();
480 if(!nsens && end_of_route)
481 signal_arrived.emit();
487 // Find the first sensor in our current blocks that's still active
488 list<BlockRef>::iterator end = cur_blocks.begin();
489 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
490 if(i->block->get_sensor_id())
492 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
498 if(end!=cur_blocks.begin())
500 // Free blocks up to the last inactive sensor
502 release_blocks(cur_blocks, cur_blocks.begin(), end);
507 void Train::turnout_event(unsigned addr, bool)
511 unsigned pending_addr = pending_block->get_turnout_id();
512 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
513 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
518 void Train::block_reserved(const Block &block, const Train *train)
520 if(&block==pending_block && !train)
524 unsigned Train::reserve_more()
527 if(!rsv_blocks.empty())
528 last = &rsv_blocks.back();
529 else if(!cur_blocks.empty())
530 last = &cur_blocks.back();
536 // See how many sensor blocks we already have
538 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
539 if(i->block->get_sensor_id())
545 const Route *cur_route = 0;
548 const set<Track *> &tracks = last->block->get_tracks();
549 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
551 if(route->get_tracks().count(*i))
553 else if(next_route && next_route->get_tracks().count(*i))
554 cur_route = next_route;
558 bool got_more = false;
559 BlockRef *good = last;
560 unsigned good_sens = nsens;
563 // Traverse to the next block
564 unsigned exit = last->block->traverse(last->entry);
565 Block *link = last->block->get_link(exit);
569 int entry = link->get_endpoint_by_link(*last->block);
571 throw LogicError("Block links are inconsistent!");
573 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
577 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
578 cur_route = next_route;
579 else if(!cur_route->get_tracks().count(entry_ep.track))
581 // Keep the blocks if we arrived at the end of the route
588 else if(route && route->get_tracks().count(entry_ep.track))
591 if(!link->reserve(this))
593 // If we found another train and it's not headed straight for us, we can keep the blocks we got
594 int other_entry = link->get_train()->get_entry_to_block(*link);
596 throw LogicError("Block reservation inconsistency");
597 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
602 pending_block = link;
606 if(link->get_turnout_id())
608 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
610 // Keep the blocks reserved so far, as either us or the other train can diverge
614 // Figure out what path we'd like to take on the turnout
617 path = cur_route->get_turnout(link->get_turnout_id());
619 path = entry_ep.track->get_active_path();
620 if(!((track_ep.paths>>path)&1))
622 for(unsigned i=0; track_ep.paths>>i; ++i)
623 if((track_ep.paths>>i)&1)
627 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
629 // The turnout is set to wrong path - switch and wait for it
631 pending_block = link;
632 entry_ep.track->set_active_path(path);
637 rsv_blocks.push_back(BlockRef(link, entry));
638 last = &rsv_blocks.back();
639 if(last->block->get_sensor_id())
646 // Unreserve blocks that were not good
647 while(!rsv_blocks.empty() && last!=good)
649 last->block->reserve(0);
650 rsv_blocks.erase(--rsv_blocks.end());
651 if(!rsv_blocks.empty())
652 last = &rsv_blocks.back();
658 float Train::get_real_speed(unsigned i) const
660 if(real_speed[i].weight)
661 return real_speed[i].speed;
665 for(low=i; low>0; --low)
666 if(real_speed[low].weight)
668 for(high=i; high<14; ++high)
669 if(real_speed[high].weight)
672 if(real_speed[high].weight)
674 if(real_speed[low].weight)
676 float f = float(i-low)/(high-low);
677 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
680 return real_speed[high].speed*float(i)/high;
682 else if(real_speed[low].weight)
683 return real_speed[low].speed*float(i)/low;
688 unsigned Train::find_speed(float real) const
690 if(real<=real_speed[0].speed)
695 for(unsigned i=0; (!high && i<=14); ++i)
696 if(real_speed[i].weight)
698 if(real_speed[i].speed<real)
707 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
710 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
711 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
714 float Train::get_travel_speed() const
716 float speed = get_real_speed(current_speed);
717 float scale = layout.get_catalogue().get_scale();
718 return static_cast<int>(round(speed/scale*3.6/5))*5;
721 void Train::set_status(const string &s)
724 signal_status_changed.emit(s);
727 void Train::release_blocks(list<BlockRef> &blocks)
729 release_blocks(blocks, blocks.begin(), blocks.end());
732 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
736 Block *block = begin->block;
737 blocks.erase(begin++);
742 void Train::reverse_blocks(list<BlockRef> &blocks) const
745 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
746 i->entry = i->block->traverse(i->entry);
750 Train::BlockRef::BlockRef(Block *b, unsigned e):
755 Train::BlockRef Train::BlockRef::next() const
757 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
759 throw InvalidState("At end of line");
761 int ep = blk->get_endpoint_by_link(*block);
763 throw LogicError("Block links are inconsistent");
765 return BlockRef(blk, ep);
769 Train::RealSpeed::RealSpeed():
774 void Train::RealSpeed::add(float s, float w)
776 speed = (speed*weight+s*w)/(weight+w);
777 weight = min(weight+w, 300.0f);
781 Train::Loader::Loader(Train &t):
782 DataFile::BasicLoader<Train>(t),
785 add("block", &Loader::block);
786 add("block_hint", &Loader::block_hint);
787 add("name", &Loader::name);
788 add("real_speed", &Loader::real_speed);
789 add("route", &Loader::route);
790 add("timetable", &Loader::timetable);
791 add("vehicle", &Loader::vehicle);
794 void Train::Loader::block(unsigned id)
796 Block &blk = obj.layout.get_block(id);
799 entry = blk.get_endpoint_by_link(*prev_block);
804 obj.cur_blocks.push_back(BlockRef(&blk, entry));
805 obj.set_status("Stopped");
806 const Block::Endpoint &bep = blk.get_endpoints()[entry];
807 obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
809 if(blk.get_sensor_id())
810 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
815 void Train::Loader::block_hint(unsigned id)
817 prev_block = &obj.layout.get_block(id);
820 void Train::Loader::name(const string &n)
825 void Train::Loader::real_speed(unsigned i, float speed, float weight)
827 obj.real_speed[i].speed = speed;
828 obj.real_speed[i].weight = weight;
831 void Train::Loader::route(const string &n)
833 obj.set_route(&obj.layout.get_route(n));
836 void Train::Loader::timetable()
839 throw InvalidState("A timetable has already been loaded");
841 obj.timetable = new Timetable(obj);
842 load_sub(*obj.timetable);
845 void Train::Loader::vehicle(unsigned n)
847 const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
848 Vehicle *veh = new Vehicle(obj.layout, vtype);
849 obj.vehicles.back()->attach_back(*veh);
850 obj.vehicles.push_back(veh);
853 } // namespace Marklin