]> git.tdb.fi Git - r2c2.git/blob - source/engineer/engineer.cpp
Compute deterministic IDs for blocks
[r2c2.git] / source / engineer / engineer.cpp
1 /* $Id$
2
3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2009 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
6 */
7
8 #include <cmath>
9 #include <limits>
10 #include <GL/gl.h>
11 #include <msp/core/except.h>
12 #include <msp/core/getopt.h>
13 #include <msp/fs/stat.h>
14 #include <msp/gbase/display.h>
15 #include <msp/gbase/window.h>
16 #include <msp/gl/immediate.h>
17 #include <msp/gl/matrix.h>
18 #include <msp/gl/projection.h>
19 #include <msp/gl/transform.h>
20 #include <msp/strings/formatter.h>
21 #include <msp/strings/lexicalcast.h>
22 #include <msp/strings/regex.h>
23 #include <msp/time/units.h>
24 #include "libmarklin/except.h"
25 #include "libmarklin/tracktype.h"
26 #include "engineer.h"
27 #include "mainpanel.h"
28 #include "trainpanel.h"
29 #include "trainproperties.h"
30
31 using namespace std;
32 using namespace Marklin;
33 using namespace Msp;
34
35 Engineer::Engineer(int argc, char **argv):
36         screen_w(1280),
37         screen_h(960),
38         fullscreen(false),
39         layout(catalogue),
40         layout_3d(layout),
41         server(0),
42         placing_train(0),
43         placing_block(0),
44         placing_entry(0),
45         no_lighting(false),
46         simulate(false)
47 {
48         string res;
49         bool debug = false;
50         string device = "/dev/ttyS0";
51         unsigned quality = 4;
52         bool network = false;
53
54         GetOpt getopt;
55         getopt.add_option('r', "resolution",  res,         GetOpt::REQUIRED_ARG);
56         getopt.add_option('f', "fullscreen",  fullscreen,  GetOpt::NO_ARG);
57         getopt.add_option('g', "debug",       debug,       GetOpt::NO_ARG);
58         getopt.add_option('d', "device",      device,      GetOpt::REQUIRED_ARG);
59         getopt.add_option('q', "quality",     quality,     GetOpt::REQUIRED_ARG);
60         getopt.add_option('s', "simulate",    simulate,    GetOpt::NO_ARG);
61         getopt.add_option('n', "network",     network,     GetOpt::NO_ARG);
62         getopt.add_option(     "no-lighting", no_lighting, GetOpt::NO_ARG);
63         getopt(argc, argv);
64
65         if(!res.empty())
66         {
67                 if(RegMatch m=Regex("([1-9][0-9]*)x([1-9][0-9]*)").match(res))
68                 {
69                         screen_w = lexical_cast<unsigned>(m[1].str);
70                         screen_h = lexical_cast<unsigned>(m[2].str);
71                 }
72                 else
73                         throw UsageError("Invalid resolution");
74         }
75
76         if(device!="none")
77                 control.open(device);
78
79         control.set_debug(debug);
80
81         layout_3d.set_quality(quality);
82
83         DataFile::load(catalogue, "tracks.dat");
84         DataFile::load(catalogue, "locos.dat");
85
86         const vector<string> &args = getopt.get_args();
87         if(args.empty())
88                 throw UsageError("No layout given");
89         DataFile::load(layout, args.front());
90
91         trfc_mgr = new TrafficManager(control, layout);
92         if(FS::exists("engineer.state"))
93                 DataFile::load(*trfc_mgr, "engineer.state");
94         trfc_mgr->signal_train_added.connect(sigc::mem_fun(this, &Engineer::train_added));
95         trfc_mgr->signal_block_reserved.connect(sigc::mem_fun(this, &Engineer::block_reserved));
96
97         if(network)
98         {
99                 server = new Server(*trfc_mgr);
100                 server->use_event_dispatcher(event_disp);
101         }
102
103         const map<unsigned, Sensor *> &sensors = control.get_sensors();
104         for(map<unsigned, Sensor *>::const_iterator i=sensors.begin(); i!=sensors.end(); ++i)
105                 i->second->signal_state_changed.connect(sigc::bind(sigc::mem_fun(this, &Engineer::sensor_event), i->second));
106
107         view_all();
108 }
109
110 Engineer::~Engineer()
111 {
112         if(!simulate)
113                 trfc_mgr->save("engineer.state");
114         delete trfc_mgr;
115         delete server;
116 }
117
118 void Engineer::place_train(Train &train)
119 {
120         placing_train = &train;
121         placing_block = 0;
122         main_panel->set_status_text("Select location");
123 }
124
125 int Engineer::main()
126 {
127         dpy = new Graphics::Display;
128
129         Graphics::WindowOptions wopt;
130         wopt.width = screen_w;
131         wopt.height = screen_h;
132         wopt.fullscreen = fullscreen;
133         wnd = new Graphics::Window(*dpy, wopt);
134
135         Graphics::GLOptions glopt;
136         //glopt.multisample = 4;
137         glc = new Graphics::GLContext(*wnd, glopt);
138
139         wnd->signal_close.connect(sigc::bind(sigc::mem_fun(this, &Engineer::exit), 0));
140         wnd->signal_button_press.connect(sigc::mem_fun(this, &Engineer::button_press));
141         wnd->signal_button_release.connect(sigc::mem_fun(this, &Engineer::button_release));
142         wnd->signal_pointer_motion.connect(sigc::mem_fun(this, &Engineer::pointer_motion));
143
144         glEnableClientState(GL_VERTEX_ARRAY);
145         glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
146         glEnable(GL_COLOR_MATERIAL);
147         glDepthFunc(GL_LEQUAL);
148         glEnable(GL_BLEND);
149         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
150
151         DataFile::load(ui_res, "marklin.res");
152         root = new GLtk::Root(ui_res, *wnd);
153         root->set_visible(true);
154
155         list<GL::Texture *> texs = ui_res.get_list<GL::Texture>();
156         for(list<GL::Texture *>::iterator i=texs.begin(); i!=texs.end(); ++i)
157         {
158                 (*i)->set_min_filter(GL::NEAREST);
159                 (*i)->set_mag_filter(GL::NEAREST);
160         }
161
162         main_panel = new MainPanel(*this, ui_res);
163         root->add(*main_panel);
164         main_panel->set_position(0, screen_h-main_panel->get_geometry().h);
165         main_panel->set_visible(true);
166
167         const list<Train *> &trains = trfc_mgr->get_trains();
168         int y = main_panel->get_geometry().y;
169         for(list<Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
170         {
171                 TrainPanel *tpanel = new TrainPanel(*this, ui_res, **i);
172                 root->add(*tpanel);
173                 tpanel->set_position(0, y-tpanel->get_geometry().h);
174                 train_panels.push_back(tpanel);
175                 tpanel->set_visible(true);
176                 y -= tpanel->get_geometry().h;
177         }
178
179         const list<Block *> &blocks = trfc_mgr->get_blocks();
180         for(list<Block *>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
181                 reset_block_color(**i);
182
183         wnd->show();
184
185         Application::main();
186
187         delete root;
188         delete glc;
189         delete wnd;
190         delete dpy;
191
192         return exit_code;
193 }
194
195 void Engineer::tick()
196 {
197         dpy->tick();
198
199         control.tick();
200         trfc_mgr->tick();
201         event_disp.tick(Time::zero);
202
203         glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
204
205         project_3d();
206         glLoadIdentity();
207         glRotatef(-cam_rot*180/M_PI, 0, 0, 1);
208         glTranslatef(-cam_pos.x, -cam_pos.y, -cam_pos.z);
209
210         if(!no_lighting)
211         {
212                 glEnable(GL_LIGHTING);
213                 glEnable(GL_LIGHT0);
214                 float params[4];
215                 params[0] = 0;
216                 params[1] = -0.2;
217                 params[2] = 1;
218                 params[3] = 0;
219                 glLightfv(GL_LIGHT0, GL_POSITION, params);
220         }
221
222         //glEnable(GL_DEPTH_TEST);
223         glEnable(GL_MULTISAMPLE);
224
225         layout_3d.render();
226
227         glDisable(GL_LIGHTING);
228         glColor4f(1, 1, 1, 1);
229         const list<Track3D *> &ltracks = layout_3d.get_tracks();
230         for(list<Track3D *>::const_iterator i=ltracks.begin(); i!=ltracks.end(); ++i)
231         {
232                 Track &track = (*i)->get_track();
233                 if(track.get_turnout_id())
234                 {
235                         Turnout &trnt = control.get_turnout(track.get_turnout_id());
236                         (*i)->render_path(trnt.get_path());
237                 }
238                 else
239                         (*i)->render_path(-1);
240         }
241
242         if(placing_train && placing_block)
243         {
244                 GL::push_matrix();
245
246                 const Marklin::Block::Endpoint &bep = placing_block->get_endpoints()[placing_entry];
247                 float rot = bep.track->get_endpoint_direction(bep.track_ep);
248                 Point pos = bep.track->get_endpoint_position(bep.track_ep);
249
250                 GL::translate(pos.x, pos.y, pos.z+0.03);
251                 GL::rotate(rot*180/M_PI+180, 0, 0, 1);
252                 GL::Texture::unbind();
253
254                 GL::Immediate imm((GL::COLOR4_UBYTE, GL::VERTEX2));
255                 imm.color(1.0f, 1.0f, 1.0f);
256                 imm.begin(GL::TRIANGLE_FAN);
257                 imm.vertex(0.08,  0);
258                 imm.vertex(0.05,  0.03);
259                 imm.vertex(0.05,  0.01);
260                 imm.vertex(0,     0.01);
261                 imm.vertex(0,    -0.01);
262                 imm.vertex(0.05, -0.01);
263                 imm.vertex(0.05, -0.03);
264                 imm.end();
265
266                 GL::pop_matrix();
267         }
268
269         const list<Train *> &trains = trfc_mgr->get_trains();
270         for(list<Train *>::const_iterator i=trains.begin(); i!=trains.end(); ++i)
271         {
272                 if(!(*i)->is_placed())
273                         continue;
274
275                 GL::PushMatrix _push;
276
277                 const Point &tp = (*i)->get_position();
278                 GL::translate(tp.x, tp.y, tp.z+0.02);
279                 GL::Immediate imm((GL::COLOR4_UBYTE, GL::VERTEX2));
280                 imm.color(0.8f, 0.8f, 1.0f);
281                 imm.begin(GL::TRIANGLE_FAN);
282                 imm.vertex(0, 0);
283                 for(unsigned j=0; j<=12; ++j)
284                         imm.vertex(0.02*cos(j*M_PI/6), 0.02*sin(j*M_PI/6));
285                 imm.end();
286
287                 GL::rotate(cam_rot*180/M_PI, 0, 0, 1);
288                 GL::translate(0.03, -0.02, 0);
289                 GL::scale_uniform(0.04);
290                 ui_res.get_default_font().draw_string((*i)->get_name());
291                 GL::Texture::unbind();
292         }
293
294         GL::matrix_mode(GL::PROJECTION);
295         GL::load_identity();
296         GL::ortho_bottomleft(screen_w, screen_h);
297         GL::matrix_mode(GL::MODELVIEW);
298         GL::load_identity();
299
300         glDisable(GL_DEPTH_TEST);
301         glDisable(GL_LIGHTING);
302         glDisable(GL_MULTISAMPLE);
303
304         root->render();
305
306         glc->swap_buffers();
307 }
308
309 void Engineer::button_press(int x, int y, unsigned btn, unsigned)
310 {
311         if(placing_train)
312         {
313                 if(btn==1 && placing_block && !placing_block->get_train())
314                 {
315                         set_block_color(*placing_block, GL::Color(1, 1, 1));
316
317                         placing_train->place(*placing_block, placing_entry);
318                         placing_train = 0;
319                         main_panel->set_status_text(string());
320                 }
321                 else if(btn==3)
322                 {
323                         const vector<Block::Endpoint> &endpoints = placing_block->get_endpoints();
324                         placing_entry = (placing_entry+1)%endpoints.size();
325                 }
326         }
327         else
328         {
329                 Track3D *track = pick_track(x, screen_h-y-1);
330                 if(track)
331                 {
332                         if(unsigned tid=track->get_track().get_turnout_id())
333                         {
334                                 Turnout &turnout = control.get_turnout(tid);
335                                 try
336                                 {
337                                         turnout.set_path((turnout.get_path()+1)%track->get_track().get_type().get_n_paths());
338                                         main_panel->set_status_text(format("Turnout %d switched", turnout.get_address()));
339                                 }
340                                 catch(const TurnoutBusy &e)
341                                 {
342                                         main_panel->set_status_text(e.what());
343                                 }
344                         }
345                         else if(simulate)
346                         {
347                                 if(unsigned sid=track->get_track().get_sensor_id())
348                                 {
349                                         Sensor &sensor = control.get_sensor(sid);
350                                         control.signal_sensor_event.emit(sid, !sensor.get_state());
351                                 }
352                         }
353                 }
354         }
355 }
356
357 void Engineer::button_release(int, int, unsigned, unsigned)
358 {
359 }
360
361 void Engineer::pointer_motion(int x, int y)
362 {
363         if(placing_train)
364         {
365                 Track3D *track = pick_track(x, screen_h-y-1);
366                 if(track && placing_train)
367                 {
368                         Block &block = trfc_mgr->get_block_by_track(track->get_track());
369                         if(&block!=placing_block)
370                         {
371                                 if(placing_block)
372                                         reset_block_color(*placing_block);
373                                 placing_block = &block;
374                                 placing_entry = 0;
375                                 set_block_color(*placing_block, GL::Color(0.5, 1, 0.7));
376                         }
377                 }
378                 else if(track && track->get_track().get_turnout_id())
379                         main_panel->set_status_text(format("Turnout %d", track->get_track().get_turnout_id()));
380                 else if(!placing_train)
381                         main_panel->set_status_text(string());
382         }
383 }
384
385 void Engineer::view_all()
386 {
387         const list<Track3D *> &tracks = layout_3d.get_tracks();
388
389         cam_rot = 0;
390         float best_height = -1;
391         float mid_x = 0;
392         float mid_y = 0;
393         for(float angle=0; angle<M_PI; angle+=0.01)
394         {
395                 float min_x = 0;
396                 float max_x = 0;
397                 float min_y = 0;
398                 float max_y = 0;
399                 for(list<Track3D *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
400                 {
401                         Point minp, maxp;
402                         (*i)->get_bounds(angle, minp, maxp);
403                         min_x = min(min_x, minp.x);
404                         max_x = max(max_x, maxp.x);
405                         min_y = min(min_y, minp.y);
406                         max_y = max(max_y, maxp.y);
407                 }
408
409                 float width = max_x-min_x;
410                 float height = max_y-min_y;
411                 height = max(height, width);
412
413                 if(height<best_height || best_height<0)
414                 {
415                         cam_rot = angle;
416                         best_height = height;
417                         mid_x = (min_x+max_x)/2;
418                         mid_y = (min_y+max_y)/2;
419                 }
420         }
421
422         float c = cos(cam_rot);
423         float s = sin(cam_rot);
424         cam_pos.x = c*mid_x-s*mid_y;
425         cam_pos.y = s*mid_x+c*mid_y;
426         cam_pos.z = max(best_height*1.05/0.82843, 0.15);
427 }
428
429 void Engineer::set_block_color(const Block &block, const GL::Color &color)
430 {
431         const set<Track *> &tracks = block.get_tracks();
432         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
433                 layout_3d.get_track(**i).set_color(color);
434 }
435
436 void Engineer::reset_block_color(const Block &block)
437 {
438         if(unsigned sid=block.get_sensor_id())
439         {
440                 Sensor &sensor = control.get_sensor(sid);
441                 if(sensor.get_state())
442                 {
443                         set_block_color(block, GL::Color(1, 0.5, 0.3));
444                         return;
445                 }
446         }
447
448         if(block.get_train())
449                 set_block_color(block, GL::Color(1, 1, 0.3));
450         else
451                 set_block_color(block, GL::Color(1, 1, 1));
452 }
453
454 void Engineer::sensor_event(bool, Sensor *sensor)
455 {
456         const list<Block *> &blocks = trfc_mgr->get_blocks();
457         for(list<Block *>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
458                 if((*i)->get_sensor_id()==sensor->get_address())
459                         reset_block_color(**i);
460 }
461
462 void Engineer::block_reserved(const Block &block, const Train *)
463 {
464         reset_block_color(block);
465 }
466
467 void Engineer::project_3d()
468 {
469         glMatrixMode(GL_PROJECTION);
470         glLoadIdentity();
471         float offset = 200.0/screen_w*0.055228;
472         glFrustum(-0.055228-offset, 0.055228-offset, -0.041421, 0.041421, 0.1, 10);
473         glMatrixMode(GL_MODELVIEW);
474 }
475
476 Track3D *Engineer::pick_track(int x, int y)
477 {
478         float xx = (static_cast<float>(x-static_cast<int>(screen_w)/2-100)/screen_h)*0.82843;
479         float yy = (static_cast<float>(y)/screen_h-0.5)*0.82843;
480         float size = 4.0/screen_h*0.82843;
481
482         project_3d();
483         glLoadIdentity();
484         glRotatef(-cam_rot*180/M_PI, 0, 0, 1);
485         glTranslatef(-cam_pos.x, -cam_pos.y, -cam_pos.z);
486
487         return layout_3d.pick_track(xx, yy, size);
488 }
489
490 void Engineer::train_added(Train &train)
491 {
492         TrainPanel *tpanel = new TrainPanel(*this, ui_res, train);
493         root->add(*tpanel);
494         int y = main_panel->get_geometry().y;
495         for(list<TrainPanel *>::iterator i=train_panels.begin(); i!=train_panels.end(); ++i)
496                 y -= (*i)->get_geometry().h;
497         tpanel->set_position(0, y-tpanel->get_geometry().h);
498         train_panels.push_back(tpanel);
499         tpanel->set_visible(true);
500
501         place_train(train);
502 }
503
504 Application::RegApp<Engineer> Engineer::reg;