]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
9a40613a3cf833587cf36f759a889ef3ebe5edfe
[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 <osg/Camera>
38 #include <osg/GraphicsContext>
39 #include <osgDB/Registry>
40
41 // Class references
42 #include <simgear/scene/model/modellib.hxx>
43 #include <simgear/scene/material/matlib.hxx>
44 #include <simgear/scene/model/animation.hxx>
45 #include <simgear/scene/sky/sky.hxx>
46 #include <simgear/structure/event_mgr.hxx>
47 #include <simgear/props/AtomicChangeListener.hxx>
48 #include <simgear/props/props.hxx>
49 #include <simgear/timing/sg_time.hxx>
50 #include <simgear/magvar/magvar.hxx>
51 #include <simgear/math/sg_random.h>
52 #include <simgear/io/raw_socket.hxx>
53 #include <simgear/scene/tsync/terrasync.hxx>
54 #include <simgear/misc/sg_sleep.hxx>
55
56 #include <Time/light.hxx>
57 #include <Aircraft/replay.hxx>
58 #include <Aircraft/controls.hxx>
59 #include <Model/panelnode.hxx>
60 #include <Model/acmodel.hxx>
61 #include <Scenery/scenery.hxx>
62 #include <Scenery/tilemgr.hxx>
63 #include <Sound/fg_fx.hxx>
64 #include <Sound/beacon.hxx>
65 #include <Sound/morse.hxx>
66 #include <Sound/fg_fx.hxx>
67 #include <ATCDCL/ATCmgr.hxx>
68 #include <Time/TimeManager.hxx>
69 #include <Environment/environment_mgr.hxx>
70 #include <Environment/ephemeris.hxx>
71 #include <GUI/gui.h>
72 #include <GUI/new_gui.hxx>
73 #include <MultiPlayer/multiplaymgr.hxx>
74
75 #include "CameraGroup.hxx"
76 #include "fg_commands.hxx"
77 #include "fg_io.hxx"
78 #include "renderer.hxx"
79 #include "splash.hxx"
80 #include "main.hxx"
81 #include "util.hxx"
82 #include "fg_init.hxx"
83 #include "fg_os.hxx"
84 #include "WindowSystemAdapter.hxx"
85 #include <Main/viewer.hxx>
86
87
88 using namespace flightgear;
89
90 using std::cerr;
91
92 // Specify our current idle function state.  This is used to run all
93 // our initializations out of the idle callback so that we can get a
94 // splash screen up and running right away.
95 int idle_state = 0;
96
97
98 void fgInitSoundManager();
99 void fgSetNewSoundDevice(const char *);
100
101 // The atexit() function handler should know when the graphical subsystem
102 // is initialized.
103 extern int _bootstrap_OSInit;
104
105 // What should we do when we have nothing else to do?  Let's get ready
106 // for the next move and update the display?
107 static void fgMainLoop( void ) {
108     
109     static SGConstPropertyNode_ptr longitude
110         = fgGetNode("/position/longitude-deg");
111     static SGConstPropertyNode_ptr latitude
112         = fgGetNode("/position/latitude-deg");
113     static SGConstPropertyNode_ptr altitude
114         = fgGetNode("/position/altitude-ft");
115     static SGConstPropertyNode_ptr vn_fps
116         = fgGetNode("/velocities/speed-north-fps");
117     static SGConstPropertyNode_ptr ve_fps
118         = fgGetNode("/velocities/speed-east-fps");
119     static SGConstPropertyNode_ptr vd_fps
120         = fgGetNode("/velocities/speed-down-fps");
121       
122     static SGPropertyNode_ptr frame_signal
123         = fgGetNode("/sim/signals/frame", true);
124
125     static SGPropertyNode_ptr _statisticsFlag
126         = fgGetNode("/sim/timing-statistics/enabled", true);
127     static SGPropertyNode_ptr _statisticsInterval
128         = fgGetNode("/sim/timing-statistics/interval-s", true);
129     static SGPropertyNode_ptr _statiticsMinJitter
130         = fgGetNode("/sim/timing-statistics/min-jitter-ms", true);
131     static SGPropertyNode_ptr _statiticsMinTime
132         = fgGetNode("/sim/timing-statistics/min-time-ms", true);
133
134     frame_signal->fireValueChanged();
135     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping");
136     
137     SG_LOG( SG_GENERAL, SG_DEBUG, "Running Main Loop");
138     SG_LOG( SG_GENERAL, SG_DEBUG, "======= ==== ====");
139     
140     
141   // update "time"
142     double sim_dt, real_dt;
143     TimeManager* timeMgr = (TimeManager*) globals->get_subsystem("time");
144     // compute simulated time (allowing for pause, warp, etc) and
145     // real elapsed time
146     timeMgr->computeTimeDeltas(sim_dt, real_dt);
147
148     // update magvar model
149     globals->get_mag()->update( longitude->getDoubleValue()
150                                 * SGD_DEGREES_TO_RADIANS,
151                                 latitude->getDoubleValue()
152                                 * SGD_DEGREES_TO_RADIANS,
153                                 altitude->getDoubleValue() * SG_FEET_TO_METER,
154                                 globals->get_time_params()->getJD() );
155
156     // Run ATC subsystem
157     globals->get_ATC_mgr()->update(sim_dt);
158     
159     globals->get_subsystem_mgr()->update(sim_dt);
160
161     // Update the sound manager last so it can use the CPU while the GPU
162     // is processing the scenery (doubled the frame-rate for me) -EMH-
163 #ifdef ENABLE_AUDIO_SUPPORT
164     static bool smgr_init = true;
165     static SGPropertyNode *sound_working = fgGetNode("/sim/sound/working");
166     if (smgr_init == true) {
167         if (sound_working->getBoolValue() == true) {
168             fgInitSoundManager();
169             smgr_init = false;
170         }
171     } else {
172         static SGPropertyNode *sound_enabled = fgGetNode("/sim/sound/enabled");
173         static SGSoundMgr *smgr = globals->get_soundmgr();
174         static bool smgr_enabled = true;
175
176         if (sound_working->getBoolValue() == false) {   // request to reinit
177            smgr->reinit();
178            smgr->resume();
179            sound_working->setBoolValue(true);
180         }
181
182         if (smgr_enabled != sound_enabled->getBoolValue()) {
183             if (smgr_enabled == true) { // request to suspend
184                 smgr->suspend();
185                 smgr_enabled = false;
186             } else {
187                 smgr->resume();
188                 smgr_enabled = true;
189             }
190         }
191
192         if (smgr_enabled == true) {
193             static SGPropertyNode *volume = fgGetNode("/sim/sound/volume");
194             smgr->set_volume(volume->getFloatValue());
195             smgr->update(sim_dt);
196         }
197     }
198 #endif
199
200     // END Tile Manager updates
201     bool scenery_loaded = fgGetBool("sim/sceneryloaded");
202     if (!scenery_loaded)
203     {
204         if (globals->get_tile_mgr()->isSceneryLoaded()
205              && fgGetBool("sim/fdm-initialized")) {
206             fgSetBool("sim/sceneryloaded",true);
207             fgSplashProgress("");
208             if (fgGetBool("/sim/sound/working")) {
209                 globals->get_soundmgr()->activate();
210             }
211             globals->get_props()->tie("/sim/sound/devices/name",
212                   SGRawValueFunctions<const char *>(0, fgSetNewSoundDevice), false);
213         }
214         else
215         {
216             fgSplashProgress("loading scenery");
217             // be nice to loader threads while waiting for initial scenery, reduce to 2fps
218             simgear::sleepForMSec(500);
219         }
220     }
221
222     // print timing statistics
223     static bool _lastStatisticsFlag = false;
224     if (_lastStatisticsFlag != _statisticsFlag->getBoolValue())
225     {
226         // flag has changed, update subsystem manager
227         _lastStatisticsFlag = _statisticsFlag->getBoolValue();
228         globals->get_subsystem_mgr()->collectDebugTiming(_lastStatisticsFlag);
229     }
230     if (_lastStatisticsFlag)
231     {
232         static double elapsed = 0;
233         elapsed += real_dt;
234         if (elapsed >= _statisticsInterval->getDoubleValue())
235         {
236             // print and reset timing statistics
237             globals->get_subsystem_mgr()->printTimingStatistics(_statiticsMinTime->getDoubleValue(),
238                                                                 _statiticsMinJitter->getDoubleValue());
239             elapsed = 0;
240         }
241     }
242
243     simgear::AtomicChangeListener::fireChangeListeners();
244
245     SG_LOG( SG_GENERAL, SG_DEBUG, "" );
246 }
247
248 void fgInitSoundManager()
249 {
250     SGSoundMgr *smgr = globals->get_soundmgr();
251
252     smgr->bind();
253     smgr->init(fgGetString("/sim/sound/device-name", NULL));
254
255     vector <const char*>devices = smgr->get_available_devices();
256     for (unsigned int i=0; i<devices.size(); i++) {
257         SGPropertyNode *p = fgGetNode("/sim/sound/devices/device", i, true);
258         p->setStringValue(devices[i]);
259     }
260     devices.clear();
261 }
262
263 void fgSetNewSoundDevice(const char *device)
264 {
265     globals->get_soundmgr()->suspend();
266     globals->get_soundmgr()->stop();
267     globals->get_soundmgr()->init(device);
268     globals->get_soundmgr()->resume();
269 }
270
271 // Operation for querying OpenGL parameters. This must be done in a
272 // valid OpenGL context, potentially in another thread.
273 namespace
274 {
275 struct GeneralInitOperation : public GraphicsContextOperation
276 {
277     GeneralInitOperation()
278         : GraphicsContextOperation(std::string("General init"))
279     {
280     }
281     void run(osg::GraphicsContext* gc)
282     {
283         SGPropertyNode* simRendering = fgGetNode("/sim/rendering");
284         
285         simRendering->setStringValue("gl-vendor", (char*) glGetString(GL_VENDOR));
286         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VENDOR));
287         
288         simRendering->setStringValue("gl-renderer", (char*) glGetString(GL_RENDERER));
289         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_RENDERER));
290         
291         simRendering->setStringValue("gl-version", (char*) glGetString(GL_VERSION));
292         SG_LOG( SG_GENERAL, SG_INFO, glGetString(GL_VERSION));
293
294         GLint tmp;
295         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
296         simRendering->setIntValue("max-texture-size", tmp);
297
298         glGetIntegerv( GL_DEPTH_BITS, &tmp );
299         simRendering->setIntValue("depth-buffer-bits", tmp);
300     }
301 };
302
303
304 osg::Node* load_panel(SGPropertyNode *n)
305 {
306     osg::Geode* geode = new osg::Geode;
307     geode->addDrawable(new FGPanelNode(n));
308     return geode;
309 }
310
311 SGPath resolve_path(const std::string& s)
312 {
313   return globals->resolve_maybe_aircraft_path(s);
314 }
315
316 }
317
318 // This is the top level master main function that is registered as
319 // our idle function
320
321 // The first few passes take care of initialization things (a couple
322 // per pass) and once everything has been initialized fgMainLoop from
323 // then on.
324
325 static void fgIdleFunction ( void ) {
326     static osg::ref_ptr<GeneralInitOperation> genOp;
327     if ( idle_state == 0 ) {
328         idle_state++;
329         // Pick some window on which to do queries.
330         // XXX Perhaps all this graphics initialization code should be
331         // moved to renderer.cxx?
332         genOp = new GeneralInitOperation;
333         osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
334         WindowSystemAdapter* wsa = WindowSystemAdapter::getWSA();
335         osg::GraphicsContext* gc = 0;
336         if (guiCamera)
337             gc = guiCamera->getGraphicsContext();
338         if (gc) {
339             gc->add(genOp.get());
340         } else {
341             wsa->windows[0]->gc->add(genOp.get());
342         }
343         guiStartInit(gc);
344     } else if ( idle_state == 1 ) {
345         if (genOp.valid()) {
346             if (!genOp->isFinished())
347                 return;
348             genOp = 0;
349         }
350         if (!guiFinishInit())
351             return;
352         idle_state++;
353         fgSplashProgress("loading aircraft list");
354
355     } else if ( idle_state == 2 ) {
356         idle_state++;
357         fgSplashProgress("loading navigation data");
358
359     } else if ( idle_state == 3 ) {
360         idle_state++;
361         fgInitNav();
362
363         fgSplashProgress("initializing scenery system");
364
365     } else if ( idle_state == 4 ) {
366         idle_state++;
367         // based on the requested presets, calculate the true starting
368         // lon, lat
369         fgInitPosition();
370         fgInitTowerLocationListener();
371
372         TimeManager* t = new TimeManager;
373         globals->add_subsystem("time", t, SGSubsystemMgr::INIT);
374         t->init(); // need to init now, not during initSubsystems
375         
376         // Do some quick general initializations
377         if( !fgInitGeneral()) {
378             SG_LOG( SG_GENERAL, SG_ALERT,
379                 "General initialization failed ..." );
380             exit(-1);
381         }
382
383         ////////////////////////////////////////////////////////////////////
384         // Initialize the property-based built-in commands
385         ////////////////////////////////////////////////////////////////////
386         fgInitCommands();
387
388         ////////////////////////////////////////////////////////////////////
389         // Initialize the material manager
390         ////////////////////////////////////////////////////////////////////
391         globals->set_matlib( new SGMaterialLib );
392         simgear::SGModelLib::init(globals->get_fg_root(), globals->get_props());
393         simgear::SGModelLib::setPanelFunc(load_panel);
394
395         ////////////////////////////////////////////////////////////////////
396         // Initialize the TG scenery subsystem.
397         ////////////////////////////////////////////////////////////////////
398         simgear::SGTerraSync* terra_sync = new simgear::SGTerraSync(globals->get_props());
399         globals->add_subsystem("terrasync", terra_sync);
400         globals->set_scenery( new FGScenery );
401         globals->get_scenery()->init();
402         globals->get_scenery()->bind();
403         globals->set_tile_mgr( new FGTileMgr );
404
405         fgSplashProgress("loading aircraft");
406
407     } else if ( idle_state == 5 ) {
408         idle_state++;
409
410         fgSplashProgress("initializing sky elements");
411
412     } else if ( idle_state == 6 ) {
413         idle_state++;
414         // Initialize the sky
415
416         Ephemeris* eph = new Ephemeris;
417         globals->add_subsystem("ephemeris", eph);
418         eph->init(); // FIXME - remove this once SGSky code below is also a subsystem
419         eph->bind();
420
421         // TODO: move to environment mgr
422         thesky = new SGSky;
423         SGPath texture_path(globals->get_fg_root());
424         texture_path.append("Textures");
425         texture_path.append("Sky");
426         for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
427             SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
428             thesky->add_cloud_layer(layer);
429         }
430
431         SGPath sky_tex_path( globals->get_fg_root() );
432         sky_tex_path.append( "Textures" );
433         sky_tex_path.append( "Sky" );
434         thesky->texture_path( sky_tex_path.str() );
435
436         // The sun and moon diameters are scaled down numbers of the
437         // actual diameters. This was needed to fit both the sun and the
438         // moon within the distance to the far clip plane.
439         // Moon diameter:    3,476 kilometers
440         // Sun diameter: 1,390,000 kilometers
441         thesky->build( 80000.0, 80000.0,
442                        463.3, 361.8,
443                        *globals->get_ephem(),
444                        fgGetNode("/environment", true));
445
446         // Initialize MagVar model
447         SGMagVar *magvar = new SGMagVar();
448         globals->set_mag( magvar );
449
450
451                                     // kludge to initialize mag compass
452                                     // (should only be done for in-flight
453                                     // startup)
454         // update magvar model
455         globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
456                                     * SGD_DEGREES_TO_RADIANS,
457                                     fgGetDouble("/position/latitude-deg")
458                                     * SGD_DEGREES_TO_RADIANS,
459                                     fgGetDouble("/position/altitude-ft")
460                                     * SG_FEET_TO_METER,
461                                     globals->get_time_params()->getJD() );
462         double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
463         fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
464         fgSetDouble("/instrumentation/heading-indicator-fg/offset-deg", -var);
465
466
467         // airport = new ssgBranch;
468         // airport->setName( "Airport Lighting" );
469         // lighting->addKid( airport );
470
471         fgSplashProgress("initializing subsystems");
472
473     } else if ( idle_state == 7 ) {
474         idle_state++;
475         // Initialize audio support
476 #ifdef ENABLE_AUDIO_SUPPORT
477
478         // Start the intro music
479         if ( fgGetBool("/sim/startup/intro-music") ) {
480             SGPath mp3file( globals->get_fg_root() );
481             mp3file.append( "Sounds/intro.mp3" );
482
483             SG_LOG( SG_GENERAL, SG_INFO,
484                 "Starting intro music: " << mp3file.str() );
485
486 # if defined( __CYGWIN__ )
487             string command = "start /m `cygpath -w " + mp3file.str() + "`";
488 # elif defined( _WIN32 )
489             string command = "start /m " + mp3file.str();
490 # else
491             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
492 # endif
493
494             system ( command.c_str() );
495         }
496 #endif
497         // This is the top level init routine which calls all the
498         // other subsystem initialization routines.  If you are adding
499         // a subsystem to flightgear, its initialization call should be
500         // located in this routine.
501         if( !fgInitSubsystems()) {
502             SG_LOG( SG_GENERAL, SG_ALERT,
503                 "Subsystem initialization failed ..." );
504             exit(-1);
505         }
506
507         // Torsten Dreyer:
508         // ugly hack for automatic runway selection on startup based on
509         // metar data. Makes startup.nas obsolete and guarantees the same
510         // runway selection as for AI traffic. However, this code belongs to
511         // somewhere(?) else - if I only new where...
512         if( true == fgGetBool( "/environment/metar/valid" ) ) {
513             // the realwx_ctrl fetches metar in the foreground on init,
514             // If it was able to fetch a metar or one was given on the commandline,
515             // the valid flag is set here, otherwise it is false
516             double hdg = fgGetDouble( "/environment/metar/base-wind-dir-deg", 9999.0 );
517             string apt = fgGetString( "/sim/startup/options/airport" );
518             string rwy = fgGetString( "/sim/startup/options/runway" );
519             double strthdg = fgGetDouble( "/sim/startup/options/heading-deg", 9999.0 );
520             string parkpos = fgGetString( "/sim/presets/parkpos" );
521             bool onground = fgGetBool( "/sim/presets/onground", false );
522             // don't check for wind-speed < 1kt, this belongs to the runway-selection code
523             // the other logic is taken from former startup.nas
524             if( hdg < 360.0 && apt.length() > 0 && strthdg > 360.0 && rwy.length() == 0 && onground && parkpos.length() == 0 ) {
525                 extern bool fgSetPosFromAirportIDandHdg( const string& id, double tgt_hdg );
526                 fgSetPosFromAirportIDandHdg( apt, hdg );
527             }
528         }
529
530         fgSplashProgress("initializing graphics engine");
531
532     } else if ( idle_state == 8 ) {
533         idle_state = 1000;
534         
535         // setup OpenGL view parameters
536         globals->get_renderer()->setupView();
537
538         globals->get_renderer()->resize( fgGetInt("/sim/startup/xsize"),
539                                          fgGetInt("/sim/startup/ysize") );
540
541         int session = fgGetInt("/sim/session",0);
542         session++;
543         fgSetInt("/sim/session",session);
544     }
545
546     if ( idle_state == 1000 ) {
547         // We've finished all our initialization steps, from now on we
548         // run the main loop.
549         fgSetBool("sim/sceneryloaded", false);
550         fgRegisterIdleHandler( fgMainLoop );
551     }
552 }
553
554 static void upper_case_property(const char *name)
555 {
556     using namespace simgear;
557     SGPropertyNode *p = fgGetNode(name, false);
558     if (!p) {
559         p = fgGetNode(name, true);
560         p->setStringValue("");
561     } else {
562         props::Type t = p->getType();
563         if (t == props::NONE || t == props::UNSPECIFIED)
564             p->setStringValue("");
565         else
566             assert(t == props::STRING);
567     }
568     p->addChangeListener(new FGMakeUpperCase);
569 }
570
571
572 // Main top level initialization
573 int fgMainInit( int argc, char **argv ) {
574
575     // set default log levels
576     sglog().setLogLevels( SG_ALL, SG_ALERT );
577
578     string version;
579 #ifdef FLIGHTGEAR_VERSION
580     version = FLIGHTGEAR_VERSION;
581 #else
582     version = "unknown version";
583 #endif
584     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
585             << version );
586     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
587
588     // Allocate global data structures.  This needs to happen before
589     // we parse command line options
590
591     globals = new FGGlobals;
592
593     // seed the random number generator
594     sg_srandom_time();
595
596     FGControls *controls = new FGControls;
597     globals->set_controls( controls );
598
599     string_list *col = new string_list;
600     globals->set_channel_options_list( col );
601
602     fgValidatePath("", false);  // initialize static variables
603     upper_case_property("/sim/presets/airport-id");
604     upper_case_property("/sim/presets/runway");
605     upper_case_property("/sim/tower/airport-id");
606     upper_case_property("/autopilot/route-manager/input");
607
608     // Scan the config file(s) and command line options to see if
609     // fg_root was specified (ignore all other options for now)
610     fgInitFGRoot(argc, argv);
611
612     // Check for the correct base package version
613     static char required_version[] = "2.5.0";
614     string base_version = fgBasePackageVersion();
615     if ( !(base_version == required_version) ) {
616         // tell the operator how to use this application
617
618         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
619         cerr << endl << "Base package check failed:" << endl \
620              << "  Version " << base_version << " found at: " \
621              << globals->get_fg_root() << endl \
622              << "  Version " << required_version << " is required." << endl \
623              << "Please upgrade/downgrade base package and set the path to your fgdata" << endl \
624              << "with --fg-root=path_to_your_fgdata" << endl;
625 #ifdef _MSC_VER
626         cerr << "Hit a key to continue..." << endl;
627         cin.get();
628 #endif
629         exit(-1);
630     }
631
632     // Load the configuration parameters.  (Command line options
633     // override config file options.  Config file options override
634     // defaults.)
635     if ( !fgInitConfig(argc, argv) ) {
636         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
637         exit(-1);
638     }
639
640     // Initialize the Window/Graphics environment.
641     fgOSInit(&argc, argv);
642     _bootstrap_OSInit++;
643
644     fgRegisterIdleHandler( &fgIdleFunction );
645
646     // Initialize sockets (WinSock needs this)
647     simgear::Socket::initSockets();
648
649     // Clouds3D requires an alpha channel
650     fgOSOpenWindow(true /* request stencil buffer */);
651
652     // Initialize the splash screen right away
653     fntInit();
654     fgSplashInit();
655
656     // pass control off to the master event handler
657     int result = fgOSMainLoop();
658     
659     // clean up here; ensure we null globals to avoid
660     // confusing the atexit() handler
661     delete globals;
662     globals = NULL;
663     
664     return result;
665 }