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