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