]> git.tdb.fi Git - r2c2.git/blob - source/libmarklin/train.cpp
Change a few functions in Train to take Block reference instead of pointer
[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                         int out = cur_track->traverse(cur_track_ep, path);
160                         if(out>=0)
161                         {
162                                 Track *next = cur_track->get_link(out);
163                                 if(next)
164                                         cur_track_ep = next->get_endpoint_by_link(*cur_track);
165                                 cur_track = next;
166                                 offset = 0;
167                         }
168                         else
169                                 cur_track = 0;
170                 }
171
172                 if(cur_track)
173                         pos = cur_track->get_point(cur_track_ep, path, offset);
174         }
175 }
176
177 void Train::save(list<DataFile::Statement> &st) const
178 {
179         st.push_back((DataFile::Statement("name"), name));
180         for(unsigned i=0; i<=14; ++i)
181                 if(real_speed[i].weight)
182                         st.push_back((DataFile::Statement("real_speed"), i, real_speed[i].speed, real_speed[i].weight));
183 }
184
185 void Train::locomotive_reverse_changed(bool)
186 {
187         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
188                 i->block->reserve(0);
189         rsv_blocks.clear();
190         cur_blocks.reverse();
191         for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
192                 i->entry = i->block->traverse(i->entry);
193         reserve_more();
194
195         if(cur_track)
196         {
197                 unsigned path = 0;
198                 if(unsigned turnout = cur_track->get_turnout_id())
199                         path = trfc_mgr.get_control().get_turnout(turnout).get_path();
200                 cur_track_ep = cur_track->traverse(cur_track_ep, path);
201                 offset = cur_track->get_type().get_path_length(path)-offset;
202         }
203 }
204
205 void Train::sensor_event(bool state, Sensor *sensor)
206 {
207         unsigned addr = sensor->get_address();
208
209         if(state)
210         {
211                 list<BlockRef>::iterator i;
212                 for(i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
213                         if(i->block->get_sensor_id() && i->block->get_sensor_id()!=addr)
214                                 break;
215
216                 if(i!=rsv_blocks.begin())
217                 {
218                         float travel_time_secs = (Time::now()-last_entry_time)/Time::sec;
219                         travel_speed = static_cast<int>(round(travel_dist/travel_time_secs*87*3.6/5))*5;
220
221                         if(pure_speed)
222                         {
223                                 RealSpeed &rs = real_speed[loco.get_speed()];
224                                 rs.add(travel_dist/travel_time_secs, travel_time_secs);
225                         }
226
227                         travel_dist = 0;
228                         float block_len;
229                         for(list<BlockRef>::iterator j=rsv_blocks.begin(); j!=i; ++j)
230                         {
231                                 j->block->traverse(j->entry, &block_len);
232                                 travel_dist += block_len;
233                         }
234                         last_entry_time = Time::now();
235                         pure_speed = true;
236
237                         cur_blocks.splice(cur_blocks.end(), rsv_blocks, rsv_blocks.begin(), i);
238                 }
239
240                 for(i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
241                         if(i->block->get_sensor_id()==addr)
242                                 set_position(i->block->get_endpoints()[i->entry]);
243
244                 if(target_speed && reserve_more()<2)
245                         update_speed();
246         }
247         else
248         {
249                 for(list<BlockRef>::iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
250                         if(unsigned b_addr = i->block->get_sensor_id())
251                         {
252                                 if(b_addr==addr)
253                                 {
254                                         ++i;
255                                         for(list<BlockRef>::iterator j=cur_blocks.begin(); j!=i; ++j)
256                                                 j->block->reserve(0);
257                                         cur_blocks.erase(cur_blocks.begin(), i);
258                                 }
259                                 break;
260                         }
261
262                 if(target_speed && pending_block && addr==pending_block->get_sensor_id())
263                         reserve_more();
264         }
265 }
266
267 void Train::turnout_path_changing(unsigned, Turnout *turnout)
268 {
269         unsigned tid = turnout->get_address();
270         for(list<BlockRef>::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
271                 if(i->block->get_turnout_id()==tid)
272                         throw TurnoutBusy(this);
273         
274         unsigned nsens = 0;
275         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
276         {
277                 if(i->block->get_turnout_id()==tid)
278                 {
279                         if(nsens<1)
280                                 throw TurnoutBusy(this);
281                         break;
282                 }
283                 else if(i->block->get_sensor_id())
284                         ++nsens;
285         }
286 }
287
288 void Train::turnout_path_changed(unsigned, Turnout *turnout)
289 {
290         unsigned tid = turnout->get_address();
291         for(list<BlockRef>::iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
292                 if(i->block->get_turnout_id()==tid)
293                 {
294                         while(i!=rsv_blocks.end())
295                         {
296                                 i->block->reserve(0);
297                                 i = rsv_blocks.erase(i);
298                         }
299                         reserve_more();
300                         return;
301                 }
302
303         if(pending_block && tid==pending_block->get_turnout_id())
304                 reserve_more();
305 }
306
307 unsigned Train::reserve_more()
308 {
309         BlockRef *last = 0;
310         if(!rsv_blocks.empty())
311                 last = &rsv_blocks.back();
312         else if(!cur_blocks.empty())
313                 last = &cur_blocks.back();
314         if(!last)
315                 return 0;
316
317         pending_block = 0;
318
319         // See how many blocks we already have
320         unsigned nsens = 0;
321         for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
322                 if(i->block->get_sensor_id())
323                         ++nsens;
324
325         bool got_more = false;
326         BlockRef *good = last;
327         unsigned good_sens = nsens;
328         while(good_sens<3)
329         {
330                 // Traverse to the next block
331                 unsigned exit = last->block->traverse(last->entry);
332                 Block *link = last->block->get_link(exit);
333                 if(!link)
334                         break;
335
336                 int entry = link->get_endpoint_by_link(*last->block);
337                 if(!link->reserve(this))
338                 {
339                         // If we found another train going in the same direction as us, we can keep the blocks we got
340                         int other_entry = link->get_train()->get_entry_to_block(*link);
341                         if(other_entry==entry || link->traverse(entry)==link->traverse(other_entry))
342                         {
343                                 good = last;
344                                 good_sens = nsens;
345                         }
346                         pending_block = link;
347                         break;
348                 }
349
350                 if(link->get_turnout_id())
351                 {
352                         const Block::Endpoint &ep = link->get_endpoints()[entry];
353                         const Endpoint &track_ep = ep.track->get_type().get_endpoints()[ep.track_ep];
354
355                         if(track_ep.paths&(track_ep.paths-1))
356                         {
357                                 // We're facing the points - keep the blocks reserved so far
358                                 good = last;
359                                 good_sens = nsens;
360                         }
361
362                         Turnout &turnout = trfc_mgr.get_control().get_turnout(link->get_turnout_id());
363
364                         // Figure out what path we'd like to take on the turnout
365                         int path = -1;
366                         if(route)
367                                 path = route->get_turnout(link->get_turnout_id());
368                         if(path<0)
369                                 path = turnout.get_path();
370                         if(!((track_ep.paths>>path)&1))
371                         {
372                                 for(unsigned i=0; track_ep.paths>>i; ++i)
373                                         if((track_ep.paths>>i)&1)
374                                                 path = i;
375                         }
376
377                         if(path!=turnout.get_path())
378                         {
379                                 // The turnout is set to wrong path - switch and wait for it
380                                 link->reserve(0);
381                                 pending_block = link;
382                                 turnout.set_path(path);
383                                 break;
384                         }
385                 }
386
387                 rsv_blocks.push_back(BlockRef(link, entry));
388                 last = &rsv_blocks.back();
389                 if(last->block->get_sensor_id())
390                 {
391                         ++nsens;
392                         got_more = true;
393                 }
394         }
395
396         // Unreserve blocks that were not good
397         while(!rsv_blocks.empty() && last!=good)
398         {
399                 last->block->reserve(0);
400                 rsv_blocks.erase(--rsv_blocks.end());
401                 if(!rsv_blocks.empty())
402                         last = &rsv_blocks.back();
403         }
404
405         if(got_more)
406                 update_speed();
407
408         return nsens;
409 }
410
411 void Train::update_speed()
412 {
413         if(!target_speed)
414         {
415                 loco.set_speed(0);
416                 try_reserve = Time::TimeStamp();
417                 set_status("Stopped");
418         }
419         else
420         {
421                 unsigned nsens = 0;
422                 for(list<BlockRef>::const_iterator i=rsv_blocks.begin(); i!=rsv_blocks.end(); ++i)
423                         if(i->block->get_sensor_id())
424                                 ++nsens;
425
426                 unsigned slow_speed = find_speed(0.1);  // 31.3 km/h
427                 if(nsens==0)
428                 {
429                         loco.set_speed(0);
430                         pure_speed = false;
431                         try_reserve = Time::now()+2*Time::sec;
432                         set_status("Blocked");
433                 }
434                 else if(nsens==1 && target_speed>slow_speed)
435                 {
436                         loco.set_speed(slow_speed);
437                         pure_speed = false;
438                         try_reserve = Time::now()+2*Time::sec;
439                         set_status("Slow");
440                 }
441                 else
442                 {
443                         loco.set_speed(target_speed);
444                         try_reserve = Time::TimeStamp();
445                         set_status(format("Traveling %d kmh", travel_speed));
446                 }
447         }
448 }
449
450 float Train::get_real_speed(unsigned i) const
451 {
452         if(real_speed[i].weight)
453                 return real_speed[i].speed;
454
455         unsigned low;
456         unsigned high;
457         for(low=i; low>0; --low)
458                 if(real_speed[low].weight)
459                         break;
460         for(high=i; high<14; ++high)
461                 if(real_speed[high].weight)
462                         break;
463
464         if(real_speed[high].weight)
465         {
466                 if(real_speed[low].weight)
467                 {
468                         float f = float(i-low)/(high-low);
469                         return real_speed[low].speed*(1-f)+real_speed[high].speed*f;
470                 }
471                 else
472                         return real_speed[high].speed*float(i)/high;
473         }
474         else if(real_speed[low].weight)
475                 return real_speed[low].speed*float(i)/low;
476         else
477                 return 0;
478 }
479
480 unsigned Train::find_speed(float real) const
481 {
482         if(real<=real_speed[0].speed)
483                 return 0;
484
485         unsigned low = 0;
486         unsigned high = 0;
487         for(unsigned i=0; (!high && i<=14); ++i)
488                 if(real_speed[i].weight)
489                 {
490                         if(real_speed[i].speed<real)
491                                 low = i;
492                         else
493                                 high = i;
494                 }
495         if(!high)
496         {
497                 if(!low)
498                         return 0;
499                 return min(static_cast<unsigned>(low*real/real_speed[low].speed), 14U);
500         }
501
502         float f = (real-real_speed[low].speed)/(real_speed[high].speed-real_speed[low].speed);
503         return static_cast<unsigned>(low*(1-f)+high*f+0.5);
504 }
505
506 void Train::set_status(const string &s)
507 {
508         status = s;
509         signal_status_changed.emit(s);
510 }
511
512 void Train::set_position(const Block::Endpoint &bep)
513 {
514         cur_track = bep.track;
515         cur_track_ep = bep.track_ep;
516         offset = 0;
517         pos = cur_track->get_endpoint_position(cur_track_ep);
518 }
519
520 void Train::release_blocks(list<BlockRef> &blocks)
521 {
522         for(list<BlockRef>::iterator i=blocks.begin(); i!=blocks.end(); ++i)
523                 i->block->reserve(0);
524         blocks.clear();
525 }
526
527
528 Train::RealSpeed::RealSpeed():
529         speed(0),
530         weight(0)
531 { }
532
533 void Train::RealSpeed::add(float s, float w)
534 {
535         speed = (speed*weight+s*w)/(weight+w);
536         weight = min(weight+w, 300.0f);
537 }
538
539
540 Train::Loader::Loader(Train &t):
541         DataFile::BasicLoader<Train>(t)
542 {
543         add("name",        &Train::name);
544         add("real_speed",  &Loader::real_speed);
545 }
546
547 void Train::Loader::real_speed(unsigned i, float speed, float weight)
548 {
549         obj.real_speed[i].speed = speed;
550         obj.real_speed[i].weight = weight;
551 }
552
553 } // namespace Marklin