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