]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/train.cpp
Implement train priority system
[r2c2.git] / source / libmarklin / train.cpp
1 /* $Id$
2
3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2010  Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
6 */
7
8 #include <cmath>
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"
14 #include "driver.h"
15 #include "layout.h"
16 #include "locotype.h"
17 #include "route.h"
18 #include "simplephysics.h"
19 #include "timetable.h"
20 #include "tracktype.h"
21 #include "train.h"
22 #include "vehicle.h"
23
24 using namespace std;
25 using namespace Msp;
26
27 namespace Marklin {
28
29 Train::Train(Layout &l, const LocoType &t, unsigned a):
30         layout(l),
31         loco_type(t),
32         address(a),
33         priority(0),
34         pending_block(0),
35         control(new AIControl(*this, new SimplePhysics)),
36         timetable(0),
37         active(false),
38         current_speed(0),
39         speed_changing(false),
40         reverse(false),
41         functions(0),
42         route(0),
43         next_route(0),
44         end_of_route(false),
45         status("Unplaced"),
46         travel_dist(0),
47         pure_speed(false),
48         real_speed(15),
49         accurate_position(false),
50         overshoot_dist(false)
51 {
52         vehicles.push_back(new Vehicle(layout, loco_type));
53
54         layout.add_train(*this);
55
56         layout.get_driver().add_loco(address);
57         layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
58         layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
59
60         layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
61         layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
62         layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
63
64         layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
65
66         control->signal_control_changed.connect(signal_control_changed);
67 }
68
69 Train::~Train()
70 {
71         delete control;
72         delete timetable;
73         for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
74                 delete *i;
75         layout.remove_train(*this);
76 }
77
78 void Train::set_name(const string &n)
79 {
80         name = n;
81
82         signal_name_changed.emit(name);
83 }
84
85 void Train::set_priority(int p)
86 {
87         priority = p;
88 }
89
90 Vehicle &Train::get_vehicle(unsigned i)
91 {
92         if(i>=vehicles.size())
93                 throw InvalidParameterValue("Vehicle index out of range");
94         return *vehicles[i];
95 }
96
97 const Vehicle &Train::get_vehicle(unsigned i) const
98 {
99         if(i>=vehicles.size())
100                 throw InvalidParameterValue("Vehicle index out of range");
101         return *vehicles[i];
102 }
103
104 void Train::set_control(const string &n, float v)
105 {
106         control->set_control(n, v);
107 }
108
109 void Train::set_active(bool a)
110 {
111         if(a==active)
112                 return;
113         if(!a && control->get_speed())
114                 throw InvalidState("Can't deactivate while moving");
115
116         active = a;
117         if(active)
118         {
119                 stop_timeout = Time::TimeStamp();
120                 reserve_more();
121         }
122         else
123         {
124                 stop_timeout = Time::now()+2*Time::sec;
125                 set_status("Stopped");
126         }
127 }
128
129 void Train::set_function(unsigned func, bool state)
130 {
131         if(!loco_type.get_functions().count(func))
132                 throw InvalidParameterValue("Invalid function");
133         if(func<5)
134                 layout.get_driver().set_loco_function(address, func, state);
135         else
136                 layout.get_driver().set_loco_function(address+1, func-4, state);
137 }
138
139 bool Train::get_function(unsigned func) const
140 {
141         return (functions>>func)&1;
142 }
143
144 void Train::set_route(const Route *r)
145 {
146         if(!rsv_blocks.empty())
147         {
148                 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
149                         if(i->block->get_sensor_id())
150                         {
151                                 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
152                                 break;
153                         }
154         }
155
156         route = r;
157         next_route = 0;
158         end_of_route = false;
159
160         if(route)
161         {
162                 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
163                 BlockRef next = last.next();
164                 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
165                 if(!route->get_tracks().count(ep.track))
166                 {
167                         next_route = route;
168                         route = Route::find(*ep.track, ep.track_ep, *next_route);
169                 }
170         }
171
172         if(active)
173                 reserve_more();
174
175         signal_route_changed.emit(route);
176 }
177
178 void Train::go_to(const Track &to)
179 {
180         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
181                 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
182                 {
183                         signal_arrived.emit();
184                         set_route(0);
185                         return;
186                 }
187
188         BlockRef *last = 0;
189         if(rsv_blocks.empty())
190                 last = &cur_blocks.back();
191         else
192         {
193                 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
194                         if(i->block->get_sensor_id())
195                                 last = &*i;
196         }
197
198         BlockRef next = last->next();
199         const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
200
201         set_route(Route::find(*ep.track, ep.track_ep, to));
202 }
203
204 void Train::place(Block &block, unsigned entry)
205 {
206         if(control->get_speed())
207                 throw InvalidState("Must be stopped before placing");
208
209         release_blocks(rsv_blocks);
210         release_blocks(cur_blocks);
211
212         set_active(false);
213         accurate_position = false;
214
215         if(!block.reserve(this))
216         {
217                 set_status("Unplaced");
218                 return;
219         }
220
221         cur_blocks.push_back(BlockRef(&block, entry));
222         if(reverse)
223         {
224                 unsigned exit = block.traverse(entry);
225                 const Block::Endpoint &bep = block.get_endpoints()[exit];
226                 Track *track = bep.track->get_link(bep.track_ep);
227                 unsigned ep = track->get_endpoint_by_link(*bep.track);
228                 vehicles.front()->place(track, ep, 0, Vehicle::FRONT_BUFFER);
229         }
230         else
231         {
232                 const Block::Endpoint &bep = block.get_endpoints()[entry];
233                 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
234         }
235 }
236
237 bool Train::free_block(Block &block)
238 {
239         unsigned nsens = 0;
240         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
241         {
242                 if(i->block==&block)
243                 {
244                         if(nsens<1)
245                                 return false;
246                         release_blocks(rsv_blocks, i, rsv_blocks.end());
247                         return true;
248                 }
249                 else if(i->block->get_sensor_id())
250                         ++nsens;
251         }
252
253         return false;
254 }
255
256 int Train::get_entry_to_block(Block &block) const
257 {
258         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
259                 if(i->block==&block)
260                         return i->entry;
261         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
262                 if(i->block==&block)
263                         return i->entry;
264         return -1;
265 }
266
267 float Train::get_reserved_distance() const
268 {
269         Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
270         const VehicleType &vtype = veh.get_type();
271
272         Track *track = veh.get_track();
273         if(!track)
274                 return 0;
275         unsigned entry = veh.get_entry();
276
277         float result = -vtype.get_length()/2;
278         if(reverse)
279         {
280                 entry = track->traverse(entry);
281                 result += veh.get_offset();
282         }
283         else
284                 result -= veh.get_offset();
285
286         bool first = true;
287         list<BlockRef>::const_iterator block = cur_blocks.begin();
288         while(1)
289         {
290                 if(!first || !reverse)
291                         result += track->get_type().get_path_length(track->get_active_path());
292                 first = false;
293
294                 if(track->get_type().get_endpoints().size()<2)
295                         return result;
296
297                 unsigned exit = track->traverse(entry);
298                 Track *next = track->get_link(exit);
299
300                 while(!block->block->get_tracks().count(next))
301                 {
302                         ++block;
303                         if(block==cur_blocks.end())
304                                 block = rsv_blocks.begin();
305                         if(block==rsv_blocks.end())
306                                 return result;
307                 }
308
309                 entry = next->get_endpoint_by_link(*track);
310                 track = next;
311         }
312 }
313
314 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
315 {
316         if(!active && stop_timeout && t>=stop_timeout)
317         {
318                 release_blocks(rsv_blocks);
319                 end_of_route = false;
320                 stop_timeout = Time::TimeStamp();
321         }
322
323         Driver &driver = layout.get_driver();
324
325         if(timetable)
326                 timetable->tick(t);
327         control->tick(dt);
328         float speed = control->get_speed();
329         unsigned speed_notch = find_speed(abs(speed));
330
331         if(control->get_reverse()!=reverse)
332         {
333                 reverse = control->get_reverse();
334                 driver.set_loco_reverse(address, reverse);
335
336                 release_blocks(rsv_blocks);
337                 reverse_blocks(cur_blocks);
338
339                 reserve_more();
340         }
341         if(speed_notch!=current_speed && !speed_changing && !driver.is_halted() && driver.get_power())
342         {
343                 speed_changing = true;
344                 driver.set_loco_speed(address, speed_notch);
345
346                 pure_speed = false;
347
348                 if(speed_notch)
349                         set_status(format("Traveling %d kmh", get_travel_speed()));
350                 else
351                         set_status("Waiting");
352         }
353
354         if(speed)
355         {
356                 if(!active)
357                         set_active(true);
358
359                 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
360                 Track *track = vehicle.get_track();
361
362                 bool ok = false;
363                 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
364                         ok = i->block->get_tracks().count(track);
365
366                 float d = get_real_speed(current_speed)*(dt/Time::sec);
367                 if(ok)
368                         vehicle.advance(reverse ? -d : d);
369                 else if(accurate_position)
370                 {
371                         overshoot_dist += d;
372                         if(overshoot_dist>40*layout.get_catalogue().get_scale())
373                         {
374                                 layout.emergency(name+" has not arrived at sensor");
375                                 accurate_position = false;
376                         }
377                 }
378         }
379         else if(end_of_route)
380                 set_route(0);
381
382         if(!cur_blocks.empty() && !cur_blocks.front().block->get_sensor_id())
383         {
384                 Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
385
386                 list<BlockRef>::iterator i = cur_blocks.begin();
387                 const Block::Endpoint &bep = i->block->get_endpoints()[i->entry];
388
389                 Track *track = bep.track;
390                 unsigned entry = bep.track_ep;
391
392                 bool found = false;
393                 float dist = veh.get_offset()-veh.get_type().get_length()/2;
394                 while(1)
395                 {
396                         if(track==veh.get_track())
397                         {
398                                 found = true;
399                                 break;
400                         }
401
402                         if(i!=cur_blocks.begin())
403                         {
404                                 float path_len = track->get_type().get_path_length(track->get_active_path());
405                                 dist += path_len;
406                         }
407
408                         unsigned exit = track->traverse(entry);
409                         Track *next = track->get_link(exit);
410                         entry = next->get_endpoint_by_link(*track);
411                         track = next;
412
413                         if(!i->block->get_tracks().count(track))
414                         {
415                                 ++i;
416                                 if(i==cur_blocks.end())
417                                         break;
418                         }
419                 }
420
421                 if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
422                 {
423                         cur_blocks.front().block->reserve(0);
424                         cur_blocks.erase(cur_blocks.begin());
425                 }
426         }
427 }
428
429 void Train::save(list<DataFile::Statement> &st) const
430 {
431         st.push_back((DataFile::Statement("name"), name));
432
433         st.push_back((DataFile::Statement("priority"), priority));
434
435         for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
436                 if(i!=vehicles.begin())
437                         st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
438
439         for(unsigned i=0; i<=14; ++i)
440                 if(real_speed[i].weight)
441                         st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
442
443         if(!cur_blocks.empty())
444         {
445                 list<BlockRef> blocks = cur_blocks;
446                 if(reverse)
447                         reverse_blocks(blocks);
448
449                 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
450                 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
451
452                 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
453                         st.push_back((DataFile::Statement("block"), i->block->get_id()));
454         }
455
456         if(route)
457         {
458                 if(!route->is_temporary())
459                         st.push_back((DataFile::Statement("route"), route->get_name()));
460                 else if(next_route && !next_route->is_temporary())
461                         st.push_back((DataFile::Statement("route"), next_route->get_name()));
462         }
463
464         if(timetable)
465         {
466                 DataFile::Statement ss("timetable");
467                 timetable->save(ss.sub);
468                 st.push_back(ss);
469         }
470 }
471
472 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
473 {
474         if(addr==address)
475         {
476                 current_speed = speed;
477                 speed_changing = false;
478                 pure_speed = false;
479         }
480 }
481
482 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
483 {
484         if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
485         {
486                 if(addr==address+1)
487                         func += 4;
488                 if(state)
489                         functions |= 1<<func;
490                 else
491                         functions &= ~(1<<func);
492
493                 signal_function_changed.emit(func, state);
494         }
495 }
496
497 void Train::sensor_event(unsigned addr, bool state)
498 {
499         if(state)
500         {
501                 // Find the first sensor block from our reserved blocks that isn't this sensor
502                 list<BlockRef>::iterator i;
503                 unsigned result = 0;
504                 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
505                         if(i->block->get_sensor_id())
506                         {
507                                 if(i->block->get_sensor_id()!=addr)
508                                 {
509                                         if(result==0)
510                                                 result = 2;
511                                         else if(result==1)
512                                                 break;
513                                 }
514                                 else if(result==0)
515                                         result = 1;
516                                 else if(result==2)
517                                         result = 3;
518                         }
519
520                 if(result==1 && i!=rsv_blocks.begin())
521                 {
522                         // Compute speed and update related state
523                         float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
524
525                         if(pure_speed)
526                         {
527                                 RealSpeed &rs = real_speed[current_speed];
528                                 rs.add(travel_dist/travel_time_secs, travel_time_secs);
529                                 set_status(format("Traveling %d kmh", get_travel_speed()));
530                         }
531
532                         travel_dist = 0;
533                         float block_len;
534                         for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
535                         {
536                                 j->block->traverse(j->entry, &block_len);
537                                 travel_dist += block_len;
538
539                                 if(j->block->get_sensor_id()==addr)
540                                 {
541                                         const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
542                                         if(reverse)
543                                         {
544                                                 Track *track = bep.track->get_link(bep.track_ep);
545                                                 unsigned ep = track->get_endpoint_by_link(*bep.track);
546                                                 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
547                                         }
548                                         else
549                                                 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
550                                 }
551                         }
552                         last_entry_time = Time::now();
553                         pure_speed = true;
554                         accurate_position = true;
555                         overshoot_dist = 0;
556
557                         // Check if we've reached the next route
558                         if(next_route)
559                         {
560                                 const set<const Track *> &rtracks = next_route->get_tracks();
561                                 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
562                                         if(rtracks.count(j->block->get_endpoints()[j->entry].track))
563                                         {
564                                                 route = next_route;
565                                                 next_route = 0;
566                                                 // XXX Exceptions?
567                                                 signal_route_changed.emit(route);
568                                                 break;
569                                         }
570                         }
571
572                         // Move blocks up to the next sensor to our current blocks
573                         cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
574
575                         // Try to get more blocks if we're moving
576                         if(active)
577                         {
578                                 unsigned nsens = reserve_more();
579                                 if(!nsens && end_of_route)
580                                         signal_arrived.emit();
581                         }
582                 }
583                 else if(result==3)
584                         layout.emergency("Sensor for "+name+" triggered out of order");
585         }
586         else
587         {
588                 // Find the first sensor in our current blocks that's still active
589                 list<BlockRef>::iterator end = cur_blocks.begin();
590                 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
591                         if(i->block->get_sensor_id())
592                         {
593                                 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
594                                         break;
595                                 else
596                                 {
597                                         end = i;
598                                         ++end;
599                                 }
600                         }
601                 
602                 if(end!=cur_blocks.begin())
603                         // Free blocks up to the last inactive sensor
604                         release_blocks(cur_blocks, cur_blocks.begin(), end);
605         }
606 }
607
608 void Train::turnout_event(unsigned addr, bool)
609 {
610         if(pending_block)
611         {
612                 unsigned pending_addr = pending_block->get_turnout_id();
613                 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
614                 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
615                         reserve_more();
616         }
617 }
618
619 void Train::halt_event(bool h)
620 {
621         if(h)
622                 accurate_position = false;
623 }
624
625 void Train::block_reserved(const Block &block, const Train *train)
626 {
627         if(&block==pending_block && !train)
628                 reserve_more();
629 }
630
631 unsigned Train::reserve_more()
632 {
633         BlockRef *last = 0;
634         if(!rsv_blocks.empty())
635                 last = &rsv_blocks.back();
636         else if(!cur_blocks.empty())
637                 last = &cur_blocks.back();
638         if(!last)
639                 return 0;
640
641         pending_block = 0;
642
643         // See how many sensor blocks we already have
644         unsigned nsens = 0;
645         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
646                 if(i->block->get_sensor_id())
647                         ++nsens;
648         
649         if(end_of_route)
650                 return nsens;
651
652         const Route *cur_route = 0;
653         if(route)
654         {
655                 const set<Track *> &tracks = last->block->get_tracks();
656                 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
657                 {
658                         if(route->get_tracks().count(*i))
659                                 cur_route = route;
660                         else if(next_route && next_route->get_tracks().count(*i))
661                                 cur_route = next_route;
662                 }
663         }
664
665         bool got_more = false;
666         BlockRef *good = last;
667         unsigned good_sens = nsens;
668         while(good_sens<3)
669         {
670                 if(last->block->get_endpoints().size()<2)
671                 {
672                         good = last;
673                         good_sens = nsens;
674                         break;
675                 }
676
677                 // Traverse to the next block
678                 unsigned exit = last->block->traverse(last->entry);
679                 Block *link = last->block->get_link(exit);
680                 if(!link)
681                         break;
682
683                 int entry = link->get_endpoint_by_link(*last->block);
684                 if(entry<0)
685                         throw LogicError("Block links are inconsistent!");
686
687                 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
688
689                 if(cur_route)
690                 {
691                         if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
692                                 cur_route = next_route;
693                         else if(!cur_route->get_tracks().count(entry_ep.track))
694                         {
695                                 // Keep the blocks if we arrived at the end of the route
696                                 good = last;
697                                 good_sens = nsens;
698                                 end_of_route = true;
699                                 break;
700                         }
701                 }
702                 else if(route && route->get_tracks().count(entry_ep.track))
703                         cur_route = route;
704
705                 bool reserved = link->reserve(this);
706                 if(!reserved)
707                 {
708                         // Ask a lesser priority train to free the block for us
709                         if(link->get_train()->get_priority()<priority)
710                                 if(link->get_train()->free_block(*link))
711                                         reserved = link->reserve(this);
712
713                         if(!reserved)
714                         {
715                                 // If we found another train and it's not headed straight for us, we can keep the blocks we got
716                                 int other_entry = link->get_train()->get_entry_to_block(*link);
717                                 if(other_entry<0)
718                                         throw LogicError("Block reservation inconsistency");
719                                 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
720                                 {
721                                         good = last;
722                                         good_sens = nsens;
723                                 }
724                                 pending_block = link;
725                                 break;
726                         }
727                 }
728
729                 if(link->get_turnout_id())
730                 {
731                         const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
732
733                         // Keep the blocks reserved so far, as either us or the other train can diverge
734                         good = last;
735                         good_sens = nsens;
736
737                         // Figure out what path we'd like to take on the turnout
738                         int path = -1;
739                         if(cur_route)
740                                 path = cur_route->get_turnout(link->get_turnout_id());
741                         if(path<0)
742                                 path = entry_ep.track->get_active_path();
743                         if(!((track_ep.paths>>path)&1))
744                         {
745                                 for(unsigned i=0; track_ep.paths>>i; ++i)
746                                         if((track_ep.paths>>i)&1)
747                                                 path = i;
748                         }
749
750                         if(path!=static_cast<int>(entry_ep.track->get_active_path()))
751                         {
752                                 // The turnout is set to wrong path - switch and wait for it
753                                 link->reserve(0);
754                                 pending_block = link;
755                                 entry_ep.track->set_active_path(path);
756                                 break;
757                         }
758                 }
759
760                 rsv_blocks.push_back(BlockRef(link, entry));
761                 last = &rsv_blocks.back();
762                 if(last->block->get_sensor_id())
763                 {
764                         ++nsens;
765                         got_more = true;
766                 }
767         }
768
769         // Unreserve blocks that were not good
770         while(!rsv_blocks.empty() && last!=good)
771         {
772                 last->block->reserve(0);
773                 rsv_blocks.erase(--rsv_blocks.end());
774                 if(!rsv_blocks.empty())
775                         last = &rsv_blocks.back();
776         }
777
778         // Make any sensorless blocks at the beginning immediately current
779         list<BlockRef>::iterator i;
780         for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
781         if(i!=rsv_blocks.begin())
782                 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
783
784         return good_sens;
785 }
786
787 float Train::get_real_speed(unsigned i) const
788 {
789         if(real_speed[i].weight)
790                 return real_speed[i].speed;
791
792         unsigned low;
793         unsigned high;
794         for(low=i; low>0; --low)
795                 if(real_speed[low].weight)
796                         break;
797         for(high=i; high<14; ++high)
798                 if(real_speed[high].weight)
799                         break;
800
801         if(real_speed[high].weight)
802         {
803                 if(real_speed[low].weight)
804                 {
805                         float f = float(i-low)/(high-low);
806                         return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
807                 }
808                 else
809                         return real_speed[high].speed*float(i)/high;
810         }
811         else if(real_speed[low].weight)
812                 return real_speed[low].speed*float(i)/low;
813         else
814                 return 0;
815 }
816
817 unsigned Train::find_speed(float real) const
818 {
819         if(real<=real_speed[0].speed)
820                 return 0;
821
822         unsigned low = 0;
823         unsigned high = 0;
824         for(unsigned i=0; (!high && i<=14); ++i)
825                 if(real_speed[i].weight)
826                 {
827                         if(real_speed[i].speed<real)
828                                 low = i;
829                         else
830                                 high = i;
831                 }
832         if(!high)
833         {
834                 if(!low)
835                         return 0;
836                 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
837         }
838
839         float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
840         return static_cast<unsigned>(low*(1-f)+high*f+0.5);
841 }
842
843 float Train::get_travel_speed() const
844 {
845         float speed = get_real_speed(current_speed);
846         float scale = layout.get_catalogue().get_scale();
847         return static_cast<int>(round(speed/scale*3.6/5))*5;
848 }
849
850 void Train::set_status(const string &s)
851 {
852         status = s;
853         signal_status_changed.emit(s);
854 }
855
856 void Train::release_blocks(list<BlockRef> &blocks)
857 {
858         release_blocks(blocks, blocks.begin(), blocks.end());
859 }
860
861 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
862 {
863         while(begin!=end)
864         {
865                 Block *block = begin->block;
866                 blocks.erase(begin++);
867                 block->reserve(0);
868         }
869 }
870
871 void Train::reverse_blocks(list<BlockRef> &blocks) const
872 {
873         blocks.reverse();
874         for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
875                 i->entry = i->block->traverse(i->entry);
876 }
877
878
879 Train::BlockRef::BlockRef(Block *b, unsigned e):
880         block(b),
881         entry(e)
882 { }
883
884 Train::BlockRef Train::BlockRef::next() const
885 {
886         Block *blk = block->get_endpoints()[block->traverse(entry)].link;
887         if(!blk)
888                 throw InvalidState("At end of line");
889
890         int ep = blk->get_endpoint_by_link(*block);
891         if(ep<0)
892                 throw LogicError("Block links are inconsistent");
893
894         return BlockRef(blk, ep);
895 }
896
897
898 Train::RealSpeed::RealSpeed():
899         speed(0),
900         weight(0)
901 { }
902
903 void Train::RealSpeed::add(float s, float w)
904 {
905         speed = (speed*weight+s*w)/(weight+w);
906         weight = min(weight+w, 300.0f);
907 }
908
909
910 Train::Loader::Loader(Train &t):
911         DataFile::BasicLoader<Train>(t),
912         prev_block(0)
913 {
914         add("block",       &Loader::block);
915         add("block_hint",  &Loader::block_hint);
916         add("name",        &Loader::name);
917         add("priority",    &Train::priority);
918         add("real_speed",  &Loader::real_speed);
919         add("route",       &Loader::route);
920         add("timetable",   &Loader::timetable);
921         add("vehicle",     &Loader::vehicle);
922 }
923
924 void Train::Loader::block(unsigned id)
925 {
926         Block &blk = obj.layout.get_block(id);
927         int entry = -1;
928         if(prev_block)
929                 entry = blk.get_endpoint_by_link(*prev_block);
930         if(entry<0)
931                 entry = 0;
932
933         blk.reserve(&obj);
934         obj.cur_blocks.push_back(BlockRef(&blk, entry));
935         obj.set_status("Stopped");
936         const Block::Endpoint &bep = blk.get_endpoints()[entry];
937         obj.vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
938
939         if(blk.get_sensor_id())
940                 obj.layout.get_driver().set_sensor(blk.get_sensor_id(), true);
941
942         prev_block = &blk;
943 }
944
945 void Train::Loader::block_hint(unsigned id)
946 {
947         prev_block = &obj.layout.get_block(id);
948 }
949
950 void Train::Loader::name(const string &n)
951 {
952         obj.set_name(n);
953 }
954
955 void Train::Loader::real_speed(unsigned i, float speed, float weight)
956 {
957         obj.real_speed[i].speed = speed;
958         obj.real_speed[i].weight = weight;
959 }
960
961 void Train::Loader::route(const string &n)
962 {
963         obj.set_route(&obj.layout.get_route(n));
964 }
965
966 void Train::Loader::timetable()
967 {
968         if(obj.timetable)
969                 throw InvalidState("A timetable has already been loaded");
970
971         obj.timetable = new Timetable(obj);
972         load_sub(*obj.timetable);
973 }
974
975 void Train::Loader::vehicle(unsigned n)
976 {
977         const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
978         Vehicle *veh = new Vehicle(obj.layout, vtype);
979         obj.vehicles.back()->attach_back(*veh);
980         obj.vehicles.push_back(veh);
981 }
982
983 } // namespace Marklin