]> git.mxchange.org Git - flightgear.git/blob - src/GUI/gui_funcs.cxx
Merge branch 'next' into durk-atc
[flightgear.git] / src / GUI / gui_funcs.cxx
1 /**************************************************************************
2  * gui_funcs.cxx
3  *
4  * Based on gui.cxx and renamed on 2002/08/13 by Erik Hofman.
5  *
6  * Written 1998 by Durk Talsma, started Juni, 1998.  For the flight gear
7  * project.
8  *
9  * Additional mouse supported added by David Megginson, 1999.
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License as
13  * published by the Free Software Foundation; either version 2 of the
14  * License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful, but
17  * WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
24  *
25  * $Id$
26  **************************************************************************/
27
28
29 #ifdef HAVE_CONFIG_H
30 #  include <config.h>
31 #endif
32
33 #include <simgear/compiler.h>
34
35 #include <fstream>
36 #include <string>
37 #include <cstring>
38 #include <sstream>
39
40 #include <stdlib.h>
41
42 #include <simgear/debug/logstream.hxx>
43 #include <simgear/misc/sg_path.hxx>
44 #include <simgear/screen/screen-dump.hxx>
45 #include <simgear/structure/event_mgr.hxx>
46
47 #include <Cockpit/panel.hxx>
48 #include <Main/globals.hxx>
49 #include <Main/fg_props.hxx>
50 #include <Main/fg_os.hxx>
51 #include <Main/renderer.hxx>
52 #include <Main/viewmgr.hxx>
53 #include <Main/WindowSystemAdapter.hxx>
54 #include <Main/CameraGroup.hxx>
55 #include <GUI/new_gui.hxx>
56
57
58 #ifdef _WIN32
59 #  include <shellapi.h>
60 #endif
61
62 #include "gui.h"
63
64 using std::string;
65
66
67 #if defined( TR_HIRES_SNAP)
68 #include <simgear/screen/tr.h>
69 extern void fgUpdateHUD( GLfloat x_start, GLfloat y_start,
70                          GLfloat x_end, GLfloat y_end );
71 #endif
72
73
74 const __fg_gui_fn_t __fg_gui_fn[] = {
75 #ifdef TR_HIRES_SNAP
76         {"dumpHiResSnapShot", fgHiResDumpWrapper},
77 #endif
78         {"dumpSnapShot", fgDumpSnapShotWrapper},
79         // Help
80         {"helpCb", helpCb},
81
82         // Structure termination
83         {"", NULL}
84 };
85
86
87 /* ================ General Purpose Functions ================ */
88
89 // General Purpose Message Box. Makes sure no more than 5 different
90 // messages are displayed at the same time, and none of them are
91 // duplicates. (5 is a *lot*, but this will hardly ever be reached
92 // and we don't want to miss any, either.)
93 void mkDialog (const char *txt)
94 {
95     NewGUI *gui = (NewGUI *)globals->get_subsystem("gui");
96     if (!gui)
97         return;
98     SGPropertyNode *master = gui->getDialogProperties("message");
99     if (!master)
100         return;
101
102     const int maxdialogs = 5;
103     string name;
104     SGPropertyNode *msg = fgGetNode("/sim/gui/dialogs", true);
105     int i;
106     for (i = 0; i < maxdialogs; i++) {
107         std::ostringstream s;
108         s << "message-" << i;
109         name = s.str();
110
111         if (!msg->getNode(name.c_str(), false))
112             break;
113
114         if (!strcmp(txt, msg->getNode(name.c_str())->getStringValue("message"))) {
115             SG_LOG(SG_GENERAL, SG_WARN, "mkDialog(): duplicate of message " << txt);
116             return;
117         }
118     }
119     if (i == maxdialogs)
120         return;
121     msg = msg->getNode(name.c_str(), true);
122     msg->setStringValue("message", txt);
123     msg = msg->getNode("dialog", true);
124     copyProperties(master, msg);
125     msg->setStringValue("name", name.c_str());
126     gui->newDialog(msg);
127     gui->showDialog(name.c_str());
128 }
129
130 // Message Box to report an error.
131 void guiErrorMessage (const char *txt)
132 {
133     SG_LOG(SG_GENERAL, SG_ALERT, txt);
134     mkDialog(txt);
135 }
136
137 // Message Box to report a throwable (usually an exception).
138 void guiErrorMessage (const char *txt, const sg_throwable &throwable)
139 {
140     string msg = txt;
141     msg += '\n';
142     msg += throwable.getFormattedMessage();
143     if (!std::strlen(throwable.getOrigin()) != 0) {
144         msg += "\n (reported by ";
145         msg += throwable.getOrigin();
146         msg += ')';
147     }
148     SG_LOG(SG_GENERAL, SG_ALERT, msg);
149     mkDialog(msg.c_str());
150 }
151
152
153
154 /* -----------------------------------------------------------------------
155 the Gui callback functions 
156 ____________________________________________________________________*/
157
158
159 // Hier Neu :-) This is my newly added code
160 // Added by David Findlay <nedz@bigpond.com>
161 // on Sunday 3rd of December
162
163
164 void helpCb ()
165 {
166     string command;
167         
168     SGPath path( globals->get_fg_root() );
169     path.append( "Docs/index.html" );
170         
171 #ifndef _WIN32
172
173     command = globals->get_browser();
174     string::size_type pos;
175     if ((pos = command.find("%u", 0)) != string::npos)
176         command.replace(pos, 2, path.str());
177     else
178         command += " " + path.str();
179
180     command += " &";
181     system( command.c_str() );
182
183 #else // _WIN32
184
185     // Look for favorite browser
186     char Dummy[1024], ExecName[1024], browserParameter[1024];
187     char win32_name[1024];
188 # ifdef __CYGWIN__
189     cygwin32_conv_to_full_win32_path(path.c_str(),win32_name);
190 # else
191     strncpy(win32_name,path.c_str(), 1024);
192 # endif
193     Dummy[0] = 0;
194     FindExecutable(win32_name, Dummy, ExecName);
195     snprintf(browserParameter, 1024, "file:///%s", win32_name);
196     ShellExecute ( NULL, "open", ExecName, browserParameter, Dummy,
197                    SW_SHOWNORMAL ) ;
198
199 #endif
200         
201     mkDialog ("Help started in your web browser window.");
202 }
203
204 #if defined( TR_HIRES_SNAP)
205 void fgHiResDump()
206 {
207     FILE *f;
208     string message;
209     bool menu_status = fgGetBool("/sim/menubar/visibility");
210     char *filename = new char [24];
211     static int count = 1;
212
213     static const SGPropertyNode *master_freeze
214         = fgGetNode("/sim/freeze/master");
215
216     bool freeze = master_freeze->getBoolValue();
217     if ( !freeze ) {
218         fgSetBool("/sim/freeze/master", true);
219     }
220
221     fgSetBool("/sim/menubar/visibility", false);
222     int mouse = fgGetMouseCursor();
223     fgSetMouseCursor(MOUSE_CURSOR_NONE);
224
225     FGRenderer *renderer = globals->get_renderer();
226 //     renderer->init();
227     renderer->resize( fgGetInt("/sim/startup/xsize"),
228                       fgGetInt("/sim/startup/ysize") );
229
230     // we need two render frames here to clear the menu and cursor
231     // ... not sure why but doing an extra fgRenderFrame() shouldn't
232     // hurt anything
233     //renderer->update( true );
234     //renderer->update( true );
235
236     // This ImageSize stuff is a temporary hack
237     // should probably use 128x128 tile size and
238     // support any image size
239
240     // This should be a requester to get multiplier from user
241     int multiplier = fgGetInt("/sim/startup/hires-multiplier", 3);
242     int width = fgGetInt("/sim/startup/xsize");
243     int height = fgGetInt("/sim/startup/ysize");
244         
245     /* allocate buffer large enough to store one tile */
246     GLubyte *tile = (GLubyte *)malloc(width * height * 3 * sizeof(GLubyte));
247     if (!tile) {
248         delete [] filename;
249         printf("Malloc of tile buffer failed!\n");
250         return;
251     }
252
253     int imageWidth  = multiplier*width;
254     int imageHeight = multiplier*height;
255
256     /* allocate buffer to hold a row of tiles */
257     GLubyte *buffer
258         = (GLubyte *)malloc(imageWidth * height * 3 * sizeof(GLubyte));
259     if (!buffer) {
260         delete [] filename;
261         free(tile);
262         printf("Malloc of tile row buffer failed!\n");
263         return;
264     }
265     TRcontext *tr = trNew();
266     trTileSize(tr, width, height, 0);
267     trTileBuffer(tr, GL_RGB, GL_UNSIGNED_BYTE, tile);
268     trImageSize(tr, imageWidth, imageHeight);
269     trRowOrder(tr, TR_TOP_TO_BOTTOM);
270     // OSGFIXME
271 //     sgFrustum *frustum = ssgGetFrustum();
272 //     trFrustum(tr,
273 //               frustum->getLeft(), frustum->getRight(),
274 //               frustum->getBot(),  frustum->getTop(), 
275 //               frustum->getNear(), frustum->getFar());
276         
277     /* Prepare ppm output file */
278     while (count < 1000) {
279         snprintf(filename, 24, "fgfs-screen-%03d.ppm", count++);
280         if ( (f = fopen(filename, "r")) == NULL )
281             break;
282         fclose(f);
283     }
284     f = fopen(filename, "wb");
285     if (!f) {
286         printf("Couldn't open image file: %s\n", filename);
287         delete [] filename;
288         free(buffer);
289         free(tile);
290         return;
291     }
292     fprintf(f,"P6\n");
293     fprintf(f,"# ppm-file created by %s\n", "trdemo2");
294     fprintf(f,"%i %i\n", imageWidth, imageHeight);
295     fprintf(f,"255\n");
296
297     /* just to be safe... */
298     glPixelStorei(GL_PACK_ALIGNMENT, 1);
299
300     // OSGFIXME
301 #if 0
302     /* Because the HUD and Panel change the ViewPort we will
303      * need to handle some lowlevel stuff ourselves */
304     int ncols = trGet(tr, TR_COLUMNS);
305     int nrows = trGet(tr, TR_ROWS);
306
307     bool do_hud = fgGetBool("/sim/hud/visibility");
308     GLfloat hud_col_step = 640.0 / ncols;
309     GLfloat hud_row_step = 480.0 / nrows;
310         
311     bool do_panel = fgPanelVisible();
312     GLfloat panel_col_step = globals->get_current_panel()->getWidth() / ncols;
313     GLfloat panel_row_step = globals->get_current_panel()->getHeight() / nrows;
314 #endif
315     glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
316     glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);
317     glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
318     glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
319     glHint(GL_FOG_HINT, GL_NICEST);
320         
321     /* Draw tiles */
322     int more = 1;
323     while (more) {
324         trBeginTile(tr);
325         int curColumn = trGet(tr, TR_CURRENT_COLUMN);
326         // int curRow =  trGet(tr, TR_CURRENT_ROW);
327
328         renderer->update( false );
329         // OSGFIXME
330 //         if ( do_hud )
331 //             fgUpdateHUD( curColumn*hud_col_step,      curRow*hud_row_step,
332 //                          (curColumn+1)*hud_col_step, (curRow+1)*hud_row_step );
333         // OSGFIXME
334 //         if (do_panel)
335 //             globals->get_current_panel()->update(
336 //                                    curColumn*panel_col_step, panel_col_step,
337 //                                    curRow*panel_row_step,    panel_row_step );
338         more = trEndTile(tr);
339
340         /* save tile into tile row buffer*/
341         int curTileWidth = trGet(tr, TR_CURRENT_TILE_WIDTH);
342         int bytesPerImageRow = imageWidth * 3*sizeof(GLubyte);
343         int bytesPerTileRow = (width) * 3*sizeof(GLubyte);
344         int xOffset = curColumn * bytesPerTileRow;
345         int bytesPerCurrentTileRow = (curTileWidth) * 3*sizeof(GLubyte);
346         int i;
347         for (i=0;i<height;i++) {
348             memcpy(buffer + i*bytesPerImageRow + xOffset, /* Dest */
349                    tile + i*bytesPerTileRow,              /* Src */
350                    bytesPerCurrentTileRow);               /* Byte count*/
351         }
352
353         if (curColumn == trGet(tr, TR_COLUMNS)-1) {
354             /* write this buffered row of tiles to the file */
355             int curTileHeight = trGet(tr, TR_CURRENT_TILE_HEIGHT);
356             int bytesPerImageRow = imageWidth * 3*sizeof(GLubyte);
357             int i;
358             for (i=0;i<curTileHeight;i++) {
359                 /* Remember, OpenGL images are bottom to top.  Have to reverse. */
360                 GLubyte *rowPtr = buffer + (curTileHeight-1-i) * bytesPerImageRow;
361                 fwrite(rowPtr, 1, imageWidth*3, f);
362             }
363         }
364
365     }
366
367     renderer->resize( width, height );
368
369     trDelete(tr);
370
371     glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
372     glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
373     glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
374     glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
375     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
376          (!fgGetBool("/sim/rendering/shading"))) {
377         // if fastest fog requested, or if flat shading force fastest
378         glHint ( GL_FOG_HINT, GL_FASTEST );
379     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
380         glHint ( GL_FOG_HINT, GL_DONT_CARE );
381     }
382
383     fclose(f);
384
385     message = "Snapshot saved to \"";
386     message += filename;
387     message += "\".";
388     mkDialog (message.c_str());
389
390     free(tile);
391     free(buffer);
392
393     delete [] filename;
394
395     fgSetMouseCursor(mouse);
396     fgSetBool("/sim/menubar/visibility", menu_status);
397
398     if ( !freeze ) {
399         fgSetBool("/sim/freeze/master", false);
400     }
401 }
402 #endif // #if defined( TR_HIRES_SNAP)
403
404 void fgDumpSnapShotWrapper () {
405     fgDumpSnapShot();
406 }
407
408
409 void fgHiResDumpWrapper () {
410     fgHiResDump();
411 }
412
413 namespace
414 {
415     using namespace flightgear;
416
417     class GUISnapShotOperation : 
418         public GraphicsContextOperation
419     {
420     public:
421
422         // start new snap shot
423         static bool start()
424         {
425             // allow only one snapshot at a time
426             if (_snapShotOp.valid())
427                 return false;
428             _snapShotOp = new GUISnapShotOperation();
429             /* register with graphics context so actual snap shot is done
430              * in the graphics context (thread) */
431             osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
432             WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
433             osg::GraphicsContext* gc = 0;
434             if (guiCamera)
435                 gc = guiCamera->getGraphicsContext();
436             if (gc) {
437                 gc->add(_snapShotOp.get());
438             } else {
439                 wsa->windows[0]->gc->add(_snapShotOp.get());
440             }
441             return true;
442         }
443
444     private:
445         // constructor to be executed in main loop's thread
446         GUISnapShotOperation() :
447             flightgear::GraphicsContextOperation(std::string("GUI snap shot")),
448             _master_freeze(fgGetNode("/sim/freeze/master", true)),
449             _freeze(_master_freeze->getBoolValue()),
450             _result(false),
451             _mouse(fgGetMouseCursor())
452         {
453             if (!_freeze)
454                 _master_freeze->setBoolValue(true);
455
456             fgSetMouseCursor(MOUSE_CURSOR_NONE);
457
458             string dir = fgGetString("/sim/paths/screenshot-dir");
459             if (dir.empty())
460                 dir = fgGetString("/sim/fg-current");
461
462             _path.set(dir + '/');
463             if (_path.create_dir( 0755 )) {
464                 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot create screenshot directory '"
465                         << dir << "'. Trying home directory.");
466                 dir = fgGetString("/sim/fg-home");
467             }
468
469             char filename[24];
470             static int count = 1;
471             while (count < 1000) {
472                 snprintf(filename, 24, "fgfs-screen-%03d.png", count++);
473
474                 SGPath p(dir);
475                 p.append(filename);
476                 if (!p.exists()) {
477                     _path.set(p.str());
478                     break;
479                 }
480             }
481
482             _xsize = fgGetInt("/sim/startup/xsize");
483             _ysize = fgGetInt("/sim/startup/ysize");
484
485             FGRenderer *renderer = globals->get_renderer();
486             renderer->resize(_xsize, _ysize);
487             globals->get_event_mgr()->addTask("SnapShotTimer",
488                     this, &GUISnapShotOperation::timerExpired,
489                     0.1, false);
490         }
491
492         // to be executed in graphics context (maybe separate thread)
493         void run(osg::GraphicsContext* gc)
494         {
495             _result = sg_glDumpWindow(_path.c_str(),
496                                      _xsize,
497                                      _ysize);
498         }
499
500         // timer method, to be executed in main loop's thread
501         virtual void timerExpired()
502         {
503             if (isFinished())
504             {
505                 globals->get_event_mgr()->removeTask("SnapShotTimer");
506
507                 fgSetString("/sim/paths/screenshot-last", _path.c_str());
508                 fgSetBool("/sim/signals/screenshot", _result);
509
510                 fgSetMouseCursor(_mouse);
511
512                 if ( !_freeze )
513                     _master_freeze->setBoolValue(false);
514
515                 _snapShotOp = 0;
516             }
517         }
518     
519         static osg::ref_ptr<GUISnapShotOperation> _snapShotOp;
520         SGPropertyNode_ptr _master_freeze;
521         bool _freeze;
522         bool _result;
523         int _mouse;
524         int _xsize, _ysize;
525         SGPath _path;
526     };
527
528 }
529
530 osg::ref_ptr<GUISnapShotOperation> GUISnapShotOperation::_snapShotOp;
531
532 // do a screen snap shot
533 bool fgDumpSnapShot ()
534 {
535 #if 1
536     // start snap shot operation, while needs to be executed in
537     // graphics context
538     return GUISnapShotOperation::start();
539 #else
540     // obsolete code => remove when new code is stable
541     static SGConstPropertyNode_ptr master_freeze = fgGetNode("/sim/freeze/master");
542
543     bool freeze = master_freeze->getBoolValue();
544     if ( !freeze ) {
545         fgSetBool("/sim/freeze/master", true);
546     }
547
548     int mouse = fgGetMouseCursor();
549     fgSetMouseCursor(MOUSE_CURSOR_NONE);
550
551     fgSetBool("/sim/signals/screenshot", true);
552
553     FGRenderer *renderer = globals->get_renderer();
554     renderer->resize( fgGetInt("/sim/startup/xsize"),
555                       fgGetInt("/sim/startup/ysize") );
556
557     // we need two render frames here to clear the menu and cursor
558     // ... not sure why but doing an extra fgRenderFrame() shouldn't
559     // hurt anything
560     renderer->update( true );
561     renderer->update( true );
562
563     string dir = fgGetString("/sim/paths/screenshot-dir");
564     if (dir.empty())
565         dir = fgGetString("/sim/fg-current");
566
567     SGPath path(dir + '/');
568     if (path.create_dir( 0755 )) {
569         SG_LOG(SG_GENERAL, SG_ALERT, "Cannot create screenshot directory '"
570                 << dir << "'. Trying home directory.");
571         dir = fgGetString("/sim/fg-home");
572     }
573
574     char filename[24];
575     static int count = 1;
576     while (count < 1000) {
577         snprintf(filename, 24, "fgfs-screen-%03d.png", count++);
578
579         SGPath p(dir);
580         p.append(filename);
581         if (!p.exists()) {
582             path.set(p.str());
583             break;
584         }
585     }
586
587     bool result = sg_glDumpWindow(path.c_str(),
588                                  fgGetInt("/sim/startup/xsize"),
589                                  fgGetInt("/sim/startup/ysize"));
590
591     fgSetString("/sim/paths/screenshot-last", path.c_str());
592     fgSetBool("/sim/signals/screenshot", false);
593
594     fgSetMouseCursor(mouse);
595
596     if ( !freeze ) {
597         fgSetBool("/sim/freeze/master", false);
598     }
599     return result;
600 #endif
601 }
602
603 // do an entire scenegraph dump
604 void fgDumpSceneGraph()
605 {
606     char *filename = new char [24];
607     string message;
608     static int count = 1;
609
610     static const SGPropertyNode *master_freeze
611         = fgGetNode("/sim/freeze/master");
612
613     bool freeze = master_freeze->getBoolValue();
614     if ( !freeze ) {
615         fgSetBool("/sim/freeze/master", true);
616     }
617
618     while (count < 1000) {
619         FILE *fp;
620         snprintf(filename, 24, "fgfs-graph-%03d.osg", count++);
621         if ( (fp = fopen(filename, "r")) == NULL )
622             break;
623         fclose(fp);
624     }
625
626     if ( fgDumpSceneGraphToFile(filename)) {
627         message = "Entire scene graph saved to \"";
628         message += filename;
629         message += "\".";
630     } else {
631         message = "Failed to save to \"";
632         message += filename;
633         message += "\".";
634     }
635
636     mkDialog (message.c_str());
637
638     delete [] filename;
639
640     if ( !freeze ) {
641         fgSetBool("/sim/freeze/master", false);
642     }
643 }
644
645     
646 // do an terrain branch dump
647 void fgDumpTerrainBranch()
648 {
649     char *filename = new char [24];
650     string message;
651     static int count = 1;
652
653     static const SGPropertyNode *master_freeze
654         = fgGetNode("/sim/freeze/master");
655
656     bool freeze = master_freeze->getBoolValue();
657     if ( !freeze ) {
658         fgSetBool("/sim/freeze/master", true);
659     }
660
661     while (count < 1000) {
662         FILE *fp;
663         snprintf(filename, 24, "fgfs-graph-%03d.osg", count++);
664         if ( (fp = fopen(filename, "r")) == NULL )
665             break;
666         fclose(fp);
667     }
668
669     if ( fgDumpTerrainBranchToFile(filename)) {
670         message = "Terrain graph saved to \"";
671         message += filename;
672         message += "\".";
673     } else {
674         message = "Failed to save to \"";
675         message += filename;
676         message += "\".";
677     }
678
679     mkDialog (message.c_str());
680
681     delete [] filename;
682
683     if ( !freeze ) {
684         fgSetBool("/sim/freeze/master", false);
685     }
686 }
687
688 void fgPrintVisibleSceneInfoCommand()
689 {
690     static const SGPropertyNode *master_freeze
691         = fgGetNode("/sim/freeze/master");
692
693     bool freeze = master_freeze->getBoolValue();
694     if ( !freeze ) {
695         fgSetBool("/sim/freeze/master", true);
696     }
697
698     flightgear::printVisibleSceneInfo(globals->get_renderer());
699
700     if ( !freeze ) {
701         fgSetBool("/sim/freeze/master", false);
702     }
703 }
704
705     
706