]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/blockallocator.cpp
Fix some issues with BlockAllocator::release_blocks_end
[r2c2.git] / source / libr2c2 / blockallocator.cpp
1 #include <msp/core/maputils.h>
2 #include <msp/core/raii.h>
3 #include "blockallocator.h"
4 #include "block.h"
5 #include "catalogue.h"
6 #include "driver.h"
7 #include "layout.h"
8 #include "trackcircuit.h"
9 #include "trackiter.h"
10 #include "train.h"
11 #include "vehicle.h"
12
13 using namespace std;
14 using namespace Msp;
15
16 namespace R2C2 {
17
18 struct BlockAllocator::BlockMatch
19 {
20         const Block &block;
21
22         BlockMatch(const Block &b): block(b) { }
23
24         bool operator()(const BlockIter &bi) const { return &*bi==&block; }
25 };
26
27
28 BlockAllocator::BlockAllocator(Train &t):
29         train(t),
30         cur_blocks_end(blocks.end()),
31         pending_block(0),
32         stop_at_block(0),
33         reserving(false)
34 {
35         Layout &layout = train.get_layout();
36         layout.signal_block_reserved.connect(sigc::mem_fun(this, &BlockAllocator::block_reserved));
37         layout.signal_sensor_state_changed.connect(sigc::mem_fun(this, &BlockAllocator::sensor_state_changed));
38
39         const set<Track *> &tracks = layout.get_all<Track>();
40         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
41                 if((*i)->get_turnout_id())
42                         (*i)->signal_path_changed.connect(sigc::hide(sigc::bind(sigc::mem_fun(this, &BlockAllocator::turnout_path_changed), sigc::ref(**i))));
43 }
44
45 void BlockAllocator::start_from(const BlockIter &block)
46 {
47         if(!block)
48                 throw invalid_argument("BlockAllocator::start_from");
49
50         clear();
51         reserve_block(block);
52 }
53
54 void BlockAllocator::clear()
55 {
56         release_blocks_begin(blocks.end());
57         pending_block = 0;
58         stop_at_block = 0;
59 }
60
61 void BlockAllocator::stop_at(const Block *block)
62 {
63         stop_at_block = block;
64 }
65
66 const BlockIter &BlockAllocator::first() const
67 {
68         if(blocks.empty())
69                 throw logic_error("no blocks");
70         return blocks.front();
71 }
72
73 const BlockIter &BlockAllocator::last() const
74 {
75         if(blocks.empty())
76                 throw logic_error("no blocks");
77         BlockList::const_iterator i = --blocks.end();
78         if(i->block()==pending_block)
79                 --i;
80         return *i;
81 }
82
83 const BlockIter &BlockAllocator::last_current() const
84 {
85         if(blocks.empty())
86                 throw logic_error("no blocks");
87         if(cur_blocks_end==blocks.begin())
88                 throw logic_error("internal error (no current blocks)");
89         BlockList::const_iterator i = cur_blocks_end;
90         return *--i;
91 }
92
93 const BlockIter &BlockAllocator::iter_for(const Block &block) const
94 {
95         BlockList::const_iterator i = find_if(blocks.begin(), blocks.end(), IterBlockMatch(block));
96         if(i==blocks.end())
97                 throw key_error(&block);
98         return *i;
99 }
100
101 bool BlockAllocator::has_block(const Block &block) const
102 {
103         return find_if(blocks.begin(), blocks.end(), IterBlockMatch(block))!=blocks.end();
104 }
105
106 bool BlockAllocator::is_block_current(const Block &block) const
107 {
108         return find_if(blocks.begin(), cur_blocks_end, IterBlockMatch(block))!=cur_blocks_end;
109 }
110
111 void BlockAllocator::reserve_more()
112 {
113         if(blocks.empty())
114                 throw logic_error("no blocks");
115
116         BlockIter start = blocks.back();
117         if(&*start==stop_at_block)
118                 return;
119         else if(&*start==pending_block)
120         {
121                 TrackIter track = start.track_iter();
122                 if(!track.endpoint().has_path(track->get_active_path()))
123                         return;
124         }
125
126         pending_block = 0;
127
128         // See how many sensor blocks and how much track we already have
129         unsigned nsens = 0;
130         float dist = 0;
131         for(BlockList::const_iterator i=cur_blocks_end; i!=blocks.end(); ++i)
132         {
133                 if((*i)->get_sensor_id())
134                         ++nsens;
135                 if(nsens>0)
136                         dist += (*i)->get_path_length(i->entry());
137         }
138
139         float approach_margin = 50*train.get_layout().get_catalogue().get_scale();
140         float min_dist = train.get_controller().get_braking_distance()*1.3+approach_margin*2;
141
142         BlockIter block = start;
143
144         SetFlag setf(reserving);
145
146         while(1)
147         {
148                 BlockIter prev = block;
149                 block = block.next();
150                 if(!block || block->get_endpoints().size()<2)
151                         // The track ends here
152                         break;
153
154                 if(block->get_turnout_id() && !prev->get_turnout_id())
155                 {
156                         /* We are arriving at a turnout.  See if we have enough blocks and
157                         distance reserved. */
158                         if(nsens>=3 && dist>=min_dist)
159                                 break;
160                 }
161
162                 if(!reserve_block(block))
163                         break;
164
165                 if(cur_blocks_end==blocks.end())
166                         --cur_blocks_end;
167
168                 TrackIter track = block.track_iter();
169                 if(track->is_path_changing())
170                 {
171                         pending_block = &*block;
172                         break;
173                 }
174                 else
175                 {
176                         const TrackType::Endpoint &entry_ep = track.endpoint();
177                         unsigned path = track->get_active_path();
178                         if(!entry_ep.has_path(path))
179                         {
180                                 const TrackType::Endpoint &exit_ep = track.reverse().endpoint();
181                                 if(entry_ep.has_common_paths(exit_ep))
182                                 {
183                                         unsigned mask = entry_ep.paths&exit_ep.paths;
184                                         for(path=0; mask>1; ++path, mask>>=1) ;
185
186                                         track->set_active_path(path);
187                                         if(track->is_path_changing())
188                                         {
189                                                 pending_block = &*block;
190                                                 break;
191                                         }
192                                 }
193                                 else
194                                         // XXX Do something here
195                                         break;
196                         }
197                 }
198
199                 if(&*block==stop_at_block)
200                         break;
201
202                 if(block->get_sensor_id())
203                         ++nsens;
204                 if(nsens>0)
205                         dist += block->get_path_length(block.entry());
206         }
207
208         // Make any sensorless blocks at the beginning immediately current
209         while(cur_blocks_end!=blocks.end() && !(*cur_blocks_end)->get_sensor_id())
210                 ++cur_blocks_end;
211 }
212
213 bool BlockAllocator::reserve_block(const BlockIter &block)
214 {
215         /* Add it to the list first to present a consistent state in block_reserved
216         signal. */
217         blocks.push_back(block);
218         try
219         {
220                 if(!block->reserve(&train))
221                 {
222                         blocks.pop_back();
223                         return false;
224                 }
225
226                 return true;
227         }
228         catch(...)
229         {
230                 blocks.pop_back();
231                 throw;
232         }
233 }
234
235 bool BlockAllocator::release_from(const Block &block)
236 {
237         bool have_sensor = false;
238         for(BlockList::iterator i=cur_blocks_end; i!=blocks.end(); ++i)
239         {
240                 if(i->block()==&block)
241                 {
242                         if(have_sensor)
243                                 release_blocks_end(i);
244                         return have_sensor;
245                 }
246                 else if((*i)->get_sensor_id())
247                         have_sensor = true;
248         }
249
250         return false;
251 }
252
253 void BlockAllocator::release_noncurrent()
254 {
255         release_blocks_end(cur_blocks_end);
256 }
257
258 void BlockAllocator::release_blocks_begin(const BlockList::iterator &end)
259 {
260         for(BlockList::iterator i=blocks.begin(); i!=end; )
261                 release_block(i++);
262 }
263
264 void BlockAllocator::release_blocks_end(const BlockList::iterator &begin)
265 {
266         // Guard against decrementing blocks.begin()
267         if(begin==blocks.begin())
268                 return release_blocks_begin(blocks.end());
269
270         if(begin==blocks.end())
271                 return;
272
273         /* Release the blocks in reverse order so that a consistent state is
274         presented in block_reserved signal. */
275         bool done = false;
276         for(BlockList::iterator i=--blocks.end(); !done; )
277         {
278                 done = (i==begin);
279                 release_block(i--);
280         }
281 }
282
283 void BlockAllocator::release_block(const BlockList::iterator &i)
284 {
285         if(i==cur_blocks_end)
286                 ++cur_blocks_end;
287         if(&**i==pending_block)
288                 pending_block = 0;
289
290         Block &block = **i;
291         blocks.erase(i);
292         block.reserve(0);
293 }
294
295 void BlockAllocator::reverse()
296 {
297         release_noncurrent();
298         blocks.reverse();
299         for(BlockList::iterator i=blocks.begin(); i!=blocks.end(); ++i)
300                 *i = i->reverse();
301 }
302
303 void BlockAllocator::turnout_path_changed(Track &track)
304 {
305         if(&track.get_block()==pending_block && !reserving)
306                 reserve_more();
307 }
308
309 void BlockAllocator::block_reserved(Block &block, const Train *tr)
310 {
311         if(&block==pending_block && !tr && !reserving)
312                 reserve_more();
313 }
314
315 void BlockAllocator::sensor_state_changed(Sensor &sensor, Sensor::State state)
316 {
317         Block *block = 0;
318         if(TrackCircuit *tc = dynamic_cast<TrackCircuit *>(&sensor))
319                 block = &tc->get_block();
320         else
321                 return;
322
323         if(block->get_train()!=&train)
324                 return;
325
326         if(state==Sensor::MAYBE_ACTIVE)
327         {
328                 // Find the first sensor block from our reserved blocks that isn't this sensor
329                 BlockList::iterator end;
330                 unsigned result = 0;
331                 for(end=cur_blocks_end; end!=blocks.end(); ++end)
332                         if((*end)->get_sensor_id())
333                         {
334                                 if(&**end!=block)
335                                 {
336                                         if(result==0)
337                                                 result = 2;
338                                         else if(result==1)
339                                                 break;
340                                 }
341                                 else if(result==0)
342                                         result = 1;
343                                 else if(result==2)
344                                         result = 3;
345                         }
346
347                 if(result==1)
348                 {
349                         // Move blocks up to the next sensor to our current blocks
350                         for(BlockList::iterator j=cur_blocks_end; j!=end; ++j)
351                                 train.signal_advanced.emit(**j);
352                         cur_blocks_end = end;
353                 }
354                 else if(result==3)
355                         train.get_layout().emergency("Sensor for "+train.get_name()+" triggered out of order");
356         }
357         else if(state==Sensor::INACTIVE)
358         {
359                 const Vehicle &veh = train.get_vehicle(train.get_controller().get_reverse() ? 0 : train.get_n_vehicles()-1);
360                 const Block &veh_block = veh.get_track()->get_block();
361                 const Driver &driver = train.get_layout().get_driver();
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                         // Avoid freeing blocks that still hold the train's vehicles
369                         if(&**i==&veh_block)
370                                 break;
371
372                         if((*i)->get_sensor_id())
373                         {
374                                 if(driver.get_sensor((*i)->get_sensor_id()))
375                                         break;
376                                 else
377                                         end = i;
378                         }
379                 }
380                 
381                 if(end!=blocks.end())
382                         // Free blocks up to the last inactive sensor
383                         release_blocks_begin(++end);
384         }
385 }
386
387 void BlockAllocator::save(list<DataFile::Statement> &st) const
388 {
389         if(!blocks.empty() && cur_blocks_end!=blocks.begin())
390         {
391                 BlockList cur_blocks(blocks.begin(), BlockList::const_iterator(cur_blocks_end));
392                 BlockIter prev;
393                 if(train.get_controller().get_reverse())
394                 {
395                         cur_blocks.reverse();
396                         prev = cur_blocks.front().next();
397                 }
398                 else
399                         prev = cur_blocks.front().flip();
400
401                 st.push_back((DataFile::Statement("hint"), prev->get_id()));
402
403                 for(BlockList::const_iterator i=cur_blocks.begin(); i!=cur_blocks.end(); ++i)
404                         st.push_back((DataFile::Statement("block"), (*i)->get_id()));
405         }
406 }
407
408
409 BlockAllocator::Loader::Loader(BlockAllocator &ba):
410         DataFile::ObjectLoader<BlockAllocator>(ba),
411         valid(true)
412 {
413         add("block", &Loader::block);
414         add("hint",  &Loader::hint);
415 }
416
417 void BlockAllocator::Loader::block(unsigned id)
418 {
419         if(!valid)
420                 return;
421
422         Block *blk;
423         try
424         {
425                 blk = &obj.train.get_layout().get_block(id);
426         }
427         catch(const key_error &)
428         {
429                 valid = false;
430                 return;
431         }
432
433         int entry = -1;
434         if(prev_block)
435                 entry = blk->get_endpoint_by_link(*prev_block);
436         if(entry<0)
437                 entry = 0;
438
439         obj.blocks.push_back(BlockIter(blk, entry));
440         blk->reserve(&obj.train);
441
442         if(blk->get_sensor_id())
443                 obj.train.get_layout().get_driver().set_sensor(blk->get_sensor_id(), true);
444
445         prev_block = blk;
446 }
447
448 void BlockAllocator::Loader::hint(unsigned id)
449 {
450         try
451         {
452                 prev_block = &obj.train.get_layout().get_block(id);
453         }
454         catch(const key_error &)
455         {
456                 valid = false;
457         }
458 }
459
460 } // namespace R2C2