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