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