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>
30 #if defined(__linux__) && defined(__i386__)
31 # include <fpu_control.h>
38 #include <osg/GraphicsContext>
39 #include <osgDB/Registry>
42 #include <simgear/scene/model/modellib.hxx>
43 #include <simgear/scene/material/matlib.hxx>
44 #include <simgear/props/AtomicChangeListener.hxx>
45 #include <simgear/props/props.hxx>
46 #include <simgear/timing/sg_time.hxx>
47 #include <simgear/magvar/magvar.hxx>
48 #include <simgear/io/raw_socket.hxx>
49 #include <simgear/scene/tsync/terrasync.hxx>
50 #include <simgear/sound/soundmgr_openal.hxx>
51 #include <simgear/math/SGMath.hxx>
52 #include <simgear/math/sg_random.h>
54 #include <Aircraft/controls.hxx>
55 #include <Model/panelnode.hxx>
56 #include <Scenery/scenery.hxx>
57 #include <Scenery/tilemgr.hxx>
58 #include <Sound/fg_fx.hxx>
59 #include <Time/TimeManager.hxx>
61 #include <Viewer/CameraGroup.hxx>
62 #include <Viewer/WindowSystemAdapter.hxx>
63 #include <Viewer/splash.hxx>
64 #include <Viewer/renderer.hxx>
66 #include "fg_commands.hxx"
70 #include "fg_init.hxx"
72 #include "fg_props.hxx"
74 using namespace flightgear;
79 // Specify our current idle function state. This is used to run all
80 // our initializations out of the idle callback so that we can get a
81 // splash screen up and running right away.
84 // The atexit() function handler should know when the graphical subsystem
86 extern int _bootstrap_OSInit;
89 void fgInitSoundManager()
91 SGSoundMgr *smgr = globals->get_soundmgr();
94 smgr->init(fgGetString("/sim/sound/device-name", NULL));
96 vector <const char*>devices = smgr->get_available_devices();
97 for (unsigned int i=0; i<devices.size(); i++) {
98 SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
99 p->setStringValue(devices[i]);
104 void fgSetNewSoundDevice(const char *device)
106 SGSoundMgr *smgr = globals->get_soundmgr();
113 // Update sound manager state (init/suspend/resume) and propagate property values,
114 // since the sound manager doesn't read any properties itself.
115 // Actual sound update is triggered by the subsystem manager.
116 static void fgUpdateSound(double dt)
118 #ifdef ENABLE_AUDIO_SUPPORT
119 static bool smgr_init = true;
120 static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
121 if (smgr_init == true) {
122 if (sound_working->getBoolValue() == true) {
123 fgInitSoundManager();
127 static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
128 static SGSoundMgr *smgr = globals->get_soundmgr();
129 static bool smgr_enabled = true;
131 if (sound_working->getBoolValue() == false) { // request to reinit
134 sound_working->setBoolValue(true);
137 if (smgr_enabled != sound_enabled->getBoolValue()) {
138 if (smgr_enabled == true) { // request to suspend
140 smgr_enabled = false;
147 if (smgr_enabled == true) {
148 static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
149 smgr->set_volume(volume->getFloatValue());
155 static void fgLoadInitialScenery()
157 static SGPropertyNode_ptr scenery_loaded
158 = fgGetNode("sim/sceneryloaded", true);
160 if (!scenery_loaded->getBoolValue())
162 if (globals->get_tile_mgr()->isSceneryLoaded()
163 && fgGetBool("sim/fdm-initialized")) {
164 fgSetBool("sim/sceneryloaded",true);
165 fgSplashProgress("");
166 if (fgGetBool("/sim/sound/working")) {
167 globals->get_soundmgr()->activate();
169 globals->get_props()->tie("/sim/sound/devices/name",
170 SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
174 fgSplashProgress("loading scenery");
175 // be nice to loader threads while waiting for initial scenery, reduce to 2fps
176 SGTimeStamp::sleepForMSec(500);
181 // What should we do when we have nothing else to do? Let's get ready
182 // for the next move and update the display?
183 static void fgMainLoop( void )
185 static SGPropertyNode_ptr frame_signal
186 = fgGetNode("/sim/signals/frame", true);
188 frame_signal->fireValueChanged();
190 SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
191 SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
193 // compute simulated time (allowing for pause, warp, etc) and
195 double sim_dt, real_dt;
196 TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
197 timeMgr->computeTimeDeltas(sim_dt, real_dt);
199 // update magvar model
200 globals->get_mag()->update( globals->get_aircraft_position(),
201 globals->get_time_params()->getJD() );
203 // Propagate sound manager properties (note: actual update is triggered
204 // by the subsystem manager).
205 fgUpdateSound(sim_dt);
207 // update all subsystems
208 globals->get_subsystem_mgr()->update(sim_dt);
210 // END Tile Manager updates
211 fgLoadInitialScenery();
213 simgear::AtomicChangeListener::fireChangeListeners();
215 SG_LOG( SG_GENERAL, SG_DEBUG, "" );
218 // Operation for querying OpenGL parameters. This must be done in a
219 // valid OpenGL context, potentially in another thread.
222 struct GeneralInitOperation : public GraphicsContextOperation
224 GeneralInitOperation()
225 : GraphicsContextOperation(std::string("General init"))
228 void run(osg::GraphicsContext* gc)
230 SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
232 simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
233 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
235 simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
236 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
238 simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
239 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
242 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
243 simRendering->setIntValue("max-texture-size", tmp);
245 glGetIntegerv( GL_DEPTH_BITS, &tmp );
246 simRendering->setIntValue("depth-buffer-bits", tmp);
252 // This is the top level master main function that is registered as
255 // The first few passes take care of initialization things (a couple
256 // per pass) and once everything has been initialized fgMainLoop from
259 static void fgIdleFunction ( void ) {
260 static osg::ref_ptr<GeneralInitOperation> genOp;
261 if ( idle_state == 0 ) {
263 // Pick some window on which to do queries.
264 // XXX Perhaps all this graphics initialization code should be
265 // moved to renderer.cxx?
266 genOp = new GeneralInitOperation;
267 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
268 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
269 osg::GraphicsContext* gc = 0;
271 gc = guiCamera->getGraphicsContext();
273 gc->add(genOp.get());
275 wsa->windows[0]->gc->add(genOp.get());
278 } else if ( idle_state == 1 ) {
280 if (!genOp->isFinished())
284 if (!guiFinishInit())
287 fgSplashProgress("loading aircraft list");
289 } else if ( idle_state == 2 ) {
291 fgSplashProgress("loading navigation data");
293 } else if ( idle_state == 3 ) {
297 fgSplashProgress("initializing scenery system");
299 } else if ( idle_state == 4 ) {
301 // based on the requested presets, calculate the true starting
304 fgInitTowerLocationListener();
306 TimeManager* t = new TimeManager;
307 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
308 t->init(); // need to init now, not during initSubsystems
310 // Do some quick general initializations
311 if( !fgInitGeneral()) {
312 SG_LOG( SG_GENERAL, SG_ALERT,
313 "General initialization failed ..." );
317 ////////////////////////////////////////////////////////////////////
318 // Initialize the property-based built-in commands
319 ////////////////////////////////////////////////////////////////////
322 ////////////////////////////////////////////////////////////////////
323 // Initialize the material manager
324 ////////////////////////////////////////////////////////////////////
325 globals->set_matlib( new SGMaterialLib );
326 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
327 simgear::SGModelLib::setPanelFunc(FGPanelNode::load);
329 ////////////////////////////////////////////////////////////////////
330 // Initialize the TG scenery subsystem.
331 ////////////////////////////////////////////////////////////////////
332 simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
333 globals->add_subsystem("terrasync", terra_sync);
334 globals->set_scenery( new FGScenery );
335 globals->get_scenery()->init();
336 globals->get_scenery()->bind();
337 globals->set_tile_mgr( new FGTileMgr );
339 fgSplashProgress("loading aircraft");
341 } else if ( idle_state == 5 ) {
344 fgSplashProgress("initializing sky elements");
346 } else if ( idle_state == 6 ) {
349 // Initialize MagVar model
350 SGMagVar *magvar = new SGMagVar();
351 globals->set_mag( magvar );
354 // kludge to initialize mag compass
355 // (should only be done for in-flight
357 // update magvar model
358 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
359 * SGD_DEGREES_TO_RADIANS,
360 fgGetDouble("/position/latitude-deg")
361 * SGD_DEGREES_TO_RADIANS,
362 fgGetDouble("/position/altitude-ft")
364 globals->get_time_params()->getJD() );
366 fgSplashProgress("initializing subsystems");
368 } else if ( idle_state == 7 ) {
370 // Initialize audio support
371 #ifdef ENABLE_AUDIO_SUPPORT
373 // Start the intro music
374 if ( fgGetBool("/sim/startup/intro-music") ) {
375 SGPath mp3file( globals->get_fg_root() );
376 mp3file.append( "Sounds/intro.mp3" );
378 SG_LOG( SG_GENERAL, SG_INFO,
379 "Starting intro music: " << mp3file.str() );
381 # if defined( __CYGWIN__ )
382 string command = "start /m `cygpath -w " + mp3file.str() + "`";
383 # elif defined( _WIN32 )
384 string command = "start /m " + mp3file.str();
386 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
389 if (0 != system ( command.c_str() ))
391 SG_LOG( SG_SOUND, SG_WARN,
392 "Failed to play mp3 file " << mp3file.str() << ". Maybe mp3 player is not installed." );
396 // This is the top level init routine which calls all the
397 // other subsystem initialization routines. If you are adding
398 // a subsystem to flightgear, its initialization call should be
399 // located in this routine.
400 if( !fgInitSubsystems()) {
401 SG_LOG( SG_GENERAL, SG_ALERT,
402 "Subsystem initialization failed ..." );
407 // ugly hack for automatic runway selection on startup based on
408 // metar data. Makes startup.nas obsolete and guarantees the same
409 // runway selection as for AI traffic. However, this code belongs to
410 // somewhere(?) else - if I only new where...
411 if( true == fgGetBool( "/environment/metar/valid" ) ) {
412 SG_LOG(SG_ENVIRONMENT, SG_INFO,
413 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
414 // the realwx_ctrl fetches metar in the foreground on init,
415 // If it was able to fetch a metar or one was given on the commandline,
416 // the valid flag is set here, otherwise it is false
417 double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
418 string apt = fgGetString( "/sim/startup/options/airport" );
419 string rwy = fgGetString( "/sim/startup/options/runway" );
420 double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
421 string parkpos = fgGetString( "/sim/presets/parkpos" );
422 bool onground = fgGetBool( "/sim/presets/onground", false );
423 // don't check for wind-speed < 1kt, this belongs to the runway-selection code
424 // the other logic is taken from former startup.nas
425 if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
426 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
427 fgSetPosFromAirportIDandHdg( apt, hdg );
430 SG_LOG(SG_ENVIRONMENT, SG_INFO,
431 "No METAR available to pick active runway" );
434 fgSplashProgress("initializing graphics engine");
436 } else if ( idle_state == 8 ) {
439 // setup OpenGL view parameters
440 globals->get_renderer()->setupView();
442 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
443 fgGetInt("/sim/startup/ysize") );
445 int session = fgGetInt("/sim/session",0);
447 fgSetInt("/sim/session",session);
450 if ( idle_state == 1000 ) {
451 // We've finished all our initialization steps, from now on we
452 // run the main loop.
453 fgSetBool("sim/sceneryloaded", false);
454 fgRegisterIdleHandler( fgMainLoop );
458 static void upper_case_property(const char *name)
460 using namespace simgear;
461 SGPropertyNode *p = fgGetNode(name, false);
463 p = fgGetNode(name, true);
464 p->setStringValue("");
466 props::Type t = p->getType();
467 if (t == props::NONE || t == props::UNSPECIFIED)
468 p->setStringValue("");
470 assert(t == props::STRING);
472 p->addChangeListener(new FGMakeUpperCase);
476 // Main top level initialization
477 int fgMainInit( int argc, char **argv ) {
479 // set default log levels
480 sglog().setLogLevels( SG_ALL, SG_ALERT );
483 #ifdef FLIGHTGEAR_VERSION
484 version = FLIGHTGEAR_VERSION;
486 version = "unknown version";
488 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
490 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
492 // Allocate global data structures. This needs to happen before
493 // we parse command line options
495 globals = new FGGlobals;
497 // seed the random number generator
500 FGControls *controls = new FGControls;
501 globals->set_controls( controls );
503 string_list *col = new string_list;
504 globals->set_channel_options_list( col );
506 fgValidatePath("", false); // initialize static variables
507 upper_case_property("/sim/presets/airport-id");
508 upper_case_property("/sim/presets/runway");
509 upper_case_property("/sim/tower/airport-id");
510 upper_case_property("/autopilot/route-manager/input");
512 // Load the configuration parameters. (Command line options
513 // override config file options. Config file options override
515 if ( !fgInitConfig(argc, argv) ) {
516 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
520 // Initialize the Window/Graphics environment.
521 fgOSInit(&argc, argv);
524 fgRegisterIdleHandler( &fgIdleFunction );
526 // Initialize sockets (WinSock needs this)
527 simgear::Socket::initSockets();
529 // Clouds3D requires an alpha channel
530 fgOSOpenWindow(true /* request stencil buffer */);
532 // Initialize the splash screen right away
536 // pass control off to the master event handler
537 int result = fgOSMainLoop();
539 // clean up here; ensure we null globals to avoid
540 // confusing the atexit() handler