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