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>
37 #include <plib/netSocket.h>
40 #include <osg/GraphicsContext>
41 #include <osgDB/Registry>
44 #include <simgear/scene/model/modellib.hxx>
45 #include <simgear/scene/material/matlib.hxx>
46 #include <simgear/scene/model/animation.hxx>
47 #include <simgear/scene/sky/sky.hxx>
48 #include <simgear/structure/event_mgr.hxx>
49 #include <simgear/props/AtomicChangeListener.hxx>
50 #include <simgear/props/props.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/math/sg_random.h>
54 #include <Time/light.hxx>
55 #include <Include/general.hxx>
56 #include <Aircraft/replay.hxx>
57 #include <Aircraft/aircraft.hxx>
58 #include <Cockpit/cockpit.hxx>
59 #include <Cockpit/hud.hxx>
60 #include <Model/panelnode.hxx>
61 #include <Model/modelmgr.hxx>
62 #include <Model/acmodel.hxx>
63 #include <Scenery/scenery.hxx>
64 #include <Scenery/tilemgr.hxx>
65 #include <Sound/fg_fx.hxx>
66 #include <Sound/beacon.hxx>
67 #include <Sound/morse.hxx>
68 #include <Sound/fg_fx.hxx>
69 #include <ATCDCL/ATCmgr.hxx>
70 #include <ATCDCL/AIMgr.hxx>
71 #include <Time/tmp.hxx>
72 #include <Environment/environment_mgr.hxx>
73 #include <Environment/ephemeris.hxx>
74 #include <GUI/new_gui.hxx>
75 #include <MultiPlayer/multiplaymgr.hxx>
77 #include "CameraGroup.hxx"
78 #include "fg_commands.hxx"
80 #include "renderer.hxx"
84 #include "fg_init.hxx"
86 #include "WindowSystemAdapter.hxx"
87 #include <Main/viewer.hxx>
89 static double real_delta_time_sec = 0.0;
90 double delta_time_sec = 0.0;
92 using namespace flightgear;
96 // This is a record containing a bit of global housekeeping information
99 // Specify our current idle function state. This is used to run all
100 // our initializations out of the idle callback so that we can get a
101 // splash screen up and running right away.
103 long global_multi_loop;
105 SGTimeStamp last_time_stamp;
106 SGTimeStamp current_time_stamp;
108 void fgInitSoundManager();
109 void fgSetNewSoundDevice(const char *);
111 // The atexit() function handler should know when the graphical subsystem
113 extern int _bootstrap_OSInit;
115 // What should we do when we have nothing else to do? Let's get ready
116 // for the next move and update the display?
117 static void fgMainLoop( void ) {
118 int model_hz = fgGetInt("/sim/model-hz");
120 static SGConstPropertyNode_ptr longitude
121 = fgGetNode("/position/longitude-deg");
122 static SGConstPropertyNode_ptr latitude
123 = fgGetNode("/position/latitude-deg");
124 static SGConstPropertyNode_ptr altitude
125 = fgGetNode("/position/altitude-ft");
126 static SGConstPropertyNode_ptr vn_fps
127 = fgGetNode("/velocities/speed-north-fps");
128 static SGConstPropertyNode_ptr ve_fps
129 = fgGetNode("/velocities/speed-east-fps");
130 static SGConstPropertyNode_ptr vd_fps
131 = fgGetNode("/velocities/speed-down-fps");
132 static SGConstPropertyNode_ptr clock_freeze
133 = fgGetNode("/sim/freeze/clock", true);
134 static SGConstPropertyNode_ptr cur_time_override
135 = fgGetNode("/sim/time/cur-time-override", true);
136 static SGConstPropertyNode_ptr max_simtime_per_frame
137 = fgGetNode("/sim/max-simtime-per-frame", true);
138 static SGPropertyNode_ptr frame_signal
139 = fgGetNode("/sim/signals/frame", true);
141 frame_signal->fireValueChanged();
142 SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
144 bool scenery_loaded = fgGetBool("sim/sceneryloaded");
145 bool wait_for_scenery = !(scenery_loaded || fgGetBool("sim/sceneryloaded-override"));
147 // Update the elapsed time.
148 static bool first_time = true;
150 last_time_stamp.stamp();
154 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
155 if ( throttle_hz > 0.0 && !wait_for_scenery ) {
156 // optionally throttle the frame rate (to get consistent frame
157 // rates or reduce cpu usage.
159 double frame_us = 1000000.0 / throttle_hz;
161 #define FG_SLEEP_BASED_TIMING 1
162 #if defined(FG_SLEEP_BASED_TIMING)
163 // sleep based timing loop.
165 // Calling sleep, even usleep() on linux is less accurate than
166 // we like, but it does free up the cpu for other tasks during
167 // the sleep so it is desirable. Because of the way sleep()
168 // is implemented in consumer operating systems like windows
169 // and linux, you almost always sleep a little longer than the
172 // To combat the problem of sleeping too long, we calculate the
173 // desired wait time and shorten it by 2000us (2ms) to avoid
174 // [hopefully] over-sleep'ing. The 2ms value was arrived at
175 // via experimentation. We follow this up at the end with a
176 // simple busy-wait loop to get the final pause timing exactly
179 // Assuming we don't oversleep by more than 2000us, this
180 // should be a reasonable compromise between sleep based
181 // waiting, and busy waiting.
183 // sleep() will always overshoot by a bit so undersleep by
184 // 2000us in the hopes of never oversleeping.
186 if ( frame_us < 0.0 ) {
189 current_time_stamp.stamp();
191 double elapsed_us = (current_time_stamp - last_time_stamp).toUSecs();
192 if ( elapsed_us < frame_us ) {
193 double requested_us = frame_us - elapsed_us;
194 ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
198 // busy wait timing loop.
200 // This yields the most accurate timing. If the previous
201 // ulMilliSecondSleep() call is omitted this will peg the cpu
202 // (which is just fine if FG is the only app you care about.)
203 current_time_stamp.stamp();
204 SGTimeStamp next_time_stamp = last_time_stamp;
205 next_time_stamp += SGTimeStamp::fromSec(1e-6*frame_us);
206 while ( current_time_stamp < next_time_stamp ) {
207 current_time_stamp.stamp();
210 // run as fast as the app will go
211 current_time_stamp.stamp();
214 real_delta_time_sec = (current_time_stamp - last_time_stamp).toSecs();
216 // Limit the time we need to spend in simulation loops
217 // That means, if the /sim/max-simtime-per-frame value is strictly positive
218 // you can limit the maximum amount of time you will do simulations for
219 // one frame to display. The cpu time spent in simulations code is roughly
220 // at least O(real_delta_time_sec). If this is (due to running debug
221 // builds or valgrind or something different blowing up execution times)
222 // larger than the real time you will no longer get any response
223 // from flightgear. This limits that effect. Just set to property from
224 // your .fgfsrc or commandline ...
225 double dtMax = max_simtime_per_frame->getDoubleValue();
226 if (0 < dtMax && dtMax < real_delta_time_sec)
227 real_delta_time_sec = dtMax;
229 SGSubsystemGroup* fdmGroup =
230 globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
231 fdmGroup->set_fixed_update_time(1.0 / model_hz);
233 // round the real time down to a multiple of 1/model-hz.
234 // this way all systems are updated the _same_ amount of dt.
235 static double reminder = 0.0;
236 real_delta_time_sec += reminder;
237 global_multi_loop = long(floor(real_delta_time_sec*model_hz));
238 global_multi_loop = SGMisc<long>::max(0, global_multi_loop);
239 reminder = real_delta_time_sec - double(global_multi_loop)/double(model_hz);
240 real_delta_time_sec = double(global_multi_loop)/double(model_hz);
242 if (clock_freeze->getBoolValue() || wait_for_scenery) {
245 delta_time_sec = real_delta_time_sec;
247 last_time_stamp = current_time_stamp;
248 globals->inc_sim_time_sec( delta_time_sec );
250 // These are useful, especially for Nasal scripts.
251 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
252 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
254 #ifdef FANCY_FRAME_COUNTER
258 static time_t last_time = 0;
259 static int frames = 0;
260 #endif // FANCY_FRAME_COUNTER
262 SGTime *t = globals->get_time_params();
264 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
265 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
268 static bool last_clock_freeze = false;
270 if ( clock_freeze->getBoolValue() ) {
271 // clock freeze requested
272 if ( cur_time_override->getLongValue() == 0 ) {
273 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
274 globals->set_warp( 0 );
277 // no clock freeze requested
278 if ( last_clock_freeze == true ) {
279 // clock just unfroze, let's set warp as the difference
280 // between frozen time and current time so we don't get a
281 // time jump (and corresponding sky object and lighting
283 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
284 fgSetLong( "/sim/time/cur-time-override", 0 );
286 if ( globals->get_warp_delta() != 0 ) {
287 globals->inc_warp( globals->get_warp_delta() );
291 last_clock_freeze = clock_freeze->getBoolValue();
293 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
294 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
295 cur_time_override->getLongValue(),
296 globals->get_warp() );
298 if (globals->get_warp_delta() != 0) {
299 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
303 // update magvar model
304 globals->get_mag()->update( longitude->getDoubleValue()
305 * SGD_DEGREES_TO_RADIANS,
306 latitude->getDoubleValue()
307 * SGD_DEGREES_TO_RADIANS,
308 altitude->getDoubleValue() * SG_FEET_TO_METER,
309 globals->get_time_params()->getJD() );
311 // Calculate frame rate average
312 #ifdef FANCY_FRAME_COUNTER
313 /* old fps calculation */
317 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
318 tmp = general.get_frame(i);
320 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
321 general.set_frame(i+1,tmp);
323 tmp = 1000000.0 / (float)elapsed;
324 general.set_frame(0,tmp);
325 // printf("frame[0] = %.2f\n", general.frames[0]);
327 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
328 // printf("ave = %.2f\n", general.frame_rate);
331 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
332 general.set_frame_rate( frames );
333 fgSetInt("/sim/frame-rate", frames);
334 SG_LOG( SG_ALL, SG_DEBUG,
335 "--> Frame rate is = " << general.get_frame_rate() );
338 last_time = t->get_cur_time();
342 // Update any multiplayer's network queues, the AIMultiplayer
343 // implementation is an AI model and depends on that
344 globals->get_multiplayer_mgr()->Update();
348 if (fgGetBool("/sim/atc/enabled"))
349 globals->get_ATC_mgr()->update(delta_time_sec);
352 // Run the AI subsystem
353 // NOTE: the AI_mgr has nothing to do with the AIModels subsystem.
354 // There was previously a comment here stating that the
355 // AI_mgr code should be run then multiplayer is enabled.
356 // Multiplayer relies on AIModels, and not on the old and
357 // depricated AI_mgr system. So, we can safely skip the following
358 // two lines at compile time when compiling with --disable-atcdcl
359 if (fgGetBool("/sim/ai-traffic/enabled"))
360 globals->get_AI_mgr()->update(delta_time_sec);
363 globals->get_subsystem_mgr()->update(delta_time_sec);
364 globals->get_aircraft_model()->update(delta_time_sec);
367 // Tile Manager updates - see if we need to load any new scenery tiles.
368 // this code ties together the fdm, viewer and scenery classes...
369 // we may want to move this to its own class at some point
371 double visibility_meters = fgGetDouble("/environment/visibility-m");
372 globals->get_tile_mgr()->prep_ssg_nodes( visibility_meters );
374 // update tile manager for view...
375 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
376 SGGeod geodViewPos = SGGeod::fromCart(viewPos);
377 globals->get_tile_mgr()->update(geodViewPos, visibility_meters);
379 // run Nasal's settimer() loops right before the view manager
380 globals->get_event_mgr()->update(delta_time_sec);
382 // pick up model coordidnates that Nasal code may have set relative to the
384 globals->get_model_mgr()->update(delta_time_sec);
386 // update the view angle as late as possible, but before sound calculations
387 globals->get_viewmgr()->update(real_delta_time_sec);
389 // Update the sound manager last so it can use the CPU while the GPU
390 // is processing the scenery (doubled the frame-rate for me) -EMH-
391 #ifdef ENABLE_AUDIO_SUPPORT
392 static bool smgr_init = true;
393 static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
394 if (smgr_init == true) {
395 if (sound_working->getBoolValue() == true) {
396 fgInitSoundManager();
400 static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
401 static SGSoundMgr *smgr = globals->get_soundmgr();
402 static bool smgr_enabled = true;
404 if (sound_working->getBoolValue() == false) { // request to reinit
407 sound_working->setBoolValue(true);
410 if (smgr_enabled != sound_enabled->getBoolValue()) {
411 if (smgr_enabled == true) { // request to suspend
413 smgr_enabled = false;
420 if (smgr_enabled == true) {
421 static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
422 smgr->set_volume(volume->getFloatValue());
423 smgr->update(delta_time_sec);
428 // END Tile Manager udpates
430 if (!scenery_loaded && globals->get_tile_mgr()->isSceneryLoaded()
431 && fgGetBool("sim/signals/fdm-initialized")) {
432 fgSetBool("sim/sceneryloaded",true);
433 if (fgGetBool("/sim/sound/working")) {
434 globals->get_soundmgr()->activate();
436 globals->get_props()->tie("/sim/sound/devices/name",
437 SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
439 simgear::AtomicChangeListener::fireChangeListeners();
442 SG_LOG( SG_ALL, SG_DEBUG, "" );
445 void fgInitSoundManager()
447 SGSoundMgr *smgr = globals->get_soundmgr();
450 smgr->init(fgGetString("/sim/sound/device-name", NULL));
452 vector <const char*>devices = smgr->get_available_devices();
453 for (unsigned int i=0; i<devices.size(); i++) {
454 SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
455 p->setStringValue(devices[i]);
460 void fgSetNewSoundDevice(const char *device)
462 globals->get_soundmgr()->suspend();
463 globals->get_soundmgr()->stop();
464 globals->get_soundmgr()->init(device);
465 globals->get_soundmgr()->resume();
468 // Operation for querying OpenGL parameters. This must be done in a
469 // valid OpenGL context, potentially in another thread.
472 struct GeneralInitOperation : public GraphicsContextOperation
474 GeneralInitOperation()
475 : GraphicsContextOperation(std::string("General init"))
478 void run(osg::GraphicsContext* gc)
480 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
481 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
482 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
483 SG_LOG( SG_GENERAL, SG_INFO, general.get_glVendor() );
484 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
485 SG_LOG( SG_GENERAL, SG_INFO, general.get_glVersion() );
488 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
489 general.set_glMaxTexSize( tmp );
490 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
492 glGetIntegerv( GL_DEPTH_BITS, &tmp );
493 general.set_glDepthBits( tmp );
494 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
499 // This is the top level master main function that is registered as
502 // The first few passes take care of initialization things (a couple
503 // per pass) and once everything has been initialized fgMainLoop from
506 static void fgIdleFunction ( void ) {
507 static osg::ref_ptr<GeneralInitOperation> genOp;
508 if ( idle_state == 0 ) {
510 // Pick some window on which to do queries.
511 // XXX Perhaps all this graphics initialization code should be
512 // moved to renderer.cxx?
513 genOp = new GeneralInitOperation;
514 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
515 WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
516 osg::GraphicsContext* gc = 0;
518 gc = guiCamera->getGraphicsContext();
520 gc->add(genOp.get());
522 wsa->windows[0]->gc->add(genOp.get());
525 } else if ( idle_state == 1 ) {
527 if (!genOp->isFinished())
531 if (!guiFinishInit())
534 fgSplashProgress("reading aircraft list");
537 } else if ( idle_state == 2 ) {
540 globals->get_commands()->addCommand("load-aircraft", fgLoadAircraft);
542 fgSplashProgress("reading airport & navigation data");
545 } else if ( idle_state == 3 ) {
548 fgSplashProgress("setting up scenery");
551 } else if ( idle_state == 4 ) {
553 // based on the requested presets, calculate the true starting
556 fgInitTowerLocationListener();
558 SGTime *t = fgInitTime();
559 globals->set_time_params( t );
561 // Do some quick general initializations
562 if( !fgInitGeneral()) {
563 SG_LOG( SG_GENERAL, SG_ALERT,
564 "General initialization failed ..." );
568 ////////////////////////////////////////////////////////////////////
569 // Initialize the property-based built-in commands
570 ////////////////////////////////////////////////////////////////////
574 ////////////////////////////////////////////////////////////////////
575 // Initialize the material manager
576 ////////////////////////////////////////////////////////////////////
577 globals->set_matlib( new SGMaterialLib );
578 simgear::SGModelLib::init(globals->get_fg_root());
581 ////////////////////////////////////////////////////////////////////
582 // Initialize the TG scenery subsystem.
583 ////////////////////////////////////////////////////////////////////
584 globals->set_scenery( new FGScenery );
585 globals->get_scenery()->init();
586 globals->get_scenery()->bind();
587 globals->set_tile_mgr( new FGTileMgr );
590 ////////////////////////////////////////////////////////////////////
591 // Initialize the general model subsystem.
592 ////////////////////////////////////////////////////////////////////
593 globals->set_model_mgr(new FGModelMgr);
594 globals->get_model_mgr()->init();
595 globals->get_model_mgr()->bind();
596 fgSplashProgress("loading aircraft");
599 } else if ( idle_state == 5 ) {
602 ////////////////////////////////////////////////////////////////////
603 // Initialize the 3D aircraft model subsystem (has a dependency on
604 // the scenery subsystem.)
605 ////////////////////////////////////////////////////////////////////
606 FGAircraftModel* acm = new FGAircraftModel;
607 globals->set_aircraft_model(acm);
608 //globals->add_subsystem("aircraft-model", acm);
612 ////////////////////////////////////////////////////////////////////
613 // Initialize the view manager subsystem.
614 ////////////////////////////////////////////////////////////////////
615 FGViewMgr *viewmgr = new FGViewMgr;
616 globals->set_viewmgr( viewmgr );
619 fgSplashProgress("generating sky elements");
622 } else if ( idle_state == 6 ) {
624 // Initialize the sky
626 Ephemeris* eph = new Ephemeris;
627 globals->add_subsystem("ephmeris", eph);
628 eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
631 // TODO: move to environment mgr
633 SGPath texture_path(globals->get_fg_root());
634 texture_path.append("Textures");
635 texture_path.append("Sky");
636 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
637 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
638 thesky->add_cloud_layer(layer);
641 SGPath sky_tex_path( globals->get_fg_root() );
642 sky_tex_path.append( "Textures" );
643 sky_tex_path.append( "Sky" );
644 thesky->texture_path( sky_tex_path.str() );
646 // The sun and moon diameters are scaled down numbers of the
647 // actual diameters. This was needed to fit both the sun and the
648 // moon within the distance to the far clip plane.
649 // Moon diameter: 3,476 kilometers
650 // Sun diameter: 1,390,000 kilometers
651 thesky->build( 80000.0, 80000.0,
653 *globals->get_ephem(),
654 fgGetNode("/environment", true));
656 // Initialize MagVar model
657 SGMagVar *magvar = new SGMagVar();
658 globals->set_mag( magvar );
661 // kludge to initialize mag compass
662 // (should only be done for in-flight
664 // update magvar model
665 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
666 * SGD_DEGREES_TO_RADIANS,
667 fgGetDouble("/position/latitude-deg")
668 * SGD_DEGREES_TO_RADIANS,
669 fgGetDouble("/position/altitude-ft")
671 globals->get_time_params()->getJD() );
672 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
673 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
674 fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
677 // airport = new ssgBranch;
678 // airport->setName( "Airport Lighting" );
679 // lighting->addKid( airport );
681 // build our custom render states
682 fgSplashProgress("initializing subsystems");
685 } else if ( idle_state == 7 ) {
687 // Initialize audio support
688 #ifdef ENABLE_AUDIO_SUPPORT
690 // Start the intro music
691 if ( fgGetBool("/sim/startup/intro-music") ) {
692 SGPath mp3file( globals->get_fg_root() );
693 mp3file.append( "Sounds/intro.mp3" );
695 SG_LOG( SG_GENERAL, SG_INFO,
696 "Starting intro music: " << mp3file.str() );
698 # if defined( __CYGWIN__ )
699 string command = "start /m `cygpath -w " + mp3file.str() + "`";
700 # elif defined( _WIN32 )
701 string command = "start /m " + mp3file.str();
703 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
706 system ( command.c_str() );
709 // This is the top level init routine which calls all the
710 // other subsystem initialization routines. If you are adding
711 // a subsystem to flightgear, its initialization call should be
712 // located in this routine.
713 if( !fgInitSubsystems()) {
714 SG_LOG( SG_GENERAL, SG_ALERT,
715 "Subsystem initialization failed ..." );
718 fgSplashProgress("setting up time & renderer");
721 } else if ( idle_state == 8 ) {
723 // Initialize the time offset (warp) after fgInitSubsystem
724 // (which initializes the lighting interpolation tables.)
727 // setup OpenGL view parameters
728 globals->get_renderer()->init();
730 globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
731 fgGetInt("/sim/startup/ysize") );
733 fgSplashProgress("loading scenery objects");
734 int session = fgGetInt("/sim/session",0);
736 fgSetInt("/sim/session",session);
739 if ( idle_state == 1000 ) {
740 // We've finished all our initialization steps, from now on we
741 // run the main loop.
742 fgSetBool("sim/sceneryloaded", false);
743 fgRegisterIdleHandler( fgMainLoop );
748 static void upper_case_property(const char *name)
750 using namespace simgear;
751 SGPropertyNode *p = fgGetNode(name, false);
753 p = fgGetNode(name, true);
754 p->setStringValue("");
756 props::Type t = p->getType();
757 if (t == props::NONE || t == props::UNSPECIFIED)
758 p->setStringValue("");
760 assert(t == props::STRING);
762 p->addChangeListener(new FGMakeUpperCase);
766 // Main top level initialization
767 bool fgMainInit( int argc, char **argv ) {
769 // set default log levels
770 sglog().setLogLevels( SG_ALL, SG_ALERT );
773 #ifdef FLIGHTGEAR_VERSION
774 version = FLIGHTGEAR_VERSION;
776 version = "unknown version";
778 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
780 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
782 // Allocate global data structures. This needs to happen before
783 // we parse command line options
785 globals = new FGGlobals;
787 // seed the random number generator
790 FGControls *controls = new FGControls;
791 globals->set_controls( controls );
793 string_list *col = new string_list;
794 globals->set_channel_options_list( col );
796 fgValidatePath("", false); // initialize static variables
797 upper_case_property("/sim/presets/airport-id");
798 upper_case_property("/sim/presets/runway");
799 upper_case_property("/sim/tower/airport-id");
800 upper_case_property("/autopilot/route-manager/input");
802 // Scan the config file(s) and command line options to see if
803 // fg_root was specified (ignore all other options for now)
804 fgInitFGRoot(argc, argv);
806 // Check for the correct base package version
807 static char required_version[] = "2.0.0";
808 string base_version = fgBasePackageVersion();
809 if ( !(base_version == required_version) ) {
810 // tell the operator how to use this application
812 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
813 cerr << endl << "Base package check failed ... " \
814 << "Found version " << base_version << " at: " \
815 << globals->get_fg_root() << endl;
816 cerr << "Please upgrade to version: " << required_version << endl;
818 cerr << "Hit a key to continue..." << endl;
824 // Load the configuration parameters. (Command line options
825 // override config file options. Config file options override
827 if ( !fgInitConfig(argc, argv) ) {
828 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
832 // Initialize the Window/Graphics environment.
833 fgOSInit(&argc, argv);
836 fgRegisterWindowResizeHandler( &FGRenderer::resize );
837 fgRegisterIdleHandler( &fgIdleFunction );
838 fgRegisterDrawHandler( &FGRenderer::update );
840 // Initialize plib net interface
841 netInit( &argc, argv );
843 // Clouds3D requires an alpha channel
844 fgOSOpenWindow(true /* request stencil buffer */);
846 // Initialize the splash screen right away
850 // pass control off to the master event handler
853 // we never actually get here ... but to avoid compiler warnings,