3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2010 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
9 #include <msp/strings/formatter.h>
10 #include <msp/time/units.h>
11 #include <msp/time/utils.h>
12 #include "aicontrol.h"
13 #include "catalogue.h"
18 #include "simplephysics.h"
19 #include "tracktype.h"
28 Train::Train(Layout &l, const LocoType &t, unsigned a):
33 control(new AIControl(*this, new SimplePhysics)),
36 speed_changing(false),
47 vehicles.push_back(new Vehicle(layout, loco_type));
49 layout.add_train(*this);
51 layout.get_driver().add_loco(address);
52 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
53 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
55 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
56 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
57 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
62 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
64 layout.remove_train(*this);
67 void Train::set_name(const string &n)
71 signal_name_changed.emit(name);
74 Vehicle &Train::get_vehicle(unsigned i)
76 if(i>=vehicles.size())
77 throw InvalidParameterValue("Vehicle index out of range");
81 const Vehicle &Train::get_vehicle(unsigned i) const
83 if(i>=vehicles.size())
84 throw InvalidParameterValue("Vehicle index out of range");
88 void Train::set_control(const string &n, float v)
90 control->set_control(n, v);
91 signal_control_changed.emit(n, control->get_control(n).value);
94 void Train::set_active(bool a)
98 if(!a && control->get_speed())
99 throw InvalidState("Can't deactivate while moving");
104 stop_timeout = Time::TimeStamp();
109 stop_timeout = Time::now()+2*Time::sec;
110 set_status("Stopped");
114 void Train::set_function(unsigned func, bool state)
116 if(!loco_type.get_functions().count(func))
117 throw InvalidParameterValue("Invalid function");
119 layout.get_driver().set_loco_function(address, func, state);
121 layout.get_driver().set_loco_function(address+1, func-4, state);
124 bool Train::get_function(unsigned func) const
126 return (functions>>func)&1;
129 void Train::set_route(const Route *r)
131 if(!rsv_blocks.empty())
133 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
134 if(i->block->get_sensor_id())
136 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
143 end_of_route = false;
147 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
148 BlockRef next = last.next();
149 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
150 if(!route->get_tracks().count(ep.track))
153 route = Route::find(*ep.track, ep.track_ep, *next_route);
160 signal_route_changed.emit(route);
163 void Train::go_to(const Track &to)
165 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
166 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
168 signal_arrived.emit();
174 if(rsv_blocks.empty())
175 last = &cur_blocks.back();
178 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
179 if(i->block->get_sensor_id())
183 BlockRef next = last->next();
184 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
186 set_route(Route::find(*ep.track, ep.track_ep, to));
189 void Train::place(Block &block, unsigned entry)
191 if(control->get_speed())
192 throw InvalidState("Must be stopped before placing");
194 release_blocks(rsv_blocks);
195 release_blocks(cur_blocks);
199 if(!block.reserve(this))
201 set_status("Unplaced");
205 cur_blocks.push_back(BlockRef(&block, entry));
208 unsigned exit = block.traverse(entry);
209 const Block::Endpoint &bep = block.get_endpoints()[exit];
210 Track *track = bep.track->get_link(bep.track_ep);
211 unsigned ep = track->get_endpoint_by_link(*bep.track);
212 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
216 const Block::Endpoint &bep = block.get_endpoints()[entry];
217 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
221 bool Train::free_block(Block &block)
224 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
230 release_blocks(rsv_blocks, i, rsv_blocks.end());
233 else if(i->block->get_sensor_id())
240 int Train::get_entry_to_block(Block &block) const
242 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
245 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
251 float Train::get_reserved_distance() const
253 Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
254 const VehicleType &vtype = veh.get_type();
256 Track *track = veh.get_track();
257 unsigned entry = veh.get_entry();
259 float result = -vtype.get_length()/2;
262 entry = track->traverse(entry);
263 result += veh.get_offset();
266 result -= veh.get_offset();
269 list<BlockRef>::const_iterator block = cur_blocks.begin();
272 if(!first || !reverse)
273 result += track->get_type().get_path_length(track->get_active_path());
276 unsigned exit = track->traverse(entry);
277 Track *next = track->get_link(exit);
279 while(!block->block->get_tracks().count(next))
282 if(block==cur_blocks.end())
283 block = rsv_blocks.begin();
284 if(block==rsv_blocks.end())
288 entry = next->get_endpoint_by_link(*track);
293 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
295 if(!active && stop_timeout && t>=stop_timeout)
297 release_blocks(rsv_blocks);
298 end_of_route = false;
299 stop_timeout = Time::TimeStamp();
303 float speed = control->get_speed();
304 unsigned speed_notch = find_speed(abs(speed));
306 if(speed && (speed<0)!=reverse)
308 layout.get_driver().set_loco_reverse(address, speed<0);
311 release_blocks(rsv_blocks);
312 reverse_blocks(cur_blocks);
316 if(speed_notch!=current_speed && !speed_changing)
318 speed_changing = true;
319 layout.get_driver().set_loco_speed(address, speed_notch);
324 set_status(format("Traveling %d kmh", get_travel_speed()));
326 set_status("Waiting");
334 Track *track = vehicles[0]->get_track();
337 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
338 ok = i->block->get_tracks().count(track);
342 float d = get_real_speed(current_speed)*(dt/Time::sec);
343 vehicles[0]->advance(reverse ? -d : d);
346 else if(end_of_route)
350 void Train::save(list<DataFile::Statement> &st) const
352 st.push_back((DataFile::Statement("name"), name));
353 for(unsigned i=0; i<=14; ++i)
354 if(real_speed[i].weight)
355 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
357 if(!cur_blocks.empty())
359 list<BlockRef> blocks = cur_blocks;
361 reverse_blocks(blocks);
363 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
364 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
366 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
367 st.push_back((DataFile::Statement("block"), i->block->get_id()));
371 st.push_back((DataFile::Statement("route"), route->get_name()));
374 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
378 current_speed = speed;
379 speed_changing = false;
383 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
385 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
390 functions |= 1<<func;
392 functions &= ~(1<<func);
394 signal_function_changed.emit(func, state);
398 void Train::sensor_event(unsigned addr, bool state)
402 // Find the first sensor block from our reserved blocks that isn't this sensor
403 list<BlockRef>::iterator i;
404 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
405 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
408 if(i!=rsv_blocks.begin())
410 // Compute speed and update related state
411 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
415 RealSpeed &rs = real_speed[current_speed];
416 rs.add(travel_dist/travel_time_secs, travel_time_secs);
417 set_status(format("Traveling %d kmh", get_travel_speed()));
422 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
424 j->block->traverse(j->entry, &block_len);
425 travel_dist += block_len;
427 if(j->block->get_sensor_id()==addr)
429 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
432 Track *track = bep.track->get_link(bep.track_ep);
433 unsigned ep = track->get_endpoint_by_link(*bep.track);
434 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
437 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
440 last_entry_time = Time::now();
443 // Check if we've reached the next route
446 const set<const Track *> &rtracks = next_route->get_tracks();
447 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
448 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
453 signal_route_changed.emit(route);
458 // Move blocks up to the next sensor to our current blocks
459 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
461 // Try to get more blocks if we're moving
464 unsigned nsens = reserve_more();
465 if(!nsens && end_of_route)
466 signal_arrived.emit();
472 // Find the first sensor in our current blocks that's still active
473 list<BlockRef>::iterator end = cur_blocks.begin();
474 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
475 if(i->block->get_sensor_id())
477 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
483 if(end!=cur_blocks.begin())
485 // Free blocks up to the last inactive sensor
487 release_blocks(cur_blocks, cur_blocks.begin(), end);
492 void Train::turnout_event(unsigned addr, bool)
496 unsigned pending_addr = pending_block->get_turnout_id();
497 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
498 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
503 void Train::block_reserved(const Block &block, const Train *train)
505 if(&block==pending_block && !train)
509 unsigned Train::reserve_more()
512 if(!rsv_blocks.empty())
513 last = &rsv_blocks.back();
514 else if(!cur_blocks.empty())
515 last = &cur_blocks.back();
521 // See how many sensor blocks we already have
523 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
524 if(i->block->get_sensor_id())
530 const Route *cur_route = 0;
533 const set<Track *> &tracks = last->block->get_tracks();
534 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
536 if(route->get_tracks().count(*i))
538 else if(next_route && next_route->get_tracks().count(*i))
539 cur_route = next_route;
543 bool got_more = false;
544 BlockRef *good = last;
545 unsigned good_sens = nsens;
548 // Traverse to the next block
549 unsigned exit = last->block->traverse(last->entry);
550 Block *link = last->block->get_link(exit);
554 int entry = link->get_endpoint_by_link(*last->block);
556 throw LogicError("Block links are inconsistent!");
558 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
562 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
563 cur_route = next_route;
564 else if(!cur_route->get_tracks().count(entry_ep.track))
566 // Keep the blocks if we arrived at the end of the route
573 else if(route && route->get_tracks().count(entry_ep.track))
576 if(!link->reserve(this))
578 // If we found another train and it's not headed straight for us, we can keep the blocks we got
579 int other_entry = link->get_train()->get_entry_to_block(*link);
581 throw LogicError("Block reservation inconsistency");
582 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
587 pending_block = link;
591 if(link->get_turnout_id())
593 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
595 // Keep the blocks reserved so far, as either us or the other train can diverge
599 // Figure out what path we'd like to take on the turnout
602 path = cur_route->get_turnout(link->get_turnout_id());
604 path = entry_ep.track->get_active_path();
605 if(!((track_ep.paths>>path)&1))
607 for(unsigned i=0; track_ep.paths>>i; ++i)
608 if((track_ep.paths>>i)&1)
612 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
614 // The turnout is set to wrong path - switch and wait for it
616 pending_block = link;
617 entry_ep.track->set_active_path(path);
622 rsv_blocks.push_back(BlockRef(link, entry));
623 last = &rsv_blocks.back();
624 if(last->block->get_sensor_id())
631 // Unreserve blocks that were not good
632 while(!rsv_blocks.empty() && last!=good)
634 last->block->reserve(0);
635 rsv_blocks.erase(--rsv_blocks.end());
636 if(!rsv_blocks.empty())
637 last = &rsv_blocks.back();
643 float Train::get_real_speed(unsigned i) const
645 if(real_speed[i].weight)
646 return real_speed[i].speed;
650 for(low=i; low>0; --low)
651 if(real_speed[low].weight)
653 for(high=i; high<14; ++high)
654 if(real_speed[high].weight)
657 if(real_speed[high].weight)
659 if(real_speed[low].weight)
661 float f = float(i-low)/(high-low);
662 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
665 return real_speed[high].speed*float(i)/high;
667 else if(real_speed[low].weight)
668 return real_speed[low].speed*float(i)/low;
673 unsigned Train::find_speed(float real) const
675 if(real<=real_speed[0].speed)
680 for(unsigned i=0; (!high && i<=14); ++i)
681 if(real_speed[i].weight)
683 if(real_speed[i].speed<real)
692 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
695 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
696 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
699 float Train::get_travel_speed() const
701 float speed = get_real_speed(current_speed);
702 float scale = layout.get_catalogue().get_scale();
703 return static_cast<int>(round(speed/scale*3.6/5))*5;
706 void Train::set_status(const string &s)
709 signal_status_changed.emit(s);
712 void Train::release_blocks(list<BlockRef> &blocks)
714 release_blocks(blocks, blocks.begin(), blocks.end());
717 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
721 Block *block = begin->block;
722 blocks.erase(begin++);
727 void Train::reverse_blocks(list<BlockRef> &blocks) const
730 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
731 i->entry = i->block->traverse(i->entry);
735 Train::BlockRef::BlockRef(Block *b, unsigned e):
740 Train::BlockRef Train::BlockRef::next() const
742 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
744 throw InvalidState("At end of line");
746 int ep = blk->get_endpoint_by_link(*block);
748 throw LogicError("Block links are inconsistent");
750 return BlockRef(blk, ep);
754 Train::RealSpeed::RealSpeed():
759 void Train::RealSpeed::add(float s, float w)
761 speed = (speed*weight+s*w)/(weight+w);
762 weight = min(weight+w, 300.0f);
766 Train::Loader::Loader(Train &t):
767 DataFile::BasicLoader<Train>(t),
770 add("block", &Loader::block);
771 add("block_hint", &Loader::block_hint);
772 add("name", &Loader::name);
773 add("real_speed", &Loader::real_speed);
774 add("route", &Loader::route);
777 void Train::Loader::block(unsigned id)
779 Block &blk = obj.layout.get_block(id);
782 entry = blk.get_endpoint_by_link(*prev_block);
787 obj.cur_blocks.push_back(BlockRef(&blk, entry));
788 obj.set_status("Stopped");
789 const Block::Endpoint &bep = blk.get_endpoints()[entry];
790 obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
792 if(blk.get_sensor_id())
793 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
798 void Train::Loader::block_hint(unsigned id)
800 prev_block = &obj.layout.get_block(id);
803 void Train::Loader::name(const string &n)
808 void Train::Loader::real_speed(unsigned i, float speed, float weight)
810 obj.real_speed[i].speed = speed;
811 obj.real_speed[i].weight = weight;
814 void Train::Loader::route(const string &n)
816 obj.set_route(&obj.layout.get_route(n));
819 } // namespace Marklin