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