]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/train.cpp
New routing system for trains
[r2c2.git] / source / libr2c2 / train.cpp
1 #include <algorithm>
2 #include <cmath>
3 #include <msp/core/maputils.h>
4 #include <msp/strings/format.h>
5 #include <msp/time/units.h>
6 #include <msp/time/utils.h>
7 #include "aicontrol.h"
8 #include "catalogue.h"
9 #include "driver.h"
10 #include "layout.h"
11 #include "route.h"
12 #include "simplecontroller.h"
13 #include "speedquantizer.h"
14 #include "timetable.h"
15 #include "trackiter.h"
16 #include "tracktype.h"
17 #include "train.h"
18 #include "trainrouter.h"
19 #include "vehicle.h"
20 #include "vehicletype.h"
21 #include "zone.h"
22
23 using namespace std;
24 using namespace Msp;
25
26 namespace {
27
28 struct SetFlag
29 {
30         bool &flag;
31
32         SetFlag(bool &f): flag(f) { flag = true; }
33         ~SetFlag() { flag = false; }
34 };
35
36 }
37
38
39 namespace R2C2 {
40
41 Train::Train(Layout &l, const VehicleType &t, unsigned a, const string &p):
42         layout(l),
43         loco_type(t),
44         address(a),
45         protocol(p),
46         preceding_train(0),
47         cur_blocks_end(blocks.end()),
48         pending_block(0),
49         reserving(false),
50         advancing(false),
51         controller(new SimpleController),
52         active(false),
53         current_speed_step(0),
54         speed_changing(false),
55         reverse(false),
56         functions(0),
57         travel_dist(0),
58         pure_speed(false),
59         speed_quantizer(0),
60         accurate_position(false),
61         overshoot_dist(false)
62 {
63         if(!loco_type.is_locomotive())
64                 throw invalid_argument("Train::Train");
65
66         unsigned speed_steps = layout.get_driver().get_protocol_speed_steps(protocol);
67         if(speed_steps)
68                 speed_quantizer = new SpeedQuantizer(speed_steps);
69
70         vehicles.push_back(new Vehicle(layout, loco_type));
71
72         layout.add_train(*this);
73
74         layout.get_driver().add_loco(address, protocol, loco_type);
75         layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
76         layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
77
78         layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
79         layout.signal_block_state_changed.connect(sigc::mem_fun(this, &Train::block_state_changed));
80
81         layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &Train::halt_event));
82
83         const set<Track *> &tracks = layout.get_tracks();
84         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
85                 if((*i)->get_turnout_id())
86                         (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &Train::turnout_path_changed), sigc::ref(**i))));
87
88         controller->signal_control_changed.connect(sigc::mem_fun(this, &Train::control_changed));
89 }
90
91 Train::~Train()
92 {
93         delete controller;
94         for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
95                 delete *i;
96         layout.remove_train(*this);
97 }
98
99 void Train::set_name(const string &n)
100 {
101         name = n;
102
103         signal_name_changed.emit(name);
104 }
105
106 void Train::add_vehicle(const VehicleType &vt)
107 {
108         Vehicle *veh = new Vehicle(layout, vt);
109         vehicles.back()->attach_back(*veh);
110         vehicles.push_back(veh);
111 }
112
113 void Train::remove_vehicle(unsigned i)
114 {
115         if(i>=vehicles.size())
116                 throw out_of_range("Train::remove_vehicle");
117         if(i==0)
118                 throw logic_error("can't remove locomotive");
119         delete vehicles[i];
120         vehicles.erase(vehicles.begin()+i);
121         if(i<vehicles.size())
122                 vehicles[i-1]->attach_back(*vehicles[i]);
123 }
124
125 unsigned Train::get_n_vehicles() const
126 {
127         return vehicles.size();
128 }
129
130 Vehicle &Train::get_vehicle(unsigned i)
131 {
132         if(i>=vehicles.size())
133                 throw out_of_range("Train::get_vehicle");
134         return *vehicles[i];
135 }
136
137 const Vehicle &Train::get_vehicle(unsigned i) const
138 {
139         if(i>=vehicles.size())
140                 throw out_of_range("Train::get_vehicle");
141         return *vehicles[i];
142 }
143
144 void Train::set_control(const string &n, float v)
145 {
146         controller->set_control(n, v);
147 }
148
149 void Train::set_active(bool a)
150 {
151         if(a==active)
152                 return;
153         if(!a && controller->get_speed())
154                 throw logic_error("moving");
155
156         active = a;
157         if(active)
158         {
159                 stop_timeout = Time::TimeStamp();
160                 reserve_more();
161         }
162         else
163                 stop_timeout = Time::now()+2*Time::sec;
164 }
165
166 void Train::set_function(unsigned func, bool state)
167 {
168         if(!loco_type.get_functions().count(func))
169                 throw invalid_argument("Train::set_function");
170         layout.get_driver().set_loco_function(address, func, state);
171 }
172
173 float Train::get_control(const string &ctrl) const
174 {
175         return controller->get_control(ctrl).value;
176 }
177
178 float Train::get_speed() const
179 {
180         return controller->get_speed();
181 }
182
183 float Train::get_quantized_speed() const
184 {
185         if(speed_quantizer)
186                 return speed_quantizer->quantize_speed(controller->get_speed());
187         else
188                 return controller->get_speed();
189 }
190
191 bool Train::get_function(unsigned func) const
192 {
193         return (functions>>func)&1;
194 }
195
196 void Train::add_ai(TrainAI &ai)
197 {
198         ais.push_back(&ai);
199         ai.signal_event.connect(sigc::bind<0>(signal_ai_event, sigc::ref(ai)));
200 }
201
202 void Train::remove_ai(TrainAI &ai)
203 {
204         list<TrainAI *>::iterator i = find(ais.begin(), ais.end(), &ai);
205         if(i!=ais.end())
206                 ais.erase(i);
207 }
208
209 void Train::ai_message(const TrainAI::Message &msg)
210 {
211         for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
212                 (*i)->message(msg);
213 }
214
215 void Train::place(Block &block, unsigned entry)
216 {
217         if(controller->get_speed())
218                 throw logic_error("moving");
219
220         release_blocks();
221
222         set_active(false);
223         accurate_position = false;
224
225         blocks.push_back(BlockIter(&block, entry));
226         if(!block.reserve(this))
227         {
228                 blocks.pop_back();
229                 return;
230         }
231
232         if(reverse)
233         {
234                 TrackIter track = BlockIter(&block, entry).reverse().track_iter();
235                 vehicles.front()->place(*track, track.entry(), 0, Vehicle::FRONT_BUFFER);
236         }
237         else
238         {
239                 const Block::Endpoint &bep = block.get_endpoint(entry);
240                 vehicles.back()->place(*bep.track, bep.track_ep, 0, Vehicle::BACK_BUFFER);
241         }
242 }
243
244 void Train::unplace()
245 {
246         if(controller->get_speed())
247                 throw logic_error("moving");
248
249         release_blocks();
250
251         set_active(false);
252         accurate_position = false;
253
254         for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
255                 (*i)->unplace();
256 }
257
258 void Train::stop_at(Block *block)
259 {
260         stop_at_block = block;
261         if(active && !stop_at_block)
262                 reserve_more();
263 }
264
265 bool Train::free_block(Block &block)
266 {
267         if(get_reserved_distance_until(&block, false)<controller->get_braking_distance()*1.3)
268                 return false;
269
270         unsigned nsens = 0;
271         for(BlockList::iterator i=cur_blocks_end; i!=blocks.end(); ++i)
272         {
273                 if(i->block()==&block)
274                 {
275                         if(nsens<1)
276                                 return false;
277                         release_blocks(i, blocks.end());
278                         return true;
279                 }
280                 else if((*i)->get_sensor_id())
281                         ++nsens;
282         }
283
284         return false;
285 }
286
287 void Train::free_noncritical_blocks()
288 {
289         if(blocks.empty())
290                 return;
291
292         if(controller->get_speed()==0)
293         {
294                 release_blocks(cur_blocks_end, blocks.end());
295                 return;
296         }
297
298         float margin = 10*layout.get_catalogue().get_scale();
299         float min_dist = controller->get_braking_distance()*1.3+margin;
300
301         Vehicle &veh = *(reverse ? vehicles.back() : vehicles.front());
302
303         TrackIter track(veh.get_track(), veh.get_entry());
304         BlockList::iterator block = blocks.begin();
305         bool in_rsv = false;
306         while(block!=blocks.end() && !(*block)->has_track(*track))
307         {
308                 ++block;
309                 if(block==cur_blocks_end)
310                         in_rsv = true;
311         }
312
313         float dist = veh.get_offset();
314         if(reverse)
315                 track.reverse();
316         else
317                 dist = track->get_type().get_path_length(track->get_active_path())-dist;
318         dist -= veh.get_type().get_length()/2;
319
320         bool nsens = 0;
321         while(1)
322         {
323                 track = track.next();
324
325                 if(!(*block)->has_track(*track))
326                 {
327                         ++block;
328                         if(block==cur_blocks_end)
329                                 in_rsv = true;
330                         if(block==blocks.end())
331                                 return;
332
333                         if(dist>min_dist && nsens>0)
334                         {
335                                 release_blocks(block, blocks.end());
336                                 return;
337                         }
338
339                         if(in_rsv && (*block)->get_sensor_id())
340                                 ++nsens;
341                 }
342
343                 dist += track->get_type().get_path_length(track->get_active_path());
344         }
345 }
346
347 const BlockIter &Train::get_head_block() const
348 {
349         if(blocks.empty())
350                 throw logic_error("no blocks");
351         return blocks.back();
352 }
353
354 const BlockIter &Train::get_tail_block() const
355 {
356         if(blocks.empty())
357                 throw logic_error("no blocks");
358         return blocks.front();
359 }
360
361 int Train::get_entry_to_block(const Block &block) const
362 {
363         for(BlockList::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
364                 if(i->block()==&block)
365                         return i->entry();
366         return -1;
367 }
368
369 float Train::get_reserved_distance() const
370 {
371         if(blocks.empty())
372                 return 0;
373
374         float margin = 0;
375         TrackIter next = blocks.back().next().track_iter();
376         if(next && next->get_type().is_turnout())
377                 margin = 15*layout.get_catalogue().get_scale();
378
379         return max(get_reserved_distance_until(pending_block, false)-margin, 0.0f);
380 }
381
382 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
383 {
384         if(!active && stop_timeout && t>=stop_timeout)
385         {
386                 release_blocks(cur_blocks_end, blocks.end());
387                 stop_timeout = Time::TimeStamp();
388         }
389
390         Driver &driver = layout.get_driver();
391
392         for(list<TrainAI *>::iterator i=ais.begin(); i!=ais.end(); ++i)
393                 (*i)->tick(t, dt);
394         controller->tick(dt);
395         float speed = controller->get_speed();
396         bool moving = speed>0;
397
398         if(controller->get_reverse()!=reverse)
399         {
400                 reverse = controller->get_reverse();
401                 bool r = reverse;
402                 if(loco_type.get_swap_direction())
403                         r = !r;
404                 driver.set_loco_reverse(address, r);
405
406                 release_blocks(cur_blocks_end, blocks.end());
407                 reverse_blocks(blocks);
408
409                 reserve_more();
410         }
411
412         if(speed_quantizer)
413         {
414                 unsigned speed_step = speed_quantizer->find_speed_step(speed);
415                 if(speed_step!=current_speed_step && !speed_changing && !driver.is_halted() && driver.get_power())
416                 {
417                         speed_changing = true;
418                         driver.set_loco_speed(address, speed_step);
419
420                         pure_speed = false;
421                 }
422
423                 speed = speed_quantizer->get_speed(current_speed_step);
424         }
425
426         if(moving)
427         {
428                 if(!active)
429                         set_active(true);
430
431                 Vehicle &vehicle = *(reverse ? vehicles.back() : vehicles.front());
432                 Track *track = vehicle.get_track();
433
434                 bool ok = false;
435                 for(BlockList::const_iterator i=blocks.begin(); (!ok && i!=cur_blocks_end); ++i)
436                         ok = (*i)->has_track(*track);
437
438                 float d = speed*(dt/Time::sec);
439                 if(ok)
440                 {
441                         SetFlag setf(advancing);
442                         vehicle.advance(reverse ? -d : d);
443                 }
444                 else if(accurate_position)
445                 {
446                         overshoot_dist += d;
447                         if(overshoot_dist>40*layout.get_catalogue().get_scale())
448                         {
449                                 layout.emergency(name+" has not arrived at sensor");
450                                 accurate_position = false;
451                         }
452                 }
453         }
454
455         if(!blocks.empty() && !blocks.front()->get_sensor_id())
456         {
457                 float dist = get_reserved_distance_until(&*blocks.front(), true);
458
459                 if(dist>10*layout.get_catalogue().get_scale())
460                 {
461                         Block &block = *blocks.front();
462                         blocks.pop_front();
463                         block.reserve(0);
464                 }
465         }
466 }
467
468 void Train::save(list<DataFile::Statement> &st) const
469 {
470         st.push_back((DataFile::Statement("name"), name));
471
472         for(vector<Vehicle *>::const_iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
473                 if(i!=vehicles.begin())
474                         st.push_back((DataFile::Statement("vehicle"), (*i)->get_type().get_article_number()));
475
476         if(speed_quantizer)
477         {
478                 DataFile::Statement ss("quantized_speed");
479                 speed_quantizer->save(ss.sub);
480                 st.push_back(ss);
481         }
482
483         if(!blocks.empty() && cur_blocks_end!=blocks.begin())
484         {
485                 BlockList blks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
486                 if(reverse)
487                         reverse_blocks(blks);
488
489                 BlockIter prev = blks.front().flip();
490                 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
491
492                 for(BlockList::const_iterator i=blks.begin(); i!=blks.end(); ++i)
493                         st.push_back((DataFile::Statement("block"), (*i)->get_id()));
494         }
495
496         // XXX Need more generic way of saving AI state
497         for(list<TrainAI *>::const_iterator i=ais.begin(); i!=ais.end(); ++i)
498         {
499                 if(TrainRouter *router = dynamic_cast<TrainRouter *>(*i))
500                 {
501                         DataFile::Statement ss("router");
502                         router->save(ss.sub);
503                         st.push_back(ss);
504                 }
505                 else if(Timetable *timetable = dynamic_cast<Timetable *>(*i))
506                 {
507                         DataFile::Statement ss("timetable");
508                         timetable->save(ss.sub);
509                         st.push_back(ss);
510                 }
511         }
512 }
513
514 void Train::control_changed(const Controller::Control &ctrl)
515 {
516         signal_control_changed.emit(ctrl.name, ctrl.value);
517 }
518
519 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
520 {
521         if(addr==address)
522         {
523                 current_speed_step = speed;
524                 bool r = reverse;
525                 if(loco_type.get_swap_direction())
526                         r = !r;
527                 if(rev!=r)
528                         layout.get_driver().set_loco_reverse(address, r);
529                 speed_changing = false;
530                 pure_speed = false;
531         }
532 }
533
534 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
535 {
536         if(addr==address)
537         {
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::block_state_changed(Block &block, Block::State state)
548 {
549         if(state==Block::MAYBE_ACTIVE)
550         {
551                 // Find the first sensor block from our reserved blocks that isn't this sensor
552                 BlockList::iterator end;
553                 unsigned result = 0;
554                 for(end=cur_blocks_end; end!=blocks.end(); ++end)
555                         if((*end)->get_sensor_id())
556                         {
557                                 if(&**end!=&block)
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)
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 && speed_quantizer && current_speed_step>0 && travel_time_secs>=2)
576                                 speed_quantizer->learn(current_speed_step, travel_dist/travel_time_secs, travel_time_secs);
577
578                         travel_dist = 0;
579                         for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
580                         {
581                                 travel_dist += (*j)->get_path_length(j->entry());
582
583                                 if(&**j==&block && !advancing)
584                                 {
585                                         TrackIter track = j->track_iter();
586                                         if(reverse)
587                                         {
588                                                 track = track.flip();
589                                                 vehicles.back()->place(*track, track.entry(), 0, Vehicle::BACK_AXLE);
590                                         }
591                                         else
592                                                 vehicles.front()->place(*track, track.entry(), 0, Vehicle::FRONT_AXLE);
593                                 }
594                         }
595                         last_entry_time = Time::now();
596                         pure_speed = true;
597                         accurate_position = true;
598                         overshoot_dist = 0;
599
600                         // Move blocks up to the next sensor to our current blocks
601                         for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
602                                 signal_advanced.emit(**j);
603                         cur_blocks_end = end;
604
605                         // Try to get more blocks if we're moving
606                         if(active)
607                                 reserve_more();
608                 }
609                 else if(result==3)
610                         layout.emergency("Sensor for "+name+" triggered out of order");
611         }
612         else if(state==Block::INACTIVE)
613         {
614                 const Vehicle &veh = *(reverse ? vehicles.front() : vehicles.back());
615
616                 // Find the first sensor in our current blocks that's still active
617                 BlockList::iterator end = blocks.begin();
618                 for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
619                 {
620                         if((*i)->has_track(*veh.get_track()))
621                                 break;
622                         if((*i)->get_sensor_id())
623                         {
624                                 if(layout.get_driver().get_sensor((*i)->get_sensor_id()))
625                                         break;
626                                 else
627                                 {
628                                         end = i;
629                                         ++end;
630                                 }
631                         }
632                 }
633                 
634                 if(end!=blocks.begin() && end!=cur_blocks_end)
635                         // Free blocks up to the last inactive sensor
636                         release_blocks(blocks.begin(), end);
637         }
638 }
639
640 void Train::turnout_path_changed(Track &track)
641 {
642         for(list<BlockIter>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
643                 if((*i)->get_turnout_id()==track.get_turnout_id() && !reserving && &**i==pending_block)
644                         reserve_more();
645 }
646
647 void Train::halt_event(bool h)
648 {
649         if(h)
650                 accurate_position = false;
651 }
652
653 void Train::block_reserved(const Block &block, const Train *train)
654 {
655         if(&block==pending_block && !train && !reserving)
656                 reserve_more();
657 }
658
659 void Train::reserve_more()
660 {
661         if(!active || blocks.empty())
662                 return;
663
664         BlockIter start = blocks.back();
665         if(&*start==stop_at_block)
666                 return;
667         else if(&*start==pending_block)
668         {
669                 TrackIter track = start.track_iter();
670                 if(!track.endpoint().has_path(track->get_active_path()))
671                         return;
672         }
673
674         pending_block = 0;
675         preceding_train = 0;
676
677         // See how many sensor blocks and how much track we already have
678         unsigned nsens = 0;
679         float dist = 0;
680         for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i)
681         {
682                 if((*i)->get_sensor_id())
683                         ++nsens;
684                 if(nsens>0)
685                         dist += (*i)->get_path_length(i->entry());
686         }
687
688         float approach_margin = 50*layout.get_catalogue().get_scale();
689         float min_dist = controller->get_braking_distance()*1.3+approach_margin*2;
690
691         BlockIter block = start;
692
693         SetFlag setf(reserving);
694
695         while(1)
696         {
697                 BlockIter last = block;
698                 block = block.next();
699                 if(!block || block->get_endpoints().size()<2)
700                         // The track ends here
701                         break;
702
703                 if(block->get_turnout_id() && !last->get_turnout_id())
704                 {
705                         /* We are arriving at a turnout.  See if we have enough blocks and
706                         distance reserved. */
707                         if(nsens>=3 && dist>=min_dist)
708                                 break;
709                 }
710
711                 blocks.push_back(block);
712                 if(!block->reserve(this))
713                 {
714                         blocks.pop_back();
715                         pending_block = &*block;
716                         break;
717                 }
718
719                 if(cur_blocks_end==blocks.end())
720                         --cur_blocks_end;
721
722                 TrackIter track = block.track_iter();
723                 if(track->is_path_changing())
724                 {
725                         pending_block = &*block;
726                         break;
727                 }
728                 else
729                 {
730                         const TrackType::Endpoint &entry_ep = track.endpoint();
731                         unsigned path = track->get_active_path();
732                         if(!entry_ep.has_path(path))
733                         {
734                                 const TrackType::Endpoint &exit_ep = track.reverse().endpoint();
735                                 if(entry_ep.has_common_paths(exit_ep))
736                                 {
737                                         unsigned mask = entry_ep.paths&exit_ep.paths;
738                                         for(path=0; mask>1; ++path, mask>>=1) ;
739
740                                         track->set_active_path(path);
741                                         if(track->is_path_changing())
742                                         {
743                                                 pending_block = &*block;
744                                                 break;
745                                         }
746                                 }
747                                 else
748                                         // XXX Do something here
749                                         break;
750                         }
751                 }
752
753                 if(&*block==stop_at_block)
754                         break;
755
756                 if(block->get_sensor_id())
757                         ++nsens;
758                 if(nsens>0)
759                         dist += block->get_path_length(block.entry());
760         }
761
762         // Make any sensorless blocks at the beginning immediately current
763         while(cur_blocks_end!=blocks.end() && !(*cur_blocks_end)->get_sensor_id())
764                 ++cur_blocks_end;
765 }
766
767 float Train::get_reserved_distance_until(const Block *until_block, bool back) const
768 {
769         if(blocks.empty())
770                 return 0;
771
772         Vehicle &veh = *(reverse!=back ? vehicles.back() : vehicles.front());
773         const VehicleType &vtype = veh.get_type();
774
775         TrackIter track(veh.get_track(), veh.get_entry());
776         if(!track)  // XXX Probably unnecessary
777                 return 0;
778
779         BlockList::const_iterator block = blocks.begin();
780         while(block!=blocks.end() && !(*block)->has_track(*track))
781                 ++block;
782         if(block==blocks.end() || &**block==until_block)
783                 return 0;
784
785         float result = veh.get_offset();
786         if(reverse!=back)
787                 track = track.reverse();
788         else
789                 result = track->get_type().get_path_length(track->get_active_path())-result;
790         result -= vtype.get_length()/2;
791
792         while(1)
793         {
794                 track = track.next();
795                 if(!track)
796                         break;
797
798                 if(!(*block)->has_track(*track))
799                 {
800                         if(back)
801                         {
802                                 if(block==blocks.begin())
803                                         break;
804                                 --block;
805                         }
806                         else
807                         {
808                                 ++block;
809                                 if(block==blocks.end())
810                                         break;
811                         }
812
813                         if(&**block==until_block)
814                                 break;
815                 }
816
817                 result += track->get_type().get_path_length(track->get_active_path());
818         }
819
820         return result;
821 }
822
823 void Train::release_blocks()
824 {
825         release_blocks(blocks.begin(), blocks.end());
826 }
827
828 void Train::release_blocks(BlockList::iterator begin, BlockList::iterator end)
829 {
830         while(begin!=end)
831         {
832                 if(begin==cur_blocks_end)
833                         cur_blocks_end = end;
834
835                 Block &block = **begin;
836                 blocks.erase(begin++);
837                 block.reserve(0);
838         }
839 }
840
841 void Train::reverse_blocks(BlockList &blks) const
842 {
843         blks.reverse();
844         for(BlockList::iterator i=blks.begin(); i!=blks.end(); ++i)
845                 *i = i->reverse();
846 }
847
848
849 Train::Loader::Loader(Train &t):
850         DataFile::ObjectLoader<Train>(t),
851         prev_block(0),
852         blocks_valid(true)
853 {
854         add("block",       &Loader::block);
855         add("block_hint",  &Loader::block_hint);
856         add("name",        &Loader::name);
857         add("quantized_speed",  &Loader::quantized_speed);
858         add("router",      &Loader::router);
859         add("timetable",   &Loader::timetable);
860         add("vehicle",     &Loader::vehicle);
861 }
862
863 void Train::Loader::finish()
864 {
865         if(!obj.blocks.empty())
866         {
867                 TrackIter track = obj.blocks.front().track_iter();
868                 float offset = 2*obj.layout.get_catalogue().get_scale();
869                 obj.vehicles.back()->place(*track, track.entry(), offset, Vehicle::BACK_BUFFER);
870         }
871 }
872
873 void Train::Loader::block(unsigned id)
874 {
875         if(!blocks_valid)
876                 return;
877
878         Block *blk;
879         try
880         {
881                 blk = &obj.layout.get_block(id);
882         }
883         catch(const key_error &)
884         {
885                 blocks_valid = false;
886                 return;
887         }
888
889         int entry = -1;
890         if(prev_block)
891                 entry = blk->get_endpoint_by_link(*prev_block);
892         if(entry<0)
893                 entry = 0;
894
895         obj.blocks.push_back(BlockIter(blk, entry));
896         blk->reserve(&obj);
897
898         if(blk->get_sensor_id())
899                 obj.layout.get_driver().set_sensor(blk->get_sensor_id(), true);
900
901         prev_block = blk;
902 }
903
904 void Train::Loader::block_hint(unsigned id)
905 {
906         try
907         {
908                 prev_block = &obj.layout.get_block(id);
909         }
910         catch(const key_error &)
911         {
912                 blocks_valid = false;
913         }
914 }
915
916 void Train::Loader::name(const string &n)
917 {
918         obj.set_name(n);
919 }
920
921 void Train::Loader::quantized_speed()
922 {
923         if(obj.speed_quantizer)
924                 load_sub(*obj.speed_quantizer);
925 }
926
927 void Train::Loader::router()
928 {
929         TrainRouter *rtr = new TrainRouter(obj);
930         load_sub(*rtr);
931 }
932
933 void Train::Loader::timetable()
934 {
935         Timetable *ttbl = new Timetable(obj);
936         load_sub(*ttbl);
937 }
938
939 void Train::Loader::vehicle(ArticleNumber art_nr)
940 {
941         const VehicleType &vtype = obj.layout.get_catalogue().get_vehicle(art_nr);
942         Vehicle *veh = new Vehicle(obj.layout, vtype);
943         obj.vehicles.back()->attach_back(*veh);
944         obj.vehicles.push_back(veh);
945 }
946
947 } // namespace R2C2