]> git.mxchange.org Git - flightgear.git/blob - src/Viewer/fg_os_osgviewer.cxx
Code cleanups, code updates and fix at least on (possible) devide-by-zero
[flightgear.git] / src / Viewer / fg_os_osgviewer.cxx
1 // fg_os_osgviewer.cxx -- common functions for fg_os interface
2 // implemented as an osgViewer
3 //
4 // Copyright (C) 2007  Tim Moore timoore@redhat.com
5 // Copyright (C) 2007 Mathias Froehlich 
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24
25 #include <algorithm>
26 #include <iostream>
27 #include <sstream>
28 #include <string>
29
30 #include <stdlib.h>
31
32 // Boost
33 #include <boost/algorithm/string/case_conv.hpp>
34 #include <boost/foreach.hpp>
35
36 #include <simgear/compiler.h>
37 #include <simgear/structure/exception.hxx>
38 #include <simgear/debug/logstream.hxx>
39 #include <simgear/props/props_io.hxx>
40
41 #include <osg/Camera>
42 #include <osg/GraphicsContext>
43 #include <osg/Group>
44 #include <osg/Matrixd>
45 #include <osg/Viewport>
46 #include <osg/Version>
47 #include <osg/Notify>
48 #include <osg/View>
49 #include <osgViewer/ViewerEventHandlers>
50 #include <osgViewer/Viewer>
51 #include <osgViewer/GraphicsWindow>
52
53 #include <Scenery/scenery.hxx>
54 #include <Main/fg_os.hxx>
55 #include <Main/fg_props.hxx>
56 #include <Main/util.hxx>
57 #include <Main/globals.hxx>
58 #include "renderer.hxx"
59 #include "CameraGroup.hxx"
60 #include "FGEventHandler.hxx"
61 #include "WindowBuilder.hxx"
62 #include "WindowSystemAdapter.hxx"
63
64 // Static linking of OSG needs special macros
65 #ifdef OSG_LIBRARY_STATIC
66 #include <osgDB/Registry>
67 USE_GRAPHICSWINDOW();
68 // Image formats
69 USE_OSGPLUGIN(bmp);
70 USE_OSGPLUGIN(dds);
71 USE_OSGPLUGIN(hdr);
72 USE_OSGPLUGIN(pic);
73 USE_OSGPLUGIN(pnm);
74 USE_OSGPLUGIN(rgb);
75 USE_OSGPLUGIN(tga);
76 #ifdef OSG_JPEG_ENABLED
77   USE_OSGPLUGIN(jpeg);
78 #endif
79 #ifdef OSG_PNG_ENABLED
80   USE_OSGPLUGIN(png);
81 #endif
82 #ifdef OSG_TIFF_ENABLED
83   USE_OSGPLUGIN(tiff);
84 #endif
85 // Model formats
86 USE_OSGPLUGIN(3ds);
87 USE_OSGPLUGIN(ac);
88 USE_OSGPLUGIN(ive);
89 USE_OSGPLUGIN(osg);
90 USE_OSGPLUGIN(txf);
91 #endif
92
93 // fg_os implementation using OpenSceneGraph's osgViewer::Viewer class
94 // to create the graphics window and run the event/update/render loop.
95
96 //
97 // fg_os implementation
98 //
99
100 using namespace std;    
101 using namespace flightgear;
102 using namespace osg;
103
104 osg::ref_ptr<osgViewer::Viewer> viewer;
105
106 static void setStereoMode( const char * mode )
107 {
108     DisplaySettings::StereoMode stereoMode = DisplaySettings::QUAD_BUFFER;
109     bool stereoOn = true;
110
111     if (strcmp(mode,"QUAD_BUFFER")==0)
112     {
113         stereoMode = DisplaySettings::QUAD_BUFFER;
114     }
115     else if (strcmp(mode,"ANAGLYPHIC")==0)
116     {
117         stereoMode = DisplaySettings::ANAGLYPHIC;
118     }
119     else if (strcmp(mode,"HORIZONTAL_SPLIT")==0)
120     {
121         stereoMode = DisplaySettings::HORIZONTAL_SPLIT;
122     }
123     else if (strcmp(mode,"VERTICAL_SPLIT")==0)
124     {
125         stereoMode = DisplaySettings::VERTICAL_SPLIT;
126     }
127     else if (strcmp(mode,"LEFT_EYE")==0)
128     {
129         stereoMode = DisplaySettings::LEFT_EYE;
130     }
131     else if (strcmp(mode,"RIGHT_EYE")==0)
132     {
133         stereoMode = DisplaySettings::RIGHT_EYE;
134     }
135     else if (strcmp(mode,"HORIZONTAL_INTERLACE")==0)
136     {
137         stereoMode = DisplaySettings::HORIZONTAL_INTERLACE;
138     }
139     else if (strcmp(mode,"VERTICAL_INTERLACE")==0)
140     {
141         stereoMode = DisplaySettings::VERTICAL_INTERLACE;
142     }
143     else if (strcmp(mode,"CHECKERBOARD")==0)
144     {
145         stereoMode = DisplaySettings::CHECKERBOARD;
146     } else {
147         stereoOn = false; 
148     }
149     DisplaySettings::instance()->setStereo( stereoOn );
150     DisplaySettings::instance()->setStereoMode( stereoMode );
151 }
152
153 static const char * getStereoMode()
154 {
155     DisplaySettings::StereoMode stereoMode = DisplaySettings::instance()->getStereoMode();
156     bool stereoOn = DisplaySettings::instance()->getStereo();
157     if( !stereoOn ) return "OFF";
158     if( stereoMode == DisplaySettings::QUAD_BUFFER ) {
159         return "QUAD_BUFFER";
160     } else if( stereoMode == DisplaySettings::ANAGLYPHIC ) {
161         return "ANAGLYPHIC";
162     } else if( stereoMode == DisplaySettings::HORIZONTAL_SPLIT ) {
163         return "HORIZONTAL_SPLIT";
164     } else if( stereoMode == DisplaySettings::VERTICAL_SPLIT ) {
165         return "VERTICAL_SPLIT";
166     } else if( stereoMode == DisplaySettings::LEFT_EYE ) {
167         return "LEFT_EYE";
168     } else if( stereoMode == DisplaySettings::RIGHT_EYE ) {
169         return "RIGHT_EYE";
170     } else if( stereoMode == DisplaySettings::HORIZONTAL_INTERLACE ) {
171         return "HORIZONTAL_INTERLACE";
172     } else if( stereoMode == DisplaySettings::VERTICAL_INTERLACE ) {
173         return "VERTICAL_INTERLACE";
174     } else if( stereoMode == DisplaySettings::CHECKERBOARD ) {
175         return "CHECKERBOARD";
176     } 
177     return "OFF";
178 }
179
180 /**
181  * merge OSG output into our logging system, so it gets recorded to file,
182  * and so we can display a GUI console with renderer issues, especially
183  * shader compilation warnings and errors.
184  */
185 class NotifyLogger : public osg::NotifyHandler
186 {
187 public:
188   // note this callback will be invoked by OSG from multiple threads.
189   // fortunately our Simgear logging implementation already handles
190   // that internally, so we simply pass the message on.
191   virtual void notify(osg::NotifySeverity severity, const char *message)
192   {
193     // Detect whether a osg::Reference derived object is deleted with a non-zero
194     // reference count. In this case trigger a segfault to get a stack trace.
195     if( strstr(message, "the final reference count was") )
196     {
197       // as this is going to segfault ignore the translation of severity and always output the message.
198       SG_LOG(SG_GL, SG_ALERT, message);
199       int* trigger_segfault = 0;
200       *trigger_segfault = 0;
201       return;
202     }
203     SG_LOG(SG_GL, translateSeverity(severity), message);
204   }
205
206 private:
207   sgDebugPriority translateSeverity(osg::NotifySeverity severity)
208   {
209     switch (severity) {
210       case osg::ALWAYS:
211       case osg::FATAL:  return SG_ALERT;
212       case osg::WARN:   return SG_WARN;
213       case osg::NOTICE:
214       case osg::INFO:   return SG_INFO;
215       case osg::DEBUG_FP:
216       case osg::DEBUG_INFO: return SG_DEBUG;
217       default: return SG_ALERT;
218     }
219   }
220 };
221
222 class NotifyLevelListener : public SGPropertyChangeListener
223 {
224 public:
225     void valueChanged(SGPropertyNode* node)
226     {
227         osg::NotifySeverity severity = osg::WARN;
228         string val = boost::to_lower_copy(string(node->getStringValue()));
229         
230         if (val == "fatal") {
231             severity = osg::FATAL;
232         } else if (val == "warn") {
233             severity = osg::WARN;
234         } else if (val == "notice") {
235             severity = osg::NOTICE;
236         } else if (val == "info") {
237             severity = osg::INFO;
238         } else if ((val == "debug") || (val == "debug-info")) {
239             severity = osg::DEBUG_INFO;
240         }
241         
242         osg::setNotifyLevel(severity);
243     }
244 };
245
246 void updateOSGNotifyLevel()
247 {
248    }
249
250 void fgOSOpenWindow(bool stencil)
251 {
252     osg::setNotifyHandler(new NotifyLogger);
253     
254     viewer = new osgViewer::Viewer;
255     viewer->setDatabasePager(FGScenery::getPagerSingleton());
256
257     std::string mode;
258     mode = fgGetString("/sim/rendering/multithreading-mode", "SingleThreaded");
259     if (mode == "AutomaticSelection")
260       viewer->setThreadingModel(osgViewer::Viewer::AutomaticSelection);
261     else if (mode == "CullDrawThreadPerContext")
262       viewer->setThreadingModel(osgViewer::Viewer::CullDrawThreadPerContext);
263     else if (mode == "DrawThreadPerContext")
264       viewer->setThreadingModel(osgViewer::Viewer::DrawThreadPerContext);
265     else if (mode == "CullThreadPerCameraDrawThreadPerContext")
266       viewer->setThreadingModel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext);
267     else
268       viewer->setThreadingModel(osgViewer::Viewer::SingleThreaded);
269     WindowBuilder::initWindowBuilder(stencil);
270     CameraGroup::buildDefaultGroup(viewer.get());
271     
272     FGEventHandler* manipulator = globals->get_renderer()->getEventHandler();
273     WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
274     if (wsa->windows.size() != 1) {
275         manipulator->setResizable(false);
276     }
277     viewer->getCamera()->setProjectionResizePolicy(osg::Camera::FIXED);
278     viewer->addEventHandler(manipulator);
279     // Let FG handle the escape key with a confirmation
280     viewer->setKeyEventSetsDone(0);
281     // The viewer won't start without some root.
282     viewer->setSceneData(new osg::Group);
283     globals->get_renderer()->setViewer(viewer.get());
284 }
285
286 void fgOSResetProperties()
287 {
288     SGPropertyNode* osgLevel = fgGetNode("/sim/rendering/osg-notify-level", true);
289     NotifyLevelListener* l = new NotifyLevelListener;
290     globals->addListenerToCleanup(l);
291     osgLevel->addChangeListener(l, true);
292     
293     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
294     if (guiCamera) {
295         Viewport* guiViewport = guiCamera->getViewport();
296         fgSetInt("/sim/startup/xsize", guiViewport->width());
297         fgSetInt("/sim/startup/ysize", guiViewport->height());
298     }
299     
300     DisplaySettings * displaySettings = DisplaySettings::instance();
301     fgTie("/sim/rendering/osg-displaysettings/eye-separation", displaySettings, &DisplaySettings::getEyeSeparation, &DisplaySettings::setEyeSeparation );
302     fgTie("/sim/rendering/osg-displaysettings/screen-distance", displaySettings, &DisplaySettings::getScreenDistance, &DisplaySettings::setScreenDistance );
303     fgTie("/sim/rendering/osg-displaysettings/screen-width", displaySettings, &DisplaySettings::getScreenWidth, &DisplaySettings::setScreenWidth );
304     fgTie("/sim/rendering/osg-displaysettings/screen-height", displaySettings, &DisplaySettings::getScreenHeight, &DisplaySettings::setScreenHeight );
305     fgTie("/sim/rendering/osg-displaysettings/stereo-mode", getStereoMode, setStereoMode );
306     fgTie("/sim/rendering/osg-displaysettings/double-buffer", displaySettings, &DisplaySettings::getDoubleBuffer, &DisplaySettings::setDoubleBuffer );
307     fgTie("/sim/rendering/osg-displaysettings/depth-buffer", displaySettings, &DisplaySettings::getDepthBuffer, &DisplaySettings::setDepthBuffer );
308     fgTie("/sim/rendering/osg-displaysettings/rgb", displaySettings, &DisplaySettings::getRGB, &DisplaySettings::setRGB );
309 }
310
311
312 static int status = 0;
313
314 void fgOSExit(int code)
315 {
316     viewer->setDone(true);
317     viewer->getDatabasePager()->cancel();
318     status = code;
319     
320     // otherwise we crash if OSG does logging during static destruction, eg
321     // GraphicsWindowX11, since OSG statics may have been created before the
322     // sglog static, despite our best efforts in boostrap.cxx
323     osg::setNotifyHandler(new osg::StandardNotifyHandler);
324 }
325
326 int fgOSMainLoop()
327 {
328     viewer->setReleaseContextAtEndOfFrameHint(false);
329     if (!viewer->isRealized())
330         viewer->realize();
331     while (!viewer->done()) {
332         fgIdleHandler idleFunc = globals->get_renderer()->getEventHandler()->getIdleHandler();
333         if (idleFunc)
334             (*idleFunc)();
335         globals->get_renderer()->update();
336         viewer->frame( globals->get_sim_time_sec() );
337     }
338     
339     return status;
340 }
341
342 int fgGetKeyModifiers()
343 {
344     FGRenderer* r = globals->get_renderer();
345     if (!r || !r->getEventHandler()) { // happens during shutdown
346       return 0;
347     }
348     
349     return r->getEventHandler()->getCurrentModifiers();
350 }
351
352 void fgWarpMouse(int x, int y)
353 {
354     warpGUIPointer(CameraGroup::getDefault(), x, y);
355 }
356
357 void fgOSInit(int* argc, char** argv)
358 {
359     globals->get_renderer()->init();
360     WindowSystemAdapter::setWSA(new WindowSystemAdapter);
361 }
362
363 void fgOSCloseWindow()
364 {
365     FGScenery::resetPagerSingleton();
366     flightgear::CameraGroup::setDefault(NULL);
367     WindowSystemAdapter::setWSA(NULL);
368     viewer = NULL;
369 }
370
371 void fgOSFullScreen()
372 {
373     std::vector<osgViewer::GraphicsWindow*> windows;
374     viewer->getWindows(windows);
375
376     if (windows.empty())
377         return; // Huh?!?
378
379     /* Toggling window fullscreen is only supported for the main GUI window.
380      * The other windows should use fixed setup from the camera.xml file anyway. */
381     osgViewer::GraphicsWindow* window = windows[0];
382
383     {
384         osg::GraphicsContext::WindowingSystemInterface    *wsi = osg::GraphicsContext::getWindowingSystemInterface();
385
386         if (wsi == NULL)
387         {
388             SG_LOG(SG_VIEW, SG_ALERT, "ERROR: No WindowSystemInterface available. Cannot toggle window fullscreen.");
389             return;
390         }
391
392         static int previous_x = 0;
393         static int previous_y = 0;
394         static int previous_width = 800;
395         static int previous_height = 600;
396
397         unsigned int screenWidth;
398         unsigned int screenHeight;
399         wsi->getScreenResolution(*(window->getTraits()), screenWidth, screenHeight);
400
401         int x;
402         int y;
403         int width;
404         int height;
405         window->getWindowRectangle(x, y, width, height);
406
407         /* Note: the simple "is window size == screen size" check to detect full screen state doesn't work with
408          * X screen servers in Xinerama mode, since the reported screen width (or height) exceeds the maximum width
409          * (or height) usable by a single window (Xserver automatically shrinks/moves the full screen window to fit a
410          * single display) - so we detect full screen mode using "WindowDecoration" state instead.
411          * "false" - even when a single window is display in fullscreen */
412         //bool isFullScreen = x == 0 && y == 0 && width == (int)screenWidth && height == (int)screenHeight;
413         bool isFullScreen = !window->getWindowDecoration();
414
415         SG_LOG(SG_VIEW, SG_DEBUG, "Toggling fullscreen. Previous window rectangle ("
416                << x << ", " << y << ") x (" << width << ", " << height << "), fullscreen: " << isFullScreen
417                << ", number of screens: " << wsi->getNumScreens());
418         if (isFullScreen)
419         {
420             // limit x,y coordinates and window size to screen area
421             if (previous_x + previous_width > (int)screenWidth)
422                 previous_x = 0;
423             if (previous_y + previous_height > (int)screenHeight)
424                 previous_y = 0;
425
426             // disable fullscreen mode, restore previous window size/coordinates
427             x = previous_x;
428             y = previous_y;
429             width = previous_width;
430             height = previous_height;
431         }
432         else
433         {
434             // remember previous setting
435             previous_x = x;
436             previous_y = y;
437             previous_width = width;
438             previous_height = height;
439
440             // enable fullscreen mode, set new width/height
441             x = 0;
442             y = 0;
443             width = screenWidth;
444             height = screenHeight;
445         }
446
447         // set xsize/ysize properties to adapt GUI planes
448         fgSetInt("/sim/startup/xsize", width);
449         fgSetInt("/sim/startup/ysize", height);
450         fgSetBool("/sim/startup/fullscreen", !isFullScreen);
451
452         // reconfigure window
453         window->setWindowDecoration(isFullScreen);
454         window->setWindowRectangle(x, y, width, height);
455         window->grabFocusIfPointerInWindow();
456     }
457 }
458
459 static void setMouseCursor(osgViewer::GraphicsWindow* gw, int cursor)
460 {
461     if (!gw) {
462         return;
463     }
464   
465     osgViewer::GraphicsWindow::MouseCursor mouseCursor;
466     mouseCursor = osgViewer::GraphicsWindow::InheritCursor;
467     if (cursor == MOUSE_CURSOR_NONE)
468         mouseCursor = osgViewer::GraphicsWindow::NoCursor;
469     else if(cursor == MOUSE_CURSOR_POINTER)
470 #ifdef SG_MAC
471         // osgViewer-Cocoa lacks RightArrowCursor, use Left
472         mouseCursor = osgViewer::GraphicsWindow::LeftArrowCursor;
473 #else
474         mouseCursor = osgViewer::GraphicsWindow::RightArrowCursor;
475 #endif
476     else if(cursor == MOUSE_CURSOR_WAIT)
477         mouseCursor = osgViewer::GraphicsWindow::WaitCursor;
478     else if(cursor == MOUSE_CURSOR_CROSSHAIR)
479         mouseCursor = osgViewer::GraphicsWindow::CrosshairCursor;
480     else if(cursor == MOUSE_CURSOR_LEFTRIGHT)
481         mouseCursor = osgViewer::GraphicsWindow::LeftRightCursor;
482     else if(cursor == MOUSE_CURSOR_TOPSIDE)
483         mouseCursor = osgViewer::GraphicsWindow::TopSideCursor;
484     else if(cursor == MOUSE_CURSOR_BOTTOMSIDE)
485         mouseCursor = osgViewer::GraphicsWindow::BottomSideCursor;
486     else if(cursor == MOUSE_CURSOR_LEFTSIDE)
487         mouseCursor = osgViewer::GraphicsWindow::LeftSideCursor;
488     else if(cursor == MOUSE_CURSOR_RIGHTSIDE)
489         mouseCursor = osgViewer::GraphicsWindow::RightSideCursor;
490     else if(cursor == MOUSE_CURSOR_TOPLEFT)
491         mouseCursor = osgViewer::GraphicsWindow::TopLeftCorner;
492     else if(cursor == MOUSE_CURSOR_TOPRIGHT)
493         mouseCursor = osgViewer::GraphicsWindow::TopRightCorner;
494     else if(cursor == MOUSE_CURSOR_BOTTOMLEFT)
495         mouseCursor = osgViewer::GraphicsWindow::BottomLeftCorner;
496     else if(cursor == MOUSE_CURSOR_BOTTOMRIGHT)
497         mouseCursor = osgViewer::GraphicsWindow::BottomRightCorner;
498
499     gw->setCursor(mouseCursor);
500 }
501
502 static int _cursor = -1;
503
504 void fgSetMouseCursor(int cursor)
505 {
506     _cursor = cursor;
507     if (!viewer)
508         return;
509     
510     std::vector<osgViewer::GraphicsWindow*> windows;
511     viewer->getWindows(windows);
512     BOOST_FOREACH(osgViewer::GraphicsWindow* gw, windows) {
513         setMouseCursor(gw, cursor);
514     }
515 }
516
517 int fgGetMouseCursor()
518 {
519     return _cursor;
520 }