]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Remove current_aircraft global, fgAIRCRAFT struct, and dead code for reading aircraft...
[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 <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>
76
77 #include "CameraGroup.hxx"
78 #include "fg_commands.hxx"
79 #include "fg_io.hxx"
80 #include "renderer.hxx"
81 #include "splash.hxx"
82 #include "main.hxx"
83 #include "util.hxx"
84 #include "fg_init.hxx"
85 #include "fg_os.hxx"
86 #include "WindowSystemAdapter.hxx"
87 #include <Main/viewer.hxx>
88
89 static double real_delta_time_sec = 0.0;
90 double delta_time_sec = 0.0;
91
92 using namespace flightgear;
93
94 using std::cerr;
95
96 // This is a record containing a bit of global housekeeping information
97 FGGeneral general;
98
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.
102 int idle_state = 0;
103 long global_multi_loop;
104
105 SGTimeStamp last_time_stamp;
106 SGTimeStamp current_time_stamp;
107
108 void fgInitSoundManager();
109 void fgSetNewSoundDevice(const char *);
110
111 // The atexit() function handler should know when the graphical subsystem
112 // is initialized.
113 extern int _bootstrap_OSInit;
114
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");
119
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);
140
141     frame_signal->fireValueChanged();
142     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
143
144     bool scenery_loaded = fgGetBool("sim/sceneryloaded");
145     bool wait_for_scenery = !(scenery_loaded || fgGetBool("sim/sceneryloaded-override"));
146
147     // Update the elapsed time.
148     static bool first_time = true;
149     if ( first_time ) {
150         last_time_stamp.stamp();
151         first_time = false;
152     }
153
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.
158
159         double frame_us = 1000000.0 / throttle_hz;
160
161 #define FG_SLEEP_BASED_TIMING 1
162 #if defined(FG_SLEEP_BASED_TIMING)
163         // sleep based timing loop.
164         //
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
170         // requested amount.
171         //
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
177         // right.
178         //
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.
182
183         // sleep() will always overshoot by a bit so undersleep by
184         // 2000us in the hopes of never oversleeping.
185         frame_us -= 2000.0;
186         if ( frame_us < 0.0 ) {
187             frame_us = 0.0;
188         }
189         current_time_stamp.stamp();
190         /* Convert to ms */
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) ) ;
195         }
196 #endif
197
198         // busy wait timing loop.
199         //
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();
208         }
209     } else {
210         // run as fast as the app will go
211         current_time_stamp.stamp();
212     }
213
214     real_delta_time_sec = (current_time_stamp - last_time_stamp).toSecs();
215
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;
228
229     SGSubsystemGroup* fdmGroup = 
230       globals->get_subsystem_mgr()->get_group(SGSubsystemMgr::FDM);
231     fdmGroup->set_fixed_update_time(1.0 / model_hz);
232
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);
241
242     if (clock_freeze->getBoolValue() || wait_for_scenery) {
243         delta_time_sec = 0;
244     } else {
245         delta_time_sec = real_delta_time_sec;
246     }
247     last_time_stamp = current_time_stamp;
248     globals->inc_sim_time_sec( delta_time_sec );
249
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);
253
254 #ifdef FANCY_FRAME_COUNTER
255     int i;
256     double accum;
257 #else
258     static time_t last_time = 0;
259     static int frames = 0;
260 #endif // FANCY_FRAME_COUNTER
261
262     SGTime *t = globals->get_time_params();
263
264     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
265     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
266
267     // update "time"
268     static bool last_clock_freeze = false;
269
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 );
275         }
276     } else {
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
282             // jump.)
283             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
284             fgSetLong( "/sim/time/cur-time-override", 0 );
285         }
286         if ( globals->get_warp_delta() != 0 ) {
287             globals->inc_warp( globals->get_warp_delta() );
288         }
289     }
290
291     last_clock_freeze = clock_freeze->getBoolValue();
292
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() );
297
298     if (globals->get_warp_delta() != 0) {
299         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
300         l->update( 0.5 );
301     }
302
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() );
310
311     // Calculate frame rate average
312 #ifdef FANCY_FRAME_COUNTER
313     /* old fps calculation */
314     if ( elapsed > 0 ) {
315         double tmp;
316         accum = 0.0;
317         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
318             tmp = general.get_frame(i);
319             accum += tmp;
320             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
321             general.set_frame(i+1,tmp);
322         }
323         tmp = 1000000.0 / (float)elapsed;
324         general.set_frame(0,tmp);
325         // printf("frame[0] = %.2f\n", general.frames[0]);
326         accum += tmp;
327         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
328         // printf("ave = %.2f\n", general.frame_rate);
329     }
330 #else
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() );
336         frames = 0;
337     }
338     last_time = t->get_cur_time();
339     ++frames;
340 #endif
341
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();
345
346 #if ENABLE_ATCDCL
347     // Run ATC subsystem
348     if (fgGetBool("/sim/atc/enabled"))
349         globals->get_ATC_mgr()->update(delta_time_sec);
350
351
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);
361 #endif  
362     
363     globals->get_subsystem_mgr()->update(delta_time_sec);
364     globals->get_aircraft_model()->update(delta_time_sec);
365     
366     //
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
370     //
371     double visibility_meters = fgGetDouble("/environment/visibility-m");
372     globals->get_tile_mgr()->prep_ssg_nodes( visibility_meters );
373
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);
378
379     // run Nasal's settimer() loops right before the view manager
380     globals->get_event_mgr()->update(delta_time_sec);
381
382     // pick up model coordidnates that Nasal code may have set relative to the
383     // aircraft's
384     globals->get_model_mgr()->update(delta_time_sec);
385
386     // update the view angle as late as possible, but before sound calculations
387     globals->get_viewmgr()->update(real_delta_time_sec);
388
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();
397             smgr_init = false;
398         }
399     } else {
400         static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
401         static SGSoundMgr *smgr = globals->get_soundmgr();
402         static bool smgr_enabled = true;
403
404         if (sound_working->getBoolValue() == false) {   // request to reinit
405            smgr->reinit();
406            smgr->resume();
407            sound_working->setBoolValue(true);
408         }
409
410         if (smgr_enabled != sound_enabled->getBoolValue()) {
411             if (smgr_enabled == true) { // request to suspend
412                 smgr->suspend();
413                 smgr_enabled = false;
414             } else {
415                 smgr->resume();
416                 smgr_enabled = true;
417             }
418         }
419
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);
424         }
425     }
426 #endif
427
428     // END Tile Manager udpates
429
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();
435         }
436         globals->get_props()->tie("/sim/sound/devices/name",
437               SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
438     }
439     simgear::AtomicChangeListener::fireChangeListeners();
440     fgRequestRedraw();
441
442     SG_LOG( SG_ALL, SG_DEBUG, "" );
443 }
444
445 void fgInitSoundManager()
446 {
447     SGSoundMgr *smgr = globals->get_soundmgr();
448
449     smgr->bind();
450     smgr->init(fgGetString("/sim/sound/device-name", NULL));
451
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]);
456     }
457     devices.clear();
458 }
459
460 void fgSetNewSoundDevice(const char *device)
461 {
462     globals->get_soundmgr()->suspend();
463     globals->get_soundmgr()->stop();
464     globals->get_soundmgr()->init(device);
465     globals->get_soundmgr()->resume();
466 }
467
468 // Operation for querying OpenGL parameters. This must be done in a
469 // valid OpenGL context, potentially in another thread.
470 namespace
471 {
472 struct GeneralInitOperation : public GraphicsContextOperation
473 {
474     GeneralInitOperation()
475         : GraphicsContextOperation(std::string("General init"))
476     {
477     }
478     void run(osg::GraphicsContext* gc)
479     {
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() );
486
487         GLint tmp;
488         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
489         general.set_glMaxTexSize( tmp );
490         SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
491
492         glGetIntegerv( GL_DEPTH_BITS, &tmp );
493         general.set_glDepthBits( tmp );
494         SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
495     }
496 };
497 }
498
499 // This is the top level master main function that is registered as
500 // our idle funciton
501
502 // The first few passes take care of initialization things (a couple
503 // per pass) and once everything has been initialized fgMainLoop from
504 // then on.
505
506 static void fgIdleFunction ( void ) {
507     static osg::ref_ptr<GeneralInitOperation> genOp;
508     if ( idle_state == 0 ) {
509         idle_state++;
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;
517         if (guiCamera)
518             gc = guiCamera->getGraphicsContext();
519         if (gc) {
520             gc->add(genOp.get());
521         } else {
522             wsa->windows[0]->gc->add(genOp.get());
523         }
524         guiStartInit(gc);
525     } else if ( idle_state == 1 ) {
526         if (genOp.valid()) {
527             if (!genOp->isFinished())
528                 return;
529             genOp = 0;
530         }
531         if (!guiFinishInit())
532             return;
533         idle_state++;
534         fgSplashProgress("reading aircraft list");
535
536
537     } else if ( idle_state == 2 ) {
538         idle_state++;
539         
540         globals->get_commands()->addCommand("load-aircraft", fgLoadAircraft);
541         
542         fgSplashProgress("reading airport & navigation data");
543
544
545     } else if ( idle_state == 3 ) {
546         idle_state++;
547         fgInitNav();
548         fgSplashProgress("setting up scenery");
549
550
551     } else if ( idle_state == 4 ) {
552         idle_state++;
553         // based on the requested presets, calculate the true starting
554         // lon, lat
555         fgInitPosition();
556         fgInitTowerLocationListener();
557
558         SGTime *t = fgInitTime();
559         globals->set_time_params( t );
560
561         // Do some quick general initializations
562         if( !fgInitGeneral()) {
563             SG_LOG( SG_GENERAL, SG_ALERT,
564                 "General initialization failed ..." );
565             exit(-1);
566         }
567
568         ////////////////////////////////////////////////////////////////////
569         // Initialize the property-based built-in commands
570         ////////////////////////////////////////////////////////////////////
571         fgInitCommands();
572
573
574         ////////////////////////////////////////////////////////////////////
575         // Initialize the material manager
576         ////////////////////////////////////////////////////////////////////
577         globals->set_matlib( new SGMaterialLib );
578         simgear::SGModelLib::init(globals->get_fg_root());
579
580
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 );
588
589
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");
597
598
599     } else if ( idle_state == 5 ) {
600         idle_state++;
601
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);
609         acm->init();
610         acm->bind();
611
612         ////////////////////////////////////////////////////////////////////
613         // Initialize the view manager subsystem.
614         ////////////////////////////////////////////////////////////////////
615         FGViewMgr *viewmgr = new FGViewMgr;
616         globals->set_viewmgr( viewmgr );
617         viewmgr->init();
618         viewmgr->bind();
619         fgSplashProgress("generating sky elements");
620
621
622     } else if ( idle_state == 6 ) {
623         idle_state++;
624         // Initialize the sky
625
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
629         eph->bind();
630
631         // TODO: move to environment mgr
632         thesky = new SGSky;
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);
639         }
640
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() );
645
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,
652                        463.3, 361.8,
653                        *globals->get_ephem(),
654                        fgGetNode("/environment", true));
655
656         // Initialize MagVar model
657         SGMagVar *magvar = new SGMagVar();
658         globals->set_mag( magvar );
659
660
661                                     // kludge to initialize mag compass
662                                     // (should only be done for in-flight
663                                     // startup)
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")
670                                     * SG_FEET_TO_METER,
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);
675
676
677         // airport = new ssgBranch;
678         // airport->setName( "Airport Lighting" );
679         // lighting->addKid( airport );
680
681         // build our custom render states
682         fgSplashProgress("initializing subsystems");
683
684
685     } else if ( idle_state == 7 ) {
686         idle_state++;
687         // Initialize audio support
688 #ifdef ENABLE_AUDIO_SUPPORT
689
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" );
694
695             SG_LOG( SG_GENERAL, SG_INFO,
696                 "Starting intro music: " << mp3file.str() );
697
698 # if defined( __CYGWIN__ )
699             string command = "start /m `cygpath -w " + mp3file.str() + "`";
700 # elif defined( _WIN32 )
701             string command = "start /m " + mp3file.str();
702 # else
703             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
704 # endif
705
706             system ( command.c_str() );
707         }
708 #endif
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 ..." );
716             exit(-1);
717         }
718         fgSplashProgress("setting up time & renderer");
719
720
721     } else if ( idle_state == 8 ) {
722         idle_state = 1000;
723         // Initialize the time offset (warp) after fgInitSubsystem
724         // (which initializes the lighting interpolation tables.)
725         fgInitTimeOffset();
726
727         // setup OpenGL view parameters
728         globals->get_renderer()->init();
729
730         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
731                                          fgGetInt("/sim/startup/ysize") );
732
733         fgSplashProgress("loading scenery objects");
734         int session = fgGetInt("/sim/session",0);
735         session++;
736         fgSetInt("/sim/session",session);
737     }
738
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 );
744     }
745 }
746
747
748 static void upper_case_property(const char *name)
749 {
750     using namespace simgear;
751     SGPropertyNode *p = fgGetNode(name, false);
752     if (!p) {
753         p = fgGetNode(name, true);
754         p->setStringValue("");
755     } else {
756         props::Type t = p->getType();
757         if (t == props::NONE || t == props::UNSPECIFIED)
758             p->setStringValue("");
759         else
760             assert(t == props::STRING);
761     }
762     p->addChangeListener(new FGMakeUpperCase);
763 }
764
765
766 // Main top level initialization
767 bool fgMainInit( int argc, char **argv ) {
768
769     // set default log levels
770     sglog().setLogLevels( SG_ALL, SG_ALERT );
771
772     string version;
773 #ifdef FLIGHTGEAR_VERSION
774     version = FLIGHTGEAR_VERSION;
775 #else
776     version = "unknown version";
777 #endif
778     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
779             << version );
780     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
781
782     // Allocate global data structures.  This needs to happen before
783     // we parse command line options
784
785     globals = new FGGlobals;
786
787     // seed the random number generator
788     sg_srandom_time();
789
790     FGControls *controls = new FGControls;
791     globals->set_controls( controls );
792
793     string_list *col = new string_list;
794     globals->set_channel_options_list( col );
795
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");
801
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);
805
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
811
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;
817 #ifdef _MSC_VER
818         cerr << "Hit a key to continue..." << endl;
819         cin.get();
820 #endif
821         exit(-1);
822     }
823
824     // Load the configuration parameters.  (Command line options
825     // override config file options.  Config file options override
826     // defaults.)
827     if ( !fgInitConfig(argc, argv) ) {
828         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
829         exit(-1);
830     }
831
832     // Initialize the Window/Graphics environment.
833     fgOSInit(&argc, argv);
834     _bootstrap_OSInit++;
835
836     fgRegisterWindowResizeHandler( &FGRenderer::resize );
837     fgRegisterIdleHandler( &fgIdleFunction );
838     fgRegisterDrawHandler( &FGRenderer::update );
839
840     // Initialize plib net interface
841     netInit( &argc, argv );
842
843     // Clouds3D requires an alpha channel
844     fgOSOpenWindow(true /* request stencil buffer */);
845
846     // Initialize the splash screen right away
847     fntInit();
848     fgSplashInit();
849
850     // pass control off to the master event handler
851     fgOSMainLoop();
852
853     // we never actually get here ... but to avoid compiler warnings,
854     // etc.
855     return false;
856 }
857
858