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>
51 #include <simgear/io/raw_socket.hxx>
53 #include <Time/light.hxx>
54 #include <Aircraft/replay.hxx>
55 #include <Cockpit/cockpit.hxx>
56 #include <Cockpit/hud.hxx>
57 #include <Model/panelnode.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 // update magvar model
137 globals->get_mag()->update( longitude->getDoubleValue()
138 * SGD_DEGREES_TO_RADIANS,
139 latitude->getDoubleValue()
140 * SGD_DEGREES_TO_RADIANS,
141 altitude->getDoubleValue() * SG_FEET_TO_METER,
142 globals->get_time_params()->getJD() );
146 if (fgGetBool("/sim/atc/enabled"))
147 globals->get_ATC_mgr()->update(sim_dt);
150 globals->get_subsystem_mgr()->update(sim_dt);
152 // Update the sound manager last so it can use the CPU while the GPU
153 // is processing the scenery (doubled the frame-rate for me) -EMH-
154 #ifdef ENABLE_AUDIO_SUPPORT
155 static bool smgr_init = true;
156 static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
157 if (smgr_init == true) {
158 if (sound_working->getBoolValue() == true) {
159 fgInitSoundManager();
163 static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
164 static SGSoundMgr *smgr = globals->get_soundmgr();
165 static bool smgr_enabled = true;
167 if (sound_working->getBoolValue() == false) { // request to reinit
170 sound_working->setBoolValue(true);
173 if (smgr_enabled != sound_enabled->getBoolValue()) {
174 if (smgr_enabled == true) { // request to suspend
176 smgr_enabled = false;
183 if (smgr_enabled == true) {
184 static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
185 smgr->set_volume(volume->getFloatValue());
186 smgr->update(sim_dt);
191 // END Tile Manager udpates
192 bool scenery_loaded = fgGetBool("sim/sceneryloaded");
193 if (!scenery_loaded && globals->get_tile_mgr()->isSceneryLoaded()
194 && fgGetBool("sim/fdm-initialized")) {
195 fgSetBool("sim/sceneryloaded",true);
196 if (fgGetBool("/sim/sound/working")) {
197 globals->get_soundmgr()->activate();
199 globals->get_props()->tie("/sim/sound/devices/name",
200 SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
202 simgear::AtomicChangeListener::fireChangeListeners();
204 SG_LOG( SG_ALL, SG_DEBUG, "" );
207 void fgInitSoundManager()
209 SGSoundMgr *smgr = globals->get_soundmgr();
212 smgr->init(fgGetString("/sim/sound/device-name", NULL));
214 vector <const char*>devices = smgr->get_available_devices();
215 for (unsigned int i=0; i<devices.size(); i++) {
216 SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
217 p->setStringValue(devices[i]);
222 void fgSetNewSoundDevice(const char *device)
224 globals->get_soundmgr()->suspend();
225 globals->get_soundmgr()->stop();
226 globals->get_soundmgr()->init(device);
227 globals->get_soundmgr()->resume();
230 // Operation for querying OpenGL parameters. This must be done in a
231 // valid OpenGL context, potentially in another thread.
234 struct GeneralInitOperation : public GraphicsContextOperation
236 GeneralInitOperation()
237 : GraphicsContextOperation(std::string("General init"))
240 void run(osg::GraphicsContext* gc)
242 SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
244 simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
245 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
247 simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
248 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
250 simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
251 SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
254 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
255 simRendering->setIntValue("max-texture-size", tmp);
257 glGetIntegerv( GL_DEPTH_BITS, &tmp );
258 simRendering->setIntValue("depth-buffer-bits", tmp);
263 osg::Node* load_panel(SGPropertyNode *n)
265 osg::Geode* geode = new osg::Geode;
266 geode->addDrawable(new FGPanelNode(n));
270 SGPath resolve_path(const std::string& s)
272 return globals->resolve_maybe_aircraft_path(s);
277 // This is the top level master main function that is registered as
280 // The first few passes take care of initialization things (a couple
281 // per pass) and once everything has been initialized fgMainLoop from
284 static void fgIdleFunction ( void ) {
285 static osg::ref_ptr<GeneralInitOperation> genOp;
286 if ( idle_state == 0 ) {
288 // Pick some window on which to do queries.
289 // XXX Perhaps all this graphics initialization code should be
290 // moved to renderer.cxx?
291 genOp = new GeneralInitOperation;
292 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
293 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
294 osg::GraphicsContext* gc = 0;
296 gc = guiCamera->getGraphicsContext();
298 gc->add(genOp.get());
300 wsa->windows[0]->gc->add(genOp.get());
303 } else if ( idle_state == 1 ) {
305 if (!genOp->isFinished())
309 if (!guiFinishInit())
312 fgSplashProgress("reading aircraft list");
315 } else if ( idle_state == 2 ) {
318 fgSplashProgress("reading airport & navigation data");
321 } else if ( idle_state == 3 ) {
324 fgSplashProgress("setting up scenery");
327 } else if ( idle_state == 4 ) {
329 // based on the requested presets, calculate the true starting
332 fgInitTowerLocationListener();
334 TimeManager* t = new TimeManager;
335 globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
336 t->init(); // need to init now, not during initSubsystems
338 // Do some quick general initializations
339 if( !fgInitGeneral()) {
340 SG_LOG( SG_GENERAL, SG_ALERT,
341 "General initialization failed ..." );
345 ////////////////////////////////////////////////////////////////////
346 // Initialize the property-based built-in commands
347 ////////////////////////////////////////////////////////////////////
351 ////////////////////////////////////////////////////////////////////
352 // Initialize the material manager
353 ////////////////////////////////////////////////////////////////////
354 globals->set_matlib( new SGMaterialLib );
355 simgear::SGModelLib::init(globals->get_fg_root());
356 simgear::SGModelLib::setPropRoot(globals->get_props());
357 simgear::SGModelLib::setPanelFunc(load_panel);
359 ////////////////////////////////////////////////////////////////////
360 // Initialize the TG scenery subsystem.
361 ////////////////////////////////////////////////////////////////////
362 globals->set_scenery( new FGScenery );
363 globals->get_scenery()->init();
364 globals->get_scenery()->bind();
365 globals->set_tile_mgr( new FGTileMgr );
368 fgSplashProgress("loading aircraft");
371 } else if ( idle_state == 5 ) {
374 fgSplashProgress("generating sky elements");
377 } else if ( idle_state == 6 ) {
379 // Initialize the sky
381 Ephemeris* eph = new Ephemeris;
382 globals->add_subsystem("ephemeris", eph);
383 eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
386 // TODO: move to environment mgr
388 SGPath texture_path(globals->get_fg_root());
389 texture_path.append("Textures");
390 texture_path.append("Sky");
391 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
392 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
393 thesky->add_cloud_layer(layer);
396 SGPath sky_tex_path( globals->get_fg_root() );
397 sky_tex_path.append( "Textures" );
398 sky_tex_path.append( "Sky" );
399 thesky->texture_path( sky_tex_path.str() );
401 // The sun and moon diameters are scaled down numbers of the
402 // actual diameters. This was needed to fit both the sun and the
403 // moon within the distance to the far clip plane.
404 // Moon diameter: 3,476 kilometers
405 // Sun diameter: 1,390,000 kilometers
406 thesky->build( 80000.0, 80000.0,
408 *globals->get_ephem(),
409 fgGetNode("/environment", true));
411 // Initialize MagVar model
412 SGMagVar *magvar = new SGMagVar();
413 globals->set_mag( magvar );
416 // kludge to initialize mag compass
417 // (should only be done for in-flight
419 // update magvar model
420 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
421 * SGD_DEGREES_TO_RADIANS,
422 fgGetDouble("/position/latitude-deg")
423 * SGD_DEGREES_TO_RADIANS,
424 fgGetDouble("/position/altitude-ft")
426 globals->get_time_params()->getJD() );
427 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
428 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
429 fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
432 // airport = new ssgBranch;
433 // airport->setName( "Airport Lighting" );
434 // lighting->addKid( airport );
436 // build our custom render states
437 fgSplashProgress("initializing subsystems");
440 } else if ( idle_state == 7 ) {
442 // Initialize audio support
443 #ifdef ENABLE_AUDIO_SUPPORT
445 // Start the intro music
446 if ( fgGetBool("/sim/startup/intro-music") ) {
447 SGPath mp3file( globals->get_fg_root() );
448 mp3file.append( "Sounds/intro.mp3" );
450 SG_LOG( SG_GENERAL, SG_INFO,
451 "Starting intro music: " << mp3file.str() );
453 # if defined( __CYGWIN__ )
454 string command = "start /m `cygpath -w " + mp3file.str() + "`";
455 # elif defined( _WIN32 )
456 string command = "start /m " + mp3file.str();
458 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
461 system ( command.c_str() );
464 // This is the top level init routine which calls all the
465 // other subsystem initialization routines. If you are adding
466 // a subsystem to flightgear, its initialization call should be
467 // located in this routine.
468 if( !fgInitSubsystems()) {
469 SG_LOG( SG_GENERAL, SG_ALERT,
470 "Subsystem initialization failed ..." );
473 fgSplashProgress("setting up time & renderer");
476 } else if ( idle_state == 8 ) {
479 // setup OpenGL view parameters
480 globals->get_renderer()->init();
482 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
483 fgGetInt("/sim/startup/ysize") );
485 fgSplashProgress("loading scenery objects");
486 int session = fgGetInt("/sim/session",0);
488 fgSetInt("/sim/session",session);
491 if ( idle_state == 1000 ) {
492 // We've finished all our initialization steps, from now on we
493 // run the main loop.
494 fgSetBool("sim/sceneryloaded", false);
495 fgRegisterIdleHandler( fgMainLoop );
500 static void upper_case_property(const char *name)
502 using namespace simgear;
503 SGPropertyNode *p = fgGetNode(name, false);
505 p = fgGetNode(name, true);
506 p->setStringValue("");
508 props::Type t = p->getType();
509 if (t == props::NONE || t == props::UNSPECIFIED)
510 p->setStringValue("");
512 assert(t == props::STRING);
514 p->addChangeListener(new FGMakeUpperCase);
518 // Main top level initialization
519 int fgMainInit( int argc, char **argv ) {
521 // set default log levels
522 sglog().setLogLevels( SG_ALL, SG_ALERT );
525 #ifdef FLIGHTGEAR_VERSION
526 version = FLIGHTGEAR_VERSION;
528 version = "unknown version";
530 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
532 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
534 // Allocate global data structures. This needs to happen before
535 // we parse command line options
537 globals = new FGGlobals;
539 // seed the random number generator
542 FGControls *controls = new FGControls;
543 globals->set_controls( controls );
545 string_list *col = new string_list;
546 globals->set_channel_options_list( col );
548 fgValidatePath("", false); // initialize static variables
549 upper_case_property("/sim/presets/airport-id");
550 upper_case_property("/sim/presets/runway");
551 upper_case_property("/sim/tower/airport-id");
552 upper_case_property("/autopilot/route-manager/input");
554 // Scan the config file(s) and command line options to see if
555 // fg_root was specified (ignore all other options for now)
556 fgInitFGRoot(argc, argv);
558 // Check for the correct base package version
559 static char required_version[] = "2.0.0";
560 string base_version = fgBasePackageVersion();
561 if ( !(base_version == required_version) ) {
562 // tell the operator how to use this application
564 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
565 cerr << endl << "Base package check failed ... " \
566 << "Found version " << base_version << " at: " \
567 << globals->get_fg_root() << endl;
568 cerr << "Please upgrade to version: " << required_version << endl;
570 cerr << "Hit a key to continue..." << endl;
576 // Load the configuration parameters. (Command line options
577 // override config file options. Config file options override
579 if ( !fgInitConfig(argc, argv) ) {
580 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
584 // Initialize the Window/Graphics environment.
585 fgOSInit(&argc, argv);
588 fgRegisterWindowResizeHandler( &FGRenderer::resize );
589 fgRegisterIdleHandler( &fgIdleFunction );
590 fgRegisterDrawHandler( &FGRenderer::update );
592 // Initialize sockets (WinSock needs this)
593 simgear::Socket::initSockets();
595 // Clouds3D requires an alpha channel
596 fgOSOpenWindow(true /* request stencil buffer */);
598 // Initialize the splash screen right away
602 // pass control off to the master event handler
603 int result = fgOSMainLoop();
605 // clean up here; ensure we null globals to avoid
606 // confusing the atexit() handler