]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/train.cpp
Fix vacated distance calculation when moving backwards
[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.back()->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();
439                 if(reverse)
440                         dist = veh.get_track()->get_type().get_path_length(veh.get_track()->get_active_path())-dist;
441                 dist -= veh.get_type().get_length()/2;
442                 while(1)
443                 {
444                         if(track==veh.get_track())
445                         {
446                                 found = true;
447                                 break;
448                         }
449
450                         if(i!=cur_blocks.begin())
451                         {
452                                 float path_len = track->get_type().get_path_length(track->get_active_path());
453                                 dist += path_len;
454                         }
455
456                         unsigned exit = track->traverse(entry);
457                         Track *next = track->get_link(exit);
458                         entry = next->get_endpoint_by_link(*track);
459                         track = next;
460
461                         if(!i->block->get_tracks().count(track))
462                         {
463                                 ++i;
464                                 if(i==cur_blocks.end())
465                                         break;
466                         }
467                 }
468
469                 if(found && i!=cur_blocks.begin() && dist>10*layout.get_catalogue().get_scale())
470                 {
471                         cur_blocks.front().block->reserve(0);
472                         cur_blocks.erase(cur_blocks.begin());
473                 }
474         }
475 }
476
477 void Train::save(list<DataFile::Statement> &st) const
478 {
479         st.push_back((DataFile::Statement("name"), name));
480
481         st.push_back((DataFile::Statement("priority"), priority));
482
483         for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
484                 if(i!=vehicles.begin())
485                         st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
486
487         for(unsigned i=0; i<=14; ++i)
488                 if(real_speed[i].weight)
489                         st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
490
491         if(!cur_blocks.empty())
492         {
493                 list<BlockRef> blocks = cur_blocks;
494                 if(reverse)
495                         reverse_blocks(blocks);
496
497                 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
498                 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
499
500                 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
501                         st.push_back((DataFile::Statement("block"), i->block->get_id()));
502         }
503
504         if(route)
505         {
506                 if(!route->is_temporary())
507                         st.push_back((DataFile::Statement("route"), route->get_name()));
508                 else if(next_route && !next_route->is_temporary())
509                         st.push_back((DataFile::Statement("route"), next_route->get_name()));
510         }
511
512         if(timetable)
513         {
514                 DataFile::Statement ss("timetable");
515                 timetable->save(ss.sub);
516                 st.push_back(ss);
517         }
518 }
519
520 void Train::control_changed(const Controller::Control &ctrl)
521 {
522         signal_control_changed.emit(ctrl.name, ctrl.value);
523 }
524
525 void Train::loco_speed_event(unsigned addr, unsigned speed, bool)
526 {
527         if(addr==address)
528         {
529                 current_speed = speed;
530                 speed_changing = false;
531                 pure_speed = false;
532         }
533 }
534
535 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
536 {
537         if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
538         {
539                 if(addr==address+1)
540                         func += 4;
541                 if(state)
542                         functions |= 1<<func;
543                 else
544                         functions &= ~(1<<func);
545
546                 signal_function_changed.emit(func, state);
547         }
548 }
549
550 void Train::sensor_event(unsigned addr, bool state)
551 {
552         if(state)
553         {
554                 // Find the first sensor block from our reserved blocks that isn't this sensor
555                 list<BlockRef>::iterator i;
556                 unsigned result = 0;
557                 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
558                         if(i->block->get_sensor_id())
559                         {
560                                 if(i->block->get_sensor_id()!=addr)
561                                 {
562                                         if(result==0)
563                                                 result = 2;
564                                         else if(result==1)
565                                                 break;
566                                 }
567                                 else if(result==0)
568                                         result = 1;
569                                 else if(result==2)
570                                         result = 3;
571                         }
572
573                 if(result==1 && i!=rsv_blocks.begin())
574                 {
575                         // Compute speed and update related state
576                         float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
577
578                         if(pure_speed)
579                         {
580                                 if(current_speed)
581                                 {
582                                         RealSpeed &rs = real_speed[current_speed];
583                                         rs.add(travel_dist/travel_time_secs, travel_time_secs);
584                                 }
585                                 set_status(format("Traveling %d kmh", get_travel_speed()));
586                         }
587
588                         travel_dist = 0;
589                         float block_len;
590                         for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
591                         {
592                                 j->block->traverse(j->entry, &block_len);
593                                 travel_dist += block_len;
594
595                                 if(j->block->get_sensor_id()==addr)
596                                 {
597                                         const Block::Endpoint &bep = j->block->get_endpoints()[j->entry];
598                                         if(reverse)
599                                         {
600                                                 Track *track = bep.track->get_link(bep.track_ep);
601                                                 unsigned ep = track->get_endpoint_by_link(*bep.track);
602                                                 vehicles.back()->place(track, ep, 0, Vehicle::BACK_AXLE);
603                                         }
604                                         else
605                                                 vehicles.front()->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
606                                 }
607                         }
608                         last_entry_time = Time::now();
609                         pure_speed = true;
610                         accurate_position = true;
611                         overshoot_dist = 0;
612
613                         // Check if we've reached the next route
614                         if(next_route)
615                         {
616                                 const set<const Track *> &rtracks = next_route->get_tracks();
617                                 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
618                                         if(rtracks.count(j->block->get_endpoints()[j->entry].track))
619                                         {
620                                                 route = next_route;
621                                                 next_route = 0;
622                                                 // XXX Exceptions?
623                                                 signal_route_changed.emit(route);
624                                                 break;
625                                         }
626                         }
627
628                         // Move blocks up to the next sensor to our current blocks
629                         cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
630
631                         // Try to get more blocks if we're moving
632                         if(active)
633                                 reserve_more();
634                 }
635                 else if(result==3)
636                         layout.emergency("Sensor for "+name+" triggered out of order");
637         }
638         else
639         {
640                 // Find the first sensor in our current blocks that's still active
641                 list<BlockRef>::iterator end = cur_blocks.begin();
642                 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
643                         if(i->block->get_sensor_id())
644                         {
645                                 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
646                                         break;
647                                 else
648                                 {
649                                         end = i;
650                                         ++end;
651                                 }
652                         }
653                 
654                 if(end!=cur_blocks.begin())
655                         // Free blocks up to the last inactive sensor
656                         release_blocks(cur_blocks, cur_blocks.begin(), end);
657         }
658 }
659
660 void Train::turnout_event(unsigned addr, bool)
661 {
662         if(pending_block)
663         {
664                 unsigned pending_addr = pending_block->get_turnout_id();
665                 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
666                 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
667                         reserve_more();
668         }
669 }
670
671 void Train::halt_event(bool h)
672 {
673         if(h)
674                 accurate_position = false;
675 }
676
677 void Train::block_reserved(const Block &block, const Train *train)
678 {
679         if(&block==pending_block && !train)
680                 reserve_more();
681 }
682
683 unsigned Train::reserve_more()
684 {
685         if(!active)
686                 return 0;
687
688         BlockRef *last = 0;
689         if(!rsv_blocks.empty())
690                 last = &rsv_blocks.back();
691         else if(!cur_blocks.empty())
692                 last = &cur_blocks.back();
693         if(!last)
694                 return 0;
695
696         pending_block = 0;
697
698         // See how many sensor blocks we already have
699         unsigned nsens = 0;
700         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
701                 if(i->block->get_sensor_id())
702                         ++nsens;
703         
704         if(end_of_route)
705                 return nsens;
706
707         const Route *cur_route = 0;
708         if(route)
709         {
710                 const set<Track *> &tracks = last->block->get_tracks();
711                 for(set<Track *>::const_iterator i=tracks.begin(); (cur_route!=route && i!=tracks.end()); ++i)
712                 {
713                         if(route->get_tracks().count(*i))
714                                 cur_route = route;
715                         else if(next_route && next_route->get_tracks().count(*i))
716                                 cur_route = next_route;
717                 }
718         }
719
720         bool got_more = false;
721         BlockRef *good = last;
722         unsigned good_sens = nsens;
723         while(good_sens<3)
724         {
725                 // Traverse to the next block
726                 unsigned exit = last->block->traverse(last->entry);
727                 Block *link = last->block->get_link(exit);
728                 if(!link)
729                         break;
730
731                 int entry = link->get_endpoint_by_link(*last->block);
732                 if(entry<0)
733                         throw LogicError("Block links are inconsistent!");
734
735                 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
736
737                 if(cur_route)
738                 {
739                         if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
740                                 cur_route = next_route;
741                         else if(!cur_route->get_tracks().count(entry_ep.track))
742                         {
743                                 // Keep the blocks if we arrived at the end of the route
744                                 good = last;
745                                 good_sens = nsens;
746                                 end_of_route = true;
747                                 break;
748                         }
749                 }
750                 else if(route && route->get_tracks().count(entry_ep.track))
751                         cur_route = route;
752
753                 if(link->get_endpoints().size()<2)
754                 {
755                         good = last;
756                         good_sens = nsens;
757                         break;
758                 }
759
760                 bool reserved = link->reserve(this);
761                 if(!reserved)
762                 {
763                         // Ask a lesser priority train to free the block for us
764                         if(link->get_train()->get_priority()<priority)
765                                 if(link->get_train()->free_block(*link))
766                                         reserved = link->reserve(this);
767
768                         if(!reserved)
769                         {
770                                 // If we found another train and it's not headed straight for us, we can keep the blocks we got
771                                 int other_entry = link->get_train()->get_entry_to_block(*link);
772                                 if(other_entry<0)
773                                         throw LogicError("Block reservation inconsistency");
774                                 if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
775                                 {
776                                         good = last;
777                                         good_sens = nsens;
778                                 }
779                                 pending_block = link;
780                                 break;
781                         }
782                 }
783
784                 if(link->get_turnout_id())
785                 {
786                         const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
787
788                         // Keep the blocks reserved so far, as either us or the other train can diverge
789                         good = last;
790                         good_sens = nsens;
791
792                         // Figure out what path we'd like to take on the turnout
793                         int path = -1;
794                         if(cur_route)
795                                 path = cur_route->get_turnout(link->get_turnout_id());
796                         if(path<0)
797                                 path = entry_ep.track->get_active_path();
798                         if(!((track_ep.paths>>path)&1))
799                         {
800                                 for(unsigned i=0; track_ep.paths>>i; ++i)
801                                         if((track_ep.paths>>i)&1)
802                                                 path = i;
803                         }
804
805                         if(path!=static_cast<int>(entry_ep.track->get_active_path()))
806                         {
807                                 // The turnout is set to wrong path - switch and wait for it
808                                 link->reserve(0);
809                                 pending_block = link;
810                                 entry_ep.track->set_active_path(path);
811                                 break;
812                         }
813                 }
814
815                 rsv_blocks.push_back(BlockRef(link, entry));
816                 last = &rsv_blocks.back();
817                 if(last->block->get_sensor_id())
818                 {
819                         ++nsens;
820                         got_more = true;
821                 }
822         }
823
824         // Unreserve blocks that were not good
825         while(!rsv_blocks.empty() && last!=good)
826         {
827                 last->block->reserve(0);
828                 rsv_blocks.erase(--rsv_blocks.end());
829                 if(!rsv_blocks.empty())
830                         last = &rsv_blocks.back();
831         }
832
833         // Make any sensorless blocks at the beginning immediately current
834         list<BlockRef>::iterator i;
835         for(i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !i->block->get_sensor_id()); ++i) ;
836         if(i!=rsv_blocks.begin())
837                 cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
838
839         return good_sens;
840 }
841
842 float Train::get_real_speed(unsigned i) const
843 {
844         if(real_speed[i].weight)
845                 return real_speed[i].speed;
846
847         unsigned low;
848         unsigned high;
849         for(low=i; low>0; --low)
850                 if(real_speed[low].weight)
851                         break;
852         for(high=i; high<14; ++high)
853                 if(real_speed[high].weight)
854                         break;
855
856         if(real_speed[high].weight)
857         {
858                 if(real_speed[low].weight)
859                 {
860                         float f = float(i-low)/(high-low);
861                         return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
862                 }
863                 else
864                         return real_speed[high].speed*float(i)/high;
865         }
866         else if(real_speed[low].weight)
867                 return real_speed[low].speed*float(i)/low;
868         else
869                 return 0;
870 }
871
872 unsigned Train::find_speed(float real) const
873 {
874         if(real<=real_speed[0].speed)
875                 return 0;
876
877         unsigned low = 0;
878         unsigned high = 0;
879         for(unsigned i=0; (!high && i<=14); ++i)
880                 if(real_speed[i].weight)
881                 {
882                         if(real_speed[i].speed<real)
883                                 low = i;
884                         else
885                                 high = i;
886                 }
887         if(!high)
888         {
889                 if(!low)
890                 {
891                         if(real)
892                                 return 3;
893                         else
894                                 return 0;
895                 }
896                 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
897         }
898
899         float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
900         return static_cast<unsigned>(low*(1-f)+high*f+0.5);
901 }
902
903 float Train::get_travel_speed() const
904 {
905         float speed = get_real_speed(current_speed);
906         float scale = layout.get_catalogue().get_scale();
907         return static_cast<int>(round(speed/scale*3.6/5))*5;
908 }
909
910 void Train::set_status(const string &s)
911 {
912         status = s;
913         signal_status_changed.emit(s);
914 }
915
916 void Train::release_blocks(list<BlockRef> &blocks)
917 {
918         release_blocks(blocks, blocks.begin(), blocks.end());
919 }
920
921 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
922 {
923         while(begin!=end)
924         {
925                 Block *block = begin->block;
926                 blocks.erase(begin++);
927                 block->reserve(0);
928         }
929 }
930
931 void Train::reverse_blocks(list<BlockRef> &blocks) const
932 {
933         blocks.reverse();
934         for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
935                 i->entry = i->block->traverse(i->entry);
936 }
937
938
939 Train::BlockRef::BlockRef(Block *b, unsigned e):
940         block(b),
941         entry(e)
942 { }
943
944 Train::BlockRef Train::BlockRef::next() const
945 {
946         Block *blk = block->get_endpoints()[block->traverse(entry)].link;
947         if(!blk)
948                 throw InvalidState("At end of line");
949
950         int ep = blk->get_endpoint_by_link(*block);
951         if(ep<0)
952                 throw LogicError("Block links are inconsistent");
953
954         return BlockRef(blk, ep);
955 }
956
957
958 Train::RealSpeed::RealSpeed():
959         speed(0),
960         weight(0)
961 { }
962
963 void Train::RealSpeed::add(float s, float w)
964 {
965         speed = (speed*weight+s*w)/(weight+w);
966         weight = min(weight+w, 300.0f);
967 }
968
969
970 Train::Loader::Loader(Train &t):
971         DataFile::BasicLoader<Train>(t),
972         prev_block(0),
973         blocks_valid(true)
974 {
975         add("block",       &Loader::block);
976         add("block_hint",  &Loader::block_hint);
977         add("name",        &Loader::name);
978         add("priority",    &Train::priority);
979         add("real_speed",  &Loader::real_speed);
980         add("route",       &Loader::route);
981         add("timetable",   &Loader::timetable);
982         add("vehicle",     &Loader::vehicle);
983 }
984
985 void Train::Loader::finish()
986 {
987         if(!obj.cur_blocks.empty())
988         {
989                 const BlockRef &blkref = obj.cur_blocks.front();
990                 const Block::Endpoint &bep = blkref.block->get_endpoints()[blkref.entry];
991                 obj.vehicles.back()->place(bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
992
993                 obj.set_status("Stopped");
994         }
995 }
996
997 void Train::Loader::block(unsigned id)
998 {
999         if(!blocks_valid)
1000                 return;
1001
1002         Block *blk;
1003         try
1004         {
1005                 blk = &obj.layout.get_block(id);
1006         }
1007         catch(const KeyError &)
1008         {
1009                 blocks_valid = false;
1010                 return;
1011         }
1012
1013         int entry = -1;
1014         if(prev_block)
1015                 entry = blk->get_endpoint_by_link(*prev_block);
1016         if(entry<0)
1017                 entry = 0;
1018
1019         blk->reserve(&obj);
1020         obj.cur_blocks.push_back(BlockRef(blk, entry));
1021
1022         if(blk->get_sensor_id())
1023                 obj.layout.get_driver().set_sensor(blk->get_sensor_id(), true);
1024
1025         prev_block = blk;
1026 }
1027
1028 void Train::Loader::block_hint(unsigned id)
1029 {
1030         try
1031         {
1032                 prev_block = &obj.layout.get_block(id);
1033         }
1034         catch(const KeyError &)
1035         {
1036                 blocks_valid = false;
1037         }
1038 }
1039
1040 void Train::Loader::name(const string &n)
1041 {
1042         obj.set_name(n);
1043 }
1044
1045 void Train::Loader::real_speed(unsigned i, float speed, float weight)
1046 {
1047         obj.real_speed[i].speed = speed;
1048         obj.real_speed[i].weight = weight;
1049 }
1050
1051 void Train::Loader::route(const string &n)
1052 {
1053         obj.set_route(&obj.layout.get_route(n));
1054 }
1055
1056 void Train::Loader::timetable()
1057 {
1058         if(obj.timetable)
1059                 throw InvalidState("A timetable has already been loaded");
1060
1061         obj.timetable = new Timetable(obj);
1062         load_sub(*obj.timetable);
1063 }
1064
1065 void Train::Loader::vehicle(unsigned n)
1066 {
1067         const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(n);
1068         Vehicle *veh = new Vehicle(obj.layout, vtype);
1069         obj.vehicles.back()->attach_back(*veh);
1070         obj.vehicles.push_back(veh);
1071 }
1072
1073 } // namespace Marklin