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