]> git.tdb.fi Git - r2c2.git/blobdiff - source/libmarklin/train.cpp
Release non-sensor blocks when the tail end of the train has passed far enough
[r2c2.git] / source / libmarklin / train.cpp
index a0943a7c76370d28a3679d24330295154e4d98e6..44f9298d142daf72682594148476699a0ce89554 100644 (file)
@@ -1,7 +1,7 @@
 /* $Id$
 
 This file is part of the MSP Märklin suite
-Copyright © 2006-2008 Mikkosoft Productions, Mikko Rasa
+Copyright © 2006-2010  Mikkosoft Productions, Mikko Rasa
 Distributed under the GPL
 */
 
@@ -9,220 +9,957 @@ Distributed under the GPL
 #include <msp/strings/formatter.h>
 #include <msp/time/units.h>
 #include <msp/time/utils.h>
-#include "control.h"
-#include "trafficmanager.h"
+#include "aicontrol.h"
+#include "catalogue.h"
+#include "driver.h"
+#include "layout.h"
+#include "locotype.h"
+#include "route.h"
+#include "simplephysics.h"
+#include "timetable.h"
+#include "tracktype.h"
 #include "train.h"
+#include "vehicle.h"
 
-using namespace Msp;
-
-#include <iostream>
 using namespace std;
