]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Code cleanups, code updates and fix at least on (possible) devide-by-zero
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
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 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <simgear/props/props_io.hxx>
30
31 #include <iostream>
32
33 #include <osg/Camera>
34 #include <osg/GraphicsContext>
35 #include <osgDB/Registry>
36
37 #if defined(HAVE_CRASHRPT)
38         #include <CrashRpt.h>
39
40 // defined in bootstrap.cxx
41 extern bool global_crashRptEnabled;
42
43 #endif
44
45 // Class references
46 #include <simgear/canvas/VGInitOperation.hxx>
47 #include <simgear/scene/model/modellib.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/scene/material/Effect.hxx>
50 #include <simgear/props/AtomicChangeListener.hxx>
51 #include <simgear/props/props.hxx>
52 #include <simgear/timing/sg_time.hxx>
53 #include <simgear/io/raw_socket.hxx>
54 #include <simgear/scene/tsync/terrasync.hxx>
55 #include <simgear/math/SGMath.hxx>
56 #include <simgear/math/sg_random.h>
57 #include <simgear/misc/strutils.hxx>
58 #include <simgear/scene/tgdb/GroundLightManager.hxx>
59
60 #include <Model/panelnode.hxx>
61 #include <Scenery/scenery.hxx>
62 #include <Scenery/tilemgr.hxx>
63 #include <Sound/soundmanager.hxx>
64 #include <Time/TimeManager.hxx>
65 #include <GUI/gui.h>
66 #include <GUI/MessageBox.hxx>
67 #include <Viewer/splash.hxx>
68 #include <Viewer/renderer.hxx>
69 #include <Viewer/WindowSystemAdapter.hxx>
70 #include <Navaids/NavDataCache.hxx>
71 #include <Include/version.h>
72
73 #include "fg_commands.hxx"
74 #include "fg_io.hxx"
75 #include "main.hxx"
76 #include "util.hxx"
77 #include "fg_init.hxx"
78 #include "fg_os.hxx"
79 #include "fg_props.hxx"
80 #include "positioninit.hxx"
81 #include "screensaver_control.hxx"
82 #include "subsystemFactory.hxx"
83 #include "options.hxx"
84
85 #if defined(HAVE_QT)
86 #include <GUI/QtLauncher.hxx>
87 #endif
88
89 using namespace flightgear;
90
91 using std::cerr;
92 using std::vector;
93
94 // The atexit() function handler should know when the graphical subsystem
95 // is initialized.
96 extern int _bootstrap_OSInit;
97
98 static SGPropertyNode_ptr frame_signal;
99 static TimeManager* timeMgr;
100
101 // What should we do when we have nothing else to do?  Let's get ready
102 // for the next move and update the display?
103 static void fgMainLoop( void )
104 {
105     frame_signal->fireValueChanged();
106
107     // compute simulated time (allowing for pause, warp, etc) and
108     // real elapsed time
109     double sim_dt, real_dt;
110     timeMgr->computeTimeDeltas(sim_dt, real_dt);
111
112     // update all subsystems
113     globals->get_subsystem_mgr()->update(sim_dt);
114
115     simgear::AtomicChangeListener::fireChangeListeners();
116 }
117
118 static void initTerrasync()
119 {
120     // add the terrasync root as a data path so data can be retrieved from it
121     // (even if we are in read-only mode)
122     std::string terraSyncDir(fgGetString("/sim/terrasync/scenery-dir"));
123     globals->append_data_path(terraSyncDir);
124     
125     if (fgGetBool("/sim/fghome-readonly", false)) {
126         return;
127     }
128     
129     // start TerraSync up now, so it can be synchronizing shared models
130     // and airports data in parallel with a nav-cache rebuild.
131     SGPath tsyncCache(terraSyncDir);
132     tsyncCache.append("terrasync-cache.xml");
133     
134     // wipe the cache file if requested
135     if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
136         SG_LOG(SG_GENERAL, SG_INFO, "restore-defaults requested, wiping terrasync update cache at " <<
137                tsyncCache);
138         if (tsyncCache.exists()) {
139             tsyncCache.remove();
140         }
141     }
142     
143     fgSetString("/sim/terrasync/cache-path", tsyncCache.c_str());
144     
145     simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync();
146     terra_sync->setRoot(globals->get_props());
147     globals->add_subsystem("terrasync", terra_sync);
148     
149     terra_sync->bind();
150     terra_sync->init();
151 }
152
153 static void fgSetVideoOptions()
154 {
155     std::string vendor = fgGetString("/sim/rendering/gl-vendor");
156     SGPath path(globals->get_fg_root());
157     path.append("Video");
158     path.append(vendor);
159     if (path.exists())
160     {
161         std::string renderer = fgGetString("/sim/rendering/gl-renderer");
162         size_t pos = renderer.find("x86/");
163         if (pos == std::string::npos) {
164             pos = renderer.find('/');
165         }
166         if (pos == std::string::npos) {
167             pos = renderer.find(" (");
168         }
169         if (pos != std::string::npos) {
170             renderer = renderer.substr(0, pos);
171         }
172         path.append(renderer+".xml");
173         if (path.exists()) {
174             SG_LOG(SG_INPUT, SG_INFO, "Reading video settings from " << path.str());
175             try {
176                 SGPropertyNode *r_prop = fgGetNode("/sim/rendering");
177                 readProperties(path.str(), r_prop);
178             } catch (sg_exception& e) {
179                 SG_LOG(SG_INPUT, SG_WARN, "failed to read video settings:" << e.getMessage()
180                 << "(from " << e.getOrigin() << ")");
181             }
182
183             flightgear::Options* options = flightgear::Options::sharedInstance();
184             if (!options->isOptionSet("ignore-autosave"))
185             {
186                 SGPath dataPath = globals->get_fg_home();
187                 globals->loadUserSettings(dataPath);
188             }
189         }
190     }
191 }
192
193 static void checkOpenGLVersion()
194 {
195 #if defined(SG_MAC)
196     // Mac users can't upgrade their drivers, so complaining about
197     // versions doesn't help them much
198     return;
199 #endif
200     
201     // format of these strings is not standardised, so be careful about
202     // parsing them.
203     std::string versionString(fgGetString("/sim/rendering/gl-version"));
204     string_list parts = simgear::strutils::split(versionString);
205     if (parts.size() == 3) {
206         if (parts[1].find("NVIDIA") != std::string::npos) {
207             // driver version number, dot-seperared
208             string_list driverVersion = simgear::strutils::split(parts[2], ".");
209             if (!driverVersion.empty()) {
210                 int majorDriverVersion = simgear::strutils::to_int(driverVersion[0]);
211                 if (majorDriverVersion < 300) {
212                     std::ostringstream ss;
213                     ss << "Please upgrade to at least version 300 of the nVidia drivers (installed version is " << parts[2] << ")";
214
215                     flightgear::modalMessageBox("Outdated graphics drivers",
216                                                 "FlightGear has detected outdated drivers for your graphics card.",
217                                                 ss.str());
218                 }
219             }
220         } // of NVIDIA-style version string
221     } // of three parts
222 }
223
224 static void registerMainLoop()
225 {
226     // stash current frame signal property
227     frame_signal = fgGetNode("/sim/signals/frame", true);
228     timeMgr = (TimeManager*) globals->get_subsystem("time");
229     fgRegisterIdleHandler( fgMainLoop );
230 }
231
232 // This is the top level master main function that is registered as
233 // our idle function
234
235 // The first few passes take care of initialization things (a couple
236 // per pass) and once everything has been initialized fgMainLoop from
237 // then on.
238
239 static int idle_state = 0;
240
241 static void fgIdleFunction ( void ) {
242     // Specify our current idle function state.  This is used to run all
243     // our initializations out of the idle callback so that we can get a
244     // splash screen up and running right away.
245     
246     if ( idle_state == 0 ) {
247         if (guiInit())
248         {
249             checkOpenGLVersion();
250             fgSetVideoOptions();
251             idle_state+=2;
252             fgSplashProgress("loading-aircraft-list");
253         }
254
255     } else if ( idle_state == 2 ) {
256         initTerrasync();
257         idle_state++;
258         fgSplashProgress("loading-nav-dat");
259
260     } else if ( idle_state == 3 ) {
261         
262         bool done = fgInitNav();
263         if (done) {
264           ++idle_state;
265           fgSplashProgress("init-scenery");
266         }
267     } else if ( idle_state == 4 ) {
268         idle_state++;
269
270         TimeManager* t = new TimeManager;
271         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
272         
273         // Do some quick general initializations
274         if( !fgInitGeneral()) {
275             throw sg_exception("General initialization failed");
276         }
277
278         ////////////////////////////////////////////////////////////////////
279         // Initialize the property-based built-in commands
280         ////////////////////////////////////////////////////////////////////
281         fgInitCommands();
282
283         flightgear::registerSubsystemCommands(globals->get_commands());
284
285         ////////////////////////////////////////////////////////////////////
286         // Initialize the material manager
287         ////////////////////////////////////////////////////////////////////
288         globals->set_matlib( new SGMaterialLib );
289         simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
290  
291     } else if (( idle_state == 5 ) || (idle_state == 2005)) {
292         idle_state+=2;
293         flightgear::initPosition();
294         flightgear::initTowerLocationListener();
295         
296         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
297         
298         TimeManager* timeManager = (TimeManager*) globals->get_subsystem("time");
299         timeManager->init();
300         
301         ////////////////////////////////////////////////////////////////////
302         // Initialize the TG scenery subsystem.
303         ////////////////////////////////////////////////////////////////////
304         
305         globals->add_new_subsystem<FGScenery>(SGSubsystemMgr::DISPLAY);
306         globals->get_scenery()->init();
307         globals->get_scenery()->bind();
308         globals->add_new_subsystem<FGTileMgr>(SGSubsystemMgr::DISPLAY);
309         
310         fgSplashProgress("creating-subsystems");
311     } else if (( idle_state == 7 ) || (idle_state == 2007)) {
312         bool isReset = (idle_state == 2007);
313         idle_state = 8; // from the next state on, reset & startup are identical
314         SGTimeStamp st;
315         st.stamp();
316         fgCreateSubsystems(isReset);
317         SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
318         fgSplashProgress("binding-subsystems");
319       
320     } else if ( idle_state == 8 ) {
321         idle_state++;
322         SGTimeStamp st;
323         st.stamp();
324         globals->get_subsystem_mgr()->bind();
325         SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
326
327         fgSplashProgress("init-subsystems");
328     } else if ( idle_state == 9 ) {
329         SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
330         if ( status == SGSubsystem::INIT_DONE) {
331           ++idle_state;
332           fgSplashProgress("finishing-subsystems");
333         } else {
334           fgSplashProgress("init-subsystems");
335         }
336       
337     } else if ( idle_state == 10 ) {
338         idle_state = 900;
339         fgPostInitSubsystems();
340         fgSplashProgress("finalize-position");
341     } else if ( idle_state == 900 ) {
342         idle_state = 1000;
343         
344         // setup OpenGL view parameters
345         globals->get_renderer()->setupView();
346
347         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
348                                          fgGetInt("/sim/startup/ysize") );
349         WindowSystemAdapter::getWSA()->windows[0]->gc->add(
350           new simgear::canvas::VGInitOperation()
351         );
352
353         int session = fgGetInt("/sim/session",0);
354         session++;
355         fgSetInt("/sim/session",session);
356     }
357
358     if ( idle_state == 1000 ) {
359         // We've finished all our initialization steps, from now on we
360         // run the main loop.
361         fgSetBool("sim/sceneryloaded", false);
362         registerMainLoop();
363     }
364     
365     if ( idle_state == 2000 ) {
366         fgStartNewReset();
367         idle_state = 2005;
368     }
369 }
370
371 void fgResetIdleState()
372 {
373     idle_state = 2000;
374     fgRegisterIdleHandler( &fgIdleFunction );
375 }
376
377
378 static void upper_case_property(const char *name)
379 {
380     using namespace simgear;
381     SGPropertyNode *p = fgGetNode(name, false);
382     if (!p) {
383         p = fgGetNode(name, true);
384         p->setStringValue("");
385     } else {
386         props::Type t = p->getType();
387         if (t == props::NONE || t == props::UNSPECIFIED)
388             p->setStringValue("");
389         else
390             assert(t == props::STRING);
391     }
392     SGPropertyChangeListener* muc = new FGMakeUpperCase;
393     globals->addListenerToCleanup(muc);
394     p->addChangeListener(muc);
395 }
396
397 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=385
398 // for the details of this.
399 static void ATIScreenSizeHack()
400 {
401     osg::ref_ptr<osg::Camera> hackCam = new osg::Camera;
402     hackCam->setRenderOrder(osg::Camera::PRE_RENDER);
403     int prettyMuchAnyInt = 1;
404     hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt);
405     globals->get_renderer()->addCamera(hackCam, false);
406 }
407
408 // Propose NVIDIA Optimus to use high-end GPU
409 #if defined(SG_WINDOWS)
410 extern "C" {
411     _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
412 }
413 #endif
414
415 static void logToFile()
416 {
417     SGPath logPath = globals->get_fg_home();
418     logPath.append("fgfs.log");
419     if (logPath.exists()) {
420         SGPath prevLogPath = globals->get_fg_home();
421         prevLogPath.append("fgfs_0.log");
422         logPath.rename(prevLogPath);
423         // bit strange, we need to restore the correct value of logPath now
424         logPath = globals->get_fg_home();
425         logPath.append("fgfs.log");
426     }
427     sglog().logToFile(logPath, SG_ALL, SG_INFO);
428
429 #if defined(HAVE_CRASHRPT)
430         if (global_crashRptEnabled) {
431                 crAddFile2(logPath.c_str(), NULL, "FlightGear Log File", CR_AF_MAKE_FILE_COPY);
432                 SG_LOG( SG_GENERAL, SG_INFO, "CrashRpt enabled");
433         } else {
434                 SG_LOG(SG_GENERAL, SG_WARN, "CrashRpt enabled at compile time but failed to install");
435         }
436 #endif
437 }
438
439 // Main top level initialization
440 int fgMainInit( int argc, char **argv )
441 {
442     // set default log levels
443     sglog().setLogLevels( SG_ALL, SG_ALERT );
444
445     globals = new FGGlobals;
446     if (!fgInitHome()) {
447         return EXIT_FAILURE;
448     }
449     
450     if (!fgGetBool("/sim/fghome-readonly")) {
451         // now home is initialised, we can log to a file inside it
452         logToFile();
453     }
454     
455     std::string version(FLIGHTGEAR_VERSION);
456     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
457             << version );
458     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR);
459         SG_LOG( SG_GENERAL, SG_INFO, "Jenkins number/ID " << HUDSON_BUILD_NUMBER << ":"
460                         << HUDSON_BUILD_ID);
461
462     // seed the random number generator
463     sg_srandom_time();
464
465     string_list *col = new string_list;
466     globals->set_channel_options_list( col );
467
468     fgValidatePath(globals->get_fg_home(), false);  // initialize static variables
469     upper_case_property("/sim/presets/airport-id");
470     upper_case_property("/sim/presets/runway");
471     upper_case_property("/sim/tower/airport-id");
472     upper_case_property("/autopilot/route-manager/input");
473
474     // Load the configuration parameters.  (Command line options
475     // override config file options.  Config file options override
476     // defaults.)
477     int configResult = fgInitConfig(argc, argv, false);
478     if (configResult == flightgear::FG_OPTIONS_ERROR) {
479         return EXIT_FAILURE;
480     } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
481         return EXIT_SUCCESS;
482     }
483
484 #if defined(HAVE_QT)
485     bool showLauncher = flightgear::Options::checkForArg(argc, argv, "launcher");
486     // an Info.plist bundle can't define command line arguments, but it can set
487     // environment variables. This avoids needed a wrapper shell-script on OS-X.
488     showLauncher |= (::getenv("FG_LAUNCHER") != 0);
489
490     if (showLauncher) {
491         flightgear::initApp(argc, argv);
492         if (!flightgear::runLauncherDialog()) {
493             return EXIT_SUCCESS;
494         }
495     }
496 #endif
497     fgInitAircraftPaths(false);
498
499     configResult = fgInitAircraft(false);
500     if (configResult == flightgear::FG_OPTIONS_ERROR) {
501         return EXIT_FAILURE;
502     } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
503         return EXIT_SUCCESS;
504     }
505     
506     configResult = flightgear::Options::sharedInstance()->processOptions();
507     if (configResult == flightgear::FG_OPTIONS_ERROR) {
508         return EXIT_FAILURE;
509     } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
510         return EXIT_SUCCESS;
511     }
512     
513     // Initialize the Window/Graphics environment.
514     fgOSInit(&argc, argv);
515     _bootstrap_OSInit++;
516
517     fgRegisterIdleHandler( &fgIdleFunction );
518
519     // Initialize sockets (WinSock needs this)
520     simgear::Socket::initSockets();
521
522     // Clouds3D requires an alpha channel
523     fgOSOpenWindow(true /* request stencil buffer */);
524     fgOSResetProperties();
525     
526     // Initialize the splash screen right away
527     fntInit();
528     fgSplashInit();
529
530     if (fgGetBool("/sim/ati-viewport-hack", true)) {
531         SG_LOG(SG_GENERAL, SG_ALERT, "Enabling ATI viewport hack");
532         ATIScreenSizeHack();
533     }
534     
535     fgOutputSettings();
536     
537     //try to disable the screensaver
538     fgOSDisableScreensaver();
539     
540     // pass control off to the master event handler
541     int result = fgOSMainLoop();
542     frame_signal.clear();
543     fgOSCloseWindow();
544     
545     simgear::clearEffectCache();
546     
547     // clean up here; ensure we null globals to avoid
548     // confusing the atexit() handler
549     delete globals;
550     globals = NULL;
551     
552     // delete the NavCache here. This will cause the destruction of many cached
553     // objects (eg, airports, navaids, runways).
554     delete flightgear::NavDataCache::instance();
555     simgear::GroundLightManager::instance()->getRunwayLightStateSet()->clear();
556     simgear::GroundLightManager::instance()->getTaxiLightStateSet()->clear();
557     simgear::GroundLightManager::instance()->getGroundLightStateSet()->clear();
558   
559     return result;
560 }