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/scene/model/animation.hxx>
45 #include <simgear/scene/sky/sky.hxx>
46 #include <simgear/structure/event_mgr.hxx>
47 #include <simgear/props/AtomicChangeListener.hxx>
48 #include <simgear/props/props.hxx>
49 #include <simgear/timing/sg_time.hxx>
50 #include <simgear/magvar/magvar.hxx>
51 #include <simgear/math/sg_random.h>
52 #include <simgear/io/raw_socket.hxx>
53 #include <simgear/misc/sg_sleep.hxx>
55 #include <Time/light.hxx>
56 #include <Aircraft/replay.hxx>
57 #include <Aircraft/controls.hxx>
58 #include <Model/panelnode.hxx>
59 #include <Model/acmodel.hxx>
60 #include <Scenery/scenery.hxx>
61 #include <Scenery/tilemgr.hxx>
62 #include <Sound/fg_fx.hxx>
63 #include <Sound/beacon.hxx>
64 #include <Sound/morse.hxx>
65 #include <Sound/fg_fx.hxx>
66 #include <ATCDCL/ATCmgr.hxx>
67 #include <Time/TimeManager.hxx>
68 #include <Environment/environment_mgr.hxx>
69 #include <Environment/ephemeris.hxx>
71 #include <GUI/new_gui.hxx>
72 #include <MultiPlayer/multiplaymgr.hxx>
74 #include "CameraGroup.hxx"
75 #include "fg_commands.hxx"
77 #include "renderer.hxx"
81 #include "fg_init.hxx"
83 #include "WindowSystemAdapter.hxx"
84 #include <Main/viewer.hxx>
87 using namespace flightgear;
91 // Specify our current idle function state. This is used to run all
92 // our initializations out of the idle callback so that we can get a
93 // splash screen up and running right away.
97 void fgInitSoundManager();
98 void fgSetNewSoundDevice(const char *);
100 // The atexit() function handler should know when the graphical subsystem
102 extern int _bootstrap_OSInit;
104 // What should we do when we have nothing else to do? Let's get ready
105 // for the next move and update the display?
106 static void fgMainLoop( void ) {
108 static SGConstPropertyNode_ptr longitude
109 = fgGetNode("/position/longitude-deg");
110 static SGConstPropertyNode_ptr latitude
111 = fgGetNode("/position/latitude-deg");
112 static SGConstPropertyNode_ptr altitude
113 = fgGetNode("/position/altitude-ft");
114 static SGConstPropertyNode_ptr vn_fps
115 = fgGetNode("/velocities/speed-north-fps");
116 static SGConstPropertyNode_ptr ve_fps
117 = fgGetNode("/velocities/speed-east-fps");
118 static SGConstPropertyNode_ptr vd_fps
119 = fgGetNode("/velocities/speed-down-fps");
121 static SGPropertyNode_ptr frame_signal
122 = fgGetNode("/sim/signals/frame", true);
124 static SGPropertyNode_ptr _statisticsFlag
125 = fgGetNode("/sim/timing-statistics/enabled", true);
126 static SGPropertyNode_ptr _statisticsInterval
127 = fgGetNode("/sim/timing-statistics/interval-s", true);
128 static SGPropertyNode_ptr _statiticsMinJitter
129 = fgGetNode("/sim/timing-statistics/min-jitter-ms", true);
130 static SGPropertyNode_ptr _statiticsMinTime
131 = fgGetNode("/sim/timing-statistics/min-time-ms", true);
133 frame_signal->fireValueChanged();
134 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
136 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
137 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
141 double sim_dt, real_dt;
142 TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
143 // compute simulated time (allowing for pause, warp, etc) and
145 timeMgr->computeTimeDeltas(sim_dt, real_dt);
147 // update magvar model
148 globals->get_mag()->update( longitude->getDoubleValue()
149 * SGD_DEGREES_TO_RADIANS,
150 latitude->getDoubleValue()
151 * SGD_DEGREES_TO_RADIANS,
152 altitude->getDoubleValue() * SG_FEET_TO_METER,
153 globals->get_time_params()->getJD() );
156 globals->get_ATC_mgr()->update(sim_dt);
158 globals->get_subsystem_mgr()->update(sim_dt);
160 // Update the sound manager last so it can use the CPU while the GPU
161 // is processing the scenery (doubled the frame-rate for me) -EMH-
162 #ifdef ENABLE_AUDIO_SUPPORT
163 static bool smgr_init = true;
164 static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
165 if (smgr_init == true) {
166 if (sound_working->getBoolValue() == true) {
167 fgInitSoundManager();
171 static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
172 static SGSoundMgr *smgr = globals->get_soundmgr();
173 static bool smgr_enabled = true;
175 if (sound_working->getBoolValue() == false) { // request to reinit
178 sound_working->setBoolValue(true);
181 if (smgr_enabled != sound_enabled->getBoolValue()) {
182 if (smgr_enabled == true) { // request to suspend
184 smgr_enabled = false;
191 if (smgr_enabled == true) {
192 static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
193 smgr->set_volume(volume->getFloatValue());
194 smgr->update(sim_dt);
199 // END Tile Manager updates
200 bool scenery_loaded = fgGetBool("sim/sceneryloaded");
203 if (globals->get_tile_mgr()->isSceneryLoaded()
204 && fgGetBool("sim/fdm-initialized")) {
205 fgSetBool("sim/sceneryloaded",true);
206 if (fgGetBool("/sim/sound/working")) {
207 globals->get_soundmgr()->activate();
209 globals->get_props()->tie("/sim/sound/devices/name",
210 SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
214 // be nice to loader threads while waiting for initial scenery, reduce to 2fps
215 simgear::sleepForMSec(500);
219 // print timing statistics
220 static bool _lastStatisticsFlag = false;
221 if (_lastStatisticsFlag != _statisticsFlag->getBoolValue())
223 // flag has changed, update subsystem manager
224 _lastStatisticsFlag = _statisticsFlag->getBoolValue();
225 globals->get_subsystem_mgr()->collectDebugTiming(_lastStatisticsFlag);
227 if (_lastStatisticsFlag)
229 static double elapsed = 0;
231 if (elapsed >= _statisticsInterval->getDoubleValue())
233 // print and reset timing statistics
234 globals->get_subsystem_mgr()->printTimingStatistics(_statiticsMinTime->getDoubleValue(),
235 _statiticsMinJitter->getDoubleValue());
240 simgear::AtomicChangeListener::fireChangeListeners();
242 SG_LOG( SG_ALL, SG_DEBUG, "" );
245 void fgInitSoundManager()
247 SGSoundMgr *smgr = globals->get_soundmgr();
250 smgr->init(fgGetString("/sim/sound/device-name", NULL));
252 vector <const char*>devices = smgr->get_available_devices();
253 for (unsigned int i=0; i<devices.size(); i++) {
254 SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
255 p->setStringValue(devices[i]);
260 void fgSetNewSoundDevice(const char *device)
262 globals->get_soundmgr()->suspend();
263 globals->get_soundmgr()->stop();
264 globals->get_soundmgr()->init(device);
265 globals->get_soundmgr()->resume();
268 // Operation for querying OpenGL parameters. This must be done in a
269 // valid OpenGL context, potentially in another thread.
272 struct GeneralInitOperation : public GraphicsContextOperation
274 GeneralInitOperation()
275 : GraphicsContextOperation(std::string("General init"))
278 void run(osg::GraphicsContext* gc)
280 SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
282 simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
283 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
285 simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
286 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
288 simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
289 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
292 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
293 simRendering->setIntValue("max-texture-size", tmp);
295 glGetIntegerv( GL_DEPTH_BITS, &tmp );
296 simRendering->setIntValue("depth-buffer-bits", tmp);
301 osg::Node* load_panel(SGPropertyNode *n)
303 osg::Geode* geode = new osg::Geode;
304 geode->addDrawable(new FGPanelNode(n));
308 SGPath resolve_path(const std::string& s)
310 return globals->resolve_maybe_aircraft_path(s);
315 // This is the top level master main function that is registered as
318 // The first few passes take care of initialization things (a couple
319 // per pass) and once everything has been initialized fgMainLoop from
322 static void fgIdleFunction ( void ) {
323 static osg::ref_ptr<GeneralInitOperation> genOp;
324 if ( idle_state == 0 ) {
326 // Pick some window on which to do queries.
327 // XXX Perhaps all this graphics initialization code should be
328 // moved to renderer.cxx?
329 genOp = new GeneralInitOperation;
330 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
331 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
332 osg::GraphicsContext* gc = 0;
334 gc = guiCamera->getGraphicsContext();
336 gc->add(genOp.get());
338 wsa->windows[0]->gc->add(genOp.get());
341 } else if ( idle_state == 1 ) {
343 if (!genOp->isFinished())
347 if (!guiFinishInit())
350 fgSplashProgress("reading aircraft list");
353 } else if ( idle_state == 2 ) {
356 fgSplashProgress("reading airport & navigation data");
359 } else if ( idle_state == 3 ) {
362 fgSplashProgress("setting up scenery");
365 } else if ( idle_state == 4 ) {
367 // based on the requested presets, calculate the true starting
370 fgInitTowerLocationListener();
372 TimeManager* t = new TimeManager;
373 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
374 t->init(); // need to init now, not during initSubsystems
376 // Do some quick general initializations
377 if( !fgInitGeneral()) {
378 SG_LOG( SG_GENERAL, SG_ALERT,
379 "General initialization failed ..." );
383 ////////////////////////////////////////////////////////////////////
384 // Initialize the property-based built-in commands
385 ////////////////////////////////////////////////////////////////////
389 ////////////////////////////////////////////////////////////////////
390 // Initialize the material manager
391 ////////////////////////////////////////////////////////////////////
392 globals->set_matlib( new SGMaterialLib );
393 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
394 simgear::SGModelLib::setPanelFunc(load_panel);
396 ////////////////////////////////////////////////////////////////////
397 // Initialize the TG scenery subsystem.
398 ////////////////////////////////////////////////////////////////////
399 globals->set_scenery( new FGScenery );
400 globals->get_scenery()->init();
401 globals->get_scenery()->bind();
402 globals->set_tile_mgr( new FGTileMgr );
405 fgSplashProgress("loading aircraft");
408 } else if ( idle_state == 5 ) {
411 fgSplashProgress("generating sky elements");
414 } else if ( idle_state == 6 ) {
416 // Initialize the sky
418 Ephemeris* eph = new Ephemeris;
419 globals->add_subsystem("ephemeris", eph);
420 eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
423 // TODO: move to environment mgr
425 SGPath texture_path(globals->get_fg_root());
426 texture_path.append("Textures");
427 texture_path.append("Sky");
428 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
429 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
430 thesky->add_cloud_layer(layer);
433 SGPath sky_tex_path( globals->get_fg_root() );
434 sky_tex_path.append( "Textures" );
435 sky_tex_path.append( "Sky" );
436 thesky->texture_path( sky_tex_path.str() );
438 // The sun and moon diameters are scaled down numbers of the
439 // actual diameters. This was needed to fit both the sun and the
440 // moon within the distance to the far clip plane.
441 // Moon diameter: 3,476 kilometers
442 // Sun diameter: 1,390,000 kilometers
443 thesky->build( 80000.0, 80000.0,
445 *globals->get_ephem(),
446 fgGetNode("/environment", true));
448 // Initialize MagVar model
449 SGMagVar *magvar = new SGMagVar();
450 globals->set_mag( magvar );
453 // kludge to initialize mag compass
454 // (should only be done for in-flight
456 // update magvar model
457 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
458 * SGD_DEGREES_TO_RADIANS,
459 fgGetDouble("/position/latitude-deg")
460 * SGD_DEGREES_TO_RADIANS,
461 fgGetDouble("/position/altitude-ft")
463 globals->get_time_params()->getJD() );
464 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
465 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
466 fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
469 // airport = new ssgBranch;
470 // airport->setName( "Airport Lighting" );
471 // lighting->addKid( airport );
473 // build our custom render states
474 fgSplashProgress("initializing subsystems");
477 } else if ( idle_state == 7 ) {
479 // Initialize audio support
480 #ifdef ENABLE_AUDIO_SUPPORT
482 // Start the intro music
483 if ( fgGetBool("/sim/startup/intro-music") ) {
484 SGPath mp3file( globals->get_fg_root() );
485 mp3file.append( "Sounds/intro.mp3" );
487 SG_LOG( SG_GENERAL, SG_INFO,
488 "Starting intro music: " << mp3file.str() );
490 # if defined( __CYGWIN__ )
491 string command = "start /m `cygpath -w " + mp3file.str() + "`";
492 # elif defined( _WIN32 )
493 string command = "start /m " + mp3file.str();
495 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
498 system ( command.c_str() );
501 // This is the top level init routine which calls all the
502 // other subsystem initialization routines. If you are adding
503 // a subsystem to flightgear, its initialization call should be
504 // located in this routine.
505 if( !fgInitSubsystems()) {
506 SG_LOG( SG_GENERAL, SG_ALERT,
507 "Subsystem initialization failed ..." );
512 // ugly hack for automatic runway selection on startup based on
513 // metar data. Makes startup.nas obsolete and guarantees the same
514 // runway selection as for AI traffic. However, this code belongs to
515 // somewhere(?) else - if I only new where...
516 if( true == fgGetBool( "/environment/metar/valid" ) ) {
517 // the realwx_ctrl fetches metar in the foreground on init,
518 // If it was able to fetch a metar or one was given on the commandline,
519 // the valid flag is set here, otherwise it is false
520 double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
521 string apt = fgGetString( "/sim/startup/options/airport" );
522 string rwy = fgGetString( "/sim/startup/options/runway" );
523 double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
524 string parkpos = fgGetString( "/sim/presets/parkpos" );
525 bool onground = fgGetBool( "/sim/presets/onground", false );
526 // don't check for wind-speed < 1kt, this belongs to the runway-selection code
527 // the other logic is taken from former startup.nas
528 if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
529 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
530 fgSetPosFromAirportIDandHdg( apt, hdg );
533 fgSplashProgress("setting up time & renderer");
535 } else if ( idle_state == 8 ) {
538 // setup OpenGL view parameters
539 globals->get_renderer()->init();
541 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
542 fgGetInt("/sim/startup/ysize") );
544 fgSplashProgress("loading scenery objects");
545 int session = fgGetInt("/sim/session",0);
547 fgSetInt("/sim/session",session);
550 if ( idle_state == 1000 ) {
551 // We've finished all our initialization steps, from now on we
552 // run the main loop.
553 fgSetBool("sim/sceneryloaded", false);
554 fgRegisterIdleHandler( fgMainLoop );
559 static void upper_case_property(const char *name)
561 using namespace simgear;
562 SGPropertyNode *p = fgGetNode(name, false);
564 p = fgGetNode(name, true);
565 p->setStringValue("");
567 props::Type t = p->getType();
568 if (t == props::NONE || t == props::UNSPECIFIED)
569 p->setStringValue("");
571 assert(t == props::STRING);
573 p->addChangeListener(new FGMakeUpperCase);
577 // Main top level initialization
578 int fgMainInit( int argc, char **argv ) {
580 // set default log levels
581 sglog().setLogLevels( SG_ALL, SG_ALERT );
584 #ifdef FLIGHTGEAR_VERSION
585 version = FLIGHTGEAR_VERSION;
587 version = "unknown version";
589 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
591 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
593 // Allocate global data structures. This needs to happen before
594 // we parse command line options
596 globals = new FGGlobals;
598 // seed the random number generator
601 FGControls *controls = new FGControls;
602 globals->set_controls( controls );
604 string_list *col = new string_list;
605 globals->set_channel_options_list( col );
607 fgValidatePath("", false); // initialize static variables
608 upper_case_property("/sim/presets/airport-id");
609 upper_case_property("/sim/presets/runway");
610 upper_case_property("/sim/tower/airport-id");
611 upper_case_property("/autopilot/route-manager/input");
613 // Scan the config file(s) and command line options to see if
614 // fg_root was specified (ignore all other options for now)
615 fgInitFGRoot(argc, argv);
617 // Check for the correct base package version
618 static char required_version[] = "2.0.0";
619 string base_version = fgBasePackageVersion();
620 if ( !(base_version == required_version) ) {
621 // tell the operator how to use this application
623 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
624 cerr << endl << "Base package check failed ... " \
625 << "Found version " << base_version << " at: " \
626 << globals->get_fg_root() << endl;
627 cerr << "Please upgrade to version: " << required_version << endl;
629 cerr << "Hit a key to continue..." << endl;
635 // Load the configuration parameters. (Command line options
636 // override config file options. Config file options override
638 if ( !fgInitConfig(argc, argv) ) {
639 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
643 // Initialize the Window/Graphics environment.
644 fgOSInit(&argc, argv);
647 fgRegisterWindowResizeHandler( &FGRenderer::resize );
648 fgRegisterIdleHandler( &fgIdleFunction );
649 fgRegisterDrawHandler( &FGRenderer::update );
651 // Initialize sockets (WinSock needs this)
652 simgear::Socket::initSockets();
654 // Clouds3D requires an alpha channel
655 fgOSOpenWindow(true /* request stencil buffer */);
657 // Initialize the splash screen right away
661 // pass control off to the master event handler
662 int result = fgOSMainLoop();
664 // clean up here; ensure we null globals to avoid
665 // confusing the atexit() handler