+using namespace Msp;
 
 namespace Marklin {
 
-Train::Train(TrafficManager &tm, Locomotive &l):
-       trfc_mgr(tm),
-       loco(l),
-       target_speed(0),
+Train::Train(Layout &l, const LocoType &t, unsigned a):
+       layout(l),
+       loco_type(t),
+       address(a),
+       pending_block(0),
+       control(new AIControl(*this, new SimplePhysics)),
+       timetable(0),
+       active(false),
+       current_speed(0),
+       speed_changing(false),
+       reverse(false),
+       functions(0),
+       route(0),
+       next_route(0),
+       end_of_route(false),
        status("Unplaced"),
        travel_dist(0),
-       real_speed(0)
+       pure_speed(false),
+       real_speed(15),
+       accurate_position(false),
+       overshoot_dist(false)
 {
-       trfc_mgr.add_train(this);
+       vehicles.push_back(new Vehicle(layout, loco_type));
+
+       layout.add_train(*this);
+
+       layout.get_driver().add_loco(address);
+       layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
+       layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
 
-       const map<unsigned, Sensor *> &sensors=trfc_mgr.get_control().get_sensors();
-       for(map<unsigned, Sensor *>::const_iterator i=sensors.begin(); i!=sensors.end(); ++i)
-               i->second->signal_state_changed.connect(sigc::bind(sigc::mem_fun(this, &Train::sensor_event), i->second));
+       layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
+       layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
+       layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
+
+       layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
+
+       control->signal_control_changed.connect(signal_control_changed);
+}
+
+Train::~Train()
+{
+       delete control;
+       delete timetable;
+       for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
+               delete *i;
+       layout.remove_train(*this);
 }
 
 void Train::set_name(const string &n)
 {
-       name=n;
+       name = n;
 
        signal_name_changed.emit(name);
 }
 
-void Train::set_speed(unsigned speed)
+Vehicle &Train::get_vehicle(unsigned i)
 {
-       unsigned old_speed=target_speed;
+       if(i>=vehicles.size())
+               throw InvalidParameterValue("Vehicle index out of range");
+       return *vehicles[i];
+}
 
-       target_speed=speed;
-       if(!target_speed)
-       {
-               // XXX We might roll onto a new sensor and get confused - should delay freeing blocks a bit
-               for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
-                       i->block->reserve(0);
-               rsv_blocks.clear();
-               try_reserve=Time::TimeStamp();
-       }
-       else if(rsv_blocks.empty() && !reserve_more())
+const Vehicle &Train::get_vehicle(unsigned i) const
+{
+       if(i>=vehicles.size())
+               throw InvalidParameterValue("Vehicle index out of range");
+       return *vehicles[i];
+}
+
+void Train::set_control(const string &n, float v)
+{
+       control->set_control(n, v);
+}
+
+void Train::set_active(bool a)
+{
+       if(a==active)
                return;
+       if(!a && control->get_speed())
+               throw InvalidState("Can't deactivate while moving");
 
-       loco.set_speed(speed);
-       if(!old_speed && target_speed)
-               set_status("Traveling --- kmh");
-       else if(old_speed && !target_speed)
+       active = a;
+       if(active)
+       {
+               stop_timeout = Time::TimeStamp();
+               reserve_more();
+       }
+       else
+       {
+               stop_timeout = Time::now()+2*Time::sec;
                set_status("Stopped");
+       }
+}
+
+void Train::set_function(unsigned func, bool state)
+{
+       if(!loco_type.get_functions().count(func))
+               throw InvalidParameterValue("Invalid function");
+       if(func<5)
+               layout.get_driver().set_loco_function(address, func, state);
+       else
+               layout.get_driver().set_loco_function(address+1, func-4, state);
+}
+
+bool Train::get_function(unsigned func) const
+{
+       return (functions>>func)&1;
 }
 
-void Train::place(Block *block, unsigned entry)
+void Train::set_route(const Route *r)
 {
-       for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end();)
+       if(!rsv_blocks.empty())
+       {
+               for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
+                       if(i->block->get_sensor_id())
+                       {
+                               release_blocks(rsv_blocks, ++i, rsv_blocks.end());
+                               break;
+                       }
+       }
+
+       route = r;
+       next_route = 0;
+       end_of_route = false;
+
+       if(route)
        {
-               i->block->reserve(0);
-               i=rsv_blocks.erase(i);
+               BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
+               BlockRef next = last.next();
+               const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
+               if(!route->get_tracks().count(ep.track))
+               {
+                       next_route = route;
+                       route = Route::find(*ep.track, ep.track_ep, *next_route);
+               }
        }
 
-       for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end();)
+       if(active)
+               reserve_more();
+
+       signal_route_changed.emit(route);
+}
+
+void Train::go_to(const Track &to)
+{
+       for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
+               if(i->block->get_tracks().count(const_cast<Track *>(&to)))
+               {
+                       signal_arrived.emit();
+                       set_route(0);
+                       return;
+               }
+
+       BlockRef *last = 0;
+       if(rsv_blocks.empty())
+               last = &cur_blocks.back();
+       else
        {
-               i->block->reserve(0);
-               i=cur_blocks.erase(i);
+               for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
+                       if(i->block->get_sensor_id())
+                               last = &*i;
        }
 
-       if(!block->reserve(this))
+       BlockRef next = last->next();
+       const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
+
+       set_route(Route::find(*ep.track, ep.track_ep, to));
+}
+
+void Train::place(Block &block, unsigned entry)
+{
+       if(control->get_speed())
+               throw InvalidState("Must be stopped before placing");
+
+       release_blocks(rsv_blocks);
+       release_blocks(cur_blocks);
+
+       set_active(false);
+       accurate_position = false;
+
+       if(!block.reserve(this))
        {
                set_status("Unplaced");
                return;
        }
 
-       cur_blocks.push_back(BlockRef(block, entry));
-
-       set_status("Stopped");
+       cur_blocks.push_back(BlockRef(&block, entry));
+       if(reverse)
+       {
+               unsigned exit = block.traverse(entry);
+               const Block::Endpoint &bep = block.get_endpoints()[exit];
+               Track *track = bep.track->get_link(bep.track_ep);
+               unsigned ep = track->get_endpoint_by_link(*bep.track);
+               vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
+       }
+       else
+       {
+               const Block::Endpoint &bep = block.get_endpoints()[entry];
+               vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
+       }
 }
 
-bool Train::free_block(Block *block)
+bool Train::free_block(Block &block)
 {
+       unsigned nsens = 0;
        for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
-               if(i->block==block)
+       {
+               if(i->block==&block)
                {
-                       while(i!=rsv_blocks.end())
-                       {
-                               i->block->reserve(0);
-                               i=rsv_blocks.erase(i);
-                       }
+                       if(nsens<1)
+                               return false;
+                       release_blocks(rsv_blocks, i, rsv_blocks.end());
                        return true;
                }
+               else if(i->block->get_sensor_id())
+                       ++nsens;
+       }
 
        return false;
 }
 
