1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
5 // Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
28 #include <simgear/compiler.h>
33 #include <osg/GraphicsContext>
34 #include <osgDB/Registry>
36 #if defined(HAVE_CRASHRPT)
39 // defined in bootstrap.cxx
40 extern bool global_crashRptEnabled;
45 #include <simgear/canvas/VGInitOperation.hxx>
46 #include <simgear/scene/model/modellib.hxx>
47 #include <simgear/scene/material/matlib.hxx>
48 #include <simgear/scene/material/Effect.hxx>
49 #include <simgear/props/AtomicChangeListener.hxx>
50 #include <simgear/props/props.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/io/raw_socket.hxx>
53 #include <simgear/scene/tsync/terrasync.hxx>
54 #include <simgear/math/SGMath.hxx>
55 #include <simgear/math/sg_random.h>
56 #include <simgear/misc/strutils.hxx>
57 #include <simgear/scene/tgdb/GroundLightManager.hxx>
59 #include <Model/panelnode.hxx>
60 #include <Scenery/scenery.hxx>
61 #include <Scenery/tilemgr.hxx>
62 #include <Sound/soundmanager.hxx>
63 #include <Time/TimeManager.hxx>
65 #include <GUI/MessageBox.hxx>
66 #include <Viewer/splash.hxx>
67 #include <Viewer/renderer.hxx>
68 #include <Viewer/WindowSystemAdapter.hxx>
69 #include <Navaids/NavDataCache.hxx>
70 #include <Include/version.h>
72 #include "fg_commands.hxx"
76 #include "fg_init.hxx"
78 #include "fg_props.hxx"
79 #include "positioninit.hxx"
80 #include "screensaver_control.hxx"
81 #include "subsystemFactory.hxx"
82 #include "options.hxx"
85 #include <GUI/QtLauncher.hxx>
88 using namespace flightgear;
93 // The atexit() function handler should know when the graphical subsystem
95 extern int _bootstrap_OSInit;
97 static SGPropertyNode_ptr frame_signal;
98 static TimeManager* timeMgr;
100 // What should we do when we have nothing else to do? Let's get ready
101 // for the next move and update the display?
102 static void fgMainLoop( void )
104 frame_signal->fireValueChanged();
106 // compute simulated time (allowing for pause, warp, etc) and
108 double sim_dt, real_dt;
109 timeMgr->computeTimeDeltas(sim_dt, real_dt);
111 // update all subsystems
112 globals->get_subsystem_mgr()->update(sim_dt);
114 simgear::AtomicChangeListener::fireChangeListeners();
117 static void initTerrasync()
119 // add the terrasync root as a data path so data can be retrieved from it
120 // (even if we are in read-only mode)
121 std::string terraSyncDir(fgGetString("/sim/terrasync/scenery-dir"));
122 globals->append_data_path(terraSyncDir);
124 if (fgGetBool("/sim/fghome-readonly", false)) {
128 // start TerraSync up now, so it can be synchronizing shared models
129 // and airports data in parallel with a nav-cache rebuild.
130 SGPath tsyncCache(terraSyncDir);
131 tsyncCache.append("terrasync-cache.xml");
133 // wipe the cache file if requested
134 if (flightgear::Options::sharedInstance()->isOptionSet("restore-defaults")) {
135 SG_LOG(SG_GENERAL, SG_INFO, "restore-defaults requested, wiping terrasync update cache at " <<
137 if (tsyncCache.exists()) {
142 fgSetString("/sim/terrasync/cache-path", tsyncCache.c_str());
144 simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync();
145 terra_sync->setRoot(globals->get_props());
146 globals->add_subsystem("terrasync", terra_sync);
152 static void checkOpenGLVersion()
155 // Mac users can't upgrade their drivers, so complaining about
156 // versions doesn't help them much
160 // format of these strings is not standardised, so be careful about
162 std::string versionString(fgGetString("/sim/rendering/gl-version"));
163 string_list parts = simgear::strutils::split(versionString);
164 if (parts.size() == 3) {
165 if (parts[1].find("NVIDIA") != std::string::npos) {
166 // driver version number, dot-seperared
167 string_list driverVersion = simgear::strutils::split(parts[2], ".");
168 if (!driverVersion.empty()) {
169 int majorDriverVersion = simgear::strutils::to_int(driverVersion[0]);
170 if (majorDriverVersion < 300) {
171 std::ostringstream ss;
172 ss << "Please upgrade to at least version 300 of the nVidia drivers (installed version is " << parts[2] << ")";
174 flightgear::modalMessageBox("Outdated graphics drivers",
175 "FlightGear has detected outdated drivers for your graphics card.",
179 } // of NVIDIA-style version string
183 static void registerMainLoop()
185 // stash current frame signal property
186 frame_signal = fgGetNode("/sim/signals/frame", true);
187 timeMgr = (TimeManager*) globals->get_subsystem("time");
188 fgRegisterIdleHandler( fgMainLoop );
191 // This is the top level master main function that is registered as
194 // The first few passes take care of initialization things (a couple
195 // per pass) and once everything has been initialized fgMainLoop from
198 static int idle_state = 0;
200 static void fgIdleFunction ( void ) {
201 // Specify our current idle function state. This is used to run all
202 // our initializations out of the idle callback so that we can get a
203 // splash screen up and running right away.
205 if ( idle_state == 0 ) {
208 checkOpenGLVersion();
210 fgSplashProgress("loading-aircraft-list");
213 } else if ( idle_state == 2 ) {
216 fgSplashProgress("loading-nav-dat");
218 } else if ( idle_state == 3 ) {
220 bool done = fgInitNav();
223 fgSplashProgress("init-scenery");
225 } else if ( idle_state == 4 ) {
228 TimeManager* t = new TimeManager;
229 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
231 // Do some quick general initializations
232 if( !fgInitGeneral()) {
233 throw sg_exception("General initialization failed");
236 ////////////////////////////////////////////////////////////////////
237 // Initialize the property-based built-in commands
238 ////////////////////////////////////////////////////////////////////
241 flightgear::registerSubsystemCommands(globals->get_commands());
243 ////////////////////////////////////////////////////////////////////
244 // Initialize the material manager
245 ////////////////////////////////////////////////////////////////////
246 globals->set_matlib( new SGMaterialLib );
247 simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
249 } else if (( idle_state == 5 ) || (idle_state == 2005)) {
251 flightgear::initPosition();
252 flightgear::initTowerLocationListener();
254 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
256 TimeManager* timeManager = (TimeManager*) globals->get_subsystem("time");
259 ////////////////////////////////////////////////////////////////////
260 // Initialize the TG scenery subsystem.
261 ////////////////////////////////////////////////////////////////////
263 globals->add_new_subsystem<FGScenery>(SGSubsystemMgr::DISPLAY);
264 globals->get_scenery()->init();
265 globals->get_scenery()->bind();
266 globals->add_new_subsystem<FGTileMgr>(SGSubsystemMgr::DISPLAY);
268 fgSplashProgress("creating-subsystems");
269 } else if (( idle_state == 7 ) || (idle_state == 2007)) {
270 bool isReset = (idle_state == 2007);
271 idle_state = 8; // from the next state on, reset & startup are identical
274 fgCreateSubsystems(isReset);
275 SG_LOG(SG_GENERAL, SG_INFO, "Creating subsystems took:" << st.elapsedMSec());
276 fgSplashProgress("binding-subsystems");
278 } else if ( idle_state == 8 ) {
282 globals->get_subsystem_mgr()->bind();
283 SG_LOG(SG_GENERAL, SG_INFO, "Binding subsystems took:" << st.elapsedMSec());
285 fgSplashProgress("init-subsystems");
286 } else if ( idle_state == 9 ) {
287 SGSubsystem::InitStatus status = globals->get_subsystem_mgr()->incrementalInit();
288 if ( status == SGSubsystem::INIT_DONE) {
290 fgSplashProgress("finishing-subsystems");
292 fgSplashProgress("init-subsystems");
295 } else if ( idle_state == 10 ) {
297 fgPostInitSubsystems();
298 fgSplashProgress("finalize-position");
299 } else if ( idle_state == 900 ) {
302 // setup OpenGL view parameters
303 globals->get_renderer()->setupView();
305 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
306 fgGetInt("/sim/startup/ysize") );
307 WindowSystemAdapter::getWSA()->windows[0]->gc->add(
308 new simgear::canvas::VGInitOperation()
311 int session = fgGetInt("/sim/session",0);
313 fgSetInt("/sim/session",session);
316 if ( idle_state == 1000 ) {
317 // We've finished all our initialization steps, from now on we
318 // run the main loop.
319 fgSetBool("sim/sceneryloaded", false);
323 if ( idle_state == 2000 ) {
329 void fgResetIdleState()
332 fgRegisterIdleHandler( &fgIdleFunction );
336 static void upper_case_property(const char *name)
338 using namespace simgear;
339 SGPropertyNode *p = fgGetNode(name, false);
341 p = fgGetNode(name, true);
342 p->setStringValue("");
344 props::Type t = p->getType();
345 if (t == props::NONE || t == props::UNSPECIFIED)
346 p->setStringValue("");
348 assert(t == props::STRING);
350 SGPropertyChangeListener* muc = new FGMakeUpperCase;
351 globals->addListenerToCleanup(muc);
352 p->addChangeListener(muc);
355 // see http://code.google.com/p/flightgear-bugs/issues/detail?id=385
356 // for the details of this.
357 static void ATIScreenSizeHack()
359 osg::ref_ptr<osg::Camera> hackCam = new osg::Camera;
360 hackCam->setRenderOrder(osg::Camera::PRE_RENDER);
361 int prettyMuchAnyInt = 1;
362 hackCam->setViewport(0, 0, prettyMuchAnyInt, prettyMuchAnyInt);
363 globals->get_renderer()->addCamera(hackCam, false);
366 // Propose NVIDIA Optimus to use high-end GPU
367 #if defined(SG_WINDOWS)
369 _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
373 static void logToFile()
375 SGPath logPath = globals->get_fg_home();
376 logPath.append("fgfs.log");
377 if (logPath.exists()) {
378 SGPath prevLogPath = globals->get_fg_home();
379 prevLogPath.append("fgfs_0.log");
380 logPath.rename(prevLogPath);
381 // bit strange, we need to restore the correct value of logPath now
382 logPath = globals->get_fg_home();
383 logPath.append("fgfs.log");
385 sglog().logToFile(logPath, SG_ALL, SG_INFO);
387 #if defined(HAVE_CRASHRPT)
388 if (global_crashRptEnabled) {
389 crAddFile2(logPath.c_str(), NULL, "FlightGear Log File", CR_AF_MAKE_FILE_COPY);
390 SG_LOG( SG_GENERAL, SG_INFO, "CrashRpt enabled");
392 SG_LOG(SG_GENERAL, SG_WARN, "CrashRpt enabled at compile time but failed to install");
397 // Main top level initialization
398 int fgMainInit( int argc, char **argv )
400 // set default log levels
401 sglog().setLogLevels( SG_ALL, SG_ALERT );
403 globals = new FGGlobals;
408 if (!fgGetBool("/sim/fghome-readonly")) {
409 // now home is initialised, we can log to a file inside it
413 std::string version(FLIGHTGEAR_VERSION);
414 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
416 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR);
417 SG_LOG( SG_GENERAL, SG_INFO, "Jenkins number/ID " << HUDSON_BUILD_NUMBER << ":"
420 // seed the random number generator
423 string_list *col = new string_list;
424 globals->set_channel_options_list( col );
426 fgValidatePath(globals->get_fg_home(), false); // initialize static variables
427 upper_case_property("/sim/presets/airport-id");
428 upper_case_property("/sim/presets/runway");
429 upper_case_property("/sim/tower/airport-id");
430 upper_case_property("/autopilot/route-manager/input");
432 // Load the configuration parameters. (Command line options
433 // override config file options. Config file options override
435 int configResult = fgInitConfig(argc, argv, false);
436 if (configResult == flightgear::FG_OPTIONS_ERROR) {
438 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
442 // launcher needs to know the aircraft paths in use
443 fgInitAircraftPaths(false);
446 bool showLauncher = flightgear::Options::checkForArg(argc, argv, "launcher");
447 // an Info.plist bundle can't define command line arguments, but it can set
448 // environment variables. This avoids needed a wrapper shell-script on OS-X.
449 showLauncher |= (::getenv("FG_LAUNCHER") != 0);
452 flightgear::initApp(argc, argv);
453 if (!flightgear::runLauncherDialog()) {
459 configResult = fgInitAircraft(false);
460 if (configResult == flightgear::FG_OPTIONS_ERROR) {
462 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
466 configResult = flightgear::Options::sharedInstance()->processOptions();
467 if (configResult == flightgear::FG_OPTIONS_ERROR) {
469 } else if (configResult == flightgear::FG_OPTIONS_EXIT) {
473 // Initialize the Window/Graphics environment.
474 fgOSInit(&argc, argv);
477 fgRegisterIdleHandler( &fgIdleFunction );
479 // Initialize sockets (WinSock needs this)
480 simgear::Socket::initSockets();
482 // Clouds3D requires an alpha channel
483 fgOSOpenWindow(true /* request stencil buffer */);
484 fgOSResetProperties();
486 // Initialize the splash screen right away
490 if (fgGetBool("/sim/ati-viewport-hack", true)) {
491 SG_LOG(SG_GENERAL, SG_ALERT, "Enabling ATI viewport hack");
497 //try to disable the screensaver
498 fgOSDisableScreensaver();
500 // pass control off to the master event handler
501 int result = fgOSMainLoop();
502 frame_signal.clear();
505 simgear::clearEffectCache();
507 // clean up here; ensure we null globals to avoid
508 // confusing the atexit() handler
512 // delete the NavCache here. This will cause the destruction of many cached
513 // objects (eg, airports, navaids, runways).
514 delete flightgear::NavDataCache::instance();
515 simgear::GroundLightManager::instance()->getRunwayLightStateSet()->clear();
516 simgear::GroundLightManager::instance()->getTaxiLightStateSet()->clear();
517 simgear::GroundLightManager::instance()->getGroundLightStateSet()->clear();