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"
24 Train::Train(Layout &l, const LocoType &t, unsigned a):
42 layout.add_train(*this);
44 layout.get_driver().add_loco(address);
45 layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
46 layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
48 layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
49 layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
50 layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
55 layout.remove_train(*this);
58 void Train::set_name(const string &n)
62 signal_name_changed.emit(name);
65 void Train::set_speed(unsigned speed)
67 if(speed==target_speed)
69 travel_speed = static_cast<int>(round(get_real_speed(speed)*87*3.6/5))*5;
75 stop_timeout = Time::now()+(800+current_speed*150)*Time::msec;
80 signal_target_speed_changed.emit(target_speed);
86 void Train::set_reverse(bool rev)
99 layout.get_driver().set_loco_reverse(address, rev);
101 release_blocks(rsv_blocks);
102 reverse_blocks(cur_blocks);
106 unsigned path = cur_track->get_active_path();
107 cur_track_ep = cur_track->traverse(cur_track_ep, path);
108 offset = cur_track->get_type().get_path_length(path)-offset;
112 void Train::set_function(unsigned func, bool state)
114 if(!loco_type.get_functions().count(func))
115 throw InvalidParameterValue("Invalid function");
117 layout.get_driver().set_loco_function(address, func, state);
119 layout.get_driver().set_loco_function(address+1, func-4, state);
122 bool Train::get_function(unsigned func) const
124 return (functions>>func)&1;
127 void Train::set_route(const Route *r)
129 if(!rsv_blocks.empty())
131 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
132 if(i->block->get_sensor_id())
134 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
140 end_of_route = false;
142 if(target_speed && reserve_more()<2)
145 signal_route_changed.emit(route);
148 void Train::go_to(const Track &to)
151 if(rsv_blocks.empty())
152 last = &cur_blocks.back();
155 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
156 if(i->block->get_sensor_id())
160 Block *next = last->block->get_endpoints()[last->block->traverse(last->entry)].link;
162 throw InvalidState("At end of line");
164 int entry = next->get_endpoint_by_link(*last->block);
166 throw LogicError("Block links are inconsistent");
168 const Block::Endpoint &ep = next->get_endpoints()[entry];
170 set_route(Route::find(*ep.track, ep.track_ep, to));
173 void Train::place(Block &block, unsigned entry)
178 release_blocks(rsv_blocks);
179 release_blocks(cur_blocks);
181 if(!block.reserve(this))
183 set_status("Unplaced");
187 cur_blocks.push_back(BlockRef(&block, entry));
188 set_position(block.get_endpoints()[entry]);
190 set_status("Stopped");
193 bool Train::free_block(Block &block)
196 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
202 release_blocks(rsv_blocks, i, rsv_blocks.end());
206 else if(i->block->get_sensor_id())
213 int Train::get_entry_to_block(Block &block) const
215 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
218 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
224 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
226 if(stop_timeout && t>=stop_timeout)
228 release_blocks(rsv_blocks);
229 end_of_route = false;
230 stop_timeout = Time::TimeStamp();
235 unsigned path = cur_track->get_active_path();
237 offset += get_real_speed(current_speed)*(dt/Time::sec);
238 float path_len = cur_track->get_type().get_path_length(path);
241 unsigned out = cur_track->traverse(cur_track_ep, path);
242 Track *next = cur_track->get_link(out);
245 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
246 ok = i->block->get_tracks().count(next);
251 cur_track_ep = next->get_endpoint_by_link(*cur_track);
256 offset = path_len-0.001;
260 pos = cur_track->get_point(cur_track_ep, path, offset).pos;
264 void Train::save(list<DataFile::Statement> &st) const
266 st.push_back((DataFile::Statement("name"), name));
267 for(unsigned i=0; i<=14; ++i)
268 if(real_speed[i].weight)
269 st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
271 st.push_back((DataFile::Statement("route"), route->get_name()));
273 if(!cur_blocks.empty())
275 list<BlockRef> blocks = cur_blocks;
277 reverse_blocks(blocks);
279 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
280 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
282 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
283 st.push_back((DataFile::Statement("block"), i->block->get_id()));
287 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
291 current_speed = speed;
294 signal_speed_changed.emit(current_speed);
295 signal_reverse_changed.emit(reverse);
299 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
301 if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
306 functions |= 1<<func;
308 functions &= ~(1<<func);
310 signal_function_changed.emit(func, state);
314 void Train::sensor_event(unsigned addr, bool state)
318 // Find the first sensor block from our reserved blocks that isn't this sensor
319 list<BlockRef>::iterator i;
320 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
321 if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
324 if(i!=rsv_blocks.begin())
326 // Compute speed and update related state
327 float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
328 travel_speed = static_cast<int>(round(travel_dist/travel_time_secs*87*3.6/5))*5;
332 RealSpeed &rs = real_speed[current_speed];
333 rs.add(travel_dist/travel_time_secs, travel_time_secs);
338 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
340 j->block->traverse(j->entry, &block_len);
341 travel_dist += block_len;
343 if(j->block->get_sensor_id()==addr)
344 set_position(j->block->get_endpoints()[j->entry]);
346 last_entry_time = Time::now();
349 // Move blocks up to the next sensor to our current blocks
350 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
352 // Try to get more blocks if we're moving
355 unsigned nsens = reserve_more();
356 if(!nsens && end_of_route)
368 // Find the first sensor in our current blocks that's still active
369 list<BlockRef>::iterator end = cur_blocks.begin();
370 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
371 if(i->block->get_sensor_id())
373 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
379 if(end!=cur_blocks.begin())
381 // Free blocks up to the last inactive sensor
383 release_blocks(cur_blocks, cur_blocks.begin(), end);
388 void Train::turnout_event(unsigned addr, bool)
392 unsigned pending_addr = pending_block->get_turnout_id();
393 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
394 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
399 void Train::block_reserved(const Block &block, const Train *train)
401 if(&block==pending_block && !train)
405 unsigned Train::reserve_more()
408 if(!rsv_blocks.empty())
409 last = &rsv_blocks.back();
410 else if(!cur_blocks.empty())
411 last = &cur_blocks.back();
417 // See how many sensor blocks we already have
419 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
420 if(i->block->get_sensor_id())
423 bool on_route = (route && route->get_tracks().count(last->block->get_endpoints()[last->entry].track));
424 bool got_more = false;
425 BlockRef *good = last;
426 unsigned good_sens = nsens;
429 // Traverse to the next block
430 unsigned exit = last->block->traverse(last->entry);
431 Block *link = last->block->get_link(exit);
435 int entry = link->get_endpoint_by_link(*last->block);
437 throw LogicError("Block links are inconsistent!");
439 if(on_route && !route->get_tracks().count(link->get_endpoints()[entry].track))
441 // Keep the blocks if we arrived at the end of the route
448 if(!link->reserve(this))
450 // If we found another train and it's not headed straight for us, we can keep the blocks we got
451 int other_entry = link->get_train()->get_entry_to_block(*link);
453 throw LogicError("Block reservation inconsistency");
454 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
459 pending_block = link;
463 if(link->get_turnout_id())
465 const Block::Endpoint &ep = link->get_endpoints()[entry];
466 const Endpoint &track_ep = ep.track->get_type().get_endpoints()[ep.track_ep];
468 // Keep the blocks reserved so far, as either us or the other train can diverge
472 // Figure out what path we'd like to take on the turnout
475 path = route->get_turnout(link->get_turnout_id());
477 path = ep.track->get_active_path();
478 if(!((track_ep.paths>>path)&1))
480 for(unsigned i=0; track_ep.paths>>i; ++i)
481 if((track_ep.paths>>i)&1)
485 if(path!=static_cast<int>(ep.track->get_active_path()))
487 // The turnout is set to wrong path - switch and wait for it
489 pending_block = link;
490 ep.track->set_active_path(path);
495 rsv_blocks.push_back(BlockRef(link, entry));
496 last = &rsv_blocks.back();
497 if(last->block->get_sensor_id())
503 if(route && !on_route)
504 on_route = route->get_tracks().count(link->get_endpoints()[entry].track);
507 // Unreserve blocks that were not good
508 while(!rsv_blocks.empty() && last!=good)
510 last->block->reserve(0);
511 rsv_blocks.erase(--rsv_blocks.end());
512 if(!rsv_blocks.empty())
513 last = &rsv_blocks.back();
522 void Train::update_speed()
524 Driver &driver = layout.get_driver();
530 set_status("Stopped");
535 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
536 if(i->block->get_sensor_id())
539 unsigned slow_speed = find_speed(0.1); // 31.3 km/h
544 set_status("Blocked");
546 else if(nsens==1 && target_speed>slow_speed)
554 speed = target_speed;
555 set_status(format("Traveling %d kmh", travel_speed));
559 driver.set_loco_speed(address, speed);
562 float Train::get_real_speed(unsigned i) const
564 if(real_speed[i].weight)
565 return real_speed[i].speed;
569 for(low=i; low>0; --low)
570 if(real_speed[low].weight)
572 for(high=i; high<14; ++high)
573 if(real_speed[high].weight)
576 if(real_speed[high].weight)
578 if(real_speed[low].weight)
580 float f = float(i-low)/(high-low);
581 return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
584 return real_speed[high].speed*float(i)/high;
586 else if(real_speed[low].weight)
587 return real_speed[low].speed*float(i)/low;
592 unsigned Train::find_speed(float real) const
594 if(real<=real_speed[0].speed)
599 for(unsigned i=0; (!high && i<=14); ++i)
600 if(real_speed[i].weight)
602 if(real_speed[i].speed<real)
611 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
614 float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
615 return static_cast<unsigned>(low*(1-f)+high*f+0.5);
618 void Train::set_status(const string &s)
621 signal_status_changed.emit(s);
624 void Train::set_position(const Block::Endpoint &bep)
626 cur_track = bep.track;
627 cur_track_ep = bep.track_ep;
629 pos = cur_track->get_endpoint_position(cur_track_ep);
632 void Train::release_blocks(list<BlockRef> &blocks)
634 release_blocks(blocks, blocks.begin(), blocks.end());
637 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
641 Block *block = begin->block;
642 blocks.erase(begin++);
647 void Train::reverse_blocks(list<BlockRef> &blocks) const
650 for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
651 i->entry = i->block->traverse(i->entry);
655 Train::RealSpeed::RealSpeed():
660 void Train::RealSpeed::add(float s, float w)
662 speed = (speed*weight+s*w)/(weight+w);
663 weight = min(weight+w, 300.0f);
667 Train::Loader::Loader(Train &t):
668 DataFile::BasicLoader<Train>(t),
671 add("block", &Loader::block);
672 add("block_hint", &Loader::block_hint);
673 add("name", &Loader::name);
674 add("real_speed", &Loader::real_speed);
675 add("route", &Loader::route);
678 void Train::Loader::block(unsigned id)
680 Block &blk = obj.layout.get_block(id);
683 entry = blk.get_endpoint_by_link(*prev_block);
688 obj.cur_blocks.push_back(BlockRef(&blk, entry));
689 obj.set_status("Stopped");
690 obj.set_position(blk.get_endpoints()[entry]);
695 void Train::Loader::block_hint(unsigned id)
697 prev_block = &obj.layout.get_block(id);
700 void Train::Loader::name(const string &n)
705 void Train::Loader::real_speed(unsigned i, float speed, float weight)
707 obj.real_speed[i].speed = speed;
708 obj.real_speed[i].weight = weight;
711 void Train::Loader::route(const string &n)
713 obj.set_route(&obj.layout.get_route(n));
716 } // namespace Marklin