-void Train::tick(const Time::TimeStamp &t)
+int Train::get_entry_to_block(Block &block) const
 {
-       if(try_reserve && t>try_reserve)
+       for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
+               if(i->block==&block)
+                       return i->entry;
+       for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
+               if(i->block==&block)
+                       return i->entry;
+       return -1;
+}
+
+float Train::get_reserved_distance() const
+{
+       Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
+       const VehicleType &vtype = veh.get_type();
+
+       Track *track = veh.get_track();
+       if(!track)
+               return 0;
+       unsigned entry = veh.get_entry();
+
+       float result = -vtype.get_length()/2;
+       if(reverse)
        {
-               if(reserve_more() || !rsv_blocks.empty())
+               entry = track->traverse(entry);
+               result += veh.get_offset();
+       }
+       else
+               result -= veh.get_offset();
+
+       bool first = true;
+       list<BlockRef>::const_iterator block = cur_blocks.begin();
+       while(1)
+       {
+               if(!first || !reverse)
+                       result += track->get_type().get_path_length(track->get_active_path());
+               first = false;
+
+               if(track->get_type().get_endpoints().size()<2)
+                       return result;
+
+               unsigned exit = track->traverse(entry);
+               Track *next = track->get_link(exit);
+
+               while(!block->block->get_tracks().count(next))
                {
-                       loco.set_speed(target_speed);
-                       set_status("Traveling --- kmh");
-                       try_reserve=Time::TimeStamp();
+                       ++block;
+                       if(block==cur_blocks.end())
+                               block = rsv_blocks.begin();
+                       if(block==rsv_blocks.end())
+                               return result;
                }
+
+               entry = next->get_endpoint_by_link(*track);
+               track = next;
+       }
+}
+
+void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
+{
+       if(!active && stop_timeout && t>=stop_timeout)
+       {
+               release_blocks(rsv_blocks);
+               end_of_route = false;
+               stop_timeout = Time::TimeStamp();
+       }
+
+       Driver &driver = layout.get_driver();
+
+       if(timetable)
+               timetable->tick(t);
+       control->tick(dt);
+       float speed = control->get_speed();
+       unsigned speed_notch = find_speed(abs(speed));
+
+       if(speed && (speed<0)!=reverse)
+       {
+               driver.set_loco_reverse(address, speed<0);
+               reverse = speed<0;
+
+               release_blocks(rsv_blocks);
+               reverse_blocks(cur_blocks);
+
+               reserve_more();
+       }
+       if(speed_notch!=current_speed && !speed_changing && !driver.is_halted() && driver.get_power())
+       {
+               speed_changing = true;
+               driver.set_loco_speed(address, speed_notch);
+
+               pure_speed = false;
+
+               if(speed_notch)
+                       set_status(format("Traveling %d kmh", get_travel_speed()));
                else
-                       try_reserve=t+2*Time::sec;
+                       set_status("Waiting");
+       }
+
+       if(speed)
+       {
+               if(!active)
+                       set_active(true);
+
+               Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
+               Track *track = vehicle.get_track();
+
+               bool ok = false;
+               for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
+                       ok = i->block->get_tracks().count(track);
+
+               float d = get_real_speed(current_speed)*(dt/Time::sec);
+               if(ok)
+                       vehicle.advance(reverse ? -d : d);
+               else if(accurate_position)
+               {
+                       overshoot_dist += d;
+                       if(overshoot_dist>40*layout.get_catalogue().get_scale())
+                       {
+                               layout.emergency(name+" has not arrived at sensor");
+                               accurate_position = false;
+                       }
+               }
+       }
+       else if(end_of_route)
+               set_route(0);
+
+       if(!cur_blocks.empty() && !cur_blocks.front().block->get_sensor_id())
+       {
+               Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
+
+               list<BlockRef>::iterator i = cur_blocks.begin();
+               const Block::Endpoint &bep = i->block->get_endpoints()[i->entry];
+
+               Track *track = bep.track;
+               unsigned entry = bep.track_ep;
+
+               bool found = false;
+               float dist = veh.get_offset()-veh.get_type().get_length()/2;
+               while(1)
+               {
+                       if(track==veh.get_track())
+                       {
+                               found = true;
+                               break;
+                       }
+
+                       if(i!=cur_blocks.begin())
+                       {
+                               float path_len = track->get_type().get_path_length(track->get_active_path());
+                               dist += path_len;
+                       }
+
+                       unsigned exit = track->traverse(entry);
+                       Track *next = track->get_link(exit);
+                       entry = next->get_endpoint_by_link(*track);
+                       track = next;
+
+                       if(!i->block->get_tracks().count(track))
+                       {
+                               ++i;
+                               if(i==cur_blocks.end())
+                                       break;
+                       }
+               }
+
+               if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
+               {
+                       cur_blocks.front().block->reserve(0);
+                       cur_blocks.erase(cur_blocks.begin());
+               }
        }
 }
 
