1 #include <msp/core/maputils.h>
2 #include <msp/core/raii.h>
4 #include "blockallocator.h"
9 #include "trackcircuit.h"
10 #include "trackiter.h"
19 struct BlockAllocator::BlockMatch
23 BlockMatch(const Block &b): block(b) { }
25 bool operator()(const BlockIter &bi) const { return &*bi==█ }
29 BlockAllocator::BlockAllocator(Train &t):
32 cur_blocks_end(blocks.end()),
38 reserve_pending(false)
40 Layout &layout = train.get_layout();
41 layout.signal_block_reserved.connect(sigc::mem_fun(this, &BlockAllocator::block_reserved));
42 layout.signal_sensor_state_changed.connect(sigc::mem_fun(this, &BlockAllocator::sensor_state_changed));
43 layout.get_driver().signal_halt.connect(sigc::mem_fun(this, &BlockAllocator::halt_event));
45 const set<Track *> &tracks = layout.get_all<Track>();
46 for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
47 if((*i)->get_type().is_turnout())
49 (*i)->signal_path_changing.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &BlockAllocator::turnout_path_changing), sigc::ref(**i))));
50 (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &BlockAllocator::turnout_path_changed), sigc::ref(**i))));
54 void BlockAllocator::set_active(bool a)
61 release_blocks_end(cur_blocks_end);
63 reserve_pending = false;
67 bool BlockAllocator::start_from(const BlockIter &block)
70 throw invalid_argument("BlockAllocator::start_from");
72 float remaining_length = 0;
73 unsigned n_vehs = train.get_n_vehicles();
74 for(unsigned i=0; i<n_vehs; ++i)
75 remaining_length += train.get_vehicle(i).get_type().get_length();
79 BlockList blocks_to_reserve;
80 for(BlockIter b=block; b; b=b.next())
84 blocks_to_reserve.push_back(b);
85 for(TrackIter t=b.track_iter(); (t && &t->get_block()==&*b); t=t.next())
86 remaining_length -= t->get_path_length();
87 if(remaining_length<=0)
91 if(remaining_length>0)
94 for(BlockList::iterator i=blocks_to_reserve.begin(); i!=blocks_to_reserve.end(); ++i)
99 (*i)->reserve(&train);
104 while(i!=blocks_to_reserve.begin())
116 void BlockAllocator::rewind_to(const Block &block)
121 BlockList::iterator i = find_if(cur_blocks_end, blocks.end(), BlockMatch(block));
124 release_blocks_end(i);
129 void BlockAllocator::clear()
131 release_blocks_begin(blocks.end());
138 void BlockAllocator::stop_at(const Block *block)
140 stop_at_block = block;
145 const BlockIter &BlockAllocator::first() const
148 throw logic_error("no blocks");
149 return blocks.front();
152 const BlockIter &BlockAllocator::last() const
155 throw logic_error("no blocks");
156 BlockList::const_iterator i = --blocks.end();
157 if(i->block()==pending_block)
162 const BlockIter &BlockAllocator::last_current() const
165 throw logic_error("no blocks");
166 if(cur_blocks_end==blocks.begin())
167 throw logic_error("internal error (no current blocks)");
168 BlockList::const_iterator i = cur_blocks_end;
172 const BlockIter &BlockAllocator::iter_for(const Block &block) const
174 BlockList::const_iterator i = find_if(blocks.begin(), blocks.end(), BlockMatch(block));
176 throw key_error(&block);
180 bool BlockAllocator::has_block(const Block &block) const
182 return find_if(blocks.begin(), blocks.end(), BlockMatch(block))!=blocks.end();
185 bool BlockAllocator::is_block_current(const Block &block) const
187 BlockList::const_iterator end = cur_blocks_end;
188 return find_if(blocks.begin(), end, BlockMatch(block))!=cur_blocks_end;
191 void BlockAllocator::tick()
195 reserve_pending = false;
200 void BlockAllocator::reserve_more()
203 throw logic_error("no blocks");
205 if(train.get_layout().get_driver().is_halted())
208 BlockIter start = blocks.back();
209 if(&*start==stop_at_block)
211 else if(&*start==pending_block)
213 TrackIter track = start.track_iter();
214 if(track->is_path_changing() || !track.endpoint().has_path(track->get_active_path()))
220 // See how many sensor blocks and how much track we already have
223 for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i)
225 if((*i)->get_sensor_address())
228 dist += (*i)->get_path_length(i->entry());
231 float approach_margin = 50*train.get_layout().get_catalogue().get_scale();
232 float min_dist = train.get_controller().get_braking_distance()*1.3+approach_margin*2;
234 BlockIter block = start;
236 SetFlag setf(reserving);
240 BlockIter prev = block;
241 block = block.next();
242 if(!block || block->get_endpoints().size()<2)
243 // The track ends here
246 if(block->get_turnout_address() && !prev->get_turnout_address())
248 /* We are arriving at a turnout. See if we have enough blocks and
249 distance reserved. */
250 if(nsens>=3 && dist>=min_dist)
254 if(!reserve_block(block))
256 pending_block = &*block;
260 if(cur_blocks_end==blocks.end())
263 TrackIter track = block.track_iter();
264 if(track->is_path_changing())
266 pending_block = &*block;
271 unsigned path = track->get_active_path();
272 if(!track.endpoint().has_path(path))
274 path = track->get_type().coerce_path(track.entry(), path);
275 track->set_active_path(path);
276 if(track->is_path_changing())
278 pending_block = &*block;
284 if(&*block==stop_at_block)
287 if(block->get_sensor_address())
290 dist += block->get_path_length(block.entry());
295 update_next_sensor(0);
296 // Immediately advance to just before the next sensor
297 advance_front(next_sensor);
301 bool BlockAllocator::reserve_block(const BlockIter &block)
303 /* Add it to the list first to present a consistent state in block_reserved
305 blocks.push_back(block);
307 bool first_reserve = (cur_blocks_end==blocks.end());
313 if(!block->reserve(&train))
316 cur_blocks_end = blocks.end();
326 cur_blocks_end = blocks.end();
332 void BlockAllocator::advance_front(const Block *block, bool inclusive)
334 BlockList::iterator end;
337 end = cur_blocks_end;
340 end = find_if(end, blocks.end(), BlockMatch(*block));
341 if(inclusive && end!=blocks.end())
347 if(end==blocks.end() && blocks.back().block()==pending_block)
350 SetFlag setf(advancing);
351 BlockList::iterator i = cur_blocks_end;
352 // Update cur_blocks_end first to keep things consistent.
353 cur_blocks_end = end;
355 signal_advanced.emit(**i, (*i)->get_sensor());
358 void BlockAllocator::advance_front(const Sensor *sensor)
361 advance_front(sensor->get_block(), dynamic_cast<const BeamGate *>(sensor));
363 advance_front(0, false);
366 void BlockAllocator::advance_back()
368 bool rev = train.get_controller().get_reverse();
369 const Vehicle &veh = train.get_vehicle(rev ? 0 : train.get_n_vehicles()-1);
370 const Block &veh_block = veh.get_placement().get_position(rev ? VehiclePlacement::FRONT_AXLE : VehiclePlacement::BACK_AXLE)->get_block();
372 bool pending_cleared = false;
374 /* Sensors aren't guaranteed to be detriggered in order. Go through the
375 block list and locate the first sensor that's still active. */
376 BlockList::iterator end = blocks.end();
377 for(BlockList::iterator i=blocks.begin(); i!=cur_blocks_end; ++i)
380 list<Sensor *> sensors;
382 /* Collect all sensors from the block in the order they are expected to
384 for(TrackIter j=i->track_iter(); (j && &j->get_block()==block); j=j.next())
385 if(!j->get_attachments().empty())
387 Track::AttachmentList attachments = j->get_attachments_ordered(j.entry());
388 for(Track::AttachmentList::const_iterator k=attachments.begin(); k!=attachments.end(); ++k)
389 if(BeamGate *gate = dynamic_cast<BeamGate *>(*k))
390 sensors.push_back(gate);
393 if(Sensor *sensor = (*i)->get_sensor())
394 sensors.push_back(sensor);
396 /* See if any sensor is still active, and record the position of the
397 last inactive sensor. */
398 bool active_sensor = false;
399 for(list<Sensor *>::const_iterator j=sensors.begin(); (!active_sensor && j!=sensors.end()); ++j)
401 if((*j)->get_state())
402 active_sensor = true;
407 if(block==pending_block)
408 pending_cleared = true;
410 // Stop if we encounter an active sensor or the train's last vehicle
411 if(block==&veh_block || active_sensor)
413 if(end!=blocks.end())
415 /* If the last inactive sensor was in an earlier block, release
416 that block as well. */
419 release_blocks_begin(end);
420 signal_rear_advanced.emit(*last());
431 void BlockAllocator::release_blocks_begin(const BlockList::iterator &end)
433 for(BlockList::iterator i=blocks.begin(); i!=end; )
437 void BlockAllocator::release_blocks_end(const BlockList::iterator &begin)
439 // Guard against decrementing blocks.begin()
440 if(begin==blocks.begin())
441 return release_blocks_begin(blocks.end());
443 if(begin==blocks.end())
446 /* Release the blocks in reverse order so that a consistent state is
447 presented in block_reserved signal. */
449 for(BlockList::iterator i=--blocks.end(); !done; )
456 void BlockAllocator::release_block(const BlockList::iterator &i)
459 throw logic_error("cannot release while advancing");
460 if(i==cur_blocks_end)
462 if(next_sensor && &**i==next_sensor->get_block())
464 if(&**i==pending_block)
472 void BlockAllocator::reverse()
474 release_blocks_end(cur_blocks_end);
476 for(BlockList::iterator i=blocks.begin(); i!=blocks.end(); ++i)
483 void BlockAllocator::turnout_path_changing(Track &track)
485 BlockList::iterator i = find_if(cur_blocks_end, blocks.end(), BlockMatch(track.get_block()));
489 release_blocks_end(i);
490 pending_block = &track.get_block();
494 void BlockAllocator::turnout_path_changed(Track &track)
496 if(&track.get_block()==pending_block && !reserving)
497 reserve_pending = true;
500 void BlockAllocator::block_reserved(Block &block, const Train *tr)
502 if(&block==pending_block && !tr && !reserving)
503 reserve_pending = true;
506 void BlockAllocator::sensor_state_changed(Sensor &sensor, Sensor::State state)
508 Block *block = sensor.get_block();
509 if(!block || block->get_train()!=&train)
512 if(state==Sensor::MAYBE_ACTIVE)
514 if(&sensor==next_sensor)
516 if(is_block_current(*block))
517 signal_advanced.emit(*block, &sensor);
518 update_next_sensor(next_sensor);
519 advance_front(next_sensor);
522 reserve_pending = true;
524 else if(!is_block_current(*block))
525 train.get_layout().emergency(block, "Sensor for "+train.get_name()+" triggered out of order");
527 else if(state==Sensor::INACTIVE)
531 void BlockAllocator::update_next_sensor(Sensor *after)
533 BeamGate *after_gate = dynamic_cast<BeamGate *>(after);
535 BlockList::iterator i = cur_blocks_end;
540 i = find_if(i, blocks.end(), BlockMatch(*after->get_block()));
543 for(; i!=blocks.end(); ++i)
545 if(Sensor *sensor = (*i)->get_sensor())
547 if(!after_gate && sensor!=next_sensor)
549 next_sensor = sensor;
555 for(TrackIter j=i->track_iter(); (j && &j->get_block()==block); j=j.next())
556 if(!j->get_attachments().empty())
558 Track::AttachmentList attachments = j->get_attachments_ordered(j.entry());
559 for(Track::AttachmentList::const_iterator k=attachments.begin(); k!=attachments.end(); ++k)
560 if(BeamGate *gate = dynamic_cast<BeamGate *>(*k))
579 void BlockAllocator::halt_event(bool halted)
581 if(active && !halted)
585 void BlockAllocator::save(list<DataFile::Statement> &st) const
587 if(!blocks.empty() && cur_blocks_end!=blocks.begin())
589 BlockList cur_blocks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
591 if(train.get_controller().get_reverse())
593 cur_blocks.reverse();
594 prev = cur_blocks.front().next();
597 prev = cur_blocks.front().flip();
599 st.push_back((DataFile::Statement("hint"), prev->get_id()));
601 for(BlockList::const_iterator i=cur_blocks.begin(); (i!=cur_blocks.end() && i->block()!=pending_block); ++i)
602 st.push_back((DataFile::Statement("block"), (*i)->get_id()));
607 BlockAllocator::Loader::Loader(BlockAllocator &ba):
608 DataFile::ObjectLoader<BlockAllocator>(ba),
611 add("block", &Loader::block);
612 add("hint", &Loader::hint);
615 void BlockAllocator::Loader::block(unsigned id)
623 blk = &obj.train.get_layout().get_block(id);
625 catch(const key_error &)
633 entry = blk->get_endpoint_by_link(*prev_block);
637 obj.blocks.push_back(BlockIter(blk, entry));
638 blk->reserve(&obj.train);
640 if(blk->get_sensor_address())
641 obj.train.get_layout().get_driver().set_sensor(blk->get_sensor_address(), true);
646 void BlockAllocator::Loader::hint(unsigned id)
650 prev_block = &obj.train.get_layout().get_block(id);
652 catch(const key_error &)