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>
16 #include "tracktype.h"
25 Train::Train(Layout &l, const LocoType &t, unsigned a):
43 vehicles.push_back(new Vehicle(layout, loco_type));
45 layout.add_train(*this);
47 layout.get_driver().add_loco(address);
48 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
49 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
51 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
52 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
53 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
58 for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
60 layout.remove_train(*this);
63 void Train::set_name(const string &n)
67 signal_name_changed.emit(name);
70 Vehicle &Train::get_vehicle(unsigned i)
72 if(i>=vehicles.size())
73 throw InvalidParameterValue("Vehicle index out of range");
77 const Vehicle &Train::get_vehicle(unsigned i) const
79 if(i>=vehicles.size())
80 throw InvalidParameterValue("Vehicle index out of range");
84 void Train::set_speed(unsigned speed)
86 if(speed==target_speed)
88 travel_speed = static_cast<int>(round(get_real_speed(speed)*87*3.6/5))*5;
94 stop_timeout = Time::now()+(800+current_speed*150)*Time::msec;
99 signal_target_speed_changed.emit(target_speed);
105 void Train::set_reverse(bool rev)
115 else if(stop_timeout)
118 layout.get_driver().set_loco_reverse(address, rev);
120 release_blocks(rsv_blocks);
121 reverse_blocks(cur_blocks);
124 void Train::set_function(unsigned func, bool state)
126 if(!loco_type.get_functions().count(func))
127 throw InvalidParameterValue("Invalid function");
129 layout.get_driver().set_loco_function(address, func, state);
131 layout.get_driver().set_loco_function(address+1, func-4, state);
134 bool Train::get_function(unsigned func) const
136 return (functions>>func)&1;
139 void Train::set_route(const Route *r)
141 if(!rsv_blocks.empty())
143 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
144 if(i->block->get_sensor_id())
146 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
153 end_of_route = false;
157 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
158 BlockRef next = last.next();
159 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
160 if(!route->get_tracks().count(ep.track))
163 route = Route::find(*ep.track, ep.track_ep, *next_route);
167 if(target_speed && reserve_more()<2)
170 signal_route_changed.emit(route);
173 void Train::go_to(const Track &to)
175 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
176 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
184 if(rsv_blocks.empty())
185 last = &cur_blocks.back();
188 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
189 if(i->block->get_sensor_id())
193 BlockRef next = last->next();
194 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
196 set_route(Route::find(*ep.track, ep.track_ep, to));
199 void Train::place(Block &block, unsigned entry)
204 release_blocks(rsv_blocks);
205 release_blocks(cur_blocks);
207 if(!block.reserve(this))
209 set_status("Unplaced");
213 cur_blocks.push_back(BlockRef(&block, entry));
216 unsigned exit = block.traverse(entry);
217 const Block::Endpoint &bep = block.get_endpoints()[exit];
218 Track *track = bep.track->get_link(bep.track_ep);
219 unsigned ep = track->get_endpoint_by_link(*bep.track);
220 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
224 const Block::Endpoint &bep = block.get_endpoints()[entry];
225 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
228 set_status("Stopped");
231 bool Train::free_block(Block &block)
234 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
240 release_blocks(rsv_blocks, i, rsv_blocks.end());
244 else if(i->block->get_sensor_id())
251 int Train::get_entry_to_block(Block &block) const
253 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
256 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
262 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
264 if(stop_timeout && t>=stop_timeout)
266 release_blocks(rsv_blocks);
267 end_of_route = false;
268 stop_timeout = Time::TimeStamp();
273 Track *track = vehicles[0]->get_track();
276 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
277 ok = i->block->get_tracks().count(track);
281 float d = get_real_speed(current_speed)*(dt/Time::sec);
282 vehicles[0]->advance(reverse ? -d : d);
287 void Train::save(list<DataFile::Statement> &st) const
289 st.push_back((DataFile::Statement("name"), name));
290 for(unsigned i=0; i<=14; ++i)
291 if(real_speed[i].weight)
292 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
294 if(!cur_blocks.empty())
296 list<BlockRef> blocks = cur_blocks;
298 reverse_blocks(blocks);
300 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
301 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
303 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
304 st.push_back((DataFile::Statement("block"), i->block->get_id()));
308 st.push_back((DataFile::Statement("route"), route->get_name()));
311 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
315 current_speed = speed;
318 signal_speed_changed.emit(current_speed);
319 signal_reverse_changed.emit(reverse);
323 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
325 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
330 functions |= 1<<func;
332 functions &= ~(1<<func);
334 signal_function_changed.emit(func, state);
338 void Train::sensor_event(unsigned addr, bool state)
342 // Find the first sensor block from our reserved blocks that isn't this sensor
343 list<BlockRef>::iterator i;
344 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
345 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
348 if(i!=rsv_blocks.begin())
350 // Compute speed and update related state
351 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
352 travel_speed = static_cast<int>(round(travel_dist/travel_time_secs*87*3.6/5))*5;
356 RealSpeed &rs = real_speed[current_speed];
357 rs.add(travel_dist/travel_time_secs, travel_time_secs);
362 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
364 j->block->traverse(j->entry, &block_len);
365 travel_dist += block_len;
367 if(j->block->get_sensor_id()==addr)
369 const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
372 Track *track = bep.track->get_link(bep.track_ep);
373 unsigned ep = track->get_endpoint_by_link(*bep.track);
374 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
377 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
380 last_entry_time = Time::now();
383 // Check if we've reached the next route
386 const set<const Track *> &rtracks = next_route->get_tracks();
387 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
388 if(rtracks.count(j->block->get_endpoints()[j->entry].track))
393 signal_route_changed.emit(route);
398 // Move blocks up to the next sensor to our current blocks
399 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
401 // Try to get more blocks if we're moving
404 unsigned nsens = reserve_more();
405 if(!nsens && end_of_route)
417 // Find the first sensor in our current blocks that's still active
418 list<BlockRef>::iterator end = cur_blocks.begin();
419 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
420 if(i->block->get_sensor_id())
422 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
428 if(end!=cur_blocks.begin())
430 // Free blocks up to the last inactive sensor
432 release_blocks(cur_blocks, cur_blocks.begin(), end);
437 void Train::turnout_event(unsigned addr, bool)
441 unsigned pending_addr = pending_block->get_turnout_id();
442 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
443 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
448 void Train::block_reserved(const Block &block, const Train *train)
450 if(&block==pending_block && !train)
454 unsigned Train::reserve_more()
457 if(!rsv_blocks.empty())
458 last = &rsv_blocks.back();
459 else if(!cur_blocks.empty())
460 last = &cur_blocks.back();
466 // See how many sensor blocks we already have
468 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
469 if(i->block->get_sensor_id())
472 const Route *cur_route = 0;
475 unsigned exit = last->block->traverse(last->entry);
476 Track *track = last->block->get_endpoints()[exit].track;
477 if(route->get_tracks().count(track))
479 else if(next_route && next_route->get_tracks().count(track))
480 cur_route = next_route;
483 bool got_more = false;
484 BlockRef *good = last;
485 unsigned good_sens = nsens;
488 // Traverse to the next block
489 unsigned exit = last->block->traverse(last->entry);
490 Block *link = last->block->get_link(exit);
494 int entry = link->get_endpoint_by_link(*last->block);
496 throw LogicError("Block links are inconsistent!");
498 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
502 if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
503 cur_route = next_route;
504 else if(!cur_route->get_tracks().count(entry_ep.track))
506 // Keep the blocks if we arrived at the end of the route
513 else if(route && route->get_tracks().count(entry_ep.track))
516 if(!link->reserve(this))
518 // If we found another train and it's not headed straight for us, we can keep the blocks we got
519 int other_entry = link->get_train()->get_entry_to_block(*link);
521 throw LogicError("Block reservation inconsistency");
522 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
527 pending_block = link;
531 if(link->get_turnout_id())
533 const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
535 // Keep the blocks reserved so far, as either us or the other train can diverge
539 // Figure out what path we'd like to take on the turnout
542 path = cur_route->get_turnout(link->get_turnout_id());
544 path = entry_ep.track->get_active_path();
545 if(!((track_ep.paths>>path)&1))
547 for(unsigned i=0; track_ep.paths>>i; ++i)
548 if((track_ep.paths>>i)&1)
552 if(path!=static_cast<int>(entry_ep.track->get_active_path()))
554 // The turnout is set to wrong path - switch and wait for it
556 pending_block = link;
557 entry_ep.track->set_active_path(path);
562 rsv_blocks.push_back(BlockRef(link, entry));
563 last = &rsv_blocks.back();
564 if(last->block->get_sensor_id())
571 // Unreserve blocks that were not good
572 while(!rsv_blocks.empty() && last!=good)
574 last->block->reserve(0);
575 rsv_blocks.erase(--rsv_blocks.end());
576 if(!rsv_blocks.empty())
577 last = &rsv_blocks.back();
586 void Train::update_speed()
588 Driver &driver = layout.get_driver();
594 set_status("Stopped");
599 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
600 if(i->block->get_sensor_id())
603 unsigned slow_speed = find_speed(0.1); // 31.3 km/h
608 set_status("Blocked");
610 else if(nsens==1 && target_speed>slow_speed)
618 speed = target_speed;
619 set_status(format("Traveling %d kmh", travel_speed));
623 driver.set_loco_speed(address, speed);
626 float Train::get_real_speed(unsigned i) const
628 if(real_speed[i].weight)
629 return real_speed[i].speed;
633 for(low=i; low>0; --low)
634 if(real_speed[low].weight)
636 for(high=i; high<14; ++high)
637 if(real_speed[high].weight)
640 if(real_speed[high].weight)
642 if(real_speed[low].weight)
644 float f = float(i-low)/(high-low);
645 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
648 return real_speed[high].speed*float(i)/high;
650 else if(real_speed[low].weight)
651 return real_speed[low].speed*float(i)/low;
656 unsigned Train::find_speed(float real) const
658 if(real<=real_speed[0].speed)
663 for(unsigned i=0; (!high && i<=14); ++i)
664 if(real_speed[i].weight)
666 if(real_speed[i].speed<real)
675 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
678 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
679 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
682 void Train::set_status(const string &s)
685 signal_status_changed.emit(s);
688 void Train::release_blocks(list<BlockRef> &blocks)
690 release_blocks(blocks, blocks.begin(), blocks.end());
693 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
697 Block *block = begin->block;
698 blocks.erase(begin++);
703 void Train::reverse_blocks(list<BlockRef> &blocks) const
706 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
707 i->entry = i->block->traverse(i->entry);
711 Train::BlockRef::BlockRef(Block *b, unsigned e):
716 Train::BlockRef Train::BlockRef::next() const
718 Block *blk = block->get_endpoints()[block->traverse(entry)].link;
720 throw InvalidState("At end of line");
722 int ep = blk->get_endpoint_by_link(*block);
724 throw LogicError("Block links are inconsistent");
726 return BlockRef(blk, ep);
730 Train::RealSpeed::RealSpeed():
735 void Train::RealSpeed::add(float s, float w)
737 speed = (speed*weight+s*w)/(weight+w);
738 weight = min(weight+w, 300.0f);
742 Train::Loader::Loader(Train &t):
743 DataFile::BasicLoader<Train>(t),
746 add("block", &Loader::block);
747 add("block_hint", &Loader::block_hint);
748 add("name", &Loader::name);
749 add("real_speed", &Loader::real_speed);
750 add("route", &Loader::route);
753 void Train::Loader::block(unsigned id)
755 Block &blk = obj.layout.get_block(id);
758 entry = blk.get_endpoint_by_link(*prev_block);
763 obj.cur_blocks.push_back(BlockRef(&blk, entry));
764 obj.set_status("Stopped");
765 const Block::Endpoint &bep = blk.get_endpoints()[entry];
766 obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
768 if(blk.get_sensor_id())
769 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
774 void Train::Loader::block_hint(unsigned id)
776 prev_block = &obj.layout.get_block(id);
779 void Train::Loader::name(const string &n)
784 void Train::Loader::real_speed(unsigned i, float speed, float weight)
786 obj.real_speed[i].speed = speed;
787 obj.real_speed[i].weight = weight;
790 void Train::Loader::route(const string &n)
792 obj.set_route(&obj.layout.get_route(n));
795 } // namespace Marklin