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/timing/timestamp.hxx>
51 #include <simgear/magvar/magvar.hxx>
52 #include <simgear/math/sg_random.h>
53 #include <simgear/io/raw_socket.hxx>
54 #include <simgear/scene/tsync/terrasync.hxx>
56 #include <Time/light.hxx>
57 #include <Aircraft/replay.hxx>
58 #include <Aircraft/controls.hxx>
59 #include <Model/panelnode.hxx>
60 #include <Model/acmodel.hxx>
61 #include <Scenery/scenery.hxx>
62 #include <Scenery/tilemgr.hxx>
63 #include <Sound/fg_fx.hxx>
64 #include <Sound/beacon.hxx>
65 #include <Sound/morse.hxx>
66 #include <Sound/fg_fx.hxx>
67 #include <ATCDCL/ATCmgr.hxx>
68 #include <Time/TimeManager.hxx>
69 #include <Environment/environment_mgr.hxx>
70 #include <Environment/ephemeris.hxx>
72 #include <GUI/new_gui.hxx>
73 #include <MultiPlayer/multiplaymgr.hxx>
75 #include "CameraGroup.hxx"
76 #include "fg_commands.hxx"
78 #include "renderer.hxx"
82 #include "fg_init.hxx"
84 #include "WindowSystemAdapter.hxx"
85 #include <Main/viewer.hxx>
88 using namespace flightgear;
92 // Specify our current idle function state. This is used to run all
93 // our initializations out of the idle callback so that we can get a
94 // splash screen up and running right away.
98 void fgInitSoundManager();
99 void fgSetNewSoundDevice(const char *);
101 // The atexit() function handler should know when the graphical subsystem
103 extern int _bootstrap_OSInit;
105 // What should we do when we have nothing else to do? Let's get ready
106 // for the next move and update the display?
107 static void fgMainLoop( void ) {
109 static SGConstPropertyNode_ptr longitude
110 = fgGetNode("/position/longitude-deg");
111 static SGConstPropertyNode_ptr latitude
112 = fgGetNode("/position/latitude-deg");
113 static SGConstPropertyNode_ptr altitude
114 = fgGetNode("/position/altitude-ft");
115 static SGConstPropertyNode_ptr vn_fps
116 = fgGetNode("/velocities/speed-north-fps");
117 static SGConstPropertyNode_ptr ve_fps
118 = fgGetNode("/velocities/speed-east-fps");
119 static SGConstPropertyNode_ptr vd_fps
120 = fgGetNode("/velocities/speed-down-fps");
122 static SGPropertyNode_ptr frame_signal
123 = fgGetNode("/sim/signals/frame", true);
125 static SGPropertyNode_ptr _statisticsFlag
126 = fgGetNode("/sim/timing-statistics/enabled", true);
127 static SGPropertyNode_ptr _statisticsInterval
128 = fgGetNode("/sim/timing-statistics/interval-s", true);
129 static SGPropertyNode_ptr _statiticsMinJitter
130 = fgGetNode("/sim/timing-statistics/min-jitter-ms", true);
131 static SGPropertyNode_ptr _statiticsMinTime
132 = fgGetNode("/sim/timing-statistics/min-time-ms", true);
134 frame_signal->fireValueChanged();
136 SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
137 SG_LOG( SG_GENERAL, 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 fgSplashProgress("");
207 if (fgGetBool("/sim/sound/working")) {
208 globals->get_soundmgr()->activate();
210 globals->get_props()->tie("/sim/sound/devices/name",
211 SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
215 fgSplashProgress("loading scenery");
216 // be nice to loader threads while waiting for initial scenery, reduce to 2fps
217 SGTimeStamp::sleepForMSec(500);
221 // print timing statistics
222 static bool _lastStatisticsFlag = false;
223 if (_lastStatisticsFlag != _statisticsFlag->getBoolValue())
225 // flag has changed, update subsystem manager
226 _lastStatisticsFlag = _statisticsFlag->getBoolValue();
227 globals->get_subsystem_mgr()->collectDebugTiming(_lastStatisticsFlag);
229 if (_lastStatisticsFlag)
231 static double elapsed = 0;
233 if (elapsed >= _statisticsInterval->getDoubleValue())
235 // print and reset timing statistics
236 globals->get_subsystem_mgr()->printTimingStatistics(_statiticsMinTime->getDoubleValue(),
237 _statiticsMinJitter->getDoubleValue());
242 simgear::AtomicChangeListener::fireChangeListeners();
244 SG_LOG( SG_GENERAL, SG_DEBUG, "" );
247 void fgInitSoundManager()
249 SGSoundMgr *smgr = globals->get_soundmgr();
252 smgr->init(fgGetString("/sim/sound/device-name", NULL));
254 vector <const char*>devices = smgr->get_available_devices();
255 for (unsigned int i=0; i<devices.size(); i++) {
256 SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
257 p->setStringValue(devices[i]);
262 void fgSetNewSoundDevice(const char *device)
264 globals->get_soundmgr()->suspend();
265 globals->get_soundmgr()->stop();
266 globals->get_soundmgr()->init(device);
267 globals->get_soundmgr()->resume();
270 // Operation for querying OpenGL parameters. This must be done in a
271 // valid OpenGL context, potentially in another thread.
274 struct GeneralInitOperation : public GraphicsContextOperation
276 GeneralInitOperation()
277 : GraphicsContextOperation(std::string("General init"))
280 void run(osg::GraphicsContext* gc)
282 SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
284 simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
285 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
287 simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
288 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
290 simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
291 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
294 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
295 simRendering->setIntValue("max-texture-size", tmp);
297 glGetIntegerv( GL_DEPTH_BITS, &tmp );
298 simRendering->setIntValue("depth-buffer-bits", tmp);
303 osg::Node* load_panel(SGPropertyNode *n)
305 osg::Geode* geode = new osg::Geode;
306 geode->addDrawable(new FGPanelNode(n));
310 SGPath resolve_path(const std::string& s)
312 return globals->resolve_maybe_aircraft_path(s);
317 // This is the top level master main function that is registered as
320 // The first few passes take care of initialization things (a couple
321 // per pass) and once everything has been initialized fgMainLoop from
324 static void fgIdleFunction ( void ) {
325 static osg::ref_ptr<GeneralInitOperation> genOp;
326 if ( idle_state == 0 ) {
328 // Pick some window on which to do queries.
329 // XXX Perhaps all this graphics initialization code should be
330 // moved to renderer.cxx?
331 genOp = new GeneralInitOperation;
332 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
333 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
334 osg::GraphicsContext* gc = 0;
336 gc = guiCamera->getGraphicsContext();
338 gc->add(genOp.get());
340 wsa->windows[0]->gc->add(genOp.get());
343 } else if ( idle_state == 1 ) {
345 if (!genOp->isFinished())
349 if (!guiFinishInit())
352 fgSplashProgress("loading aircraft list");
354 } else if ( idle_state == 2 ) {
356 fgSplashProgress("loading navigation data");
358 } else if ( idle_state == 3 ) {
362 fgSplashProgress("initializing scenery system");
364 } else if ( idle_state == 4 ) {
366 // based on the requested presets, calculate the true starting
369 fgInitTowerLocationListener();
371 TimeManager* t = new TimeManager;
372 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
373 t->init(); // need to init now, not during initSubsystems
375 // Do some quick general initializations
376 if( !fgInitGeneral()) {
377 SG_LOG( SG_GENERAL, SG_ALERT,
378 "General initialization failed ..." );
382 ////////////////////////////////////////////////////////////////////
383 // Initialize the property-based built-in commands
384 ////////////////////////////////////////////////////////////////////
387 ////////////////////////////////////////////////////////////////////
388 // Initialize the material manager
389 ////////////////////////////////////////////////////////////////////
390 globals->set_matlib( new SGMaterialLib );
391 simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
392 simgear::SGModelLib::setPanelFunc(load_panel);
394 ////////////////////////////////////////////////////////////////////
395 // Initialize the TG scenery subsystem.
396 ////////////////////////////////////////////////////////////////////
397 simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
398 globals->add_subsystem("terrasync", terra_sync);
399 globals->set_scenery( new FGScenery );
400 globals->get_scenery()->init();
401 globals->get_scenery()->bind();
402 globals->set_tile_mgr( new FGTileMgr );
404 fgSplashProgress("loading aircraft");
406 } else if ( idle_state == 5 ) {
409 fgSplashProgress("initializing sky elements");
411 } else if ( idle_state == 6 ) {
413 // Initialize the sky
415 Ephemeris* eph = new Ephemeris;
416 globals->add_subsystem("ephemeris", eph);
417 eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
420 // TODO: move to environment mgr
422 SGPath texture_path(globals->get_fg_root());
423 texture_path.append("Textures");
424 texture_path.append("Sky");
425 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
426 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
427 thesky->add_cloud_layer(layer);
430 SGPath sky_tex_path( globals->get_fg_root() );
431 sky_tex_path.append( "Textures" );
432 sky_tex_path.append( "Sky" );
433 thesky->texture_path( sky_tex_path.str() );
435 // The sun and moon diameters are scaled down numbers of the
436 // actual diameters. This was needed to fit both the sun and the
437 // moon within the distance to the far clip plane.
438 // Moon diameter: 3,476 kilometers
439 // Sun diameter: 1,390,000 kilometers
440 thesky->build( 80000.0, 80000.0,
442 *globals->get_ephem(),
443 fgGetNode("/environment", true));
445 // Initialize MagVar model
446 SGMagVar *magvar = new SGMagVar();
447 globals->set_mag( magvar );
450 // kludge to initialize mag compass
451 // (should only be done for in-flight
453 // update magvar model
454 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
455 * SGD_DEGREES_TO_RADIANS,
456 fgGetDouble("/position/latitude-deg")
457 * SGD_DEGREES_TO_RADIANS,
458 fgGetDouble("/position/altitude-ft")
460 globals->get_time_params()->getJD() );
461 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
462 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
463 fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
466 // airport = new ssgBranch;
467 // airport->setName( "Airport Lighting" );
468 // lighting->addKid( airport );
470 fgSplashProgress("initializing subsystems");
472 } else if ( idle_state == 7 ) {
474 // Initialize audio support
475 #ifdef ENABLE_AUDIO_SUPPORT
477 // Start the intro music
478 if ( fgGetBool("/sim/startup/intro-music") ) {
479 SGPath mp3file( globals->get_fg_root() );
480 mp3file.append( "Sounds/intro.mp3" );
482 SG_LOG( SG_GENERAL, SG_INFO,
483 "Starting intro music: " << mp3file.str() );
485 # if defined( __CYGWIN__ )
486 string command = "start /m `cygpath -w " + mp3file.str() + "`";
487 # elif defined( _WIN32 )
488 string command = "start /m " + mp3file.str();
490 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
493 system ( command.c_str() );
496 // This is the top level init routine which calls all the
497 // other subsystem initialization routines. If you are adding
498 // a subsystem to flightgear, its initialization call should be
499 // located in this routine.
500 if( !fgInitSubsystems()) {
501 SG_LOG( SG_GENERAL, SG_ALERT,
502 "Subsystem initialization failed ..." );
507 // ugly hack for automatic runway selection on startup based on
508 // metar data. Makes startup.nas obsolete and guarantees the same
509 // runway selection as for AI traffic. However, this code belongs to
510 // somewhere(?) else - if I only new where...
511 if( true == fgGetBool( "/environment/metar/valid" ) ) {
512 SG_LOG(SG_ENVIRONMENT, SG_INFO,
513 "Using METAR for runway selection: '" << fgGetString("/environment/metar/data") << "'" );
514 // the realwx_ctrl fetches metar in the foreground on init,
515 // If it was able to fetch a metar or one was given on the commandline,
516 // the valid flag is set here, otherwise it is false
517 double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
518 string apt = fgGetString( "/sim/startup/options/airport" );
519 string rwy = fgGetString( "/sim/startup/options/runway" );
520 double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
521 string parkpos = fgGetString( "/sim/presets/parkpos" );
522 bool onground = fgGetBool( "/sim/presets/onground", false );
523 // don't check for wind-speed < 1kt, this belongs to the runway-selection code
524 // the other logic is taken from former startup.nas
525 if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
526 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
527 fgSetPosFromAirportIDandHdg( apt, hdg );
530 SG_LOG(SG_ENVIRONMENT, SG_INFO,
531 "No METAR available to pick active runway" );
534 fgSplashProgress("initializing graphics engine");
536 } else if ( idle_state == 8 ) {
539 // setup OpenGL view parameters
540 globals->get_renderer()->setupView();
542 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
543 fgGetInt("/sim/startup/ysize") );
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 );
558 static void upper_case_property(const char *name)
560 using namespace simgear;
561 SGPropertyNode *p = fgGetNode(name, false);
563 p = fgGetNode(name, true);
564 p->setStringValue("");
566 props::Type t = p->getType();
567 if (t == props::NONE || t == props::UNSPECIFIED)
568 p->setStringValue("");
570 assert(t == props::STRING);
572 p->addChangeListener(new FGMakeUpperCase);
576 // Main top level initialization
577 int fgMainInit( int argc, char **argv ) {
579 // set default log levels
580 sglog().setLogLevels( SG_ALL, SG_ALERT );
583 #ifdef FLIGHTGEAR_VERSION
584 version = FLIGHTGEAR_VERSION;
586 version = "unknown version";
588 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
590 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << std::endl );
592 // Allocate global data structures. This needs to happen before
593 // we parse command line options
595 globals = new FGGlobals;
597 // seed the random number generator
600 FGControls *controls = new FGControls;
601 globals->set_controls( controls );
603 string_list *col = new string_list;
604 globals->set_channel_options_list( col );
606 fgValidatePath("", false); // initialize static variables
607 upper_case_property("/sim/presets/airport-id");
608 upper_case_property("/sim/presets/runway");
609 upper_case_property("/sim/tower/airport-id");
610 upper_case_property("/autopilot/route-manager/input");
612 // Load the configuration parameters. (Command line options
613 // override config file options. Config file options override
615 if ( !fgInitConfig(argc, argv) ) {
616 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
620 // Initialize the Window/Graphics environment.
621 fgOSInit(&argc, argv);
624 fgRegisterIdleHandler( &fgIdleFunction );
626 // Initialize sockets (WinSock needs this)
627 simgear::Socket::initSockets();
629 // Clouds3D requires an alpha channel
630 fgOSOpenWindow(true /* request stencil buffer */);
632 // Initialize the splash screen right away
636 // pass control off to the master event handler
637 int result = fgOSMainLoop();
639 // clean up here; ensure we null globals to avoid
640 // confusing the atexit() handler