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