]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
d69478e55c533f294bd0c2a48d1cc3503feca997
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #if defined(__linux__) && defined(__i386__)
31 #  include <fpu_control.h>
32 #  include <signal.h>
33 #endif
34
35 #include <iostream>
36
37 #include <plib/netSocket.h>
38
39 #include <osg/Camera>
40 #include <osg/GraphicsContext>
41 #include <osgDB/Registry>
42
43 // Class references
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>
53
54 #include <Time/light.hxx>
55 #include <Include/general.hxx>
56 #include <Aircraft/replay.hxx>
57 #include <Cockpit/cockpit.hxx>
58 #include <Cockpit/hud.hxx>
59 #include <Model/panelnode.hxx>
60 #include <Model/modelmgr.hxx>
61 #include <Model/acmodel.hxx>
62 #include <Scenery/scenery.hxx>
63 #include <Scenery/tilemgr.hxx>
64 #include <Sound/fg_fx.hxx>
65 #include <Sound/beacon.hxx>
66 #include <Sound/morse.hxx>
67 #include <Sound/fg_fx.hxx>
68 #include <ATCDCL/ATCmgr.hxx>
69 #include <ATCDCL/AIMgr.hxx>
70 #include <Time/tmp.hxx>
71 #include <Environment/environment_mgr.hxx>
72 #include <Environment/ephemeris.hxx>
73 #include <GUI/new_gui.hxx>
74 #include <MultiPlayer/multiplaymgr.hxx>
75
76 #include "CameraGroup.hxx"
77 #include "fg_commands.hxx"
78 #include "fg_io.hxx"
79 #include "renderer.hxx"
80 #include "splash.hxx"
81 #include "main.hxx"
82 #include "util.hxx"
83 #include "fg_init.hxx"
84 #include "fg_os.hxx"
85 #include "WindowSystemAdapter.hxx"
86 #include <Main/viewer.hxx>
87
88 static double real_delta_time_sec = 0.0;
89 double delta_time_sec = 0.0;
90
91 using namespace flightgear;
92
93 using std::cerr;
94
95 // This is a record containing a bit of global housekeeping information
96 FGGeneral general;
97
98 // Specify our current idle function state.  This is used to run all
99 // our initializations out of the idle callback so that we can get a
100 // splash screen up and running right away.
101 int idle_state = 0;
102 long global_multi_loop;
103
104 SGTimeStamp last_time_stamp;
105 SGTimeStamp current_time_stamp;
106
107 void fgInitSoundManager();
108 void fgSetNewSoundDevice(const char *);
109
110 // The atexit() function handler should know when the graphical subsystem
111 // is initialized.
112 extern int _bootstrap_OSInit;
113
114 // What should we do when we have nothing else to do?  Let's get ready
115 // for the next move and update the display?
116 static void fgMainLoop( void ) {
117     int model_hz = fgGetInt("/sim/model-hz");
118
119     static SGConstPropertyNode_ptr longitude
120         = fgGetNode("/position/longitude-deg");
121     static SGConstPropertyNode_ptr latitude
122         = fgGetNode("/position/latitude-deg");
123     static SGConstPropertyNode_ptr altitude
124         = fgGetNode("/position/altitude-ft");
125     static SGConstPropertyNode_ptr vn_fps
126         = fgGetNode("/velocities/speed-north-fps");
127     static SGConstPropertyNode_ptr ve_fps
128         = fgGetNode("/velocities/speed-east-fps");
129     static SGConstPropertyNode_ptr vd_fps
130         = fgGetNode("/velocities/speed-down-fps");
131     static SGConstPropertyNode_ptr clock_freeze
132         = fgGetNode("/sim/freeze/clock", true);
133     static SGConstPropertyNode_ptr cur_time_override
134         = fgGetNode("/sim/time/cur-time-override", true);
135     static SGConstPropertyNode_ptr max_simtime_per_frame
136         = fgGetNode("/sim/max-simtime-per-frame", true);
137     static SGPropertyNode_ptr frame_signal
138         = fgGetNode("/sim/signals/frame", true);
139
140     frame_signal->fireValueChanged();
141     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
142
143     bool scenery_loaded = fgGetBool("sim/sceneryloaded");
144     bool wait_for_scenery = !(scenery_loaded || fgGetBool("sim/sceneryloaded-override"));
145
146     // Update the elapsed time.
147     static bool first_time = true;
148     if ( first_time ) {
149         last_time_stamp.stamp();
150         first_time = false;
151     }
152
153     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
154     if ( throttle_hz > 0.0 && !wait_for_scenery ) {
155         // optionally throttle the frame rate (to get consistent frame
156         // rates or reduce cpu usage.
157
158         double frame_us = 1000000.0 / throttle_hz;
159
160 #define FG_SLEEP_BASED_TIMING 1
161 #if defined(FG_SLEEP_BASED_TIMING)
162         // sleep based timing loop.
163         //
164         // Calling sleep, even usleep() on linux is less accurate than
165         // we like, but it does free up the cpu for other tasks during
166         // the sleep so it is desirable.  Because of the way sleep()
167         // is implemented in consumer operating systems like windows
168         // and linux, you almost always sleep a little longer than the
169         // requested amount.
170         //
171         // To combat the problem of sleeping too long, we calculate the
172         // desired wait time and shorten it by 2000us (2ms) to avoid
173         // [hopefully] over-sleep'ing.  The 2ms value was arrived at
174         // via experimentation.  We follow this up at the end with a
175         // simple busy-wait loop to get the final pause timing exactly
176         // right.
177         //
178         // Assuming we don't oversleep by more than 2000us, this
179         // should be a reasonable compromise between sleep based
180         // waiting, and busy waiting.
181
182         // sleep() will always overshoot by a bit so undersleep by
183         // 2000us in the hopes of never oversleeping.
184         frame_us -= 2000.0;
185         if ( frame_us < 0.0 ) {
186             frame_us = 0.0;
187         }
188         current_time_stamp.stamp();
189         /* Convert to ms */
190         double elapsed_us = (current_time_stamp - last_time_stamp).toUSecs();
191         if ( elapsed_us < frame_us ) {
192             double requested_us = frame_us - elapsed_us;
193             ulMilliSecondSleep ( (int)(requested_us / 1000.0) ) ;
194         }
195 #endif
196
197         // busy wait timing loop.
198         //
199         // This yields the most accurate timing.  If the previous
200         // ulMilliSecondSleep() call is omitted this will peg the cpu
201         // (which is just fine if FG is the only app you care about.)
202         current_time_stamp.stamp();
203         SGTimeStamp next_time_stamp = last_time_stamp;
204         next_time_stamp += SGTimeStamp::fromSec(1e-6*frame_us);
205         while ( current_time_stamp < next_time_stamp ) {
206             current_time_stamp.stamp();
207         }
208     } else {
209         // run as fast as the app will go
210         current_time_stamp.stamp();
211     }
212
213     real_delta_time_sec = (current_time_stamp - last_time_stamp).toSecs();
214
215     // Limit the time we need to spend in simulation loops
216     // That means, if the /sim/max-simtime-per-frame value is strictly positive
217     // you can limit the maximum amount of time you will do simulations for
218     // one frame to display. The cpu time spent in simulations code is roughly
219     // at least O(real_delta_time_sec). If this is (due to running debug
220     // builds or valgrind or something different blowing up execution times)
221     // larger than the real time you will no longer get any response
222     // from flightgear. This limits that effect. Just set to property from
223     // your .fgfsrc or commandline ...
224     double dtMax = max_simtime_per_frame->getDoubleValue();
225     if (0 < dtMax && dtMax < real_delta_time_sec)
226         real_delta_time_sec = dtMax;
227
228     SGSubsystemGroup* fdmGroup = 
229       globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
230     fdmGroup->set_fixed_update_time(1.0 / model_hz);
231
232     // round the real time down to a multiple of 1/model-hz.
233     // this way all systems are updated the _same_ amount of dt.
234     static double reminder = 0.0;
235     real_delta_time_sec += reminder;
236     global_multi_loop = long(floor(real_delta_time_sec*model_hz));
237     global_multi_loop = SGMisc<long>::max(0, global_multi_loop);
238     reminder = real_delta_time_sec - double(global_multi_loop)/double(model_hz);
239     real_delta_time_sec = double(global_multi_loop)/double(model_hz);
240
241     if (clock_freeze->getBoolValue() || wait_for_scenery) {
242         delta_time_sec = 0;
243     } else {
244         delta_time_sec = real_delta_time_sec;
245     }
246     last_time_stamp = current_time_stamp;
247     globals->inc_sim_time_sec( delta_time_sec );
248
249     // These are useful, especially for Nasal scripts.
250     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
251     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
252
253 #ifdef FANCY_FRAME_COUNTER
254     int i;
255     double accum;
256 #else
257     static time_t last_time = 0;
258     static int frames = 0;
259 #endif // FANCY_FRAME_COUNTER
260
261     SGTime *t = globals->get_time_params();
262
263     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
264     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
265
266     // update "time"
267     static bool last_clock_freeze = false;
268
269     if ( clock_freeze->getBoolValue() ) {
270         // clock freeze requested
271         if ( cur_time_override->getLongValue() == 0 ) {
272             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
273             globals->set_warp( 0 );
274         }
275     } else {
276         // no clock freeze requested
277         if ( last_clock_freeze == true ) {
278             // clock just unfroze, let's set warp as the difference
279             // between frozen time and current time so we don't get a
280             // time jump (and corresponding sky object and lighting
281             // jump.)
282             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
283             fgSetLong( "/sim/time/cur-time-override", 0 );
284         }
285         if ( globals->get_warp_delta() != 0 ) {
286             globals->inc_warp( globals->get_warp_delta() );
287         }
288     }
289
290     last_clock_freeze = clock_freeze->getBoolValue();
291
292     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
293                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
294                cur_time_override->getLongValue(),
295                globals->get_warp() );
296
297     if (globals->get_warp_delta() != 0) {
298         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
299         l->update( 0.5 );
300     }
301
302     // update magvar model
303     globals->get_mag()->update( longitude->getDoubleValue()
304                                 * SGD_DEGREES_TO_RADIANS,
305                                 latitude->getDoubleValue()
306                                 * SGD_DEGREES_TO_RADIANS,
307                                 altitude->getDoubleValue() * SG_FEET_TO_METER,
308                                 globals->get_time_params()->getJD() );
309
310     // Calculate frame rate average
311 #ifdef FANCY_FRAME_COUNTER
312     /* old fps calculation */
313     if ( elapsed > 0 ) {
314         double tmp;
315         accum = 0.0;
316         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
317             tmp = general.get_frame(i);
318             accum += tmp;
319             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
320             general.set_frame(i+1,tmp);
321         }
322         tmp = 1000000.0 / (float)elapsed;
323         general.set_frame(0,tmp);
324         // printf("frame[0] = %.2f\n", general.frames[0]);
325         accum += tmp;
326         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
327         // printf("ave = %.2f\n", general.frame_rate);
328     }
329 #else
330     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
331         general.set_frame_rate( frames );
332         fgSetInt("/sim/frame-rate", frames);
333         SG_LOG( SG_ALL, SG_DEBUG,
334                 "--> Frame rate is = " << general.get_frame_rate() );
335         frames = 0;
336     }
337     last_time = t->get_cur_time();
338     ++frames;
339 #endif
340
341     // Update any multiplayer's network queues, the AIMultiplayer
342     // implementation is an AI model and depends on that
343     globals->get_multiplayer_mgr()->Update();
344
345     // Run ATC subsystem
346     if (fgGetBool("/sim/atc/enabled"))
347         globals->get_ATC_mgr()->update(delta_time_sec);
348
349     // Run the AI subsystem
350     // FIXME: run that also if we have multiplaying enabled since the
351     // multiplayer information is interpreted by an AI model
352     if (fgGetBool("/sim/ai-traffic/enabled"))
353         globals->get_AI_mgr()->update(delta_time_sec);
354   
355     
356     globals->get_subsystem_mgr()->update(delta_time_sec);
357     globals->get_aircraft_model()->update(delta_time_sec);
358     
359     //
360     // Tile Manager updates - see if we need to load any new scenery tiles.
361     //   this code ties together the fdm, viewer and scenery classes...
362     //   we may want to move this to its own class at some point
363     //
364     double visibility_meters = fgGetDouble("/environment/visibility-m");
365     globals->get_tile_mgr()->prep_ssg_nodes( visibility_meters );
366
367     // update tile manager for view...
368     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
369     SGGeod geodViewPos = SGGeod::fromCart(viewPos);
370     globals->get_tile_mgr()->update(geodViewPos, visibility_meters);
371
372     // run Nasal's settimer() loops right before the view manager
373     globals->get_event_mgr()->update(delta_time_sec);
374
375     // pick up model coordidnates that Nasal code may have set relative to the
376     // aircraft's
377     globals->get_model_mgr()->update(delta_time_sec);
378
379     // update the view angle as late as possible, but before sound calculations
380     globals->get_viewmgr()->update(real_delta_time_sec);
381
382     // Update the sound manager last so it can use the CPU while the GPU
383     // is processing the scenery (doubled the frame-rate for me) -EMH-
384 #ifdef ENABLE_AUDIO_SUPPORT
385     static bool smgr_init = true;
386     static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
387     if (smgr_init == true) {
388         if (sound_working->getBoolValue() == true) {
389             fgInitSoundManager();
390             smgr_init = false;
391         }
392     } else {
393         static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
394         static SGSoundMgr *smgr = globals->get_soundmgr();
395         static bool smgr_enabled = true;
396
397         if (sound_working->getBoolValue() == false) {   // request to reinit
398            smgr->reinit();
399            smgr->resume();
400            sound_working->setBoolValue(true);
401         }
402
403         if (smgr_enabled != sound_enabled->getBoolValue()) {
404             if (smgr_enabled == true) { // request to suspend
405                 smgr->suspend();
406                 smgr_enabled = false;
407             } else {
408                 smgr->resume();
409                 smgr_enabled = true;
410             }
411         }
412
413         if (smgr_enabled == true) {
414             static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
415             smgr->set_volume(volume->getFloatValue());
416             smgr->update(delta_time_sec);
417         }
418     }
419 #endif
420
421     // END Tile Manager udpates
422
423     if (!scenery_loaded && globals->get_tile_mgr()->isSceneryLoaded()
424         && fgGetBool("sim/signals/fdm-initialized")) {
425         fgSetBool("sim/sceneryloaded",true);
426         if (fgGetBool("/sim/sound/working")) {
427             globals->get_soundmgr()->activate();
428         }
429         globals->get_props()->tie("/sim/sound/devices/name",
430               SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
431     }
432     simgear::AtomicChangeListener::fireChangeListeners();
433     fgRequestRedraw();
434
435     SG_LOG( SG_ALL, SG_DEBUG, "" );
436 }
437
438 void fgInitSoundManager()
439 {
440     SGSoundMgr *smgr = globals->get_soundmgr();
441
442     smgr->bind();
443     smgr->init(fgGetString("/sim/sound/device-name", NULL));
444
445     vector <const char*>devices = smgr->get_available_devices();
446     for (unsigned int i=0; i<devices.size(); i++) {
447         SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
448         p->setStringValue(devices[i]);
449     }
450     devices.clear();
451 }
452
453 void fgSetNewSoundDevice(const char *device)
454 {
455     globals->get_soundmgr()->suspend();
456     globals->get_soundmgr()->stop();
457     globals->get_soundmgr()->init(device);
458     globals->get_soundmgr()->resume();
459 }
460
461 // Operation for querying OpenGL parameters. This must be done in a
462 // valid OpenGL context, potentially in another thread.
463 namespace
464 {
465 struct GeneralInitOperation : public GraphicsContextOperation
466 {
467     GeneralInitOperation()
468         : GraphicsContextOperation(std::string("General init"))
469     {
470     }
471     void run(osg::GraphicsContext* gc)
472     {
473         general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
474         general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
475         general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
476         SG_LOG( SG_GENERAL, SG_INFO, general.get_glVendor() );
477         SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
478         SG_LOG( SG_GENERAL, SG_INFO, general.get_glVersion() );
479
480         GLint tmp;
481         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
482         general.set_glMaxTexSize( tmp );
483         SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
484
485         glGetIntegerv( GL_DEPTH_BITS, &tmp );
486         general.set_glDepthBits( tmp );
487         SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
488     }
489 };
490 }
491
492 // This is the top level master main function that is registered as
493 // our idle funciton
494
495 // The first few passes take care of initialization things (a couple
496 // per pass) and once everything has been initialized fgMainLoop from
497 // then on.
498
499 static void fgIdleFunction ( void ) {
500     static osg::ref_ptr<GeneralInitOperation> genOp;
501     if ( idle_state == 0 ) {
502         idle_state++;
503         // Pick some window on which to do queries.
504         // XXX Perhaps all this graphics initialization code should be
505         // moved to renderer.cxx?
506         genOp = new GeneralInitOperation;
507         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
508         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
509         osg::GraphicsContext* gc = 0;
510         if (guiCamera)
511             gc = guiCamera->getGraphicsContext();
512         if (gc) {
513             gc->add(genOp.get());
514         } else {
515             wsa->windows[0]->gc->add(genOp.get());
516         }
517         guiStartInit(gc);
518     } else if ( idle_state == 1 ) {
519         if (genOp.valid()) {
520             if (!genOp->isFinished())
521                 return;
522             genOp = 0;
523         }
524         if (!guiFinishInit())
525             return;
526         idle_state++;
527         fgSplashProgress("reading aircraft list");
528
529
530     } else if ( idle_state == 2 ) {
531         idle_state++;
532         // Read the list of available aircraft
533         fgReadAircraft();
534         fgSplashProgress("reading airport & navigation data");
535
536
537     } else if ( idle_state == 3 ) {
538         idle_state++;
539         fgInitNav();
540         fgSplashProgress("setting up scenery");
541
542
543     } else if ( idle_state == 4 ) {
544         idle_state++;
545         // based on the requested presets, calculate the true starting
546         // lon, lat
547         fgInitPosition();
548         fgInitTowerLocationListener();
549
550         SGTime *t = fgInitTime();
551         globals->set_time_params( t );
552
553         // Do some quick general initializations
554         if( !fgInitGeneral()) {
555             SG_LOG( SG_GENERAL, SG_ALERT,
556                 "General initialization failed ..." );
557             exit(-1);
558         }
559
560         ////////////////////////////////////////////////////////////////////
561         // Initialize the property-based built-in commands
562         ////////////////////////////////////////////////////////////////////
563         fgInitCommands();
564
565
566         ////////////////////////////////////////////////////////////////////
567         // Initialize the material manager
568         ////////////////////////////////////////////////////////////////////
569         globals->set_matlib( new SGMaterialLib );
570         simgear::SGModelLib::init(globals->get_fg_root());
571
572
573         ////////////////////////////////////////////////////////////////////
574         // Initialize the TG scenery subsystem.
575         ////////////////////////////////////////////////////////////////////
576         globals->set_scenery( new FGScenery );
577         globals->get_scenery()->init();
578         globals->get_scenery()->bind();
579         globals->set_tile_mgr( new FGTileMgr );
580
581
582         ////////////////////////////////////////////////////////////////////
583         // Initialize the general model subsystem.
584         ////////////////////////////////////////////////////////////////////
585         globals->set_model_mgr(new FGModelMgr);
586         globals->get_model_mgr()->init();
587         globals->get_model_mgr()->bind();
588         fgSplashProgress("loading aircraft");
589
590
591     } else if ( idle_state == 5 ) {
592         idle_state++;
593
594         ////////////////////////////////////////////////////////////////////
595         // Initialize the 3D aircraft model subsystem (has a dependency on
596         // the scenery subsystem.)
597         ////////////////////////////////////////////////////////////////////
598         FGAircraftModel* acm = new FGAircraftModel;
599         globals->set_aircraft_model(acm);
600         //globals->add_subsystem("aircraft-model", acm);
601         acm->init();
602         acm->bind();
603
604         ////////////////////////////////////////////////////////////////////
605         // Initialize the view manager subsystem.
606         ////////////////////////////////////////////////////////////////////
607         FGViewMgr *viewmgr = new FGViewMgr;
608         globals->set_viewmgr( viewmgr );
609         viewmgr->init();
610         viewmgr->bind();
611         fgSplashProgress("generating sky elements");
612
613
614     } else if ( idle_state == 6 ) {
615         idle_state++;
616         // Initialize the sky
617
618         Ephemeris* eph = new Ephemeris;
619         globals->add_subsystem("ephmeris", eph);
620         eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
621
622         // TODO: move to environment mgr
623         thesky = new SGSky;
624         SGPath texture_path(globals->get_fg_root());
625         texture_path.append("Textures");
626         texture_path.append("Sky");
627         for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
628             SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
629             thesky->add_cloud_layer(layer);
630         }
631
632         SGPath sky_tex_path( globals->get_fg_root() );
633         sky_tex_path.append( "Textures" );
634         sky_tex_path.append( "Sky" );
635         thesky->texture_path( sky_tex_path.str() );
636
637         // The sun and moon diameters are scaled down numbers of the
638         // actual diameters. This was needed to fit both the sun and the
639         // moon within the distance to the far clip plane.
640         // Moon diameter:    3,476 kilometers
641         // Sun diameter: 1,390,000 kilometers
642         thesky->build( 80000.0, 80000.0,
643                        463.3, 361.8,
644                        *globals->get_ephem(),
645                        fgGetNode("/environment", true));
646
647         // Initialize MagVar model
648         SGMagVar *magvar = new SGMagVar();
649         globals->set_mag( magvar );
650
651
652                                     // kludge to initialize mag compass
653                                     // (should only be done for in-flight
654                                     // startup)
655         // update magvar model
656         globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
657                                     * SGD_DEGREES_TO_RADIANS,
658                                     fgGetDouble("/position/latitude-deg")
659                                     * SGD_DEGREES_TO_RADIANS,
660                                     fgGetDouble("/position/altitude-ft")
661                                     * SG_FEET_TO_METER,
662                                     globals->get_time_params()->getJD() );
663         double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
664         fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
665         fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
666
667
668         // airport = new ssgBranch;
669         // airport->setName( "Airport Lighting" );
670         // lighting->addKid( airport );
671
672         // build our custom render states
673         fgSplashProgress("initializing subsystems");
674
675
676     } else if ( idle_state == 7 ) {
677         idle_state++;
678         // Initialize audio support
679 #ifdef ENABLE_AUDIO_SUPPORT
680
681         // Start the intro music
682         if ( fgGetBool("/sim/startup/intro-music") ) {
683             SGPath mp3file( globals->get_fg_root() );
684             mp3file.append( "Sounds/intro.mp3" );
685
686             SG_LOG( SG_GENERAL, SG_INFO,
687                 "Starting intro music: " << mp3file.str() );
688
689 # if defined( __CYGWIN__ )
690             string command = "start /m `cygpath -w " + mp3file.str() + "`";
691 # elif defined( _WIN32 )
692             string command = "start /m " + mp3file.str();
693 # else
694             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
695 # endif
696
697             system ( command.c_str() );
698         }
699 #endif
700         // This is the top level init routine which calls all the
701         // other subsystem initialization routines.  If you are adding
702         // a subsystem to flightgear, its initialization call should be
703         // located in this routine.
704         if( !fgInitSubsystems()) {
705             SG_LOG( SG_GENERAL, SG_ALERT,
706                 "Subsystem initialization failed ..." );
707             exit(-1);
708         }
709         fgSplashProgress("setting up time & renderer");
710
711
712     } else if ( idle_state == 8 ) {
713         idle_state = 1000;
714         // Initialize the time offset (warp) after fgInitSubsystem
715         // (which initializes the lighting interpolation tables.)
716         fgInitTimeOffset();
717
718         // setup OpenGL view parameters
719         globals->get_renderer()->init();
720
721         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
722         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
723                                          fgGetInt("/sim/startup/ysize") );
724
725         fgSplashProgress("loading scenery objects");
726         int session = fgGetInt("/sim/session",0);
727         session++;
728         fgSetInt("/sim/session",session);
729     }
730
731     if ( idle_state == 1000 ) {
732         // We've finished all our initialization steps, from now on we
733         // run the main loop.
734         fgSetBool("sim/sceneryloaded", false);
735         fgRegisterIdleHandler( fgMainLoop );
736     }
737 }
738
739
740 static void upper_case_property(const char *name)
741 {
742     using namespace simgear;
743     SGPropertyNode *p = fgGetNode(name, false);
744     if (!p) {
745         p = fgGetNode(name, true);
746         p->setStringValue("");
747     } else {
748         props::Type t = p->getType();
749         if (t == props::NONE || t == props::UNSPECIFIED)
750             p->setStringValue("");
751         else
752             assert(t == props::STRING);
753     }
754     p->addChangeListener(new FGMakeUpperCase);
755 }
756
757
758 // Main top level initialization
759 bool fgMainInit( int argc, char **argv ) {
760
761     // set default log levels
762     sglog().setLogLevels( SG_ALL, SG_ALERT );
763
764     string version;
765 #ifdef FLIGHTGEAR_VERSION
766     version = FLIGHTGEAR_VERSION;
767 #else
768     version = "unknown version";
769 #endif
770     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
771             << version );
772     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
773
774     // Allocate global data structures.  This needs to happen before
775     // we parse command line options
776
777     globals = new FGGlobals;
778
779     // seed the random number generator
780     sg_srandom_time();
781
782     FGControls *controls = new FGControls;
783     globals->set_controls( controls );
784
785     string_list *col = new string_list;
786     globals->set_channel_options_list( col );
787
788     fgValidatePath("", false);  // initialize static variables
789     upper_case_property("/sim/presets/airport-id");
790     upper_case_property("/sim/presets/runway");
791     upper_case_property("/sim/tower/airport-id");
792     upper_case_property("/autopilot/route-manager/input");
793
794     // Scan the config file(s) and command line options to see if
795     // fg_root was specified (ignore all other options for now)
796     fgInitFGRoot(argc, argv);
797
798     // Check for the correct base package version
799     static char required_version[] = "2.0.0";
800     string base_version = fgBasePackageVersion();
801     if ( !(base_version == required_version) ) {
802         // tell the operator how to use this application
803
804         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
805         cerr << endl << "Base package check failed ... " \
806              << "Found version " << base_version << " at: " \
807              << globals->get_fg_root() << endl;
808         cerr << "Please upgrade to version: " << required_version << endl;
809 #ifdef _MSC_VER
810         cerr << "Hit a key to continue..." << endl;
811         cin.get();
812 #endif
813         exit(-1);
814     }
815
816     // Load the configuration parameters.  (Command line options
817     // override config file options.  Config file options override
818     // defaults.)
819     if ( !fgInitConfig(argc, argv) ) {
820         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
821         exit(-1);
822     }
823
824     // Initialize the Window/Graphics environment.
825     fgOSInit(&argc, argv);
826     _bootstrap_OSInit++;
827
828     fgRegisterWindowResizeHandler( &FGRenderer::resize );
829     fgRegisterIdleHandler( &fgIdleFunction );
830     fgRegisterDrawHandler( &FGRenderer::update );
831
832 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
833     bool get_stencil_buffer = true;
834 #else
835     bool get_stencil_buffer = false;
836 #endif
837
838     // Initialize plib net interface
839     netInit( &argc, argv );
840
841     // Clouds3D requires an alpha channel
842     // clouds may require stencil buffer
843     fgOSOpenWindow(get_stencil_buffer);
844
845     // Initialize the splash screen right away
846     fntInit();
847     fgSplashInit();
848
849     // pass control off to the master event handler
850     fgOSMainLoop();
851
852     // we never actually get here ... but to avoid compiler warnings,
853     // etc.
854     return false;
855 }
856
857