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