]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/blockallocator.cpp
79274b77ded54cd6df67fb7e38329e36a2a4b03a
[r2c2.git] / source / libr2c2 / blockallocator.cpp
1 #include <msp/core/maputils.h>
2 #include <msp/core/raii.h>
3 #include "beamgate.h"
4 #include "blockallocator.h"
5 #include "block.h"
6 #include "catalogue.h"
7 #include "driver.h"
8 #include "layout.h"
9 #include "trackcircuit.h"
10 #include "trackiter.h"
11 #include "train.h"
12 #include "vehicle.h"
13
14 using namespace std;
15 using namespace Msp;
16
17 namespace R2C2 {
18
19 struct BlockAllocator::BlockMatch
20 {
21         const Block &block;
22
23         BlockMatch(const Block &b): block(b) { }
24
25         bool operator()(const BlockIter &bi) const { return &*bi==&block; }
26 };
27
28
29 BlockAllocator::BlockAllocator(Train &t):
30         train(t),
31         active(false),
32         cur_blocks_end(blocks.end()),
33         next_sensor(0),
34         pending_block(0),
35         stop_at_block(0),
36         reserving(false),
37         advancing(false)
38 {
39         Layout &layout = train.get_layout();
40         layout.signal_block_reserved.connect(sigc::mem_fun(this, &BlockAllocator::block_reserved));
41         layout.signal_sensor_state_changed.connect(sigc::mem_fun(this, &BlockAllocator::sensor_state_changed));
42         layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &BlockAllocator::halt_event));
43
44         const set<Track *> &tracks = layout.get_all<Track>();
45         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
46                 if((*i)->get_type().is_turnout())
47                 {
48                         (*i)->signal_path_changing.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &BlockAllocator::turnout_path_changing), sigc::ref(**i))));
49                         (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &BlockAllocator::turnout_path_changed), sigc::ref(**i))));
50                 }
51 }
52
53 void BlockAllocator::set_active(bool a)
54 {
55         active = a;
56         if(active)
57                 reserve_more();
58         else
59         {
60                 release_blocks_end(cur_blocks_end);
61                 pending_block = 0;
62         }
63 }
64
65 bool BlockAllocator::start_from(const BlockIter &block)
66 {
67         if(!block)
68                 throw invalid_argument("BlockAllocator::start_from");
69
70         float remaining_length = 0;
71         unsigned n_vehs = train.get_n_vehicles();
72         for(unsigned i=0; i<n_vehs; ++i)
73                 remaining_length += train.get_vehicle(i).get_type().get_length();
74
75         clear();
76
77         BlockList blocks_to_reserve;
78         for(BlockIter b=block; b; b=b.next())
79         {
80                 if(b->get_train())
81                         break;
82                 blocks_to_reserve.push_back(b);
83                 for(TrackIter t=b.track_iter(); (t && &t->get_block()==&*b); t=t.next())
84                         remaining_length -= t->get_path_length();
85                 if(remaining_length<=0)
86                         break;
87         }
88
89         if(remaining_length>0)
90                 return false;
91
92         for(BlockList::iterator i=blocks_to_reserve.begin(); i!=blocks_to_reserve.end(); ++i)
93         {
94                 blocks.push_back(*i);
95                 try
96                 {
97                         (*i)->reserve(&train);
98                 }
99                 catch(...)
100                 {
101                         blocks.pop_back();
102                         while(i!=blocks_to_reserve.begin())
103                         {
104                                 blocks.pop_back();
105                                 (*--i)->reserve(0);
106                         }
107                         throw;
108                 }
109         }
110
111         return true;
112 }
113
114 void BlockAllocator::rewind_to(const Block &block)
115 {
116         if(!active)
117                 return;
118
119         BlockList::iterator i = find_if(cur_blocks_end, blocks.end(), BlockMatch(block));
120         if(i!=blocks.end())
121         {
122                 release_blocks_end(i);
123                 reserve_more();
124         }
125 }
126
127 void BlockAllocator::clear()
128 {
129         release_blocks_begin(blocks.end());
130         active = false;
131         next_sensor = 0;
132         pending_block = 0;
133         stop_at_block = 0;
134 }
135
136 void BlockAllocator::stop_at(const Block *block)
137 {
138         stop_at_block = block;
139         if(active && !block)
140                 reserve_more();
141 }
142
143 const BlockIter &BlockAllocator::first() const
144 {
145         if(blocks.empty())
146                 throw logic_error("no blocks");
147         return blocks.front();
148 }
149
150 const BlockIter &BlockAllocator::last() const
151 {
152         if(blocks.empty())
153                 throw logic_error("no blocks");
154         BlockList::const_iterator i = --blocks.end();
155         if(i->block()==pending_block)
156                 --i;
157         return *i;
158 }
159
160 const BlockIter &BlockAllocator::last_current() const
161 {
162         if(blocks.empty())
163                 throw logic_error("no blocks");
164         if(cur_blocks_end==blocks.begin())
165                 throw logic_error("internal error (no current blocks)");
166         BlockList::const_iterator i = cur_blocks_end;
167         return *--i;
168 }
169
170 const BlockIter &BlockAllocator::iter_for(const Block &block) const
171 {
172         BlockList::const_iterator i = find_if(blocks.begin(), blocks.end(), BlockMatch(block));
173         if(i==blocks.end())
174                 throw key_error(&block);
175         return *i;
176 }
177
178 bool BlockAllocator::has_block(const Block &block) const
179 {
180         return find_if(blocks.begin(), blocks.end(), BlockMatch(block))!=blocks.end();
181 }
182
183 bool BlockAllocator::is_block_current(const Block &block) const
184 {
185         BlockList::const_iterator end = cur_blocks_end;
186         return find_if(blocks.begin(), end, BlockMatch(block))!=cur_blocks_end;
187 }
188
189 void BlockAllocator::reserve_more()
190 {
191         if(blocks.empty())
192                 throw logic_error("no blocks");
193
194         if(train.get_layout().get_driver().is_halted())
195                 return;
196
197         BlockIter start = blocks.back();
198         if(&*start==stop_at_block)
199                 return;
200         else if(&*start==pending_block)
201         {
202                 TrackIter track = start.track_iter();
203                 if(track->is_path_changing() || !track.endpoint().has_path(track->get_active_path()))
204                         return;
205         }
206
207         pending_block = 0;
208
209         // See how many sensor blocks and how much track we already have
210         unsigned nsens = 0;
211         float dist = 0;
212         for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i)
213         {
214                 if((*i)->get_sensor_address())
215                         ++nsens;
216                 if(nsens>0)
217                         dist += (*i)->get_path_length(i->entry());
218         }
219
220         float approach_margin = 50*train.get_layout().get_catalogue().get_scale();
221         float min_dist = train.get_controller().get_braking_distance()*1.3+approach_margin*2;
222
223         BlockIter block = start;
224
225         SetFlag setf(reserving);
226
227         while(1)
228         {
229                 BlockIter prev = block;
230                 block = block.next();
231                 if(!block || block->get_endpoints().size()<2)
232                         // The track ends here
233                         break;
234
235                 if(block->get_turnout_address() && !prev->get_turnout_address())
236                 {
237                         /* We are arriving at a turnout.  See if we have enough blocks and
238                         distance reserved. */
239                         if(nsens>=3 && dist>=min_dist)
240                                 break;
241                 }
242
243                 if(!reserve_block(block))
244                 {
245                         pending_block = &*block;
246                         break;
247                 }
248
249                 if(cur_blocks_end==blocks.end())
250                         --cur_blocks_end;
251
252                 TrackIter track = block.track_iter();
253                 if(track->is_path_changing())
254                 {
255                         pending_block = &*block;
256                         break;
257                 }
258                 else
259                 {
260                         unsigned path = track->get_active_path();
261                         if(!track.endpoint().has_path(path))
262                         {
263                                 path = track->get_type().coerce_path(track.entry(), path);
264                                 track->set_active_path(path);
265                                 if(track->is_path_changing())
266                                 {
267                                         pending_block = &*block;
268                                         break;
269                                 }
270                         }
271                 }
272
273                 if(&*block==stop_at_block)
274                         break;
275
276                 if(block->get_sensor_address())
277                         ++nsens;
278                 if(nsens>0)
279                         dist += block->get_path_length(block.entry());
280         }
281
282         if(!next_sensor)
283         {
284                 update_next_sensor(0);
285                 // Immediately advance to just before the next sensor
286                 advance_front(next_sensor);
287         }
288 }
289
290 bool BlockAllocator::reserve_block(const BlockIter &block)
291 {
292         /* Add it to the list first to present a consistent state in block_reserved
293         signal. */
294         blocks.push_back(block);
295
296         bool first_reserve = (cur_blocks_end==blocks.end());
297         if(first_reserve)
298                 --cur_blocks_end;
299
300         try
301         {
302                 if(!block->reserve(&train))
303                 {
304                         if(first_reserve)
305                                 cur_blocks_end = blocks.end();
306                         blocks.pop_back();
307                         return false;
308                 }
309
310                 return true;
311         }
312         catch(...)
313         {
314                 if(first_reserve)
315                         cur_blocks_end = blocks.end();
316                 blocks.pop_back();
317                 throw;
318         }
319 }
320
321 void BlockAllocator::advance_front(const Block *block, bool inclusive)
322 {
323         BlockList::iterator end;
324         if(block)
325         {
326                 end = cur_blocks_end;
327                 if(inclusive)
328                         --end;
329                 end = find_if(end, blocks.end(), BlockMatch(*block));
330                 if(inclusive && end!=blocks.end())
331                         ++end;
332         }
333         else
334                 end = blocks.end();
335
336         if(end==blocks.end() && blocks.back().block()==pending_block)
337                 --end;
338
339         SetFlag setf(advancing);
340         BlockList::iterator i = cur_blocks_end;
341         // Update cur_blocks_end first to keep things consistent.
342         cur_blocks_end = end;
343         for(; i!=end; ++i)
344                 signal_advanced.emit(**i, (*i)->get_sensor());
345 }
346
347 void BlockAllocator::advance_front(const Sensor *sensor)
348 {
349         if(sensor)
350                 advance_front(sensor->get_block(), dynamic_cast<const BeamGate *>(sensor));
351         else
352                 advance_front(0, false);
353 }
354
355 void BlockAllocator::advance_back()
356 {
357         bool rev = train.get_controller().get_reverse();
358         const Vehicle &veh = train.get_vehicle(rev ? 0 : train.get_n_vehicles()-1);
359         const Block &veh_block = veh.get_placement().get_position(rev ? VehiclePlacement::FRONT_AXLE : VehiclePlacement::BACK_AXLE)->get_block();
360
361         bool pending_cleared = false;
362
363         /* Sensors aren't guaranteed to be detriggered in order.  Go through the
364         block list and locate the first sensor that's still active. */
365         BlockList::iterator end = blocks.end();
366         for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
367         {
368                 Block *block = &**i;
369                 list<Sensor *> sensors;
370
371                 /* Collect all sensors from the block in the order they are expected to
372                 detrigger. */
373                 for(TrackIter j=i->track_iter(); (j && &j->get_block()==block); j=j.next())
374                         if(!j->get_attachments().empty())
375                         {
376                                 Track::AttachmentList attachments = j->get_attachments_ordered(j.entry());
377                                 for(Track::AttachmentList::const_iterator k=attachments.begin(); k!=attachments.end(); ++k)
378                                         if(BeamGate *gate = dynamic_cast<BeamGate *>(*k))
379                                                 sensors.push_back(gate);
380                         }
381
382                 if(Sensor *sensor = (*i)->get_sensor())
383                         sensors.push_back(sensor);
384
385                 /* See if any sensor is still active, and record the position of the
386                 last inactive sensor. */
387                 bool active_sensor = false;
388                 for(list<Sensor *>::const_iterator j=sensors.begin(); (!active_sensor && j!=sensors.end()); ++j)
389                 {
390                         if((*j)->get_state())
391                                 active_sensor = true;
392                         else
393                                 end = i;
394                 }
395
396                 if(block==pending_block)
397                         pending_cleared = true;
398
399                 // Stop if we encounter an active sensor or the train's last vehicle
400                 if(block==&veh_block || active_sensor)
401                 {
402                         if(end!=blocks.end())
403                         {
404                                 /* If the last inactive sensor was in an earlier block, release
405                                 that block as well. */
406                                 if(i!=end)
407                                         ++end;
408                                 release_blocks_begin(end);
409                                 signal_rear_advanced.emit(*last());
410                         }
411
412                         if(pending_cleared)
413                                 reserve_more();
414
415                         return;
416                 }
417         }
418 }
419
420 void BlockAllocator::release_blocks_begin(const BlockList::iterator &end)
421 {
422         for(BlockList::iterator i=blocks.begin(); i!=end; )
423                 release_block(i++);
424 }
425
426 void BlockAllocator::release_blocks_end(const BlockList::iterator &begin)
427 {
428         // Guard against decrementing blocks.begin()
429         if(begin==blocks.begin())
430                 return release_blocks_begin(blocks.end());
431
432         if(begin==blocks.end())
433                 return;
434
435         /* Release the blocks in reverse order so that a consistent state is
436         presented in block_reserved signal. */
437         bool done = false;
438         for(BlockList::iterator i=--blocks.end(); !done; )
439         {
440                 done = (i==begin);
441                 release_block(i--);
442         }
443 }
444
445 void BlockAllocator::release_block(const BlockList::iterator &i)
446 {
447         if(advancing)
448                 throw logic_error("cannot release while advancing");
449         if(i==cur_blocks_end)
450                 ++cur_blocks_end;
451         if(next_sensor && &**i==next_sensor->get_block())
452                 next_sensor = 0;
453         if(&**i==pending_block)
454                 pending_block = 0;
455
456         Block &block = **i;
457         blocks.erase(i);
458         block.reserve(0);
459 }
460
461 void BlockAllocator::reverse()
462 {
463         release_blocks_end(cur_blocks_end);
464         blocks.reverse();
465         for(BlockList::iterator i=blocks.begin(); i!=blocks.end(); ++i)
466                 *i = i->reverse();
467
468         if(active)
469                 reserve_more();
470 }
471
472 void BlockAllocator::turnout_path_changing(Track &track)
473 {
474         BlockList::iterator i = find_if(cur_blocks_end, blocks.end(), BlockMatch(track.get_block()));
475         if(i!=blocks.end())
476         {
477                 ++i;
478                 release_blocks_end(i);
479                 pending_block = &track.get_block();
480         }
481 }
482
483 void BlockAllocator::turnout_path_changed(Track &track)
484 {
485         if(&track.get_block()==pending_block && !reserving)
486                 reserve_more();
487 }
488
489 void BlockAllocator::block_reserved(Block &block, const Train *tr)
490 {
491         if(&block==pending_block && !tr && !reserving)
492                 reserve_more();
493 }
494
495 void BlockAllocator::sensor_state_changed(Sensor &sensor, Sensor::State state)
496 {
497         Block *block = sensor.get_block();
498         if(!block || block->get_train()!=&train)
499                 return;
500
501         if(state==Sensor::MAYBE_ACTIVE)
502         {
503                 if(&sensor==next_sensor)
504                 {
505                         if(is_block_current(*block))
506                                 signal_advanced.emit(*block, &sensor);
507                         update_next_sensor(next_sensor);
508                         advance_front(next_sensor);
509
510                         if(active)
511                                 reserve_more();
512                 }
513                 else if(!is_block_current(*block))
514                         train.get_layout().emergency(block, "Sensor for "+train.get_name()+" triggered out of order");
515         }
516         else if(state==Sensor::INACTIVE)
517                 advance_back();
518 }
519
520 void BlockAllocator::update_next_sensor(Sensor *after)
521 {
522         BeamGate *after_gate = dynamic_cast<BeamGate *>(after);
523
524         BlockList::iterator i = cur_blocks_end;
525         if(after)
526         {
527                 if(after_gate)
528                         --i;
529                 i = find_if(i, blocks.end(), BlockMatch(*after->get_block()));
530         }
531
532         for(; i!=blocks.end(); ++i)
533         {
534                 if(Sensor *sensor = (*i)->get_sensor())
535                 {
536                         if(!after_gate && sensor!=next_sensor)
537                         {
538                                 next_sensor = sensor;
539                                 return;
540                         }
541                 }
542
543                 Block *block = &**i;
544                 for(TrackIter j=i->track_iter(); (j && &j->get_block()==block); j=j.next())
545                         if(!j->get_attachments().empty())
546                         {
547                                 Track::AttachmentList attachments = j->get_attachments_ordered(j.entry());
548                                 for(Track::AttachmentList::const_iterator k=attachments.begin(); k!=attachments.end(); ++k)
549                                         if(BeamGate *gate = dynamic_cast<BeamGate *>(*k))
550                                         {
551                                                 if(after_gate)
552                                                 {
553                                                         if(gate==after_gate)
554                                                                 after_gate = 0;
555                                                 }
556                                                 else
557                                                 {
558                                                         next_sensor = gate;
559                                                         return;
560                                                 }
561                                         }
562                         }
563         }
564
565         next_sensor = 0;
566 }
567
568 void BlockAllocator::halt_event(bool halted)
569 {
570         if(active && !halted)
571                 reserve_more();
572 }
573
574 void BlockAllocator::save(list<DataFile::Statement> &st) const
575 {
576         if(!blocks.empty() && cur_blocks_end!=blocks.begin())
577         {
578                 BlockList cur_blocks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
579                 BlockIter prev;
580                 if(train.get_controller().get_reverse())
581                 {
582                         cur_blocks.reverse();
583                         prev = cur_blocks.front().next();
584                 }
585                 else
586                         prev = cur_blocks.front().flip();
587
588                 st.push_back((DataFile::Statement("hint"), prev->get_id()));
589
590                 for(BlockList::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
591                         st.push_back((DataFile::Statement("block"), (*i)->get_id()));
592         }
593 }
594
595
596 BlockAllocator::Loader::Loader(BlockAllocator &ba):
597         DataFile::ObjectLoader<BlockAllocator>(ba),
598         valid(true)
599 {
600         add("block", &Loader::block);
601         add("hint",  &Loader::hint);
602 }
603
604 void BlockAllocator::Loader::block(unsigned id)
605 {
606         if(!valid)
607                 return;
608
609         Block *blk;
610         try
611         {
612                 blk = &obj.train.get_layout().get_block(id);
613         }
614         catch(const key_error &)
615         {
616                 valid = false;
617                 return;
618         }
619
620         int entry = -1;
621         if(prev_block)
622                 entry = blk->get_endpoint_by_link(*prev_block);
623         if(entry<0)
624                 entry = 0;
625
626         obj.blocks.push_back(BlockIter(blk, entry));
627         blk->reserve(&obj.train);
628
629         if(blk->get_sensor_address())
630                 obj.train.get_layout().get_driver().set_sensor(blk->get_sensor_address(), true);
631
632         prev_block = blk;
633 }
634
635 void BlockAllocator::Loader::hint(unsigned id)
636 {
637         try
638         {
639                 prev_block = &obj.train.get_layout().get_block(id);
640         }
641         catch(const key_error &)
642         {
643                 valid = false;
644         }
645 }
646
647 } // namespace R2C2