X-Git-Url: http://git.tdb.fi/?a=blobdiff_plain;f=source%2Flibmarklin%2Ftrain.cpp;h=859d3daea7988ea7544eb111cb72964613e7a8cd;hb=9b05c573a38639827697fe393d55b7c76f5bde45;hp=330bb70e1fdd7de75a70e91e138c9a8d52e49e44;hpb=03aa7d090507e40f6362cd242d711de4bbba8f18;p=r2c2.git diff --git a/source/libmarklin/train.cpp b/source/libmarklin/train.cpp index 330bb70..859d3da 100644 --- a/source/libmarklin/train.cpp +++ b/source/libmarklin/train.cpp @@ -1,7 +1,7 @@ /* $Id$ This file is part of the MSP Märklin suite -Copyright © 2006-2009 Mikkosoft Productions, Mikko Rasa +Copyright © 2006-2010 Mikkosoft Productions, Mikko Rasa Distributed under the GPL */ @@ -9,45 +9,95 @@ Distributed under the GPL #include #include #include -#include "control.h" -#include "except.h" +#include "aicontrol.h" +#include "catalogue.h" +#include "driver.h" +#include "layout.h" #include "route.h" +#include "simplecontroller.h" +#include "timetable.h" +#include "trackiter.h" #include "tracktype.h" -#include "trafficmanager.h" #include "train.h" +#include "vehicle.h" +#include "vehicletype.h" using namespace std; using namespace Msp; +namespace { + +struct SetFlag +{ + bool &flag; + + SetFlag(bool &f): flag(f) { flag = true; } + ~SetFlag() { flag = false; } +}; + +} + + namespace Marklin { -Train::Train(TrafficManager &tm, Locomotive &l): - trfc_mgr(tm), - loco(l), +Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p): + layout(l), + loco_type(t), + address(a), + protocol(p), + priority(0), + yielding_to(0), + cur_blocks_end(blocks.end()), + clear_blocks_end(blocks.end()), pending_block(0), - target_speed(0), - route(0), + reserving(false), + advancing(false), + controller(new AIControl(*this, new SimpleController)), + timetable(0), + active(false), + current_speed_step(0), + speed_changing(false), + reverse(false), + functions(0), + end_of_route(false), status("Unplaced"), travel_dist(0), - travel_speed(0), pure_speed(false), - real_speed(15), - cur_track(0) + real_speed(layout.get_driver().get_protocol_speed_steps(protocol)+1), + accurate_position(false), + overshoot_dist(false) { - trfc_mgr.add_train(this); + if(!loco_type.is_locomotive()) + throw InvalidParameterValue("Initial vehicle must be a locomotive"); - loco.signal_reverse_changed.connect(sigc::mem_fun(this, &Train::locomotive_reverse_changed)); + vehicles.push_back(new Vehicle(layout, loco_type)); - const map &sensors = trfc_mgr.get_control().get_sensors(); - for(map::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.add_train(*this); - const map &turnouts = trfc_mgr.get_control().get_turnouts(); - for(map::const_iterator i=turnouts.begin(); i!=turnouts.end(); ++i) - { - i->second->signal_path_changing.connect(sigc::bind(sigc::mem_fun(this, &Train::turnout_path_changing), i->second)); - i->second->signal_path_changed.connect(sigc::bind(sigc::mem_fun(this, &Train::turnout_path_changed), i->second)); - } + layout.get_driver().add_loco(address, protocol); + 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)); + + 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_halt.connect(sigc::mem_fun(this, &Train::halt_event)); + + const set &tracks = layout.get_tracks(); + for(set::const_iterator i=tracks.begin(); i!=tracks.end(); ++i) + if((*i)->get_turnout_id()) + (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &Train::turnout_path_changed), sigc::ref(**i)))); + + controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed)); +} + +Train::~Train() +{ + delete controller; + delete timetable; + for(vector::iterator i=vehicles.begin(); i!=vehicles.end(); ++i) + delete *i; + layout.remove_train(*this); } void Train::set_name(const string &n) @@ -57,45 +107,276 @@ void Train::set_name(const string &n) signal_name_changed.emit(name); } -void Train::set_speed(unsigned speed) +void Train::set_priority(int p) { - if(speed==target_speed) + priority = p; +} + +void Train::yield_to(const Train &t) +{ + yielding_to = &t; +} + +void Train::add_vehicle(const VehicleType &vt) +{ + Vehicle *veh = new Vehicle(layout, vt); + vehicles.back()->attach_back(*veh); + vehicles.push_back(veh); +} + +void Train::remove_vehicle(unsigned i) +{ + if(i>=vehicles.size()) + throw InvalidParameterValue("Vehicle index out of range"); + if(i==0) + throw InvalidParameterValue("Can't remove the locomotive"); + delete vehicles[i]; + vehicles.erase(vehicles.begin()+i); + if(iattach_back(*vehicles[i]); +} + +unsigned Train::get_n_vehicles() const +{ + return vehicles.size(); +} + +Vehicle &Train::get_vehicle(unsigned i) +{ + if(i>=vehicles.size()) + throw InvalidParameterValue("Vehicle index out of range"); + return *vehicles[i]; +} + +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) +{ + controller->set_control(n, v); +} + +void Train::set_active(bool a) +{ + if(a==active) return; - travel_speed = static_cast(round(get_real_speed(speed)*87*3.6/5))*5; + if(!a && controller->get_speed()) + throw InvalidState("Can't deactivate while moving"); - target_speed = speed; - if(!target_speed) + active = a; + if(active) { - trfc_mgr.get_control().set_timer(3*Time::sec).signal_timeout.connect( - sigc::bind_return(sigc::bind(sigc::mem_fun(this, &Train::release_blocks), sigc::ref(rsv_blocks)), false)); + stop_timeout = Time::TimeStamp(); + reserve_more(); } else - reserve_more(); + { + stop_timeout = Time::now()+2*Time::sec; + set_status("Stopped"); + } +} - signal_target_speed_changed.emit(target_speed); +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); +} + +float Train::get_control(const string &ctrl) const +{ + return controller->get_control(ctrl).value; +} - update_speed(); - pure_speed = false; +float Train::get_speed() const +{ + return controller->get_speed(); } -void Train::set_reverse(bool rev) +bool Train::get_function(unsigned func) const { - loco.set_reverse(rev); + return (functions>>func)&1; +} + +void Train::set_timetable(Timetable *tt) +{ + delete timetable; + timetable = tt; +} + +bool Train::set_route(const Route *r) +{ + free_noncritical_blocks(); + + Route *lead = 0; + if(r && !blocks.empty()) + { + TrackIter first = blocks.front().track_iter(); + TrackIter next = blocks.back().next().track_iter(); + if(!r->has_track(*next)) + { + lead = Route::find(next, *r); + if(!lead) + return false; + create_lead_route(lead, lead); + routes.push_front(lead); + } + else if(!r->has_track(*first)) + lead = create_lead_route(0, r); + } + + routes.clear(); + if(lead) + routes.push_back(lead); + if(r) + routes.push_back(r); + end_of_route = false; + + reserve_more(); + + signal_route_changed.emit(get_route()); + + return true; +} + +bool Train::go_to(Track &to) +{ + for(BlockList::const_iterator i=blocks.begin(); i!=cur_blocks_end; ++i) + if((*i)->has_track(to)) + { + signal_arrived.emit(); + return set_route(0); + } + + free_noncritical_blocks(); + + TrackIter next = blocks.back().next().track_iter(); + + Route *route = Route::find(next, to); + if(!route) + return false; + create_lead_route(route, route); + return set_route(route); +} + +bool Train::divert(Track &from) +{ + if(!from.get_turnout_id()) + throw InvalidParameterValue("Can't divert from a non-turnout"); + if(routes.empty()) + return false; + + unsigned path = 0; + unsigned entry = 0; + list::iterator route = routes.begin(); + + // Follow our routes to find out where we're entering the turnout + for(TrackLoopIter track = blocks.front().track_iter();;) + { + if(!advance_route(route, *track)) + return false; + + if(&*track==&from) + { + Block &block = track->get_block(); + if(block.get_train()==this && !free_block(block)) + return false; + + int route_path = route->route->get_turnout(from.get_turnout_id()); + + // Check that more than one path is available + unsigned ep_paths = track.endpoint().paths; + if(!(ep_paths&(ep_paths-1))) + return false; + + // Choose some other path + for(int i=0; ep_paths>>i; ++i) + if((ep_paths&(1<route->get_path(*track)); + + if(!track || track.looped()) + return false; + } + + TrackIter track = TrackIter(&from, entry).next(path); + if(!track) + return false; + + set tracks; + for(list::iterator i=routes.begin(); i!=routes.end(); ++i) + tracks.insert(i->route->get_tracks().begin(), i->route->get_tracks().end()); + RefPtr diversion = Route::find(track, tracks); + if(!diversion) + return false; + + diversion->set_name("Diversion"); + diversion->add_track(from); + diversion->set_turnout(from.get_turnout_id(), path); + + if(!is_valid_diversion(*diversion, TrackIter(&from, entry))) + return false; + + // Follow the diversion route until we get back to the original route + list::iterator end = routes.end(); + while(1) + { + for(list::iterator i=route; (end==routes.end() && i!=routes.end()); ++i) + if(i->route->has_track(*track)) + end = i; + + if(end!=routes.end()) + break; + else if(!diversion->has_track(*track)) + throw LogicError("Pathfinder returned a bad route"); + + track = track.next(diversion->get_path(*track)); + } + + if(route==end) + // We are rejoining the same route we diverted from, duplicate it + routes.insert(end, *route); + else + { + ++route; + routes.erase(route, end); + } + routes.insert(end, RouteRef(diversion.release(), from.get_turnout_id())); + + return true; } -void Train::set_route(const Route *r) +const Route *Train::get_route() const { - route = r; - signal_route_changed.emit(route); + if(routes.empty()) + return 0; + return routes.front().route; } void Train::place(Block &block, unsigned entry) { - if(target_speed) - set_speed(0); + if(controller->get_speed()) + throw InvalidState("Must be stopped before placing"); + + release_blocks(); - release_blocks(rsv_blocks); - release_blocks(cur_blocks); + set_active(false); + accurate_position = false; if(!block.reserve(this)) { @@ -103,352 +384,723 @@ void Train::place(Block &block, unsigned entry) return; } - cur_blocks.push_back(BlockRef(&block, entry)); - set_position(block.get_endpoints()[entry]); + blocks.push_back(BlockIter(&block, entry)); + if(reverse) + { + TrackIter track = BlockIter(&block, entry).reverse().track_iter(); + vehicles.front()->place(*track, track.entry(), 0, Vehicle::FRONT_BUFFER); + } + else + { + const Block::Endpoint &bep = block.get_endpoint(entry); + vehicles.back()->place(*bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER); + } +} + +void Train::unplace() +{ + if(controller->get_speed()) + throw InvalidState("Must be stopped before unplacing"); + + release_blocks(); + + set_active(false); + accurate_position = false; - set_status("Stopped"); + for(vector::iterator i=vehicles.begin(); i!=vehicles.end(); ++i) + (*i)->unplace(); + + set_status("Unplaced"); } bool Train::free_block(Block &block) { + float margin = 10*layout.get_catalogue().get_scale(); + if(get_reserved_distance_until(&block, false)get_braking_distance()*1.3+margin) + return false; + unsigned nsens = 0; - for(list::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i) + for(BlockList::iterator i=cur_blocks_end; i!=blocks.end(); ++i) { - if(i->block==&block) + if(i->block()==&block) { if(nsens<1) return false; - for(list::iterator j=i; j!=rsv_blocks.end(); ++j) - j->block->reserve(0); - rsv_blocks.erase(i, rsv_blocks.end()); - update_speed(); + release_blocks(i, blocks.end()); return true; } - else if(i->block->get_sensor_id()) + else if((*i)->get_sensor_id()) ++nsens; } return false; } +void Train::free_noncritical_blocks() +{ + if(blocks.empty()) + return; + + if(controller->get_speed()==0) + { + release_blocks(cur_blocks_end, blocks.end()); + return; + } + + float margin = 10*layout.get_catalogue().get_scale(); + float min_dist = controller->get_braking_distance()*1.3+margin; + + Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front()); + + TrackIter track(veh.get_track(), veh.get_entry()); + BlockList::iterator block = blocks.begin(); + bool in_rsv = false; + while(block!=blocks.end() && !(*block)->has_track(*track)) + { + ++block; + if(block==cur_blocks_end) + in_rsv = true; + } + + float dist = veh.get_offset(); + if(reverse) + track.reverse(); + else + dist = track->get_type().get_path_length(track->get_active_path())-dist; + dist -= veh.get_type().get_length()/2; + + bool nsens = 0; + while(1) + { + track = track.next(); + + if(!(*block)->has_track(*track)) + { + ++block; + if(block==cur_blocks_end) + in_rsv = true; + if(block==blocks.end()) + return; + + if(dist>min_dist && nsens>0) + { + release_blocks(block, blocks.end()); + return; + } + + if(in_rsv && (*block)->get_sensor_id()) + ++nsens; + } + + dist += track->get_type().get_path_length(track->get_active_path()); + } +} + int Train::get_entry_to_block(Block &block) const { - for(list::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i) - if(i->block==&block) - return i->entry; - for(list::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i) - if(i->block==&block) - return i->entry; + for(BlockList::const_iterator i=blocks.begin(); i!=blocks.end(); ++i) + if(i->block()==&block) + return i->entry(); return -1; } +float Train::get_reserved_distance() const +{ + return get_reserved_distance_until(0, false); +} + void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt) { - if(try_reserve && t>try_reserve) + if(!active && stop_timeout && t>=stop_timeout) + { + release_blocks(cur_blocks_end, blocks.end()); + stop_timeout = Time::TimeStamp(); + } + + Driver &driver = layout.get_driver(); + + if(timetable) + timetable->tick(t); + controller->tick(dt); + float speed = controller->get_speed(); + unsigned speed_step = find_speed_step(speed); + + if(controller->get_reverse()!=reverse) + { + reverse = controller->get_reverse(); + driver.set_loco_reverse(address, reverse); + + release_blocks(cur_blocks_end, blocks.end()); + reverse_blocks(blocks); + reserve_more(); + } + if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power()) + { + speed_changing = true; + driver.set_loco_speed(address, speed_step); + + pure_speed = false; + + if(speed_step) + set_status(format("Traveling %d kmh", get_travel_speed())); + else + set_status("Waiting"); + } - if(cur_track) + if(speed) { - unsigned path = 0; - if(cur_track->get_turnout_id()) - path = trfc_mgr.get_control().get_turnout(cur_track->get_turnout_id()).get_path(); + if(!active) + set_active(true); + + Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front()); + Track *track = vehicle.get_track(); - offset += get_real_speed(loco.get_speed())*(dt/Time::sec); - if(offset>cur_track->get_type().get_path_length(path)) + bool ok = false; + for(BlockList::const_iterator i=blocks.begin(); (!ok && i!=cur_blocks_end); ++i) + ok = (*i)->has_track(*track); + + float d; + if(real_speed.size()>1) + d = get_real_speed(current_speed_step)*(dt/Time::sec); + else + d = speed*(dt/Time::sec); + if(ok) { - int out = cur_track->traverse(cur_track_ep, path); - if(out>=0) + SetFlag setf(advancing); + vehicle.advance(reverse ? -d : d); + } + else if(accurate_position) + { + overshoot_dist += d; + if(overshoot_dist>40*layout.get_catalogue().get_scale()) { - Track *next = cur_track->get_link(out); - if(next) - cur_track_ep = next->get_endpoint_by_link(*cur_track); - cur_track = next; - offset = 0; + layout.emergency(name+" has not arrived at sensor"); + accurate_position = false; } - else - cur_track = 0; } + } + else if(end_of_route && cur_blocks_end==blocks.end()) + { + set_active(false); + signal_arrived.emit(); + set_route(0); + } - if(cur_track) - pos = cur_track->get_point(cur_track_ep, path, offset); + if(!blocks.empty() && !blocks.front()->get_sensor_id()) + { + float dist = get_reserved_distance_until(&*blocks.front(), true); + + if(dist>10*layout.get_catalogue().get_scale()) + { + blocks.front()->reserve(0); + blocks.pop_front(); + } } } void Train::save(list &st) const { st.push_back((DataFile::Statement("name"), name)); - for(unsigned i=0; i<=14; ++i) + + st.push_back((DataFile::Statement("priority"), priority)); + + for(vector::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; iget_id())); + + for(BlockList::const_iterator i=blks.begin(); i!=blks.end(); ++i) + st.push_back((DataFile::Statement("block"), (*i)->get_id())); + } + + if(!routes.empty()) + { + list::const_iterator i = routes.begin(); + for(; (i!=routes.end() && i->route->is_temporary()); ++i) ; + if(i!=routes.end()) + st.push_back((DataFile::Statement("route"), i->route->get_name())); + } + + if(timetable) + { + DataFile::Statement ss("timetable"); + timetable->save(ss.sub); + st.push_back(ss); + } } -void Train::locomotive_reverse_changed(bool) +void Train::control_changed(const Controller::Control &ctrl) { - for(list::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i) - i->block->reserve(0); - rsv_blocks.clear(); - cur_blocks.reverse(); - for(list::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i) - i->entry = i->block->traverse(i->entry); - reserve_more(); + signal_control_changed.emit(ctrl.name, ctrl.value); +} - if(cur_track) +void Train::loco_speed_event(unsigned addr, unsigned speed, bool) +{ + if(addr==address) { - unsigned path = 0; - if(unsigned turnout = cur_track->get_turnout_id()) - path = trfc_mgr.get_control().get_turnout(turnout).get_path(); - cur_track_ep = cur_track->traverse(cur_track_ep, path); - offset = cur_track->get_type().get_path_length(path)-offset; + current_speed_step = speed; + speed_changing = false; + pure_speed = false; } } -void Train::sensor_event(bool state, Sensor *sensor) +void Train::loco_func_event(unsigned addr, unsigned func, bool state) { - unsigned addr = sensor->get_address(); + if(addr==address || (addr==address+1 && loco_type.get_max_function()>4)) + { + if(addr==address+1) + func += 4; + if(state) + functions |= 1<::iterator i; - for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i) - if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr) - break; + // Find the first sensor block from our reserved blocks that isn't this sensor + BlockList::iterator end; + unsigned result = 0; + for(end=cur_blocks_end; end!=blocks.end(); ++end) + if((*end)->get_sensor_id()) + { + if((*end)->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) { + // Compute speed and update related state float travel_time_secs = (Time::now()-last_entry_time)/Time::sec; - travel_speed = static_cast(round(travel_dist/travel_time_secs*87*3.6/5))*5; if(pure_speed) { - RealSpeed &rs = real_speed[loco.get_speed()]; - rs.add(travel_dist/travel_time_secs, travel_time_secs); + if(current_speed_step>0) + { + RealSpeed &rs = real_speed[current_speed_step]; + 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::iterator j=rsv_blocks.begin(); j!=i; ++j) + for(BlockList::iterator j=cur_blocks_end; j!=end; ++j) { - j->block->traverse(j->entry, &block_len); - travel_dist += block_len; + travel_dist += (*j)->get_path_length(j->entry()); + + if((*j)->get_sensor_id()==addr && !advancing) + { + TrackIter track = j->track_iter(); + if(reverse) + { + track = track.flip(); + vehicles.back()->place(*track, track.entry(), 0, Vehicle::BACK_AXLE); + } + else + vehicles.front()->place(*track, track.entry(), 0, Vehicle::FRONT_AXLE); + } } last_entry_time = Time::now(); pure_speed = true; + accurate_position = true; + overshoot_dist = 0; - cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i); - } + // Check if we've reached the next route + if(routes.size()>1) + { + const Route &route = *(++routes.begin())->route; + for(BlockList::iterator j=cur_blocks_end; j!=end; ++j) + if(route.has_track(*j->track_iter())) + { + routes.pop_front(); + // XXX Exceptions? + signal_route_changed.emit(routes.front().route); + break; + } + } - for(i=cur_blocks.begin(); i!=cur_blocks.end(); ++i) - if(i->block->get_sensor_id()==addr) - set_position(i->block->get_endpoints()[i->entry]); + // Move blocks up to the next sensor to our current blocks + cur_blocks_end = end; - if(target_speed && reserve_more()<2) - update_speed(); + // 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 { - for(list::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i) - if(unsigned b_addr = i->block->get_sensor_id()) + const Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back()); + + // Find the first sensor in our current blocks that's still active + BlockList::iterator end = blocks.begin(); + for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i) + { + if((*i)->has_track(*veh.get_track())) + break; + if((*i)->get_sensor_id()) { - if(b_addr==addr) + if(layout.get_driver().get_sensor((*i)->get_sensor_id())) + break; + else { - ++i; - for(list::iterator j=cur_blocks.begin(); j!=i; ++j) - j->block->reserve(0); - cur_blocks.erase(cur_blocks.begin(), i); + end = i; + ++end; } - break; } - - if(target_speed && pending_block && addr==pending_block->get_sensor_id()) - reserve_more(); + } + + if(end!=blocks.begin() && end!=cur_blocks_end) + // Free blocks up to the last inactive sensor + release_blocks(blocks.begin(), end); } } -void Train::turnout_path_changing(unsigned, Turnout *turnout) +void Train::turnout_path_changed(Track &track) { - unsigned tid = turnout->get_address(); - for(list::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i) - if(i->block->get_turnout_id()==tid) - throw TurnoutBusy(this); - - unsigned nsens = 0; - for(list::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i) - { - if(i->block->get_turnout_id()==tid) - { - if(nsens<1) - throw TurnoutBusy(this); - break; - } - else if(i->block->get_sensor_id()) - ++nsens; - } + for(list::iterator i=blocks.begin(); i!=blocks.end(); ++i) + if((*i)->get_turnout_id()==track.get_turnout_id() && !reserving) + check_turnout_paths(false); } -void Train::turnout_path_changed(unsigned, Turnout *turnout) +void Train::halt_event(bool h) { - unsigned tid = turnout->get_address(); - for(list::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i) - if(i->block->get_turnout_id()==tid) - { - while(i!=rsv_blocks.end()) - { - i->block->reserve(0); - i = rsv_blocks.erase(i); - } - reserve_more(); - return; - } + if(h) + accurate_position = false; +} - if(pending_block && tid==pending_block->get_turnout_id()) +void Train::block_reserved(const Block &block, const Train *train) +{ + if(&block==pending_block && !train && !reserving) reserve_more(); } -unsigned Train::reserve_more() +void Train::reserve_more() { - BlockRef *last = 0; - if(!rsv_blocks.empty()) - last = &rsv_blocks.back(); - else if(!cur_blocks.empty()) - last = &cur_blocks.back(); - if(!last) - return 0; + if(!active || blocks.empty() || end_of_route) + return; + + BlockIter start = blocks.back(); pending_block = 0; - // See how many blocks we already have + // See how many sensor blocks and how much track we already have unsigned nsens = 0; - for(list::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i) - if(i->block->get_sensor_id()) + float dist = 0; + for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i) + { + if((*i)->get_sensor_id()) ++nsens; + if(nsens>0) + dist += (*i)->get_path_length(i->entry()); + } + + list::iterator cur_route = routes.begin(); + advance_route(cur_route, *start.track_iter()); + + float approach_margin = 50*layout.get_catalogue().get_scale(); + float min_dist = controller->get_braking_distance()*1.3+approach_margin*2; + + BlockIter block = start; + list::iterator good_end = blocks.end(); + Track *divert_track = 0; + bool try_divert = false; + Train *blocking_train = 0; + BlockList contested_blocks; - bool got_more = false; - BlockRef *good = last; - unsigned good_sens = nsens; - while(good_sens<3) + SetFlag setf(reserving); + + while(1) { - // Traverse to the next block - unsigned exit = last->block->traverse(last->entry); - Block *link = last->block->get_link(exit); - if(!link) + BlockIter last = block; + block = block.next(cur_route!=routes.end() ? cur_route->route : 0); + if(!block || block->get_endpoints().size()<2) + { + if(!blocking_train) + good_end = blocks.end(); break; + } + + TrackIter track = block.track_iter(); - int entry = link->get_endpoint_by_link(*last->block); - if(!link->reserve(this)) + if(cur_route!=routes.end()) { - // If we found another train going in the same direction as us, we can keep the blocks we got - int other_entry = link->get_train()->get_entry_to_block(*link); - if(other_entry==entry || link->traverse(entry)==link->traverse(other_entry)) + if(!advance_route(cur_route, *track)) { - good = last; - good_sens = nsens; + // Keep the blocks if we arrived at the end of the route + if(!blocking_train) + { + good_end = blocks.end(); + end_of_route = true; + } + break; } - pending_block = link; - break; } - if(link->get_turnout_id()) + if(block->get_turnout_id() && !last->get_turnout_id()) { - const Block::Endpoint &ep = link->get_endpoints()[entry]; - const Endpoint &track_ep = ep.track->get_type().get_endpoints()[ep.track_ep]; + /* We can keep the blocks if we arrive at a turnout from a non-turnout + block. Having a turnout block as our last reserved block is not good + as it would limit our diversion possibilities for little benefit. */ + good_end = blocks.end(); + if(nsens>=3 && dist>=min_dist) + break; + } - if(track_ep.paths&(track_ep.paths-1)) + if(blocking_train) + { + if(block->get_train()!=blocking_train) { - // We're facing the points - keep the blocks reserved so far - good = last; - good_sens = nsens; + if(blocking_train->free_block(*contested_blocks.back())) + { + // Roll back and start actually reserving the blocks + block = blocks.back(); + cur_route = routes.begin(); + advance_route(cur_route, *block.track_iter().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(block); + continue; + } + } - Turnout &turnout = trfc_mgr.get_control().get_turnout(link->get_turnout_id()); - - // Figure out what path we'd like to take on the turnout - int path = -1; - if(route) - path = route->get_turnout(link->get_turnout_id()); - if(path<0) - path = turnout.get_path(); - if(!((track_ep.paths>>path)&1)) + bool reserved = block->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 = block->get_train(); + int other_entry = other_train->get_entry_to_block(*block); + if(other_entry<0) + throw LogicError("Block reservation inconsistency"); + + unsigned exit = block.reverse().entry(); + unsigned other_exit = BlockIter(block.block(), other_entry).reverse().entry(); + bool entry_conflict = (block.entry()==other_exit); + bool exit_conflict = (exit==static_cast(other_entry)); + if(!entry_conflict && !last->get_turnout_id()) + /* The other train is not coming to the blocks we're holding, so we + can keep them. */ + good_end = blocks.end(); + + int other_prio = other_train->get_priority(); + + if(!entry_conflict && !exit_conflict && other_priofree_block(*block)) + reserved = block->reserve(this); + } + else if(other_train!=yielding_to && (other_prio>i; ++i) - if((track_ep.paths>>i)&1) - path = i; + /* 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(block); + continue; } + else if(divert_track && (entry_conflict || exit_conflict)) + // We are blocked, but there's a diversion possibility + try_divert = true; - if(path!=turnout.get_path()) + if(!reserved) { - // The turnout is set to wrong path - switch and wait for it - link->reserve(0); - pending_block = link; - turnout.set_path(path); + pending_block = &*block; break; } } - rsv_blocks.push_back(BlockRef(link, entry)); - last = &rsv_blocks.back(); - if(last->block->get_sensor_id()) + if(block->get_turnout_id()) { - ++nsens; - got_more = true; + const TrackType::Endpoint &track_ep = track.endpoint(); + bool multiple_paths = (track_ep.paths&(track_ep.paths-1)); + + if(multiple_paths && cur_route!=routes.end() && cur_route->diversion!=block->get_turnout_id()) + /* There's multiple paths to be taken and we are on a route - take + note of the diversion possibility */ + divert_track = &*track; } + + if(!contested_blocks.empty() && contested_blocks.front()==block) + contested_blocks.pop_front(); + + blocks.push_back(block); + + if(cur_blocks_end==blocks.end()) + --cur_blocks_end; + if(clear_blocks_end==blocks.end()) + --clear_blocks_end; + if(good_end==blocks.end()) + --good_end; + + if(block->get_sensor_id()) + ++nsens; + if(nsens>0) + dist += block->get_path_length(block.entry()); } // 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(); - } + release_blocks(good_end, blocks.end()); + + if(blocks.back()!=start) + // We got some new blocks, so no longer need to yield + yielding_to = 0; - if(got_more) - update_speed(); + check_turnout_paths(true); - return nsens; + // Make any sensorless blocks at the beginning immediately current + while(cur_blocks_end!=clear_blocks_end && !(*cur_blocks_end)->get_sensor_id()) + ++cur_blocks_end; + + if(try_divert && divert(*divert_track)) + reserve_more(); } -void Train::update_speed() +void Train::check_turnout_paths(bool set) { - if(!target_speed) + if(clear_blocks_end==blocks.end()) + return; + + for(list::iterator i=clear_blocks_end; i!=blocks.end(); ++i) { - loco.set_speed(0); - try_reserve = Time::TimeStamp(); - set_status("Stopped"); + if((*i)->get_turnout_id()) + { + TrackIter track = i->track_iter(); + const TrackType::Endpoint &track_ep = track.endpoint(); + + unsigned path = 0; + list::iterator j = i; + if(++j!=blocks.end()) + { + TrackIter rev = j->track_iter().flip(); + unsigned mask = rev.endpoint().paths&track_ep.paths; + for(path=0; mask>1; mask>>=1, ++path) ; + } + else + return; + + if(path!=track->get_active_path()) + { + if(set) + track->set_active_path(path); + + /* Check again, in case the driver was able to service the request + instantly */ + if(!set || path!=track->get_active_path()) + continue; + } + } + + if(i==clear_blocks_end) + ++clear_blocks_end; } +} + +float Train::get_reserved_distance_until(const Block *until_block, bool back) const +{ + if(blocks.empty()) + return 0; + + Vehicle &veh = *(reverse!=back ? vehicles.back() : vehicles.front()); + const VehicleType &vtype = veh.get_type(); + + TrackIter track(veh.get_track(), veh.get_entry()); + if(!track) // XXX Probably unnecessary + return 0; + + BlockList::const_iterator block = blocks.begin(); + while(block!=clear_blocks_end && !(*block)->has_track(*track)) + ++block; + if(block==clear_blocks_end || &**block==until_block) + return 0; + + float result = veh.get_offset(); + if(reverse!=back) + track = track.reverse(); else + result = track->get_type().get_path_length(track->get_active_path())-result; + result -= vtype.get_length()/2; + + while(1) { - unsigned nsens = 0; - for(list::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i) - if(i->block->get_sensor_id()) - ++nsens; + track = track.next(); + if(!track) + break; - unsigned slow_speed = find_speed(0.1); // 31.3 km/h - if(nsens==0) + if(!(*block)->has_track(*track)) { - loco.set_speed(0); - pure_speed = false; - try_reserve = Time::now()+2*Time::sec; - set_status("Blocked"); - } - else if(nsens==1 && target_speed>slow_speed) - { - loco.set_speed(slow_speed); - pure_speed = false; - try_reserve = Time::now()+2*Time::sec; - set_status("Slow"); - } - else - { - loco.set_speed(target_speed); - try_reserve = Time::TimeStamp(); - set_status(format("Traveling %d kmh", travel_speed)); + if(back) + { + if(block==blocks.begin()) + break; + --block; + } + else + { + ++block; + if(block==clear_blocks_end) + break; + } + + if(&**block==until_block) + break; } + + result += track->get_type().get_path_length(track->get_active_path()); } + + return result; } float Train::get_real_speed(unsigned i) const { + if(i==0) + return 0; if(real_speed[i].weight) return real_speed[i].speed; @@ -457,7 +1109,7 @@ float Train::get_real_speed(unsigned i) const for(low=i; low>0; --low) if(real_speed[low].weight) break; - for(high=i; high<14; ++high) + for(high=i; high+1(low*real/real_speed[low].speed), 14U); + { + if(real) + return limit; + else + return 0; + } + return min(min(static_cast(low*real/real_speed[low].speed), real_speed.size()-1), last+limit); } float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed); return static_cast(low*(1-f)+high*f+0.5); } +float Train::get_travel_speed() const +{ + float speed = get_real_speed(current_speed_step); + float scale = layout.get_catalogue().get_scale(); + return static_cast(round(speed/scale*3.6/5))*5; +} + void Train::set_status(const string &s) { status = s; signal_status_changed.emit(s); } -void Train::set_position(const Block::Endpoint &bep) +void Train::release_blocks() +{ + release_blocks(blocks.begin(), blocks.end()); +} + +void Train::release_blocks(BlockList::iterator begin, BlockList::iterator end) +{ + while(begin!=end) + { + if(begin==cur_blocks_end) + cur_blocks_end = end; + if(begin==clear_blocks_end) + clear_blocks_end = end; + + Block &block = **begin; + blocks.erase(begin++); + block.reserve(0); + + if(begin==blocks.end()) + end_of_route = false; + } +} + +void Train::reverse_blocks(BlockList &blks) const { - cur_track = bep.track; - cur_track_ep = bep.track_ep; - offset = 0; - pos = cur_track->get_endpoint_position(cur_track_ep); + blks.reverse(); + for(BlockList::iterator i=blks.begin(); i!=blks.end(); ++i) + *i = i->reverse(); +} + +bool Train::advance_route(list::iterator &iter, Track &track) +{ + while(iter!=routes.end() && !iter->route->has_track(track)) + ++iter; + if(iter==routes.end()) + return false; + + list::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 tracks; + for(BlockList::iterator i=blocks.begin(); i!=blocks.end(); ++i) + { + const set &btracks = (*i)->get_tracks(); + for(set::const_iterator j=btracks.begin(); j!=btracks.end(); ++j) + if(!target || !target->has_track(**j)) + tracks.insert(*j); + } + + lead->add_tracks(tracks); + + return lead; } -void Train::release_blocks(list &blocks) +bool Train::is_valid_diversion(const Route &diversion, const TrackIter &from) { - for(list::iterator i=blocks.begin(); i!=blocks.end(); ++i) - i->block->reserve(0); - blocks.clear(); + float diversion_len = 0; + TrackLoopIter track1 = from; + while(diversion.has_track(*track1)) + { + unsigned path = diversion.get_path(*track1); + diversion_len += track1->get_type().get_path_length(path); + + track1 = track1.next(path); + + if(track1.looped()) + return false; + } + + list::iterator route = routes.begin(); + if(!advance_route(route, *from)) + return false; + + float route_len = 0; + TrackLoopIter track2 = from; + while(1) + { + unsigned path = route->route->get_path(*track2); + route_len += track2->get_type().get_path_length(path); + + bool ok = (track2!=from && diversion.has_track(*track2)); + + track2 = track2.next(path); + + if(ok) + break; + + if(track2.looped()) + return false; + + if(!advance_route(route, *track2)) + return false; + } + + // Must end up at the same place through both routes + if(track2!=track1) + return false; + + return diversion_len(t) + DataFile::BasicLoader(t), + prev_block(0), + blocks_valid(true) { - add("name", &Train::name); + 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.blocks.empty()) + { + TrackIter track = obj.blocks.front().track_iter(); + float offset = 2*obj.layout.get_catalogue().get_scale(); + obj.vehicles.back()->place(*track, track.entry(), 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.blocks.push_back(BlockIter(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) { + if(i>=obj.real_speed.size()) + return; 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(ArticleNumber art_nr) +{ + const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr); + Vehicle *veh = new Vehicle(obj.layout, vtype); + obj.vehicles.back()->attach_back(*veh); + obj.vehicles.push_back(veh); +} + } // namespace Marklin