]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/layout.cpp
Support inverted sensors that give low output when active
[r2c2.git] / source / libr2c2 / layout.cpp
1 #include <algorithm>
2 #include <msp/core/maputils.h>
3 #include <msp/core/refptr.h>
4 #include <msp/datafile/parser.h>
5 #include <msp/datafile/writer.h>
6 #include <msp/io/print.h>
7 #include <msp/time/utils.h>
8 #include "block.h"
9 #include "catalogue.h"
10 #include "driver.h"
11 #include "layout.h"
12 #include "route.h"
13 #include "signal.h"
14 #include "signaltype.h"
15 #include "track.h"
16 #include "trackcircuit.h"
17 #include "tracktype.h"
18 #include "train.h"
19 #include "vehicle.h"
20 #include "vehicletype.h"
21 #include "zone.h"
22
23 using namespace std;
24 using namespace Msp;
25
26 namespace {
27
28 bool zone_order(const R2C2::Zone *z1, const R2C2::Zone *z2)
29 {
30         return z1->get_number()<z2->get_number();
31 }
32
33 }
34
35
36 namespace R2C2 {
37
38 Layout::Layout(Catalogue &c, Driver *d):
39         catalogue(c),
40         driver(d),
41         next_turnout_id(0x800)
42 {
43         clock.set_rate(60);
44 }
45
46 Layout::~Layout()
47 {
48         delete driver;
49         driver = 0;
50
51         while(!trains.empty())
52                 delete trains.begin()->second;
53         track_chains.del<Route>();
54         track_chains.del<Zone>();
55         objects.del<Signal>();
56         objects.del<Track>();
57         track_chains.del<Block>();
58 }
59
60 Driver &Layout::get_driver() const
61 {
62         if(!driver)
63                 throw logic_error("!driver");
64         return *driver;
65 }
66
67 void Layout::add(Object &o)
68 {
69         if(objects.insert(o))
70                 signal_object_added.emit(o);
71 }
72
73 void Layout::add(Track &t)
74 {
75         if(objects.insert(t))
76         {
77                 // Blocks must be recreated first
78                 create_blocks();
79                 signal_object_added.emit(t);
80         }
81 }
82
83 void Layout::add(TrackChain &g)
84 {
85         if(track_chains.insert(g))
86                 signal_track_chain_added.emit(g);
87 }
88
89 void Layout::add(Block &b)
90 {
91         if(track_chains.insert(b))
92         {
93                 b.signal_reserved.connect(sigc::bind<0>(signal_block_reserved, sigc::ref(b)));
94                 signal_track_chain_added.emit(b);
95         }
96 }
97
98 void Layout::add(Sensor &s)
99 {
100         if(sensors.insert(s))
101         {
102                 s.signal_state_changed.connect(sigc::bind<0>(sigc::mem_fun(this, &Layout::sensor_state_changed), sigc::ref(s)));
103                 s.signal_state_changed.connect(sigc::bind<0>(signal_sensor_state_changed, sigc::ref(s)));
104         }
105 }
106
107 template<>
108 const set<Object *> &Layout::get_all<Object>() const
109 {
110         return objects.get();
111 }
112
113 template<>
114 const set<Track *> &Layout::get_all<Track>() const
115 {
116         return objects.get<Track>();
117 }
118
119 template<>
120 const set<Signal *> &Layout::get_all<Signal>() const
121 {
122         return objects.get<Signal>();
123 }
124
125 template<>
126 const set<Vehicle *> &Layout::get_all<Vehicle>() const
127 {
128         return objects.get<Vehicle>();
129 }
130
131 template<>
132 const set<TrackChain *> &Layout::get_all<TrackChain>() const
133 {
134         return track_chains.get();
135 }
136
137 template<>
138 const set<Block *> &Layout::get_all<Block>() const
139 {
140         return track_chains.get<Block>();
141 }
142
143 template<>
144 const set<Route *> &Layout::get_all<Route>() const
145 {
146         return track_chains.get<Route>();
147 }
148
149 template<>
150 const set<Zone *> &Layout::get_all<Zone>() const
151 {
152         return track_chains.get<Zone>();
153 }
154
155 template<>
156 const set<Sensor *> &Layout::get_all<Sensor>() const
157 {
158         return sensors.get<Sensor>();
159 }
160
161 template<>
162 const set<TrackCircuit *> &Layout::get_all<TrackCircuit>() const
163 {
164         return sensors.get<TrackCircuit>();
165 }
166
167 template<typename T>
168 T *Layout::pick(const Ray &ray)
169 {
170         const set<Object *> &objs = objects.get();
171         for(set<Object *>::const_iterator i=objs.begin(); i!=objs.end(); ++i)
172                 if(T *t = dynamic_cast<T *>(*i))
173                         if(t->collide_ray(ray))
174                                 return t;
175
176         return 0;
177 }
178
179 template Object *Layout::pick<Object>(const Ray &);
180 template Track *Layout::pick<Track>(const Ray &);
181 template Signal *Layout::pick<Signal>(const Ray &);
182 template Vehicle *Layout::pick<Vehicle>(const Ray &);
183
184 void Layout::remove(Object &o)
185 {
186         if(objects.erase(o))
187                 signal_object_removed.emit(o);
188 }
189
190 void Layout::remove(Track &t)
191 {
192         if(objects.erase(t))
193         {
194                 // Blocks must be recreated first
195                 create_blocks(t);
196                 signal_object_removed.emit(t);
197         }
198 }
199
200 void Layout::remove(TrackChain &g)
201 {
202         if(track_chains.erase(g))
203                 signal_track_chain_removed.emit(g);
204 }
205
206 void Layout::remove(Sensor &s)
207 {
208         sensors.erase(s);
209 }
210
211 unsigned Layout::allocate_turnout_id()
212 {
213         set<unsigned> used_ids;
214         const set<Track *> &tracks = objects.get<Track>();
215         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
216                 if((*i)->get_turnout_id())
217                         used_ids.insert((*i)->get_turnout_id());
218
219         unsigned result = next_turnout_id;
220         while(used_ids.count(result))
221                 ++result;
222         next_turnout_id = result+1;
223
224         return result;
225 }
226
227 Block &Layout::get_block(unsigned id) const
228 {
229         const set<Block *> &blocks = track_chains.get<Block>();
230         for(set<Block *>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
231                 if((*i)->get_id()==id)
232                         return **i;
233
234         throw key_error(id);
235 }
236
237 void Layout::create_blocks()
238 {
239         set<Track *> used_tracks;
240         const set<Block *> *blocks = &track_chains.get<Block>();
241         for(set<Block *>::const_iterator i=blocks->begin(); i!=blocks->end(); ++i)
242         {
243                 const set<Track *> &btracks = (*i)->get_tracks();
244                 used_tracks.insert(btracks.begin(), btracks.end());
245         }
246
247         const set<Track *> &tracks = objects.get<Track>();
248         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
249                 if(used_tracks.count(*i)==0)
250                 {
251                         Block *block = new Block(*this, **i);
252                         used_tracks.insert(block->get_tracks().begin(), block->get_tracks().end());
253                 }
254
255         blocks = &track_chains.get<Block>();
256         for(set<Block *>::iterator i=blocks->begin(); i!=blocks->end(); ++i)
257                 for(set<Block *>::iterator j=i; j!=blocks->end(); ++j)
258                         if(j!=i)
259                                 (*i)->check_link(**j);
260 }
261
262 void Layout::create_blocks(Track &track)
263 {
264         /* Must collect the blocks in a set first while all tracks are still
265         guaranteed to have blocks and to avoid duplicate deletes */
266         set<Block *> del_blocks;
267
268         del_blocks.insert(&track.get_block());
269
270         const vector<Track *> &links = track.get_links();
271         for(vector<Track *>::const_iterator i=links.begin(); i!=links.end(); ++i)
272                 if(*i)
273                         del_blocks.insert(&(*i)->get_block());
274
275         for(set<Block *>::iterator i=del_blocks.begin(); i!=del_blocks.end(); ++i)
276                 delete *i;
277
278         create_blocks();
279 }
280
281 Route &Layout::get_route(const string &name) const
282 {
283         const set<Route *> &routes = track_chains.get<Route>();
284         for(set<Route *>::const_iterator i=routes.begin(); i!=routes.end(); ++i)
285                 if((*i)->get_name()==name)
286                         return **i;
287         throw key_error(name);
288 }
289
290 void Layout::update_routes()
291 {
292         const set<Route *> &routes = track_chains.get<Route>();
293         for(set<Route *>::iterator i=routes.begin(); i!=routes.end(); ++i)
294                 (*i)->update_turnouts();
295 }
296
297 Layout::ZoneArray Layout::get_zones(const string &group) const
298 {
299         ZoneArray result;
300         const set<Zone *> &zones = track_chains.get<Zone>();
301         for(set<Zone *>::const_iterator i=zones.begin(); i!=zones.end(); ++i)
302                 if((*i)->get_group()==group)
303                         result.push_back(*i);
304
305         sort(result.begin(), result.end(), zone_order);
306
307         return result;
308 }
309
310 Zone &Layout::get_zone(const string &group, unsigned num) const
311 {
312         const set<Zone *> &zones = track_chains.get<Zone>();
313         for(set<Zone *>::const_iterator i=zones.begin(); i!=zones.end(); ++i)
314                 if((*i)->get_group()==group && (*i)->get_number()==num)
315                         return **i;
316
317         throw key_error(format("%s %d", group, num));
318 }
319
320 void Layout::add_train(Train &t)
321 {
322         insert_unique(trains, t.get_address(), &t);
323         signal_train_added.emit(t);
324 }
325
326 Train &Layout::get_train(unsigned addr) const
327 {
328         return *get_item(trains, addr);
329 }
330
331 void Layout::remove_train(Train &t)
332 {
333         if(trains.erase(t.get_address()))
334                 signal_train_removed.emit(t);
335 }
336
337 void Layout::tick()
338 {
339         if(driver)
340                 driver->tick();
341
342         Time::TimeStamp t = Time::now();
343         Time::TimeDelta dt;
344         if(last_tick)
345                 dt = t-last_tick;
346         last_tick = t;
347
348         clock.tick(dt);
349
350         for(set<Sensor *>::iterator i=sensors.get().begin(); i!=sensors.get().end(); ++i)
351                 (*i)->tick(dt);
352         const set<Signal *> &signals = objects.get<Signal>();
353         for(set<Signal *>::iterator i=signals.begin(); i!=signals.end(); ++i)
354                 (*i)->tick(dt);
355         for(map<unsigned, Train *>::iterator i=trains.begin(); i!=trains.end(); ++i)
356                 i->second->tick(dt);
357 }
358
359 void Layout::emergency(const string &msg)
360 {
361         if(driver)
362                 driver->halt(true);
363         IO::print("Emergency: %s\n", msg);
364         signal_emergency.emit(msg);
365 }
366
367 void Layout::save(const string &fn) const
368 {
369         IO::BufferedFile out(fn, IO::M_WRITE);
370         DataFile::Writer writer(out);
371
372         if(!base.empty())
373                 writer.write((DataFile::Statement("base"), base));
374
375         const set<Track *> &tracks = objects.get<Track>();
376         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
377         {
378                 DataFile::Statement st("track");
379                 st.append((*i)->get_type().get_article_number());
380                 (*i)->save(st.sub);
381                 writer.write(st);
382         }
383
384         const set<Signal *> &signals = objects.get<Signal>();
385         for(set<Signal *>::const_iterator i=signals.begin(); i!=signals.end(); ++i)
386         {
387                 DataFile::Statement st("signal");
388                 st.append((*i)->get_type().get_article_number());
389                 (*i)->save(st.sub);
390                 writer.write(st);
391         }
392
393         const set<Route *> &routes = track_chains.get<Route>();
394         for(set<Route *>::const_iterator i=routes.begin(); i!=routes.end(); ++i)
395         {
396                 if((*i)->is_temporary())
397                         continue;
398
399                 DataFile::Statement st("route");
400                 (*i)->save(st.sub);
401                 writer.write(st);
402         }
403
404         const set<Zone *> &zones = track_chains.get<Zone>();
405         for(set<Zone *>::const_iterator i=zones.begin(); i!=zones.end(); ++i)
406         {
407                 DataFile::Statement st("zone");
408                 (*i)->save(st.sub);
409                 writer.write(st);
410         }
411 }
412
413 void Layout::save_dynamic(const string &fn) const
414 {
415         IO::BufferedFile out(fn, IO::M_WRITE);
416         DataFile::Writer writer(out);
417
418         const set<Track *> &tracks = objects.get<Track>();
419         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
420                 if(unsigned tid = (*i)->get_turnout_id())
421                         writer.write((DataFile::Statement("turnout"), tid, (*i)->get_active_path()));
422
423         for(map<unsigned, Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
424         {
425                 DataFile::Statement st("train");
426                 st.append(i->second->get_locomotive_type().get_article_number());
427                 st.append(i->second->get_address());
428                 st.append(i->second->get_protocol());
429                 i->second->save(st.sub);
430                 writer.write(st);
431         }
432 }
433
434 void Layout::sensor_state_changed(Sensor &sensor, Sensor::State state)
435 {
436         if(state==Sensor::ACTIVE)
437         {
438                 Block *block = sensor.get_block();
439                 if(block && !block->get_train())
440                         emergency(format("Unreserved sensor %d triggered", sensor.get_address()));
441         }
442 }
443
444
445 template<typename B>
446 Layout::Storage<B>::~Storage()
447 {
448         while(!base.empty())
449                 delete *base.begin();
450 }
451
452 template<typename B>
453 bool Layout::Storage<B>::insert(B &b)
454 {
455         bool result = base.insert(&b).second;
456         if(result)
457                 caches.clear();
458         return result;
459 }
460
461 template<typename B>
462 bool Layout::Storage<B>::erase(B &b)
463 {
464         bool result = base.erase(&b);
465         if(result)
466                 caches.clear();
467         return result;
468 }
469
470 template<typename B>
471 template<typename T>
472 const set<T *> &Layout::Storage<B>::get() const
473 {
474         for(list<Variant>::const_iterator i=caches.begin(); i!=caches.end(); ++i)
475                 if(i->check_type<set<T *> >())
476                         return i->value<set<T *> >();
477
478         caches.push_back(set<T *>());
479         set<T *> &result = caches.back().value<set<T *> >();
480         for(typename set<B *>::const_iterator i=base.begin(); i!=base.end(); ++i)
481                 if(T *t = dynamic_cast<T *>(*i))
482                         result.insert(t);
483
484         return result;
485 }
486
487 template<typename B>
488 template<typename T>
489 void Layout::Storage<B>::del()
490 {
491         set<T *> ts = get<T>();
492         for(typename set<T *>::iterator i=ts.begin(); i!=ts.end(); ++i)
493                 if(base.count(*i))
494                         delete *i;
495 }
496
497
498 Layout::Loader::Loader(Layout &l):
499         DataFile::ObjectLoader<Layout>(l),
500         new_tracks(false)
501 {
502         add("base",  &Layout::base);
503         add("route", &Loader::route);
504         add("signal", &Loader::signal);
505         add("track", &Loader::track);
506         add("train", &Loader::train);
507         add("turnout", &Loader::turnout);
508         add("zone",  &Loader::zone);
509 }
510
511 void Layout::Loader::route()
512 {
513         Route *rte = new Route(obj);
514         load_sub(*rte);
515 }
516
517 void Layout::Loader::signal(ArticleNumber art_nr)
518 {
519         Signal *sig = new Signal(obj, obj.catalogue.get_signal(art_nr));
520         load_sub(*sig);
521 }
522
523 void Layout::Loader::track(ArticleNumber art_nr)
524 {
525         Track *trk = new Track(obj, obj.catalogue.get_track(art_nr));
526         load_sub(*trk);
527         new_tracks = true;
528         const set<Track *> &tracks = obj.objects.get<Track>();
529         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
530                 if(*i!=trk)
531                         trk->link_to(**i);
532 }
533
534 void Layout::Loader::train(ArticleNumber art_nr, unsigned addr, const std::string &proto)
535 {
536         Train *trn = new Train(obj, obj.catalogue.get_vehicle(art_nr), addr, proto);
537         load_sub(*trn);
538 }
539
540 void Layout::Loader::turnout(unsigned addr, unsigned path)
541 {
542         if(obj.driver)
543                 obj.driver->set_turnout(addr, path);
544 }
545
546 void Layout::Loader::zone()
547 {
548         Zone *zne = new Zone(obj);
549         load_sub(*zne);
550 }
551
552 } // namespace R2C2