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