-void Train::sensor_event(bool state, Sensor *sensor)
+void Train::save(list<DataFile::Statement> &st) const
 {
-       unsigned addr=sensor->get_address();
+       st.push_back((DataFile::Statement("name"), name));
 
+       for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
+               if(i!=vehicles.begin())
+                       st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
+
+       for(unsigned i=0; i<=14; ++i)
+               if(real_speed[i].weight)
+                       st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
+
+       if(!cur_blocks.empty())
+       {
+               list<BlockRef> blocks = cur_blocks;
+               if(reverse)
+                       reverse_blocks(blocks);
+
+               Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
+               st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
+
+               for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
+                       st.push_back((DataFile::Statement("block"), i->block->get_id()));
+       }
+
+       if(route)
+       {
+               if(!route->is_temporary())
+                       st.push_back((DataFile::Statement("route"), route->get_name()));
+               else if(next_route && !next_route->is_temporary())
+                       st.push_back((DataFile::Statement("route"), next_route->get_name()));
+       }
+
+       if(timetable)
+       {
+               DataFile::Statement ss("timetable");
+               timetable->save(ss.sub);
+               st.push_back(ss);
+       }
+}
+
+void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
+{
+       if(addr==address)
+       {
+               current_speed = speed;
+               speed_changing = false;
+               pure_speed = false;
+       }
+}
+
+void Train::loco_func_event(unsigned addr, unsigned func, bool state)
+{
+       if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
+       {
+               if(addr==address+1)
+                       func += 4;
+               if(state)
+                       functions |= 1<<func;
+               else
+                       functions &= ~(1<<func);
+
+               signal_function_changed.emit(func, state);
+       }
+}
+
+void Train::sensor_event(unsigned addr, bool state)
+{
        if(state)
        {
+               // Find the first sensor block from our reserved blocks that isn't this sensor
                list<BlockRef>::iterator i;
+               unsigned result = 0;
                for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
-                       if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
-                               break;
+                       if(i->block->get_sensor_id())
+                       {
+                               if(i->block->get_sensor_id()!=addr)
+                               {
+                                       if(result==0)
+                                               result = 2;
+                                       else if(result==1)
+                                               break;
+                               }
+                               else if(result==0)
+                                       result = 1;
+                               else if(result==2)
+                                       result = 3;
+                       }
 
-               if(i!=rsv_blocks.begin())
+               if(result==1 && i!=rsv_blocks.begin())
                {
-                       real_speed=static_cast<int>(round(travel_dist/((Time::now()-last_entry_time)/Time::sec)*87*3.6/5))*5;
-                       set_status(format("Traveling %3d kmh", real_speed));
+                       // Compute speed and update related state
+                       float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
+
+                       if(pure_speed)
+                       {
+                               RealSpeed &rs = real_speed[current_speed];
+                               rs.add(travel_dist/travel_time_secs, travel_time_secs);
+                               set_status(format("Traveling %d kmh", get_travel_speed()));
+                       }
 
-                       travel_dist=0;
+                       travel_dist = 0;
                        float block_len;
                        for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
                        {
                                j->block->traverse(j->entry, &block_len);
-                               cout<<"Advancing: block "<<j->block<<" (sensor "<<j->block->get_sensor_id()<<") length "<<block_len<<'\n';
-                               travel_dist+=block_len;
+                               travel_dist += block_len;
+
+                               if(j->block->get_sensor_id()==addr)
+                               {
+                                       const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
+                                       if(reverse)
+                                       {
+                                               Track *track = bep.track->get_link(bep.track_ep);
+                                               unsigned ep = track->get_endpoint_by_link(*bep.track);
+                                               vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
+                                       }
+                                       else
+                                               vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
+                               }
                        }
-                       last_entry_time=Time::now();
+                       last_entry_time = Time::now();
+                       pure_speed = true;
+                       accurate_position = true;
+                       overshoot_dist = 0;
 
+                       // Check if we've reached the next route
+                       if(next_route)
+                       {
+                               const set<const Track *> &rtracks = next_route->get_tracks();
+                               for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
+                                       if(rtracks.count(j->block->get_endpoints()[j->entry].track))
+                                       {
+                                               route = next_route;
+                                               next_route = 0;
+                                               // XXX Exceptions?
+                                               signal_route_changed.emit(route);
+                                               break;
+                                       }
+                       }
+
+                       // Move blocks up to the next sensor to our current blocks
                        cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
-                       cout<<"Train "<<name<<" advanced, "<<cur_blocks.size()<<" cur_blocks, "<<rsv_blocks.size()<<" rsv_blocks\n";
-               }
 
-               if(target_speed && !reserve_more() && rsv_blocks.empty())
-               {
-                       loco.set_speed(0);
-                       try_reserve=Time::now()+2*Time::sec;
-                       set_status("Blocked");
+                       // Try to get more blocks if we're moving
+                       if(active)
+                       {
+                               unsigned nsens = reserve_more();
+                               if(!nsens && end_of_route)
+                                       signal_arrived.emit();
+                       }
                }
+               else if(result==3)
+                       layout.emergency("Sensor for "+name+" triggered out of order");
        }
        else
        {
-               cout<<"Train "<<name<<" finding blocks to free\n";
-               list<BlockRef>::iterator i;
-               for(i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
-               {
-                       if(i->block->get_sensor_id()==addr)
+               // Find the first sensor in our current blocks that's still active
+               list<BlockRef>::iterator end = cur_blocks.begin();
+               for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
+                       if(i->block->get_sensor_id())
                        {
-                               ++i;
-                               for(list<BlockRef>::iterator j=cur_blocks.begin(); j!=i; ++j)
-                                       j->block->reserve(0);
-                               cout<<"  "<<distance(cur_blocks.begin(), i)<<" blocks freed, ";
-                               cur_blocks.erase(cur_blocks.begin(), i);
-                               cout<<cur_blocks.size()<<" cur_blocks\n";
+                               if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
+                                       break;
+                               else
+                               {
+                                       end = i;
+                                       ++end;
+                               }
                        }
-               }
+               
+               if(end!=cur_blocks.begin())
+                       // Free blocks up to the last inactive sensor
+                       release_blocks(cur_blocks, cur_blocks.begin(), end);
+       }
+}
 
-               if(target_speed)
+void Train::turnout_event(unsigned addr, bool)
+{
+       if(pending_block)
+       {
+               unsigned pending_addr = pending_block->get_turnout_id();
+               bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
+               if(addr==pending_addr || (double_addr && addr==pending_addr+1))
                        reserve_more();
        }
 }
 
-bool Train::reserve_more()
+void Train::halt_event(bool h)
+{
+       if(h)
+               accurate_position = false;
+}
+
+void Train::block_reserved(const Block &block, const Train *train)
 {
-       BlockRef *last=0;
+       if(&block==pending_block && !train)
+               reserve_more();
+}
+
+unsigned Train::reserve_more()
+{
+       BlockRef *last = 0;
        if(!rsv_blocks.empty())
-               last=&rsv_blocks.back();
+               last = &rsv_blocks.back();
        else if(!cur_blocks.empty())
-               last=&cur_blocks.back();
+               last = &cur_blocks.back();
        if(!last)
-               return false;
+               return 0;
+
+       pending_block = 0;
 
-       cout<<"Train "<<name<<" reserving more blocks\n";
+       // See how many sensor blocks we already have
+       unsigned nsens = 0;
+       for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
+               if(i->block->get_sensor_id())
+                       ++nsens;
+       
+       if(end_of_route)
+               return nsens;
 
-       bool result=false;
-       unsigned size=rsv_blocks.size();
-       while(size<3)
+       const Route *cur_route = 0;
+       if(route)
        {
-               int exit=last->block->traverse(last->entry);
-               if(exit>=0) 
+               const set<Track *> &tracks = last->block->get_tracks();
+               for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
                {
-                       Block *link=last->block->get_link(exit);
-                       if(link && link->reserve(this))
+                       if(route->get_tracks().count(*i))
+                               cur_route = route;
+                       else if(next_route && next_route->get_tracks().count(*i))
+                               cur_route = next_route;
+               }
+       }
+
+       bool got_more = false;
+       BlockRef *good = last;
+       unsigned good_sens = nsens;
+       while(good_sens<3)
+       {
+               if(last->block->get_endpoints().size()<2)
+               {
+                       good = last;
+                       good_sens = nsens;
+                       break;
+               }
+
+               // Traverse to the next block
+               unsigned exit = last->block->traverse(last->entry);
+               Block *link = last->block->get_link(exit);
+               if(!link)
+                       break;
+
+               int entry = link->get_endpoint_by_link(*last->block);
+               if(entry<0)
+                       throw LogicError("Block links are inconsistent!");
+
+               const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
+
+               if(cur_route)
+               {
+                       if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
+                               cur_route = next_route;
+                       else if(!cur_route->get_tracks().count(entry_ep.track))
                        {
-                               rsv_blocks.push_back(BlockRef(link, link->get_endpoint_by_link(*last->block)));
-                               last=&rsv_blocks.back();
-                               ++size;
-                               result=true;
+                               // Keep the blocks if we arrived at the end of the route
+                               good = last;
+                               good_sens = nsens;
+                               end_of_route = true;
+                               break;
                        }
-                       else
+               }
+               else if(route && route->get_tracks().count(entry_ep.track))
+                       cur_route = route;
+
+               if(!link->reserve(this))
+               {
+                       // If we found another train and it's not headed straight for us, we can keep the blocks we got
+                       int other_entry = link->get_train()->get_entry_to_block(*link);
+                       if(other_entry<0)
+                               throw LogicError("Block reservation inconsistency");
+                       if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
+                       {
+                               good = last;
+                               good_sens = nsens;
+                       }
+                       pending_block = link;
+                       break;
+               }
+
+               if(link->get_turnout_id())
+               {
+                       const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
+
+                       // Keep the blocks reserved so far, as either us or the other train can diverge
+                       good = last;
+                       good_sens = nsens;
+
+                       // Figure out what path we'd like to take on the turnout
+                       int path = -1;
+                       if(cur_route)
+                               path = cur_route->get_turnout(link->get_turnout_id());
+                       if(path<0)
+                               path = entry_ep.track->get_active_path();
+                       if(!((track_ep.paths>>path)&1))
+                       {
+                               for(unsigned i=0; track_ep.paths>>i; ++i)
+                                       if((track_ep.paths>>i)&1)
+                                               path = i;
+                       }
+
+                       if(path!=static_cast<int>(entry_ep.track->get_active_path()))
+                       {
+                               // The turnout is set to wrong path - switch and wait for it
+                               link->reserve(0);
+                               pending_block = link;
+                               entry_ep.track->set_active_path(path);
                                break;
+                       }
                }
-               else
+
+               rsv_blocks.push_back(BlockRef(link, entry));
+               last = &rsv_blocks.back();
+               if(last->block->get_sensor_id())
+               {
+                       ++nsens;
+                       got_more = true;
+               }
+       }
+
+       // Unreserve blocks that were not good
+       while(!rsv_blocks.empty() && last!=good)
+       {
+               last->block->reserve(0);
+               rsv_blocks.erase(--rsv_blocks.end());
+               if(!rsv_blocks.empty())
+                       last = &rsv_blocks.back();
+       }
+
+       // Make any sensorless blocks at the beginning immediately current
+       list<BlockRef>::iterator i;
+       for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
+       if(i!=rsv_blocks.begin())
+               cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
+
+       return good_sens;
+}
+
+float Train::get_real_speed(unsigned i) const
+{
+       if(real_speed[i].weight)
+               return real_speed[i].speed;
+
+       unsigned low;
+       unsigned high;
+       for(low=i; low>0; --low)
+               if(real_speed[low].weight)
+                       break;
+       for(high=i; high<14; ++high)
+               if(real_speed[high].weight)
                        break;
+
+       if(real_speed[high].weight)
+       {
+               if(real_speed[low].weight)
+               {
+                       float f = float(i-low)/(high-low);
+                       return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
+               }
+               else
+                       return real_speed[high].speed*float(i)/high;
        }
+       else if(real_speed[low].weight)
+               return real_speed[low].speed*float(i)/low;
+       else
+               return 0;
+}
 
-       cout<<"  "<<rsv_blocks.size()<<" rsv_blocks\n";
+unsigned Train::find_speed(float real) const
+{
+       if(real<=real_speed[0].speed)
+               return 0;
 
-       return result;
+       unsigned low = 0;
+       unsigned high = 0;
+       for(unsigned i=0; (!high && i<=14); ++i)
+               if(real_speed[i].weight)
+               {
+                       if(real_speed[i].speed<real)
+                               low = i;
+                       else
+                               high = i;
+               }
+       if(!high)
+       {
+               if(!low)
+                       return 0;
+               return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
+       }
+
+       float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
+       return static_cast<unsigned>(low*(1-f)+high*f+0.5);
+}
+
+float Train::get_travel_speed() const
+{
+       float speed = get_real_speed(current_speed);
+       float scale = layout.get_catalogue().get_scale();
+       return static_cast<int>(round(speed/scale*3.6/5))*5;
 }
 
 void Train::set_status(const string &s)
 {
-       status=s;
+       status = s;
        signal_status_changed.emit(s);
 }
 
+void Train::release_blocks(list<BlockRef> &blocks)
+{
+       release_blocks(blocks, blocks.begin(), blocks.end());
+}
+
+void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
+{
+       while(begin!=end)
+       {
+               Block *block = begin->block;
+               blocks.erase(begin++);
+               block->reserve(0);
+       }
+}
+
+void Train::reverse_blocks(list<BlockRef> &blocks) const
+{
+       blocks.reverse();
+       for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
+               i->entry = i->block->traverse(i->entry);
+}
+
+
+Train::BlockRef::BlockRef(Block *b, unsigned e):
+       block(b),
+       entry(e)
+{ }
+
+Train::BlockRef Train::BlockRef::next() const
+{
+       Block *blk = block->get_endpoints()[block->traverse(entry)].link;
+       if(!blk)
+               throw InvalidState("At end of line");
+
+       int ep = blk->get_endpoint_by_link(*block);
+       if(ep<0)
+               throw LogicError("Block links are inconsistent");
+
+       return BlockRef(blk, ep);
+}
+
+
+Train::RealSpeed::RealSpeed():
+       speed(0),
+       weight(0)
+{ }
+
+void Train::RealSpeed::add(float s, float w)
+{
+       speed = (speed*weight+s*w)/(weight+w);
+       weight = min(weight+w, 300.0f);
+}
+
+
+Train::Loader::Loader(Train &t):
+       DataFile::BasicLoader<Train>(t),
+       prev_block(0)
+{
+       add("block",       &Loader::block);
+       add("block_hint",  &Loader::block_hint);
+       add("name",        &Loader::name);
+       add("real_speed",  &Loader::real_speed);
+       add("route",       &Loader::route);
+       add("timetable",   &Loader::timetable);
+       add("vehicle",     &Loader::vehicle);
+}
+
+void Train::Loader::block(unsigned id)
+{
+       Block &blk = obj.layout.get_block(id);
+       int entry = -1;
+       if(prev_block)
+               entry = blk.get_endpoint_by_link(*prev_block);
+       if(entry<0)
+               entry = 0;
+
+       blk.reserve(&obj);
+       obj.cur_blocks.push_back(BlockRef(&blk, entry));
+       obj.set_status("Stopped");
+       const Block::Endpoint &bep = blk.get_endpoints()[entry];
+       obj.vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
+
+       if(blk.get_sensor_id())
+               obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
+
+       prev_block = &blk;
+}
+
+void Train::Loader::block_hint(unsigned id)
+{
+       prev_block = &obj.layout.get_block(id);
+}
+
+void Train::Loader::name(const string &n)
+{
+       obj.set_name(n);
+}
+
+void Train::Loader::real_speed(unsigned i, float speed, float weight)
+{
+       obj.real_speed[i].speed = speed;
+       obj.real_speed[i].weight = weight;
+}
+
+void Train::Loader::route(const string &n)
+{
+       obj.set_route(&obj.layout.get_route(n));
+}
+
+void Train::Loader::timetable()
+{
+       if(obj.timetable)
+               throw InvalidState("A timetable has already been loaded");
+
+       obj.timetable = new Timetable(obj);
+       load_sub(*obj.timetable);
+}
+
+void Train::Loader::vehicle(unsigned n)
+{
+       const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
+       Vehicle *veh = new Vehicle(obj.layout, vtype);
+       obj.vehicles.back()->attach_back(*veh);
+       obj.vehicles.push_back(veh);
+}
+
 } // namespace Marklin