]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/train.cpp
Add vehicles
[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 "driver.h"
13 #include "layout.h"
14 #include "locotype.h"
15 #include "route.h"
16 #include "tracktype.h"
17 #include "train.h"
18 #include "vehicle.h"
19
20 using namespace std;
21 using namespace Msp;
22
23 namespace Marklin {
24
25 Train::Train(Layout &l, const LocoType &t, unsigned a):
26         layout(l),
27         loco_type(t),
28         address(a),
29         pending_block(0),
30         target_speed(0),
31         current_speed(0),
32         reverse(false),
33         functions(0),
34         route(0),
35         next_route(0),
36         end_of_route(false),
37         status("Unplaced"),
38         travel_dist(0),
39         travel_speed(0),
40         pure_speed(false),
41         real_speed(15)
42 {
43         vehicles.push_back(new Vehicle(layout, loco_type));
44
45         layout.add_train(*this);
46
47         layout.get_driver().add_loco(address);
48         layout.get_driver().signal_loco_speed.connect(sigc::mem_fun(this, &Train::loco_speed_event));
49         layout.get_driver().signal_loco_function.connect(sigc::mem_fun(this, &Train::loco_func_event));
50
51         layout.signal_block_reserved.connect(sigc::mem_fun(this, &Train::block_reserved));
52         layout.get_driver().signal_sensor.connect(sigc::mem_fun(this, &Train::sensor_event));
53         layout.get_driver().signal_turnout.connect(sigc::mem_fun(this, &Train::turnout_event));
54 }
55
56 Train::~Train()
57 {
58         for(vector<Vehicle *>::iterator i=vehicles.begin(); i!=vehicles.end(); ++i)
59                 delete *i;
60         layout.remove_train(*this);
61 }
62
63 void Train::set_name(const string &n)
64 {
65         name = n;
66
67         signal_name_changed.emit(name);
68 }
69
70 Vehicle &Train::get_vehicle(unsigned i)
71 {
72         if(i>=vehicles.size())
73                 throw InvalidParameterValue("Vehicle index out of range");
74         return *vehicles[i];
75 }
76
77 const Vehicle &Train::get_vehicle(unsigned i) const
78 {
79         if(i>=vehicles.size())
80                 throw InvalidParameterValue("Vehicle index out of range");
81         return *vehicles[i];
82 }
83
84 void Train::set_speed(unsigned speed)
85 {
86         if(speed==target_speed)
87                 return;
88         travel_speed = static_cast<int>(round(get_real_speed(speed)*87*3.6/5))*5;
89
90         target_speed = speed;
91         if(!target_speed)
92         {
93                 pending_block = 0;
94                 stop_timeout = Time::now()+(800+current_speed*150)*Time::msec;
95         }
96         else
97                 reserve_more();
98
99         signal_target_speed_changed.emit(target_speed);
100
101         update_speed();
102         pure_speed = false;
103 }
104
105 void Train::set_reverse(bool rev)
106 {
107         if(rev==reverse)
108                 return;
109
110         if(target_speed)
111         {
112                 set_speed(0);
113                 return;
114         }
115         else if(stop_timeout)
116                 return;
117
118         layout.get_driver().set_loco_reverse(address, rev);
119
120         release_blocks(rsv_blocks);
121         reverse_blocks(cur_blocks);
122
123         // XXX Do something about the vehicles
124 }
125
126 void Train::set_function(unsigned func, bool state)
127 {
128         if(!loco_type.get_functions().count(func))
129                 throw InvalidParameterValue("Invalid function");
130         if(func<5)
131                 layout.get_driver().set_loco_function(address, func, state);
132         else
133                 layout.get_driver().set_loco_function(address+1, func-4, state);
134 }
135
136 bool Train::get_function(unsigned func) const
137 {
138         return (functions>>func)&1;
139 }
140
141 void Train::set_route(const Route *r)
142 {
143         if(!rsv_blocks.empty())
144         {
145                 for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
146                         if(i->block->get_sensor_id())
147                         {
148                                 release_blocks(rsv_blocks, ++i, rsv_blocks.end());
149                                 break;
150                         }
151         }
152
153         route = r;
154         next_route = 0;
155         end_of_route = false;
156
157         if(route)
158         {
159                 BlockRef &last = (rsv_blocks.empty() ? cur_blocks.back() : rsv_blocks.back());
160                 BlockRef next = last.next();
161                 const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
162                 if(!route->get_tracks().count(ep.track))
163                 {
164                         next_route = route;
165                         route = Route::find(*ep.track, ep.track_ep, *next_route);
166                 }
167         }
168
169         if(target_speed && reserve_more()<2)
170                 update_speed();
171
172         signal_route_changed.emit(route);
173 }
174
175 void Train::go_to(const Track &to)
176 {
177         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
178                 if(i->block->get_tracks().count(const_cast<Track *>(&to)))
179                 {
180                         set_speed(0);
181                         set_route(0);
182                         return;
183                 }
184
185         BlockRef *last = 0;
186         if(rsv_blocks.empty())
187                 last = &cur_blocks.back();
188         else
189         {
190                 for(list<BlockRef>::iterator i=rsv_blocks.begin(); (i!=rsv_blocks.end() && !last); ++i)
191                         if(i->block->get_sensor_id())
192                                 last = &*i;
193         }
194
195         BlockRef next = last->next();
196         const Block::Endpoint &ep = next.block->get_endpoints()[next.entry];
197
198         set_route(Route::find(*ep.track, ep.track_ep, to));
199 }
200
201 void Train::place(Block &block, unsigned entry)
202 {
203         if(target_speed)
204                 set_speed(0);
205
206         release_blocks(rsv_blocks);
207         release_blocks(cur_blocks);
208
209         if(!block.reserve(this))
210         {
211                 set_status("Unplaced");
212                 return;
213         }
214
215         cur_blocks.push_back(BlockRef(&block, entry));
216         set_position(block.get_endpoints()[entry]);
217
218         set_status("Stopped");
219 }
220
221 bool Train::free_block(Block &block)
222 {
223         unsigned nsens = 0;
224         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
225         {
226                 if(i->block==&block)
227                 {
228                         if(nsens<1)
229                                 return false;
230                         release_blocks(rsv_blocks, i, rsv_blocks.end());
231                         update_speed();
232                         return true;
233                 }
234                 else if(i->block->get_sensor_id())
235                         ++nsens;
236         }
237
238         return false;
239 }
240
241 int Train::get_entry_to_block(Block &block) const
242 {
243         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
244                 if(i->block==&block)
245                         return i->entry;
246         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
247                 if(i->block==&block)
248                         return i->entry;
249         return -1;
250 }
251
252 void Train::tick(const Time::TimeStamp &t, const Time::TimeDelta &dt)
253 {
254         if(stop_timeout && t>=stop_timeout)
255         {
256                 release_blocks(rsv_blocks);
257                 end_of_route = false;
258                 stop_timeout = Time::TimeStamp();
259         }
260
261         if(current_speed)
262         {
263                 Track *track = vehicles[0]->get_track();
264
265                 bool ok = false;
266                 for(list<BlockRef>::const_iterator i=cur_blocks.begin(); (!ok && i!=cur_blocks.end()); ++i)
267                         ok = i->block->get_tracks().count(track);
268
269                 if(ok)
270                         vehicles[0]->advance(get_real_speed(current_speed)*(dt/Time::sec));
271         }
272 }
273
274 void Train::save(list<DataFile::Statement> &st) const
275 {
276         st.push_back((DataFile::Statement("name"), name));
277         for(unsigned i=0; i<=14; ++i)
278                 if(real_speed[i].weight)
279                         st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
280
281         if(!cur_blocks.empty())
282         {
283                 list<BlockRef> blocks = cur_blocks;
284                 if(reverse)
285                         reverse_blocks(blocks);
286
287                 Block *prev = blocks.front().block->get_endpoints()[blocks.front().entry].link;
288                 st.push_back((DataFile::Statement("block_hint"), prev->get_id()));
289
290                 for(list<BlockRef>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
291                         st.push_back((DataFile::Statement("block"), i->block->get_id()));
292         }
293
294         if(route)
295                 st.push_back((DataFile::Statement("route"), route->get_name()));
296 }
297
298 void Train::loco_speed_event(unsigned addr, unsigned speed, bool rev)
299 {
300         if(addr==address)
301         {
302                 current_speed = speed;
303                 reverse = rev;
304
305                 signal_speed_changed.emit(current_speed);
306                 signal_reverse_changed.emit(reverse);
307         }
308 }
309
310 void Train::loco_func_event(unsigned addr, unsigned func, bool state)
311 {
312         if(addr==address || (addr==address+1 && loco_type.get_max_function()>4))
313         {
314                 if(addr==address+1)
315                         func += 4;
316                 if(state)
317                         functions |= 1<<func;
318                 else
319                         functions &= ~(1<<func);
320
321                 signal_function_changed.emit(func, state);
322         }
323 }
324
325 void Train::sensor_event(unsigned addr, bool state)
326 {
327         if(state)
328         {
329                 // Find the first sensor block from our reserved blocks that isn't this sensor
330                 list<BlockRef>::iterator i;
331                 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
332                         if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
333                                 break;
334
335                 if(i!=rsv_blocks.begin())
336                 {
337                         // Compute speed and update related state
338                         float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
339                         travel_speed = static_cast<int>(round(travel_dist/travel_time_secs*87*3.6/5))*5;
340
341                         if(pure_speed)
342                         {
343                                 RealSpeed &rs = real_speed[current_speed];
344                                 rs.add(travel_dist/travel_time_secs, travel_time_secs);
345                         }
346
347                         travel_dist = 0;
348                         float block_len;
349                         for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
350                         {
351                                 j->block->traverse(j->entry, &block_len);
352                                 travel_dist += block_len;
353
354                                 if(j->block->get_sensor_id()==addr)
355                                         set_position(j->block->get_endpoints()[j->entry]);
356                         }
357                         last_entry_time = Time::now();
358                         pure_speed = true;
359
360                         // Check if we've reached the next route
361                         if(next_route)
362                         {
363                                 const set<const Track *> &rtracks = next_route->get_tracks();
364                                 for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
365                                         if(rtracks.count(j->block->get_endpoints()[j->entry].track))
366                                         {
367                                                 route = next_route;
368                                                 next_route = 0;
369                                                 // XXX Exceptions?
370                                                 signal_route_changed.emit(route);
371                                                 break;
372                                         }
373                         }
374
375                         // Move blocks up to the next sensor to our current blocks
376                         cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
377
378                         // Try to get more blocks if we're moving
379                         if(target_speed)
380                         {
381                                 unsigned nsens = reserve_more();
382                                 if(!nsens && end_of_route)
383                                 {
384                                         set_speed(0);
385                                         set_route(0);
386                                 }
387                                 else if(nsens<2)
388                                         update_speed();
389                         }
390                 }
391         }
392         else
393         {
394                 // Find the first sensor in our current blocks that's still active
395                 list<BlockRef>::iterator end = cur_blocks.begin();
396                 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
397                         if(i->block->get_sensor_id())
398                         {
399                                 if(layout.get_driver().get_sensor(i->block->get_sensor_id()))
400                                         break;
401                                 else
402                                         end = i;
403                         }
404                 
405                 if(end!=cur_blocks.begin())
406                 {
407                         // Free blocks up to the last inactive sensor
408                         ++end;
409                         release_blocks(cur_blocks, cur_blocks.begin(), end);
410                 }
411         }
412 }
413
414 void Train::turnout_event(unsigned addr, bool)
415 {
416         if(pending_block)
417         {
418                 unsigned pending_addr = pending_block->get_turnout_id();
419                 bool double_addr = (*pending_block->get_tracks().begin())->get_type().is_double_address();
420                 if(addr==pending_addr || (double_addr && addr==pending_addr+1))
421                         reserve_more();
422         }
423 }
424
425 void Train::block_reserved(const Block &block, const Train *train)
426 {
427         if(&block==pending_block && !train)
428                 reserve_more();
429 }
430
431 unsigned Train::reserve_more()
432 {
433         BlockRef *last = 0;
434         if(!rsv_blocks.empty())
435                 last = &rsv_blocks.back();
436         else if(!cur_blocks.empty())
437                 last = &cur_blocks.back();
438         if(!last)
439                 return 0;
440
441         pending_block = 0;
442
443         // See how many sensor blocks we already have
444         unsigned nsens = 0;
445         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
446                 if(i->block->get_sensor_id())
447                         ++nsens;
448         
449         const Route *cur_route = 0;
450         if(route)
451         {
452                 unsigned exit = last->block->traverse(last->entry);
453                 Track *track = last->block->get_endpoints()[exit].track;
454                 if(route->get_tracks().count(track))
455                         cur_route = route;
456                 else if(next_route && next_route->get_tracks().count(track))
457                         cur_route = next_route;
458         }
459
460         bool got_more = false;
461         BlockRef *good = last;
462         unsigned good_sens = nsens;
463         while(good_sens<3)
464         {
465                 // Traverse to the next block
466                 unsigned exit = last->block->traverse(last->entry);
467                 Block *link = last->block->get_link(exit);
468                 if(!link)
469                         break;
470
471                 int entry = link->get_endpoint_by_link(*last->block);
472                 if(entry<0)
473                         throw LogicError("Block links are inconsistent!");
474
475                 const Block::Endpoint &entry_ep = link->get_endpoints()[entry];
476
477                 if(cur_route)
478                 {
479                         if(cur_route!=next_route && next_route && next_route->get_tracks().count(entry_ep.track))
480                                 cur_route = next_route;
481                         else if(!cur_route->get_tracks().count(entry_ep.track))
482                         {
483                                 // Keep the blocks if we arrived at the end of the route
484                                 good = last;
485                                 good_sens = nsens;
486                                 end_of_route = true;
487                                 break;
488                         }
489                 }
490                 else if(route && route->get_tracks().count(entry_ep.track))
491                         cur_route = route;
492
493                 if(!link->reserve(this))
494                 {
495                         // If we found another train and it's not headed straight for us, we can keep the blocks we got
496                         int other_entry = link->get_train()->get_entry_to_block(*link);
497                         if(other_entry<0)
498                                 throw LogicError("Block reservation inconsistency");
499                         if(static_cast<unsigned>(entry)!=link->traverse(other_entry))
500                         {
501                                 good = last;
502                                 good_sens = nsens;
503                         }
504                         pending_block = link;
505                         break;
506                 }
507
508                 if(link->get_turnout_id())
509                 {
510                         const Endpoint &track_ep = entry_ep.track->get_type().get_endpoints()[entry_ep.track_ep];
511
512                         // Keep the blocks reserved so far, as either us or the other train can diverge
513                         good = last;
514                         good_sens = nsens;
515
516                         // Figure out what path we'd like to take on the turnout
517                         int path = -1;
518                         if(cur_route)
519                                 path = cur_route->get_turnout(link->get_turnout_id());
520                         if(path<0)
521                                 path = entry_ep.track->get_active_path();
522                         if(!((track_ep.paths>>path)&1))
523                         {
524                                 for(unsigned i=0; track_ep.paths>>i; ++i)
525                                         if((track_ep.paths>>i)&1)
526                                                 path = i;
527                         }
528
529                         if(path!=static_cast<int>(entry_ep.track->get_active_path()))
530                         {
531                                 // The turnout is set to wrong path - switch and wait for it
532                                 link->reserve(0);
533                                 pending_block = link;
534                                 entry_ep.track->set_active_path(path);
535                                 break;
536                         }
537                 }
538
539                 rsv_blocks.push_back(BlockRef(link, entry));
540                 last = &rsv_blocks.back();
541                 if(last->block->get_sensor_id())
542                 {
543                         ++nsens;
544                         got_more = true;
545                 }
546         }
547
548         // Unreserve blocks that were not good
549         while(!rsv_blocks.empty() && last!=good)
550         {
551                 last->block->reserve(0);
552                 rsv_blocks.erase(--rsv_blocks.end());
553                 if(!rsv_blocks.empty())
554                         last = &rsv_blocks.back();
555         }
556
557         if(got_more)
558                 update_speed();
559
560         return good_sens;
561 }
562
563 void Train::update_speed()
564 {
565         Driver &driver = layout.get_driver();
566
567         unsigned speed;
568         if(!target_speed)
569         {
570                 speed = 0;
571                 set_status("Stopped");
572         }
573         else
574         {
575                 unsigned nsens = 0;
576                 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
577                         if(i->block->get_sensor_id())
578                                 ++nsens;
579
580                 unsigned slow_speed = find_speed(0.1);  // 31.3 km/h
581                 if(nsens==0)
582                 {
583                         speed = 0;
584                         pure_speed = false;
585                         set_status("Blocked");
586                 }
587                 else if(nsens==1 && target_speed>slow_speed)
588                 {
589                         speed = slow_speed;
590                         pure_speed = false;
591                         set_status("Slow");
592                 }
593                 else
594                 {
595                         speed = target_speed;
596                         set_status(format("Traveling %d kmh", travel_speed));
597                 }
598         }
599
600         driver.set_loco_speed(address, speed);
601 }
602
603 float Train::get_real_speed(unsigned i) const
604 {
605         if(real_speed[i].weight)
606                 return real_speed[i].speed;
607
608         unsigned low;
609         unsigned high;
610         for(low=i; low>0; --low)
611                 if(real_speed[low].weight)
612                         break;
613         for(high=i; high<14; ++high)
614                 if(real_speed[high].weight)
615                         break;
616
617         if(real_speed[high].weight)
618         {
619                 if(real_speed[low].weight)
620                 {
621                         float f = float(i-low)/(high-low);
622                         return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
623                 }
624                 else
625                         return real_speed[high].speed*float(i)/high;
626         }
627         else if(real_speed[low].weight)
628                 return real_speed[low].speed*float(i)/low;
629         else
630                 return 0;
631 }
632
633 unsigned Train::find_speed(float real) const
634 {
635         if(real<=real_speed[0].speed)
636                 return 0;
637
638         unsigned low = 0;
639         unsigned high = 0;
640         for(unsigned i=0; (!high && i<=14); ++i)
641                 if(real_speed[i].weight)
642                 {
643                         if(real_speed[i].speed<real)
644                                 low = i;
645                         else
646                                 high = i;
647                 }
648         if(!high)
649         {
650                 if(!low)
651                         return 0;
652                 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
653         }
654
655         float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
656         return static_cast<unsigned>(low*(1-f)+high*f+0.5);
657 }
658
659 void Train::set_status(const string &s)
660 {
661         status = s;
662         signal_status_changed.emit(s);
663 }
664
665 void Train::set_position(const Block::Endpoint &bep)
666 {
667         vehicles[0]->place(bep.track, bep.track_ep, 0, Vehicle::FRONT_AXLE);
668 }
669
670 void Train::release_blocks(list<BlockRef> &blocks)
671 {
672         release_blocks(blocks, blocks.begin(), blocks.end());
673 }
674
675 void Train::release_blocks(list<BlockRef> &blocks, list<BlockRef>::iterator begin, list<BlockRef>::iterator end)
676 {
677         while(begin!=end)
678         {
679                 Block *block = begin->block;
680                 blocks.erase(begin++);
681                 block->reserve(0);
682         }
683 }
684
685 void Train::reverse_blocks(list<BlockRef> &blocks) const
686 {
687         blocks.reverse();
688         for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
689                 i->entry = i->block->traverse(i->entry);
690 }
691
692
693 Train::BlockRef::BlockRef(Block *b, unsigned e):
694         block(b),
695         entry(e)
696 { }
697
698 Train::BlockRef Train::BlockRef::next() const
699 {
700         Block *blk = block->get_endpoints()[block->traverse(entry)].link;
701         if(!blk)
702                 throw InvalidState("At end of line");
703
704         int ep = blk->get_endpoint_by_link(*block);
705         if(ep<0)
706                 throw LogicError("Block links are inconsistent");
707
708         return BlockRef(blk, ep);
709 }
710
711
712 Train::RealSpeed::RealSpeed():
713         speed(0),
714         weight(0)
715 { }
716
717 void Train::RealSpeed::add(float s, float w)
718 {
719         speed = (speed*weight+s*w)/(weight+w);
720         weight = min(weight+w, 300.0f);
721 }
722
723
724 Train::Loader::Loader(Train &t):
725         DataFile::BasicLoader<Train>(t),
726         prev_block(0)
727 {
728         add("block",       &Loader::block);
729         add("block_hint",  &Loader::block_hint);
730         add("name",        &Loader::name);
731         add("real_speed",  &Loader::real_speed);
732         add("route",       &Loader::route);
733 }
734
735 void Train::Loader::block(unsigned id)
736 {
737         Block &blk = obj.layout.get_block(id);
738         int entry = -1;
739         if(prev_block)
740                 entry = blk.get_endpoint_by_link(*prev_block);
741         if(entry<0)
742                 entry = 0;
743
744         blk.reserve(&obj);
745         obj.cur_blocks.push_back(BlockRef(&blk, entry));
746         obj.set_status("Stopped");
747         obj.set_position(blk.get_endpoints()[entry]);
748
749         prev_block = &blk;
750 }
751
752 void Train::Loader::block_hint(unsigned id)
753 {
754         prev_block = &obj.layout.get_block(id);
755 }
756
757 void Train::Loader::name(const string &n)
758 {
759         obj.set_name(n);
760 }
761
762 void Train::Loader::real_speed(unsigned i, float speed, float weight)
763 {
764         obj.real_speed[i].speed = speed;
765         obj.real_speed[i].weight = weight;
766 }
767
768 void Train::Loader::route(const string &n)
769 {
770         obj.set_route(&obj.layout.get_route(n));
771 }
772
773 } // namespace Marklin