+ if(pure_speed)
+ {
+ if(current_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;
+ float block_len;
+ for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
+ {
+ j->block->traverse(j->entry, &block_len);
+ travel_dist += block_len;
+
+ if(j->block->get_sensor_id()==addr && !advancing)
+ {
+ 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();
+ pure_speed = true;
+ accurate_position = true;
+ overshoot_dist = 0;
+
+ // Check if we've reached the next route
+ if(routes.size()>1)
+ {
+ const set<Track *> &rtracks = (++routes.begin())->route->get_tracks();
+ for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
+ if(rtracks.count(j->block->get_endpoints()[j->entry].track))
+ {
+ routes.pop_front();
+ // XXX Exceptions?
+ signal_route_changed.emit(routes.front().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);
+
+ // Try to get more blocks if we're moving
+ if(active)
+ reserve_more();
+ }
+ else if(result==3)
+ layout.emergency("Sensor for "+name+" triggered out of order");
+ }
+ else
+ {
+ const Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
+
+ // 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->has_track(*veh.get_track()))
+ break;
+ if(i->block->get_sensor_id())
+ {
+ if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
+ break;
+ else
+ {
+ end = i;
+ ++end;
+ }
+ }
+ }
+
+ if(end!=cur_blocks.begin() && end!=cur_blocks.end())
+ // Free blocks up to the last inactive sensor
+ release_blocks(cur_blocks, cur_blocks.begin(), end);
+ }
+}
+
+void Train::turnout_event(unsigned addr, bool)
+{
+ if(pending_block && (!pending_block->get_train() || pending_block->get_train()==this))
+ {
+ 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))
+ {
+ if(reserving)
+ pending_block = 0;
+ else
+ reserve_more();
+ }
+ }
+}
+
+void Train::halt_event(bool h)
+{
+ if(h)
+ accurate_position = false;
+}
+
+void Train::block_reserved(const Block &block, const Train *train)
+{
+ if(&block==pending_block && !train && !reserving)
+ reserve_more();
+}
+
+unsigned Train::reserve_more()
+{
+ if(!active)
+ return 0;
+
+ BlockRef *start = 0;
+ if(!rsv_blocks.empty())
+ start = &rsv_blocks.back();
+ else if(!cur_blocks.empty())
+ start = &cur_blocks.back();
+ if(!start)
+ return 0;
+
+ pending_block = 0;
+
+ // See how many sensor blocks and how much track we already have
+ unsigned nsens = 0;
+ float dist = 0;
+ for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
+ {
+ if(i->block->get_sensor_id())
+ ++nsens;
+ if(nsens>0)
+ {
+ float length = 0;
+ i->block->traverse(i->entry, &length);
+ dist += length;
+ }
+ }
+
+ if(end_of_route)
+ return nsens;
+
+ list<RouteRef>::iterator cur_route = routes.begin();
+ advance_route(cur_route, *start->block->get_endpoints()[start->entry].track);
+
+ float approach_margin = 50*layout.get_catalogue().get_scale();
+ float min_dist = controller->get_braking_distance()*1.3+approach_margin*2;
+
+ BlockRef *last = start;
+ BlockRef *good = start;
+ Track *divert_track = 0;
+ bool try_divert = false;
+ unsigned good_sens = nsens;
+ float good_dist = dist;
+ Train *blocking_train = 0;
+ std::list<BlockRef> contested_blocks;
+
+ SetFlag setf(reserving);
+
+ while(good_sens<3 || good_dist<min_dist || !contested_blocks.empty())
+ {
+ // Traverse to the next block
+ float length = 0;
+ Block *link = 0;
+ {
+ const Route *route = (cur_route!=routes.end() ? cur_route->route : 0);
+ unsigned exit = last->block->traverse(last->entry, route, &length);
+ 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!=routes.end())
+ {
+ if(!advance_route(cur_route, *entry_ep.track))
+ {
+ // Keep the blocks if we arrived at the end of the route
+ if(!blocking_train)
+ {
+ good = last;
+ good_sens = nsens;
+ good_dist = dist;
+ end_of_route = true;
+ }
+ break;
+ }
+ }
+ else if(!routes.empty() && routes.front().route->has_track(*entry_ep.track))
+ cur_route = routes.begin();
+
+ if(link->get_endpoints().size()<2)
+ {
+ if(!blocking_train)
+ {
+ good = last;
+ good_sens = nsens;
+ good_dist = dist;
+ }
+ break;
+ }
+
+ if(blocking_train)
+ {
+ if(link->get_train()!=blocking_train)
+ {
+ if(blocking_train->free_block(*contested_blocks.back().block))
+ {
+ // Roll back and start actually reserving the blocks
+ last = &rsv_blocks.back();
+ cur_route = routes.begin();
+ advance_route(cur_route, *last->block->get_endpoints()[last->entry].track);
+ if(blocking_train->get_priority()==priority)
+ blocking_train->yield_to(*this);
+ blocking_train = 0;
+ continue;
+ }
+ else
+ {
+ yield_to(*blocking_train);
+ pending_block = contested_blocks.front().block;
+ try_divert = divert_track;
+ break;
+ }
+ }
+ else
+ {
+ contested_blocks.push_back(BlockRef(link, entry));
+ last = &contested_blocks.back();
+ continue;
+ }
+ }
+
+ bool reserved = link->reserve(this);
+ if(!reserved)
+ {
+ /* We've found another train. If it wants to exit the block from the
+ same endpoint we're trying to enter from or the other way around,
+ treat it as coming towards us. Otherwise treat it as going in the
+ same direction. */
+ Train *other_train = link->get_train();
+ int other_entry = other_train->get_entry_to_block(*link);
+ if(other_entry<0)
+ throw LogicError("Block reservation inconsistency");
+
+ bool entry_conflict = (static_cast<unsigned>(entry)==link->traverse(other_entry));
+ bool exit_conflict = (link->traverse(entry)==static_cast<unsigned>(other_entry));
+ if(!entry_conflict && !last->block->get_turnout_id())
+ {
+ /* The other train is not coming to the blocks we're holding, so we
+ can keep them. */
+ good = last;
+ good_sens = nsens;
+ good_dist = dist;
+ }
+
+ int other_prio = other_train->get_priority();
+
+ if(!entry_conflict && !exit_conflict && other_prio<priority)
+ {
+ /* Ask a lesser priority train going to the same direction to free
+ the block for us */
+ if(other_train->free_block(*link))
+ reserved = link->reserve(this);
+ }
+ else if(other_train!=yielding_to && (other_prio<priority || (other_prio==priority && entry_conflict)))
+ {
+ /* A lesser priority train is coming at us, we must ask it to free
+ enough blocks to get clear of it to avoid a potential deadlock */
+ blocking_train = other_train;
+ contested_blocks.clear();
+ contested_blocks.push_back(BlockRef(link, entry));
+ last = &contested_blocks.back();
+ continue;
+ }
+ else if(divert_track && (entry_conflict || exit_conflict))
+ // We are blocked, but there's a diversion possibility
+ try_divert = true;
+
+ if(!reserved)
+ {
+ pending_block = link;
+ break;
+ }
+ }
+
+ if(link->get_turnout_id())
+ {
+ const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
+ bool multiple_paths = (track_ep.paths&(track_ep.paths-1));
+
+ if(multiple_paths || !last->block->get_turnout_id())
+ {
+ /* We can keep the blocks reserved so far if we are facing the
+ points or if there was no turnout immediately before this one.
+ With multiple successive turnouts (as is common in crossovers) it's
+ best to hold at one we can divert from. */
+ good = last;
+ good_sens = nsens;
+ good_dist = dist;
+ }
+
+ // Figure out what path we'd like to take on the turnout
+ int path = -1;
+ for(list<RouteRef>::iterator i=cur_route; (path<0 && i!=routes.end()); ++i)
+ path = i->route->get_turnout(link->get_turnout_id());
+ if(path<0)
+ path = entry_ep.track->get_active_path();
+ if(!(track_ep.paths&(1<<path)))
+ {
+ for(unsigned i=0; track_ep.paths>>i; ++i)
+ if(track_ep.paths&(1<<i))
+ 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
+ pending_block = link;
+ entry_ep.track->set_active_path(path);
+ if(pending_block)
+ {
+ link->reserve(0);
+ break;
+ }
+ }
+
+ if(multiple_paths && cur_route!=routes.end() && cur_route->diversion!=link->get_turnout_id())
+ /* There's multiple paths to be taken and we are on a route - take
+ note of the diversion possibility */
+ divert_track = entry_ep.track;
+ }
+
+ if(!contested_blocks.empty() && contested_blocks.front().block==link)
+ contested_blocks.pop_front();
+
+ rsv_blocks.push_back(BlockRef(link, entry));
+ last = &rsv_blocks.back();
+ if(last->block->get_sensor_id())
+ ++nsens;
+ if(nsens>0)
+ dist += length;
+ }
+
+ // Unreserve blocks that were not good
+ while(!rsv_blocks.empty() && &rsv_blocks.back()!=good)
+ {
+ rsv_blocks.back().block->reserve(0);
+ rsv_blocks.pop_back();
+ }
+
+ if(!rsv_blocks.empty() && &rsv_blocks.back()!=start)
+ // We got some new blocks, so no longer need to yield
+ yielding_to = 0;
+
+ // 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);
+
+ if(try_divert && divert(*divert_track))
+ return reserve_more();
+
+ return good_sens;
+}
+
+float Train::get_reserved_distance_until(const Block *until_block, bool back) const
+{
+ if(cur_blocks.empty())
+ return 0;
+
+ Vehicle &veh = *(reverse!=back ? vehicles.back() : vehicles.front());
+ const VehicleType &vtype = veh.get_type();
+
+ Track *track = veh.get_track();
+ if(!track)
+ return 0;
+
+ list<BlockRef>::const_iterator block = cur_blocks.begin();
+ while(block!=rsv_blocks.end() && !block->block->has_track(*track))
+ {
+ ++block;
+ if(block==cur_blocks.end())
+ {
+ if(back)
+ return 0;
+ block = rsv_blocks.begin();
+ }
+ }
+ if(block==rsv_blocks.end() || block->block==until_block)
+ return 0;
+
+ unsigned entry = veh.get_entry();
+
+ float result = veh.get_offset();
+ if(reverse!=back)
+ entry = track->traverse(entry);
+ else
+ result = track->get_type().get_path_length(track->get_active_path())-result;
+ result -= vtype.get_length()/2;
+
+ while(1)
+ {
+ if(track->get_type().get_endpoints().size()<2)
+ break;
+
+ Track *next = track->get_link(track->traverse(entry));
+
+ if(!block->block->has_track(*next))
+ {
+ if(back)
+ {
+ if(block==cur_blocks.begin())
+ break;
+ --block;
+ }
+ else
+ {
+ ++block;
+ if(block==cur_blocks.end())
+ block = rsv_blocks.begin();
+ if(block==rsv_blocks.end())
+ break;
+ }
+
+ if(block->block==until_block)
+ break;
+ }
+
+ entry = next->get_endpoint_by_link(*track);
+ track = next;
+
+ result += track->get_type().get_path_length(track->get_active_path());
+ }
+
+ return result;
+}
+
+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;
+}
+
+unsigned Train::find_speed(float real) const
+{
+ if(real<=real_speed[0].speed)
+ return 0;
+
+ unsigned low = 0;
+ unsigned high = 0;
+ unsigned last = 0;
+ for(unsigned i=0; (!high && i<=14); ++i)
+ if(real_speed[i].weight)
+ {
+ last = i;
+ if(real_speed[i].speed<real)
+ low = i;
+ else
+ high = i;
+ }
+ if(!high)
+ {
+ if(!low)
+ {
+ if(real)
+ return 3;
+ else
+ return 0;
+ }
+ return min(min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U), last+3);
+ }
+
+ 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;
+ 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);
+}
+
+bool Train::advance_route(list<RouteRef>::iterator &iter, Track &track)
+{
+ while(iter!=routes.end() && !iter->route->has_track(track))
+ ++iter;
+ if(iter==routes.end())
+ return false;
+
+ list<RouteRef>::iterator next = iter;
+ ++next;
+ if(next!=routes.end() && next->diversion && next->route->has_track(track))
+ iter = next;
+
+ return true;
+}
+
+Route *Train::create_lead_route(Route *lead, const Route *target)
+{
+ if(!lead)
+ {
+ lead = new Route(layout);
+ lead->set_name("Lead");
+ lead->set_temporary(true);
+ }
+
+ set<Track *> tracks;
+ for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=rsv_blocks.end(); )
+ {
+ const set<Track *> &btracks = i->block->get_tracks();
+ for(set<Track *>::const_iterator j=btracks.begin(); j!=btracks.end(); ++j)
+ if(!target || !target->has_track(**j))
+ tracks.insert(*j);
+
+ if(++i==cur_blocks.end())
+ i = rsv_blocks.begin();
+ }
+
+ lead->add_tracks(tracks);
+
+ return lead;
+}
+
+bool Train::is_valid_diversion(const Route &diversion, Track &from, unsigned from_ep)
+{
+ float diversion_len = 0;
+ Track *track = &from;
+ unsigned ep = from_ep;
+ while(diversion.has_track(*track))
+ {
+ unsigned path = 0;
+ if(track->get_turnout_id())
+ path = diversion.get_turnout(track->get_turnout_id());
+ diversion_len += track->get_type().get_path_length(path);
+
+ Track *next = track->get_link(track->traverse(ep, path));
+ ep = next->get_endpoint_by_link(*track);
+ track = next;
+
+ if(track==&from)
+ return false;
+ }
+
+ list<RouteRef>::iterator route = routes.begin();
+ if(!advance_route(route, from))
+ return false;
+
+ set<Track *> visited;
+ float route_len = 0;
+ track = &from;
+ ep = from_ep;
+ while(1)
+ {
+ unsigned path = 0;
+ if(track->get_turnout_id())
+ path = route->route->get_turnout(track->get_turnout_id());
+ route_len += track->get_type().get_path_length(path);
+
+ if(track!=&from && diversion.has_track(*track))
+ break;
+
+ if(visited.count(track))
+ return false;
+ visited.insert(track);
+
+ Track *next = track->get_link(track->traverse(ep, path));
+ ep = next->get_endpoint_by_link(*track);
+ track = next;
+
+ if(!advance_route(route, *track))
+ return false;
+ }
+
+ return diversion_len<route_len*1.2;
+}
+
+
+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::RouteRef::RouteRef(const Route *r, unsigned d):
+ route(r),
+ diversion(d)
+{ }
+
+
+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),
+ blocks_valid(true)
+{
+ add("block", &Loader::block);
+ add("block_hint", &Loader::block_hint);
+ add("name", &Loader::name);
+ add("priority", &Train::priority);
+ add("real_speed", &Loader::real_speed);
+ add("route", &Loader::route);
+ add("timetable", &Loader::timetable);
+ add("vehicle", &Loader::vehicle);
+}
+
+void Train::Loader::finish()
+{
+ if(!obj.cur_blocks.empty())
+ {
+ const BlockRef &blkref = obj.cur_blocks.front();
+ const Block::Endpoint &bep = blkref.block->get_endpoints()[blkref.entry];
+ float offset = 2*obj.layout.get_catalogue().get_scale();
+ obj.vehicles.back()->place(*bep.track, bep.track_ep, offset, Vehicle::BACK_BUFFER);
+
+ obj.set_status("Stopped");
+ }
+}
+
+void Train::Loader::block(unsigned id)
+{
+ if(!blocks_valid)
+ return;
+
+ Block *blk;
+ try
+ {
+ blk = &obj.layout.get_block(id);
+ }
+ catch(const KeyError &)
+ {
+ blocks_valid = false;
+ return;
+ }
+
+ 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));
+
+ 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)
+{
+ try
+ {
+ prev_block = &obj.layout.get_block(id);
+ }
+ catch(const KeyError &)
+ {
+ blocks_valid = false;
+ }
+}
+
+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);