]> git.tdb.fi Git - r2c2.git/blob - source/engineer/engineer.cpp
Allow setting sensor ID for multiple tracks at once
[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         GL::matrix_mode(GL::PROJECTION);
267         GL::load_identity();
268         GL::ortho_bottomleft(screen_w, screen_h);
269         GL::matrix_mode(GL::MODELVIEW);
270         GL::load_identity();
271
272         glDisable(GL_DEPTH_TEST);
273         glDisable(GL_LIGHTING);
274         glDisable(GL_MULTISAMPLE);
275
276         root->render();
277
278         if(train_prop_stale)
279         {
280                 delete train_prop;
281                 train_prop=0;
282         }
283
284         glc->swap_buffers();
285 }
286
287 void Engineer::key_press(unsigned key, unsigned mod, wchar_t ch)
288 {
289         if(train_prop)
290                 train_prop->key_press(key, mod, ch);
291 }
292
293 void Engineer::button_press(int x, int y, unsigned btn, unsigned)
294 {
295         if(placing_train)
296         {
297                 if(btn==1 && placing_block && !placing_block->get_train())
298                 {
299                         set_block_color(*placing_block, GL::Color(1, 1, 1));
300
301                         placing_train->place(placing_block, placing_entry);
302                         placing_train=0;
303                         main_panel->set_status_text(string());
304                 }
305                 else if(btn==3)
306                 {
307                         const vector<Block::Endpoint> &endpoints=placing_block->get_endpoints();
308                         placing_entry=(placing_entry+1)%endpoints.size();
309                 }
310         }
311         else
312         {
313                 Track3D *track=pick_track(x, screen_h-y-1);
314                 if(track)
315                 {
316                         if(unsigned tid=track->get_track().get_turnout_id())
317                         {
318                                 Turnout &turnout=control.get_turnout(tid);
319                                 turnout.set_route((turnout.get_route()+1)%track->get_track().get_type().get_n_routes());
320                         }
321                         else if(simulate)
322                         {
323                                 if(unsigned sid=track->get_track().get_sensor_id())
324                                 {
325                                         Sensor &sensor=control.get_sensor(sid);
326                                         control.signal_sensor_event.emit(sid, !sensor.get_state());
327                                 }
328                         }
329                 }
330         }
331 }
332
333 void Engineer::button_release(int, int, unsigned, unsigned)
334 {
335 }
336
337 void Engineer::pointer_motion(int x, int y)
338 {
339         if(placing_train)
340         {
341                 Track3D *track=pick_track(x, screen_h-y-1);
342                 if(track && placing_train)
343                 {
344                         Block &block=trfc_mgr->get_block_by_track(track->get_track());
345                         if(&block!=placing_block)
346                         {
347                                 if(placing_block)
348                                         reset_block_color(*placing_block);
349                                 placing_block=&block;
350                                 placing_entry=0;
351                                 set_block_color(*placing_block, GL::Color(0.5, 1, 0.7));
352                         }
353                 }
354                 else if(track && track->get_track().get_turnout_id())
355                         main_panel->set_status_text(format("Turnout %d", track->get_track().get_turnout_id()));
356                 else if(!placing_train)
357                         main_panel->set_status_text(string());
358         }
359 }
360
361 void Engineer::view_all()
362 {
363         const list<Track3D *> &tracks=layout_3d.get_tracks();
364
365         cam_rot=0;
366         float best_height=-1;
367         float mid_x=0;
368         float mid_y=0;
369         for(float angle=0; angle<M_PI; angle+=0.01)
370         {
371                 float min_x=0;
372                 float max_x=0;
373                 float min_y=0;
374                 float max_y=0;
375                 for(list<Track3D *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
376                 {
377                         Point minp, maxp;
378                         (*i)->get_bounds(angle, minp, maxp);
379                         min_x=min(min_x, minp.x);
380                         max_x=max(max_x, maxp.x);
381                         min_y=min(min_y, minp.y);
382                         max_y=max(max_y, maxp.y);
383                 }
384
385                 float width=max_x-min_x;
386                 float height=max_y-min_y;
387                 height=max(height, width);
388
389                 if(height<best_height || best_height<0)
390                 {
391                         cam_rot=angle;
392                         best_height=height;
393                         mid_x=(min_x+max_x)/2;
394                         mid_y=(min_y+max_y)/2;
395                 }
396         }
397
398         float c=cos(cam_rot);
399         float s=sin(cam_rot);
400         cam_pos.x=c*mid_x-s*mid_y;
401         cam_pos.y=s*mid_x+c*mid_y;
402         cam_pos.z=max(best_height*1.05/0.82843, 0.15);
403 }
404
405 void Engineer::set_block_color(const Block &block, const GL::Color &color)
406 {
407         const set<Track *> &tracks=block.get_tracks();
408         for(set<Track *>::const_iterator i=tracks.begin(); i!=tracks.end(); ++i)
409                 layout_3d.get_track(**i).set_color(color);
410 }
411
412 void Engineer::reset_block_color(const Block &block)
413 {
414         if(unsigned sid=block.get_sensor_id())
415         {
416                 Sensor &sensor=control.get_sensor(sid);
417                 if(sensor.get_state())
418                 {
419                         set_block_color(block, GL::Color(1, 0.5, 0.3));
420                         return;
421                 }
422         }
423
424         if(block.get_train())
425                 set_block_color(block, GL::Color(1, 1, 0.3));
426         else
427                 set_block_color(block, GL::Color(1, 1, 1));
428 }
429
430 void Engineer::sensor_event(bool, Sensor *sensor)
431 {
432         const list<Block *> &blocks=trfc_mgr->get_blocks();
433         for(list<Block *>::const_iterator i=blocks.begin(); i!=blocks.end(); ++i)
434                 if((*i)->get_sensor_id()==sensor->get_address())
435                         reset_block_color(**i);
436 }
437
438 void Engineer::block_reserved(const Block &block, const Train *)
439 {
440         reset_block_color(block);
441 }
442
443 void Engineer::project_3d()
444 {
445         glMatrixMode(GL_PROJECTION);
446         glLoadIdentity();
447         float offset=200.0/screen_w*0.055228;
448         glFrustum(-0.055228-offset, 0.055228-offset, -0.041421, 0.041421, 0.1, 10);
449         glMatrixMode(GL_MODELVIEW);
450 }
451
452 Track3D *Engineer::pick_track(int x, int y)
453 {
454         float xx=(static_cast<float>(x-static_cast<int>(screen_w)/2-100)/screen_h)*0.82843;
455         float yy=(static_cast<float>(y)/screen_h-0.5)*0.82843;
456         float size=4.0/screen_h*0.82843;
457
458         project_3d();
459         glLoadIdentity();
460         glRotatef(-cam_rot*180/M_PI, 0, 0, 1);
461         glTranslatef(-cam_pos.x, -cam_pos.y, -cam_pos.z);
462
463         return layout_3d.pick_track(xx, yy, size);
464 }
465
466 void Engineer::dismiss_train_prop()
467 {
468         train_prop_stale=true;
469 }
470
471 Application::RegApp<Engineer> Engineer::reg;