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