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/math/sg_random.h>
52 #include <Time/light.hxx>
53 #include <Aircraft/replay.hxx>
54 #include <Cockpit/cockpit.hxx>
55 #include <Cockpit/hud.hxx>
56 #include <Model/panelnode.hxx>
57 #include <Model/modelmgr.hxx>
58 #include <Model/acmodel.hxx>
59 #include <Scenery/scenery.hxx>
60 #include <Scenery/tilemgr.hxx>
61 #include <Sound/fg_fx.hxx>
62 #include <Sound/beacon.hxx>
63 #include <Sound/morse.hxx>
64 #include <Sound/fg_fx.hxx>
65 #include <ATCDCL/ATCmgr.hxx>
66 #include <Time/TimeManager.hxx>
67 #include <Environment/environment_mgr.hxx>
68 #include <Environment/ephemeris.hxx>
69 #include <GUI/new_gui.hxx>
70 #include <MultiPlayer/multiplaymgr.hxx>
72 #include "CameraGroup.hxx"
73 #include "fg_commands.hxx"
75 #include "renderer.hxx"
79 #include "fg_init.hxx"
81 #include "WindowSystemAdapter.hxx"
82 #include <Main/viewer.hxx>
85 using namespace flightgear;
89 // Specify our current idle function state. This is used to run all
90 // our initializations out of the idle callback so that we can get a
91 // splash screen up and running right away.
95 void fgInitSoundManager();
96 void fgSetNewSoundDevice(const char *);
98 // The atexit() function handler should know when the graphical subsystem
100 extern int _bootstrap_OSInit;
102 // What should we do when we have nothing else to do? Let's get ready
103 // for the next move and update the display?
104 static void fgMainLoop( void ) {
106 static SGConstPropertyNode_ptr longitude
107 = fgGetNode("/position/longitude-deg");
108 static SGConstPropertyNode_ptr latitude
109 = fgGetNode("/position/latitude-deg");
110 static SGConstPropertyNode_ptr altitude
111 = fgGetNode("/position/altitude-ft");
112 static SGConstPropertyNode_ptr vn_fps
113 = fgGetNode("/velocities/speed-north-fps");
114 static SGConstPropertyNode_ptr ve_fps
115 = fgGetNode("/velocities/speed-east-fps");
116 static SGConstPropertyNode_ptr vd_fps
117 = fgGetNode("/velocities/speed-down-fps");
119 static SGPropertyNode_ptr frame_signal
120 = fgGetNode("/sim/signals/frame", true);
122 frame_signal->fireValueChanged();
123 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
125 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
126 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
130 double sim_dt, real_dt;
131 TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
132 // compute simulated time (allowing for pause, warp, etc) and
134 timeMgr->computeTimeDeltas(sim_dt, real_dt);
136 if (globals->get_warp_delta() != 0) {
137 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
141 // update magvar model
142 globals->get_mag()->update( longitude->getDoubleValue()
143 * SGD_DEGREES_TO_RADIANS,
144 latitude->getDoubleValue()
145 * SGD_DEGREES_TO_RADIANS,
146 altitude->getDoubleValue() * SG_FEET_TO_METER,
147 globals->get_time_params()->getJD() );
150 // Update any multiplayer's network queues, the AIMultiplayer
151 // implementation is an AI model and depends on that
152 globals->get_multiplayer_mgr()->Update();
156 if (fgGetBool("/sim/atc/enabled"))
157 globals->get_ATC_mgr()->update(sim_dt);
160 globals->get_subsystem_mgr()->update(sim_dt);
161 globals->get_aircraft_model()->update(sim_dt);
163 // run Nasal's settimer() loops right before the view manager
164 globals->get_event_mgr()->update(sim_dt);
166 // pick up model coordidnates that Nasal code may have set relative to the
168 globals->get_model_mgr()->update(sim_dt);
170 // update the view angle as late as possible, but before sound calculations
171 globals->get_viewmgr()->update(real_dt);
173 // Update the sound manager last so it can use the CPU while the GPU
174 // is processing the scenery (doubled the frame-rate for me) -EMH-
175 #ifdef ENABLE_AUDIO_SUPPORT
176 static bool smgr_init = true;
177 static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
178 if (smgr_init == true) {
179 if (sound_working->getBoolValue() == true) {
180 fgInitSoundManager();
184 static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
185 static SGSoundMgr *smgr = globals->get_soundmgr();
186 static bool smgr_enabled = true;
188 if (sound_working->getBoolValue() == false) { // request to reinit
191 sound_working->setBoolValue(true);
194 if (smgr_enabled != sound_enabled->getBoolValue()) {
195 if (smgr_enabled == true) { // request to suspend
197 smgr_enabled = false;
204 if (smgr_enabled == true) {
205 static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
206 smgr->set_volume(volume->getFloatValue());
207 smgr->update(sim_dt);
212 // END Tile Manager udpates
213 bool scenery_loaded = fgGetBool("sim/sceneryloaded");
214 if (!scenery_loaded && globals->get_tile_mgr()->isSceneryLoaded()
215 && fgGetBool("sim/fdm-initialized")) {
216 fgSetBool("sim/sceneryloaded",true);
217 if (fgGetBool("/sim/sound/working")) {
218 globals->get_soundmgr()->activate();
220 globals->get_props()->tie("/sim/sound/devices/name",
221 SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
223 simgear::AtomicChangeListener::fireChangeListeners();
225 SG_LOG( SG_ALL, SG_DEBUG, "" );
228 void fgInitSoundManager()
230 SGSoundMgr *smgr = globals->get_soundmgr();
233 smgr->init(fgGetString("/sim/sound/device-name", NULL));
235 vector <const char*>devices = smgr->get_available_devices();
236 for (unsigned int i=0; i<devices.size(); i++) {
237 SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
238 p->setStringValue(devices[i]);
243 void fgSetNewSoundDevice(const char *device)
245 globals->get_soundmgr()->suspend();
246 globals->get_soundmgr()->stop();
247 globals->get_soundmgr()->init(device);
248 globals->get_soundmgr()->resume();
251 // Operation for querying OpenGL parameters. This must be done in a
252 // valid OpenGL context, potentially in another thread.
255 struct GeneralInitOperation : public GraphicsContextOperation
257 GeneralInitOperation()
258 : GraphicsContextOperation(std::string("General init"))
261 void run(osg::GraphicsContext* gc)
263 SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
265 simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
266 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
268 simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
269 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
271 simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
272 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
275 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
276 simRendering->setIntValue("max-texture-size", tmp);
278 glGetIntegerv( GL_DEPTH_BITS, &tmp );
279 simRendering->setIntValue("depth-buffer-bits", tmp);
284 osg::Node* load_panel(SGPropertyNode *n)
286 osg::Geode* geode = new osg::Geode;
287 geode->addDrawable(new FGPanelNode(n));
291 SGPath resolve_path(const std::string& s)
293 return globals->resolve_maybe_aircraft_path(s);
298 // This is the top level master main function that is registered as
301 // The first few passes take care of initialization things (a couple
302 // per pass) and once everything has been initialized fgMainLoop from
305 static void fgIdleFunction ( void ) {
306 static osg::ref_ptr<GeneralInitOperation> genOp;
307 if ( idle_state == 0 ) {
309 // Pick some window on which to do queries.
310 // XXX Perhaps all this graphics initialization code should be
311 // moved to renderer.cxx?
312 genOp = new GeneralInitOperation;
313 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
314 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
315 osg::GraphicsContext* gc = 0;
317 gc = guiCamera->getGraphicsContext();
319 gc->add(genOp.get());
321 wsa->windows[0]->gc->add(genOp.get());
324 } else if ( idle_state == 1 ) {
326 if (!genOp->isFinished())
330 if (!guiFinishInit())
333 fgSplashProgress("reading aircraft list");
336 } else if ( idle_state == 2 ) {
339 fgSplashProgress("reading airport & navigation data");
342 } else if ( idle_state == 3 ) {
345 fgSplashProgress("setting up scenery");
348 } else if ( idle_state == 4 ) {
350 // based on the requested presets, calculate the true starting
353 fgInitTowerLocationListener();
355 TimeManager* t = new TimeManager;
356 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
357 t->init(); // need to init now, not during initSubsystems
359 // Do some quick general initializations
360 if( !fgInitGeneral()) {
361 SG_LOG( SG_GENERAL, SG_ALERT,
362 "General initialization failed ..." );
366 ////////////////////////////////////////////////////////////////////
367 // Initialize the property-based built-in commands
368 ////////////////////////////////////////////////////////////////////
372 ////////////////////////////////////////////////////////////////////
373 // Initialize the material manager
374 ////////////////////////////////////////////////////////////////////
375 globals->set_matlib( new SGMaterialLib );
376 simgear::SGModelLib::init(globals->get_fg_root());
377 simgear::SGModelLib::setPropRoot(globals->get_props());
378 simgear::SGModelLib::setPanelFunc(load_panel);
380 ////////////////////////////////////////////////////////////////////
381 // Initialize the TG scenery subsystem.
382 ////////////////////////////////////////////////////////////////////
383 globals->set_scenery( new FGScenery );
384 globals->get_scenery()->init();
385 globals->get_scenery()->bind();
386 globals->set_tile_mgr( new FGTileMgr );
389 ////////////////////////////////////////////////////////////////////
390 // Initialize the general model subsystem.
391 ////////////////////////////////////////////////////////////////////
392 globals->set_model_mgr(new FGModelMgr);
393 globals->get_model_mgr()->init();
394 globals->get_model_mgr()->bind();
395 fgSplashProgress("loading aircraft");
398 } else if ( idle_state == 5 ) {
401 ////////////////////////////////////////////////////////////////////
402 // Initialize the 3D aircraft model subsystem (has a dependency on
403 // the scenery subsystem.)
404 ////////////////////////////////////////////////////////////////////
405 FGAircraftModel* acm = new FGAircraftModel;
406 globals->set_aircraft_model(acm);
407 //globals->add_subsystem("aircraft-model", acm);
411 ////////////////////////////////////////////////////////////////////
412 // Initialize the view manager subsystem.
413 ////////////////////////////////////////////////////////////////////
414 FGViewMgr *viewmgr = new FGViewMgr;
415 globals->set_viewmgr( viewmgr );
418 fgSplashProgress("generating sky elements");
421 } else if ( idle_state == 6 ) {
423 // Initialize the sky
425 Ephemeris* eph = new Ephemeris;
426 globals->add_subsystem("ephemeris", eph);
427 eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
430 // TODO: move to environment mgr
432 SGPath texture_path(globals->get_fg_root());
433 texture_path.append("Textures");
434 texture_path.append("Sky");
435 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
436 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
437 thesky->add_cloud_layer(layer);
440 SGPath sky_tex_path( globals->get_fg_root() );
441 sky_tex_path.append( "Textures" );
442 sky_tex_path.append( "Sky" );
443 thesky->texture_path( sky_tex_path.str() );
445 // The sun and moon diameters are scaled down numbers of the
446 // actual diameters. This was needed to fit both the sun and the
447 // moon within the distance to the far clip plane.
448 // Moon diameter: 3,476 kilometers
449 // Sun diameter: 1,390,000 kilometers
450 thesky->build( 80000.0, 80000.0,
452 *globals->get_ephem(),
453 fgGetNode("/environment", true));
455 // Initialize MagVar model
456 SGMagVar *magvar = new SGMagVar();
457 globals->set_mag( magvar );
460 // kludge to initialize mag compass
461 // (should only be done for in-flight
463 // update magvar model
464 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
465 * SGD_DEGREES_TO_RADIANS,
466 fgGetDouble("/position/latitude-deg")
467 * SGD_DEGREES_TO_RADIANS,
468 fgGetDouble("/position/altitude-ft")
470 globals->get_time_params()->getJD() );
471 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
472 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
473 fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
476 // airport = new ssgBranch;
477 // airport->setName( "Airport Lighting" );
478 // lighting->addKid( airport );
480 // build our custom render states
481 fgSplashProgress("initializing subsystems");
484 } else if ( idle_state == 7 ) {
486 // Initialize audio support
487 #ifdef ENABLE_AUDIO_SUPPORT
489 // Start the intro music
490 if ( fgGetBool("/sim/startup/intro-music") ) {
491 SGPath mp3file( globals->get_fg_root() );
492 mp3file.append( "Sounds/intro.mp3" );
494 SG_LOG( SG_GENERAL, SG_INFO,
495 "Starting intro music: " << mp3file.str() );
497 # if defined( __CYGWIN__ )
498 string command = "start /m `cygpath -w " + mp3file.str() + "`";
499 # elif defined( _WIN32 )
500 string command = "start /m " + mp3file.str();
502 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
505 system ( command.c_str() );
508 // This is the top level init routine which calls all the
509 // other subsystem initialization routines. If you are adding
510 // a subsystem to flightgear, its initialization call should be
511 // located in this routine.
512 if( !fgInitSubsystems()) {
513 SG_LOG( SG_GENERAL, SG_ALERT,
514 "Subsystem initialization failed ..." );
517 fgSplashProgress("setting up time & renderer");
520 } else if ( idle_state == 8 ) {
523 // setup OpenGL view parameters
524 globals->get_renderer()->init();
526 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
527 fgGetInt("/sim/startup/ysize") );
529 fgSplashProgress("loading scenery objects");
530 int session = fgGetInt("/sim/session",0);
532 fgSetInt("/sim/session",session);
535 if ( idle_state == 1000 ) {
536 // We've finished all our initialization steps, from now on we
537 // run the main loop.
538 fgSetBool("sim/sceneryloaded", false);
539 fgRegisterIdleHandler( fgMainLoop );
544 static void upper_case_property(const char *name)
546 using namespace simgear;
547 SGPropertyNode *p = fgGetNode(name, false);
549 p = fgGetNode(name, true);
550 p->setStringValue("");
552 props::Type t = p->getType();
553 if (t == props::NONE || t == props::UNSPECIFIED)
554 p->setStringValue("");
556 assert(t == props::STRING);
558 p->addChangeListener(new FGMakeUpperCase);
562 // Main top level initialization
563 int fgMainInit( int argc, char **argv ) {
565 // set default log levels
566 sglog().setLogLevels( SG_ALL, SG_ALERT );
569 #ifdef FLIGHTGEAR_VERSION
570 version = FLIGHTGEAR_VERSION;
572 version = "unknown version";
574 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
576 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
578 // Allocate global data structures. This needs to happen before
579 // we parse command line options
581 globals = new FGGlobals;
583 // seed the random number generator
586 FGControls *controls = new FGControls;
587 globals->set_controls( controls );
589 string_list *col = new string_list;
590 globals->set_channel_options_list( col );
592 fgValidatePath("", false); // initialize static variables
593 upper_case_property("/sim/presets/airport-id");
594 upper_case_property("/sim/presets/runway");
595 upper_case_property("/sim/tower/airport-id");
596 upper_case_property("/autopilot/route-manager/input");
598 // Scan the config file(s) and command line options to see if
599 // fg_root was specified (ignore all other options for now)
600 fgInitFGRoot(argc, argv);
602 // Check for the correct base package version
603 static char required_version[] = "2.0.0";
604 string base_version = fgBasePackageVersion();
605 if ( !(base_version == required_version) ) {
606 // tell the operator how to use this application
608 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
609 cerr << endl << "Base package check failed ... " \
610 << "Found version " << base_version << " at: " \
611 << globals->get_fg_root() << endl;
612 cerr << "Please upgrade to version: " << required_version << endl;
614 cerr << "Hit a key to continue..." << endl;
620 // Load the configuration parameters. (Command line options
621 // override config file options. Config file options override
623 if ( !fgInitConfig(argc, argv) ) {
624 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
628 // Initialize the Window/Graphics environment.
629 fgOSInit(&argc, argv);
632 fgRegisterWindowResizeHandler( &FGRenderer::resize );
633 fgRegisterIdleHandler( &fgIdleFunction );
634 fgRegisterDrawHandler( &FGRenderer::update );
636 // Initialize plib net interface
637 netInit( &argc, argv );
639 // Clouds3D requires an alpha channel
640 fgOSOpenWindow(true /* request stencil buffer */);
642 // Initialize the splash screen right away
646 // pass control off to the master event handler
647 int result = fgOSMainLoop();
649 // clean up here; ensure we null globals to avoid
650 // confusing the atexit() handler