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