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