]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Show the mouse cursor again, just before exiting. This could prevent an X windows...
[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  - curt@flightgear.org
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., 675 Mass Ave, Cambridge, MA 02139, 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 #ifdef SG_MATH_EXCEPTION_CLASH
36 #  include <math.h>
37 #endif
38
39 #ifdef HAVE_WINDOWS_H
40 #  include <windows.h>
41 #  include <float.h>
42 #endif
43
44 #include <plib/ssg.h>
45 #include <plib/netSocket.h>
46
47 #include <simgear/screen/extensions.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/props/props.hxx>
50 #include <simgear/scene/sky/sky.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/scene/model/animation.hxx>
53 #include <simgear/ephemeris/ephemeris.hxx>
54 #include <simgear/scene/model/placement.hxx>
55 #include <simgear/math/sg_random.h>
56 #include <simgear/scene/model/modellib.hxx>
57
58 #ifdef FG_USE_CLOUDS_3D
59 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
60 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
61 #endif
62
63 #include <Include/general.hxx>
64 #include <Scenery/tileentry.hxx>
65 #include <Time/light.hxx>
66 #include <Time/light.hxx>
67 #include <Aircraft/aircraft.hxx>
68 #include <Cockpit/panel.hxx>
69 #include <Cockpit/cockpit.hxx>
70 #include <Cockpit/radiostack.hxx>
71 #include <Cockpit/hud.hxx>
72 #include <Model/panelnode.hxx>
73 #include <Model/modelmgr.hxx>
74 #include <Model/acmodel.hxx>
75 #include <Scenery/scenery.hxx>
76 #include <Scenery/tilemgr.hxx>
77 #include <FDM/flight.hxx>
78 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
79 #include <FDM/ADA.hxx>
80 #include <ATC/ATCdisplay.hxx>
81 #include <ATC/ATCmgr.hxx>
82 #include <ATC/AIMgr.hxx>
83 #include <Replay/replay.hxx>
84 #include <Time/tmp.hxx>
85 #include <Time/fg_timer.hxx>
86 #include <Environment/environment_mgr.hxx>
87 #include <GUI/new_gui.hxx>
88
89 #ifdef FG_MPLAYER_AS
90 #include <MultiPlayer/multiplaytxmgr.hxx>
91 #include <MultiPlayer/multiplayrxmgr.hxx>
92 #endif
93
94 #include "splash.hxx"
95 #include "fg_commands.hxx"
96 #include "fg_io.hxx"
97 #include "main.hxx"
98
99 float default_attenuation[3] = {1.0, 0.0, 0.0};
100 ssgSelector *ship_sel=NULL;
101 // upto 32 instances of a same object can be loaded.
102 ssgTransform *ship_pos[32];
103 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
104 int objc=0;
105 ssgSelector *lightpoints_brightness = new ssgSelector;
106 ssgTransform *lightpoints_transform = new ssgTransform;
107 FGTileEntry *dummy_tile;
108 sgVec3 rway_ols;
109 // ADA
110 // Clip plane settings...
111 float scene_nearplane = 0.5f;
112 float scene_farplane = 120000.0f;
113
114 static double real_delta_time_sec = 0.0;
115 static double delta_time_sec = 0.0;
116
117 glPointParameterfProc glPointParameterfPtr = 0;
118 glPointParameterfvProc glPointParameterfvPtr = 0;
119 bool glPointParameterIsSupported = false;
120
121
122 #ifdef macintosh
123 #  include <console.h>          // -dw- for command line dialog
124 #endif
125
126 // This is a record containing a bit of global housekeeping information
127 FGGeneral general;
128
129 // Specify our current idle function state.  This is used to run all
130 // our initializations out of the idle callback so that we can get a
131 // splash screen up and running right away.
132 static int idle_state = 0;
133 static long global_multi_loop;
134
135 // fog constants.  I'm a little nervous about putting actual code out
136 // here but it seems to work (?)
137 static const double m_log01 = -log( 0.01 );
138 static const double sqrt_m_log01 = sqrt( m_log01 );
139 static GLfloat fog_exp_density;
140 static GLfloat fog_exp2_density;
141 static GLfloat rwy_exp2_punch_through;
142 static GLfloat taxi_exp2_punch_through;
143 static GLfloat ground_exp2_punch_through;
144
145 // Sky structures
146 SGSky *thesky;
147
148 #ifdef FG_USE_CLOUDS_3D
149   SkySceneLoader *sgClouds3d;
150   bool _bcloud_orig = true;
151 #endif
152
153 // hack
154 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
155 {
156   {  1.0f,  0.0f,  0.0f,  0.0f },
157   {  0.0f,  0.0f, -1.0f,  0.0f },
158   {  0.0f,  1.0f,  0.0f,  0.0f },
159   {  0.0f,  0.0f,  0.0f,  1.0f }
160 };
161
162 ssgSimpleState *cloud3d_imposter_state;
163 ssgSimpleState *default_state;
164 ssgSimpleState *hud_and_panel;
165 ssgSimpleState *menus;
166
167 SGTimeStamp last_time_stamp;
168 SGTimeStamp current_time_stamp;
169
170
171 void fgBuildRenderStates( void ) {
172     default_state = new ssgSimpleState;
173     default_state->ref();
174     default_state->disable( GL_TEXTURE_2D );
175     default_state->enable( GL_CULL_FACE );
176     default_state->enable( GL_COLOR_MATERIAL );
177     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
178     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
179     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
180     default_state->disable( GL_BLEND );
181     default_state->disable( GL_ALPHA_TEST );
182     default_state->disable( GL_LIGHTING );
183
184     cloud3d_imposter_state = new ssgSimpleState;
185     cloud3d_imposter_state->ref();
186     cloud3d_imposter_state->enable( GL_TEXTURE_2D );
187     cloud3d_imposter_state->enable( GL_CULL_FACE );
188     cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
189     cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
190     cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
191     cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
192     cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
193     cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
194     cloud3d_imposter_state->enable( GL_BLEND );
195     cloud3d_imposter_state->enable( GL_ALPHA_TEST );
196     cloud3d_imposter_state->disable( GL_LIGHTING );
197
198     hud_and_panel = new ssgSimpleState;
199     hud_and_panel->ref();
200     hud_and_panel->disable( GL_CULL_FACE );
201     hud_and_panel->disable( GL_TEXTURE_2D );
202     hud_and_panel->disable( GL_LIGHTING );
203     hud_and_panel->enable( GL_BLEND );
204
205     menus = new ssgSimpleState;
206     menus->ref();
207     menus->disable( GL_CULL_FACE );
208     menus->disable( GL_TEXTURE_2D );
209     menus->enable( GL_BLEND );
210 }
211
212
213 // fgInitVisuals() -- Initialize various GL/view parameters
214 void fgInitVisuals( void ) {
215
216     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
217
218     // Go full screen if requested ...
219     if ( fgGetBool("/sim/startup/fullscreen") ) {
220         fgOSFullScreen();
221     }
222
223     // If enabled, normal vectors specified with glNormal are scaled
224     // to unit length after transformation.  Enabling this has
225     // performance implications.  See the docs for glNormal.
226     // glEnable( GL_NORMALIZE );
227
228     glEnable( GL_LIGHTING );
229     glEnable( GL_LIGHT0 );
230     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
231
232     sgVec3 sunpos;
233     sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
234     ssgGetLight( 0 ) -> setPosition( sunpos );
235
236     glFogi (GL_FOG_MODE, GL_EXP2);
237     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
238          (!fgGetBool("/sim/rendering/shading"))) {
239         // if fastest fog requested, or if flat shading force fastest
240         glHint ( GL_FOG_HINT, GL_FASTEST );
241     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
242         glHint ( GL_FOG_HINT, GL_NICEST );
243     }
244     if ( fgGetBool("/sim/rendering/wireframe") ) {
245         // draw wire frame
246         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
247     }
248
249     // This is the default anyways, but it can't hurt
250     glFrontFace ( GL_CCW );
251
252     // Just testing ...
253     // glEnable(GL_POINT_SMOOTH);
254     // glEnable(GL_LINE_SMOOTH);
255     // glEnable(GL_POLYGON_SMOOTH);      
256 }
257
258
259 // For HiRes screen Dumps using Brian Pauls TR Library
260 void trRenderFrame( void ) {
261 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
262     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
263                             !SGCloudLayer::enable_bump_mapping; // ugly artefact now
264 #else
265     bool multi_pass_clouds = false;
266 #endif
267     bool draw_clouds = fgGetBool("/environment/clouds/status");
268
269     if ( fgPanelVisible() ) {
270         GLfloat height = fgGetInt("/sim/startup/ysize");
271         GLfloat view_h =
272             (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
273             * (height / 768.0) + 1;
274         glTranslatef( 0.0, view_h, 0.0 );
275     }
276
277     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
278     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
279
280     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
281
282     glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1], 
283                  l->adj_fog_color()[2], l->adj_fog_color()[3]);
284
285     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
286
287     // set the opengl state to known default values
288     default_state->force();
289
290     glEnable( GL_FOG );
291     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
292     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
293     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color() );
294
295     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
296     // we only update GL_AMBIENT for our lights we will never get
297     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
298     // explicitely to black.
299     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
300     glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
301
302     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
303
304     // texture parameters
305     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
306     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
307
308     // we need a white diffuse light for the phase of the moon
309     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
310     thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
311                      fog_exp2_density );
312
313     // draw the ssg scene
314     // return to the desired diffuse color
315     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
316     glEnable( GL_DEPTH_TEST );
317     ssgSetNearFar( scene_nearplane, scene_farplane );
318     if ( draw_clouds ) {
319         // Draw the terrain
320         FGTileMgr::set_tile_filter( true );
321         sgSetModelFilter( false );
322         globals->get_aircraft_model()->select( false );
323         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
324         // Disable depth buffer update, draw the clouds
325         glDepthMask( GL_FALSE );
326         thesky->drawUpperClouds();
327         if ( multi_pass_clouds ) {
328             thesky->drawLowerClouds();
329         }
330         glDepthMask( GL_TRUE );
331         if ( multi_pass_clouds ) {
332             // Draw the objects except the aircraft
333             //  and update the stencil buffer with 1
334             glEnable( GL_STENCIL_TEST );
335             glStencilFunc( GL_ALWAYS, 1, 1 );
336             glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
337         }
338         FGTileMgr::set_tile_filter( false );
339         sgSetModelFilter( true );
340         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
341     } else {
342         FGTileMgr::set_tile_filter( true );
343         sgSetModelFilter( true );
344         globals->get_aircraft_model()->select( false );
345         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
346     }
347
348     // draw the lights
349     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
350     ssgSetNearFar( scene_nearplane, scene_farplane );
351     ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
352     ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
353
354     ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
355
356     if ( draw_clouds ) {
357         if ( multi_pass_clouds ) {
358             // Disable depth buffer update, draw the clouds where the
359             //  objects overwrite the already drawn clouds, by testing
360             //  the stencil buffer against 1
361             glDepthMask( GL_FALSE );
362             glStencilFunc( GL_EQUAL, 1, 1 );
363             glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
364             thesky->drawUpperClouds();
365             thesky->drawLowerClouds();
366             glDepthMask( GL_TRUE );
367             glDisable( GL_STENCIL_TEST );
368         } else {
369             glDepthMask( GL_FALSE );
370             thesky->drawLowerClouds();
371             glDepthMask( GL_TRUE );
372         }
373     }
374
375     globals->get_aircraft_model()->select( true );
376     globals->get_model_mgr()->draw();
377     globals->get_aircraft_model()->draw();
378 }
379
380
381 // Update all Visuals (redraws anything graphics related)
382 void fgRenderFrame() {
383     bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
384     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
385     bool skyblend = fgGetBool("/sim/rendering/skyblend");
386     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
387     bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
388 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
389     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") && 
390                                 !SGCloudLayer::enable_bump_mapping;  // ugly artefact now
391 #else
392     bool multi_pass_clouds = false;
393 #endif
394     bool draw_clouds = fgGetBool("/environment/clouds/status");
395
396     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
397     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
398
399     // static const SGPropertyNode *longitude
400     //     = fgGetNode("/position/longitude-deg");
401     // static const SGPropertyNode *latitude
402     //     = fgGetNode("/position/latitude-deg");
403     // static const SGPropertyNode *altitude
404     //     = fgGetNode("/position/altitude-ft");
405     static const SGPropertyNode *groundlevel_nearplane
406         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
407
408     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
409     static double last_visibility = -9999;
410
411     // update fog params
412     double actual_visibility;
413     if (fgGetBool("/environment/clouds/status"))
414         actual_visibility = thesky->get_visibility();
415     else
416         actual_visibility = fgGetDouble("/environment/visibility-m");
417     if ( actual_visibility != last_visibility ) {
418         last_visibility = actual_visibility;
419
420         fog_exp_density = m_log01 / actual_visibility;
421         fog_exp2_density = sqrt_m_log01 / actual_visibility;
422         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
423         if ( actual_visibility < 8000 ) {
424             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
425             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
426         } else {
427             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
428             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
429         }
430     }
431
432     // double angle;
433     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
434     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
435     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
436     // GLfloat mat_shininess[] = { 10.0 };
437     GLbitfield clear_mask;
438
439     if ( idle_state != 1000 || !scenery_loaded ) {
440         // still initializing, draw the splash screen
441         if ( fgGetBool("/sim/startup/splash-screen") ) {
442             fgSplashUpdate(0.0, 1.0);
443         }
444         // Keep resetting sim time while the sim is initializing
445         globals->set_sim_time_sec( 0.0 );
446         SGAnimation::set_sim_time_sec( 0.0 );
447     } else {
448         // idle_state is now 1000 meaning we've finished all our
449         // initializations and are running the main loop, so this will
450         // now work without seg faulting the system.
451
452         FGViewer *current__view = globals->get_current_view();
453
454         // calculate our current position in cartesian space
455         globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
456
457         // update view port
458         fgReshape( fgGetInt("/sim/startup/xsize"),
459                    fgGetInt("/sim/startup/ysize") );
460
461         if ( fgGetBool("/sim/rendering/clouds3d") ) {
462             glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
463             cloud3d_imposter_state->force();
464             glDisable( GL_FOG );
465             glColor4f( 1.0, 1.0, 1.0, 1.0 );
466             glEnable(GL_DEPTH_TEST);
467             glEnable(GL_BLEND);
468             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
469
470 #ifdef FG_USE_CLOUDS_3D
471             if ( _bcloud_orig ) {
472                 Point3D c = globals->get_scenery()->get_center();
473                 sgClouds3d->Set_Cloud_Orig( &c );
474                 _bcloud_orig = false;
475             }
476             sgClouds3d->Update( current__view->get_absolute_view_pos() );
477 #endif
478             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
479             glDisable(GL_DEPTH_TEST);
480         }
481
482         clear_mask = GL_DEPTH_BUFFER_BIT;
483         if ( fgGetBool("/sim/rendering/wireframe") ) {
484             clear_mask |= GL_COLOR_BUFFER_BIT;
485         }
486
487         if ( skyblend ) {
488             if ( fgGetBool("/sim/rendering/textures") ) {
489             // glClearColor(black[0], black[1], black[2], black[3]);
490             glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
491                          l->adj_fog_color()[2], l->adj_fog_color()[3]);
492             clear_mask |= GL_COLOR_BUFFER_BIT;
493             }
494         } else {
495             glClearColor(l->sky_color()[0], l->sky_color()[1],
496                          l->sky_color()[2], l->sky_color()[3]);
497             clear_mask |= GL_COLOR_BUFFER_BIT;
498         }
499         if ( multi_pass_clouds && draw_clouds ) {
500             glClearStencil( 0 );
501             clear_mask |= GL_STENCIL_BUFFER_BIT;
502         }
503         glClear( clear_mask );
504
505         // Tell GL we are switching to model view parameters
506
507         // I really should create a derived ssg node or use a call
508         // back or something so that I can draw the sky within the
509         // ssgCullAndDraw() function, but for now I just mimic what
510         // ssg does to set up the model view matrix
511         glMatrixMode(GL_MODELVIEW);
512         glLoadIdentity();
513         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
514
515         // set the opengl state to known default values
516         default_state->force();
517
518         // update fog params if visibility has changed
519         double visibility_meters = fgGetDouble("/environment/visibility-m");
520         thesky->set_visibility(visibility_meters);
521
522         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
523                             ( global_multi_loop * fgGetInt("/sim/speed-up") )
524                             / (double)fgGetInt("/sim/model-hz") );
525
526         // Set correct opengl fog density
527         glFogf (GL_FOG_DENSITY, fog_exp2_density);
528
529         // update the sky dome
530         if ( skyblend ) {
531             /*
532              SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
533              << l->sky_color()[0] << " "
534              << l->sky_color()[1] << " "
535              << l->sky_color()[2] << " "
536              << l->sky_color()[3] );
537             SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
538              << l->fog_color()[0] << " "
539              << l->fog_color()[1] << " "
540              << l->fog_color()[2] << " "
541              << l->fog_color()[3] ); 
542             SG_LOG( SG_GENERAL, SG_BULK,
543                     "    sun_angle = " << l->sun_angle
544              << "    moon_angle = " << l->moon_angle );
545             */
546
547             static SGSkyColor scolor;
548             FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
549
550             scolor.sky_color   = l->sky_color();
551             scolor.fog_color   = l->adj_fog_color();
552             scolor.cloud_color = l->cloud_color();
553             scolor.sun_angle   = l->get_sun_angle();
554             scolor.moon_angle  = l->get_moon_angle();
555             scolor.nplanets    = globals->get_ephem()->getNumPlanets();
556             scolor.nstars      = globals->get_ephem()->getNumStars();
557             scolor.planet_data = globals->get_ephem()->getPlanets();
558             scolor.star_data   = globals->get_ephem()->getStars();
559
560             thesky->repaint( scolor );
561
562             /*
563             SG_LOG( SG_GENERAL, SG_BULK,
564                     "thesky->reposition( view_pos = " << view_pos[0] << " "
565              << view_pos[1] << " " << view_pos[2] );
566             SG_LOG( SG_GENERAL, SG_BULK,
567                     "    zero_elev = " << zero_elev[0] << " "
568              << zero_elev[1] << " " << zero_elev[2]
569              << " lon = " << cur_fdm_state->get_Longitude()
570              << " lat = " << cur_fdm_state->get_Latitude() );
571             SG_LOG( SG_GENERAL, SG_BULK,
572                     "    sun_rot = " << l->get_sun_rotation
573              << " gst = " << SGTime::cur_time_params->getGst() );
574             SG_LOG( SG_GENERAL, SG_BULK,
575                  "    sun ra = " << globals->get_ephem()->getSunRightAscension()
576               << " sun dec = " << globals->get_ephem()->getSunDeclination()
577               << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
578               << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
579             */
580
581             // The sun and moon distances are scaled down versions
582             // of the actual distance to get both the moon and the sun
583             // within the range of the far clip plane.
584             // Moon distance:    384,467 kilometers
585             // Sun distance: 150,000,000 kilometers
586             double sun_horiz_eff, moon_horiz_eff;
587             if (fgGetBool("/sim/rendering/horizon-effect")) {
588             sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
589             moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
590             } else {
591                sun_horiz_eff = moon_horiz_eff = 1.0;
592             }
593
594             static SGSkyState sstate;
595
596             sstate.view_pos  = current__view->get_view_pos();
597             sstate.zero_elev = current__view->get_zero_elev();
598             sstate.view_up   = current__view->get_world_up();
599             sstate.lon       = current__view->getLongitude_deg()
600                                 * SGD_DEGREES_TO_RADIANS;
601             sstate.lat       = current__view->getLatitude_deg()
602                                 * SGD_DEGREES_TO_RADIANS;
603             sstate.alt       = current__view->getAltitudeASL_ft()
604                                 * SG_FEET_TO_METER;
605             sstate.spin      = l->get_sun_rotation();
606             sstate.gst       = globals->get_time_params()->getGst();
607             sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
608             sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
609             sstate.sun_dist  = 50000.0 * sun_horiz_eff;
610             sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
611             sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
612             sstate.moon_dist = 40000.0 * moon_horiz_eff;
613
614             thesky->reposition( sstate, delta_time_sec );
615         }
616
617         glEnable( GL_DEPTH_TEST );
618         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
619             glEnable( GL_FOG );
620             glFogi( GL_FOG_MODE, GL_EXP2 );
621             glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
622         }
623
624         // set sun/lighting parameters
625         ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
626
627         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
628         // we only update GL_AMBIENT for our lights we will never get
629         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
630         // explicitely to black.
631         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
632
633         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
634         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
635         ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
636
637         // texture parameters
638         // glEnable( GL_TEXTURE_2D );
639         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
640         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
641
642         // glMatrixMode( GL_PROJECTION );
643         // glLoadIdentity();
644         ssgSetFOV( current__view->get_h_fov(),
645                    current__view->get_v_fov() );
646
647         double agl =
648             current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
649             - globals->get_scenery()->get_cur_elev();
650
651         if ( agl > 10.0 ) {
652             scene_nearplane = 10.0f;
653             scene_farplane = 120000.0f;
654         } else {
655             scene_nearplane = groundlevel_nearplane->getDoubleValue();
656             scene_farplane = 120000.0f;
657         }
658
659         ssgSetNearFar( scene_nearplane, scene_farplane );
660
661 #ifdef FG_MPLAYER_AS
662         // Update any multiplayer models
663         globals->get_multiplayer_rx_mgr()->Update();
664 #endif
665
666         if ( draw_otw && skyblend ) {
667             // draw the sky backdrop
668
669             // we need a white diffuse light for the phase of the moon
670             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
671             thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
672                              fog_exp2_density );
673             // return to the desired diffuse color
674             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
675         }
676
677         // draw the ssg scene
678         glEnable( GL_DEPTH_TEST );
679
680         ssgSetNearFar( scene_nearplane, scene_farplane );
681
682         if ( fgGetBool("/sim/rendering/wireframe") ) {
683             // draw wire frame
684             glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
685         }
686         if ( draw_otw ) {
687             if ( draw_clouds ) {
688
689                 // Draw the terrain
690                 FGTileMgr::set_tile_filter( true );
691                 sgSetModelFilter( false );
692                 globals->get_aircraft_model()->select( false );
693                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
694
695                 // Disable depth buffer update, draw the clouds
696                 glDepthMask( GL_FALSE );
697                 thesky->drawUpperClouds();
698                 if ( multi_pass_clouds ) {
699                     thesky->drawLowerClouds();
700                 }
701                 glDepthMask( GL_TRUE );
702
703                 if ( multi_pass_clouds ) {
704                     // Draw the objects except the aircraft
705                     //  and update the stencil buffer with 1
706                     glEnable( GL_STENCIL_TEST );
707                     glStencilFunc( GL_ALWAYS, 1, 1 );
708                     glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
709                 }
710                 FGTileMgr::set_tile_filter( false );
711                 sgSetModelFilter( true );
712                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
713             } else {
714                 FGTileMgr::set_tile_filter( true );
715                 sgSetModelFilter( true );
716                 globals->get_aircraft_model()->select( false );
717                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
718             }
719         }
720
721         // This is a bit kludgy.  Every 200 frames, do an extra
722         // traversal of the scene graph without drawing anything, but
723         // with the field-of-view set to 360x360 degrees.  This
724         // ensures that out-of-range random objects that are not in
725         // the current view frustum will still be freed properly.
726         static int counter = 0;
727         counter++;
728         if (counter == 200) {
729             sgFrustum f;
730             f.setFOV(360, 360);
731                     // No need to put the near plane too close;
732                     // this way, at least the aircraft can be
733                     // culled.
734             f.setNearFar(1000, 1000000);
735             sgMat4 m;
736             ssgGetModelviewMatrix(m);
737             FGTileMgr::set_tile_filter( true );
738             sgSetModelFilter( true );
739             globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
740             counter = 0;
741         }
742
743         // change state for lighting here
744
745         // draw runway lighting
746         glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
747         ssgSetNearFar( scene_nearplane, scene_farplane );
748
749         if ( enhanced_lighting ) {
750
751             // Enable states for drawing points with GL_extension
752             glEnable(GL_POINT_SMOOTH);
753
754             if ( distance_attenuation && glPointParameterIsSupported )
755             {
756                 // Enable states for drawing points with GL_extension
757                 glEnable(GL_POINT_SMOOTH);
758
759                 float quadratic[3] = {1.0, 0.001, 0.0000001};
760                 // makes the points fade as they move away
761                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
762                 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
763             }
764
765             glPointSize(4.0);
766
767             // blending function for runway lights
768             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
769         }
770
771         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
772         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
773         glEnable(GL_TEXTURE_GEN_S);
774         glEnable(GL_TEXTURE_GEN_T);
775         glPolygonMode(GL_FRONT, GL_POINT);
776
777         // draw runway lighting
778         if ( draw_otw ) {
779             ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
780             ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
781         }
782
783         // change punch through and then draw taxi lighting
784         glFogf ( GL_FOG_DENSITY, fog_exp2_density );
785         // sgVec3 taxi_fog;
786         // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
787         // glFogfv ( GL_FOG_COLOR, taxi_fog );
788         if ( draw_otw ) {
789             ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
790         }
791
792         // clean up lighting
793         glPolygonMode(GL_FRONT, GL_FILL);
794         glDisable(GL_TEXTURE_GEN_S);
795         glDisable(GL_TEXTURE_GEN_T);
796
797         //static int _frame_count = 0;
798         //if (_frame_count % 30 == 0) {
799         //  printf("SSG: %s\n", ssgShowStats());
800         //}
801         //else {
802         //  ssgShowStats();
803         //}
804         //_frame_count++;
805
806
807         if ( enhanced_lighting ) {
808             if ( distance_attenuation && glPointParameterIsSupported ) {
809                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
810                                       default_attenuation);
811             }
812
813             glPointSize(1.0);
814             glDisable(GL_POINT_SMOOTH);
815         }
816
817         // draw ground lighting
818         glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
819         if ( draw_otw ) {
820             ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
821         }
822
823         if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") ) {
824             glDisable( GL_FOG );
825             glDisable( GL_LIGHTING );
826             // cout << "drawing new clouds" << endl;
827
828             glEnable(GL_DEPTH_TEST);
829             glEnable(GL_BLEND);
830             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
831
832             /*
833             glEnable( GL_TEXTURE_2D );
834             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
835             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
836             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
837             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
838             */
839
840 #ifdef FG_USE_CLOUDS_3D
841             sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
842 #endif
843             glEnable( GL_FOG );
844             glEnable( GL_LIGHTING );
845             glEnable( GL_DEPTH_TEST );
846             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
847         }
848
849         if ( draw_otw && draw_clouds ) {
850             if ( multi_pass_clouds ) {
851                 // Disable depth buffer update, draw the clouds where the
852                 //  objects overwrite the already drawn clouds, by testing
853                 //  the stencil buffer against 1
854                 glDepthMask( GL_FALSE );
855                 glStencilFunc( GL_EQUAL, 1, 1 );
856                 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
857                 thesky->drawUpperClouds();
858                 thesky->drawLowerClouds();
859                 glDepthMask( GL_TRUE );
860                 glDisable( GL_STENCIL_TEST );
861             } else {
862                 glDepthMask( GL_FALSE );
863                 thesky->drawLowerClouds();
864                 glDepthMask( GL_TRUE );
865             }
866         }
867
868         if ( draw_otw ) {
869             FGTileMgr::set_tile_filter( false );
870             sgSetModelFilter( false );
871             globals->get_aircraft_model()->select( true );
872             globals->get_model_mgr()->draw();
873             globals->get_aircraft_model()->draw();
874             // If the view is internal, the previous line draw the 
875             //  cockpit with modified near/far clip planes and deselect
876             //  the aircraft in the global scenegraph
877             // Otherwise, it just enables the aircraft: The scenegraph
878             //  must be drawn again to see the plane.
879             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
880             FGTileMgr::set_tile_filter( true );
881             sgSetModelFilter( true );
882             globals->get_aircraft_model()->select( true );
883         }
884
885         // display HUD && Panel
886         glDisable( GL_FOG );
887         glDisable( GL_DEPTH_TEST );
888         // glDisable( GL_CULL_FACE );
889         // glDisable( GL_TEXTURE_2D );
890
891         // update the controls subsystem
892         globals->get_controls()->update(delta_time_sec);
893
894         hud_and_panel->apply();
895         fgCockpitUpdate();
896
897         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
898         // This only works properly if called before the panel call
899         if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
900             globals->get_ATC_display()->update(delta_time_sec);
901
902         // update the panel subsystem
903         if ( globals->get_current_panel() != NULL ) {
904             globals->get_current_panel()->update(delta_time_sec);
905         }
906         fgUpdate3DPanels();
907
908         // We can do translucent menus, so why not. :-)
909         menus->apply();
910         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
911         puDisplay();
912         // glDisable ( GL_BLEND ) ;
913
914         glEnable( GL_DEPTH_TEST );
915         glEnable( GL_FOG );
916
917         // Fade out the splash screen over the first three seconds.
918         double t = globals->get_sim_time_sec();
919         if ( t <= 1.0 ) {
920             fgSplashUpdate(0.0, 1.0);
921         } else if ( t <= 3.0) {
922             fgSplashUpdate(0.0, (3.0 - t) / 2.0);
923         }
924     }
925 }
926
927
928 // Update internal time dependent calculations (i.e. flight model)
929 // FIXME: this distinction is obsolete; all subsystems now get delta
930 // time on update.
931 void fgUpdateTimeDepCalcs() {
932     static bool inited = false;
933
934     static const SGPropertyNode *replay_master
935         = fgGetNode( "/sim/freeze/replay", true );
936     static SGPropertyNode *replay_time
937         = fgGetNode( "/sim/replay/time", true );
938     // static const SGPropertyNode *replay_end_time
939     //     = fgGetNode( "/sim/replay/end-time", true );
940
941     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
942
943     // Initialize the FDM here if it hasn't been and if we have a
944     // scenery elevation hit.
945
946     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
947     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
948
949     if ( !cur_fdm_state->get_inited() &&
950          globals->get_scenery()->get_cur_elev() > -9990 )
951     {
952         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
953         cur_fdm_state->init();
954         if ( cur_fdm_state->get_bound() ) {
955             cur_fdm_state->unbind();
956         }
957         cur_fdm_state->bind();
958     }
959
960     // conceptually, the following block could be done for each fdm
961     // instance ...
962     if ( cur_fdm_state->get_inited() ) {
963         // we have been inited, and  we are good to go ...
964
965         if ( !inited ) {
966             inited = true;
967         }
968
969         if ( ! replay_master->getBoolValue() ) {
970             cur_fdm_state->update( delta_time_sec );
971         } else {
972             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
973             r->replay( replay_time->getDoubleValue() );
974             replay_time->setDoubleValue( replay_time->getDoubleValue()
975                                          + ( delta_time_sec
976                                              * fgGetInt("/sim/speed-up") ) );
977         }
978     } else {
979         // do nothing, fdm isn't inited yet
980     }
981
982     globals->get_model_mgr()->update(delta_time_sec);
983     globals->get_aircraft_model()->update(delta_time_sec);
984
985     // update the view angle
986     globals->get_viewmgr()->update(delta_time_sec);
987
988     // Update solar system
989     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
990                                   globals->get_time_params()->getLst(),
991                                   cur_fdm_state->get_Latitude() );
992
993     // Update radio stack model
994     current_radiostack->update(delta_time_sec);
995 }
996
997
998 void fgInitTimeDepCalcs( void ) {
999     // noop for now
1000 }
1001
1002
1003 static const double alt_adjust_ft = 3.758099;
1004 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1005
1006
1007 // What should we do when we have nothing else to do?  Let's get ready
1008 // for the next move and update the display?
1009 static void fgMainLoop( void ) {
1010     int model_hz = fgGetInt("/sim/model-hz");
1011
1012     static const SGPropertyNode *longitude
1013         = fgGetNode("/position/longitude-deg");
1014     static const SGPropertyNode *latitude
1015         = fgGetNode("/position/latitude-deg");
1016     static const SGPropertyNode *altitude
1017         = fgGetNode("/position/altitude-ft");
1018     static const SGPropertyNode *clock_freeze
1019         = fgGetNode("/sim/freeze/clock", true);
1020     static const SGPropertyNode *cur_time_override
1021         = fgGetNode("/sim/time/cur-time-override", true);
1022     // static const SGPropertyNode *replay_master
1023     //     = fgGetNode("/sim/freeze/replay", true);
1024
1025     SGCloudLayer::enable_bump_mapping = fgGetBool("/sim/rendering/bump-mapping",true);
1026
1027     // Update the elapsed time.
1028     static bool first_time = true;
1029     if ( first_time ) {
1030         last_time_stamp.stamp();
1031         first_time = false;
1032     }
1033
1034     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1035     if ( throttle_hz > 0.0 ) {
1036         // simple frame rate throttle
1037         double dt = 1000000.0 / throttle_hz;
1038         current_time_stamp.stamp();
1039         while ( current_time_stamp - last_time_stamp < dt ) {
1040             current_time_stamp.stamp();
1041         }
1042     } else {
1043         // run as fast as the app will go
1044         current_time_stamp.stamp();
1045     }
1046
1047     real_delta_time_sec
1048         = double(current_time_stamp - last_time_stamp) / 1000000.0;
1049     if ( clock_freeze->getBoolValue() ) {
1050         delta_time_sec = 0;
1051     } else {
1052         delta_time_sec = real_delta_time_sec;
1053     }
1054     last_time_stamp = current_time_stamp;
1055     globals->inc_sim_time_sec( delta_time_sec );
1056     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1057
1058     // These are useful, especially for Nasal scripts.
1059     fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
1060     fgSetDouble("/sim/time/delta-sec", delta_time_sec);
1061
1062     static long remainder = 0;
1063     long elapsed;
1064 #ifdef FANCY_FRAME_COUNTER
1065     int i;
1066     double accum;
1067 #else
1068     static time_t last_time = 0;
1069     static int frames = 0;
1070 #endif // FANCY_FRAME_COUNTER
1071
1072     SGTime *t = globals->get_time_params();
1073
1074     globals->get_event_mgr()->update(delta_time_sec);
1075
1076     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1077     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1078
1079 #if defined( ENABLE_PLIB_JOYSTICK )
1080     // Read joystick and update control settings
1081     // if ( fgGetString("/sim/control-mode") == "joystick" )
1082     // {
1083     //    fgJoystickRead();
1084     // }
1085 #endif
1086
1087     // Fix elevation.  I'm just sticking this here for now, it should
1088     // probably move eventually
1089
1090     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
1091            scenery.get_cur_elev(),
1092            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1093            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1094
1095     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
1096            scenery.get_cur_elev(),
1097            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1098            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1099
1100     // cout << "Warp = " << globals->get_warp() << endl;
1101
1102     // update "time"
1103     static bool last_clock_freeze = false;
1104
1105     if ( clock_freeze->getBoolValue() ) {
1106         // clock freeze requested
1107         if ( cur_time_override->getLongValue() == 0 ) {
1108             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1109             globals->set_warp( 0 );
1110         }
1111     } else {
1112         // no clock freeze requested
1113         if ( last_clock_freeze == true ) {
1114             // clock just unfroze, let's set warp as the difference
1115             // between frozen time and current time so we don't get a
1116             // time jump (and corresponding sky object and lighting
1117             // jump.)
1118             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1119             fgSetLong( "/sim/time/cur-time-override", 0 );
1120         }
1121         if ( globals->get_warp_delta() != 0 ) {
1122             globals->inc_warp( globals->get_warp_delta() );
1123         }
1124     }
1125
1126     last_clock_freeze = clock_freeze->getBoolValue();
1127
1128     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1129                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1130                cur_time_override->getLongValue(),
1131                globals->get_warp() );
1132
1133     if (globals->get_warp_delta() != 0) {
1134         FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1135         l->update( 0.5 );
1136     }
1137
1138     // update magvar model
1139     globals->get_mag()->update( longitude->getDoubleValue()
1140                               * SGD_DEGREES_TO_RADIANS,
1141                             latitude->getDoubleValue()
1142                               * SGD_DEGREES_TO_RADIANS,
1143                             altitude->getDoubleValue() * SG_FEET_TO_METER,
1144                             globals->get_time_params()->getJD() );
1145
1146     // Get elapsed time (in usec) for this past frame
1147     elapsed = fgGetTimeInterval();
1148     SG_LOG( SG_ALL, SG_DEBUG, 
1149             "Elapsed time interval is = " << elapsed 
1150             << ", previous remainder is = " << remainder );
1151
1152     // Calculate frame rate average
1153 #ifdef FANCY_FRAME_COUNTER
1154     /* old fps calculation */
1155     if ( elapsed > 0 ) {
1156         double tmp;
1157         accum = 0.0;
1158         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1159             tmp = general.get_frame(i);
1160             accum += tmp;
1161             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1162             general.set_frame(i+1,tmp);
1163         }
1164         tmp = 1000000.0 / (float)elapsed;
1165         general.set_frame(0,tmp);
1166         // printf("frame[0] = %.2f\n", general.frames[0]);
1167         accum += tmp;
1168         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1169         // printf("ave = %.2f\n", general.frame_rate);
1170     }
1171 #else
1172     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1173         general.set_frame_rate( frames );
1174         fgSetInt("/sim/frame-rate", frames);
1175         SG_LOG( SG_ALL, SG_DEBUG, 
1176             "--> Frame rate is = " << general.get_frame_rate() );
1177         frames = 0;
1178     }
1179     last_time = t->get_cur_time();
1180     ++frames;
1181 #endif
1182
1183     // Run ATC subsystem
1184     if (fgGetBool("/sim/ATC/enabled"))
1185         globals->get_ATC_mgr()->update(delta_time_sec);
1186
1187     // Run the AI subsystem
1188     if (fgGetBool("/sim/ai-traffic/enabled"))
1189         globals->get_AI_mgr()->update(delta_time_sec);
1190
1191     // Run flight model
1192
1193     // Calculate model iterations needed for next frame
1194     elapsed += remainder;
1195
1196     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1197     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1198     SG_LOG( SG_ALL, SG_DEBUG, 
1199             "Model iterations needed = " << global_multi_loop
1200             << ", new remainder = " << remainder );
1201         
1202     // chop max interations to something reasonable if the sim was
1203     // delayed for an excesive amount of time
1204     if ( global_multi_loop > 2.0 * model_hz ) {
1205         global_multi_loop = (int)(2.0 * model_hz );
1206         remainder = 0;
1207     }
1208
1209     bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
1210
1211     // flight model
1212     if ( global_multi_loop > 0) {
1213         // first run the flight model each frame until it is intialized
1214         // then continue running each frame only after initial scenery load is complete.
1215         if (!cur_fdm_state->get_inited() || scenery_loaded) {
1216             fgUpdateTimeDepCalcs();
1217         }
1218     } else {
1219         SG_LOG( SG_ALL, SG_DEBUG, 
1220             "Elapsed time is zero ... we're zinging" );
1221     }
1222
1223     // Do any I/O channel work that might need to be done
1224     globals->get_io()->update( real_delta_time_sec );
1225
1226     // see if we need to load any deferred-load textures
1227     globals->get_matlib()->load_next_deferred();
1228
1229     // Run audio scheduler
1230 #ifdef ENABLE_AUDIO_SUPPORT
1231     if ( globals->get_soundmgr()->is_working() ) {
1232         globals->get_soundmgr()->update( delta_time_sec );
1233     }
1234 #endif
1235
1236     globals->get_subsystem_mgr()->update(delta_time_sec);
1237
1238     //
1239     // Tile Manager updates - see if we need to load any new scenery tiles.
1240     //   this code ties together the fdm, viewer and scenery classes...
1241     //   we may want to move this to it's own class at some point
1242     //
1243     double visibility_meters = fgGetDouble("/environment/visibility-m");
1244     FGViewer *current_view = globals->get_current_view();
1245
1246     // get the location data for the primary FDM (now hardcoded to ac model)...
1247     SGLocation *acmodel_loc = NULL;
1248     acmodel_loc = (SGLocation *)globals->
1249         get_aircraft_model()->get3DModel()->getSGLocation();
1250
1251     // update tile manager for FDM...
1252     // ...only if location is different than the current-view location
1253     // (to avoid duplicating effort)
1254     if( !fgGetBool("/sim/current-view/config/from-model") ) {
1255         if( acmodel_loc != NULL ) {
1256             globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
1257                                                      visibility_meters );
1258             globals->get_tile_mgr()->
1259                 update( acmodel_loc, visibility_meters,
1260                         acmodel_loc->
1261                         get_absolute_view_pos(globals->
1262                                               get_scenery()->get_center()) );
1263             // save results of update in SGLocation for fdm...
1264             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1265                 acmodel_loc->
1266                     set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1267                 fgSetDouble("/position/ground-elev-m",
1268                             globals->get_scenery()->get_cur_elev());
1269             }
1270             acmodel_loc->
1271                 set_tile_center( globals->get_scenery()->get_next_center() );
1272         }
1273     }
1274
1275     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1276                                              visibility_meters );
1277     // update tile manager for view...
1278     // IMPORTANT!!! the tilemgr update for view location _must_ be
1279     // done last after the FDM's until all of Flight Gear code
1280     // references the viewer's location for elevation instead of the
1281     // "scenery's" current elevation.
1282     SGLocation *view_location = globals->get_current_view()->getSGLocation();
1283     globals->get_tile_mgr()->update( view_location, visibility_meters,
1284                                      current_view->get_absolute_view_pos() );
1285     // save results of update in SGLocation for fdm...
1286     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1287         current_view->getSGLocation()->
1288             set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1289     }
1290     current_view->getSGLocation()->
1291         set_tile_center( globals->get_scenery()->get_next_center() );
1292
1293 #ifdef ENABLE_AUDIO_SUPPORT
1294     // Right now we make a simplifying assumption that the primary
1295     // aircraft is the source of all sounds and that all sounds are
1296     // positioned relative to the current view position.
1297
1298     static sgVec3 last_pos_offset;
1299
1300     // set positional offset for sources
1301     sgVec3 source_pos_offset;
1302     sgSubVec3( source_pos_offset,
1303                view_location->get_view_pos(), acmodel_loc->get_view_pos() );
1304     // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
1305     globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
1306
1307     // set the velocity
1308     sgVec3 source_vel;
1309     sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
1310     sgScaleVec3( source_vel, delta_time_sec );
1311     sgCopyVec3( last_pos_offset, source_pos_offset );
1312     // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
1313     globals->get_soundmgr()->set_source_vel_all( source_vel );
1314
1315     // Right now we make a simplifying assumption that the listener is
1316     // always positioned at the origin.
1317     sgVec3 listener_pos;
1318     sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
1319     // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
1320     globals->get_soundmgr()->set_listener_pos( listener_pos );
1321 #endif
1322
1323     // If fdm location is same as viewer's then we didn't do the
1324     // update for fdm location above so we need to save the viewer
1325     // results in the fdm SGLocation as well...
1326     if( fgGetBool("/sim/current-view/config/from-model") ) {
1327         if( acmodel_loc != 0 ) {
1328             if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1329                 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
1330                                              get_cur_elev() );
1331                 fgSetDouble("/position/ground-elev-m",
1332                             globals->get_scenery()->get_cur_elev());
1333             }
1334             acmodel_loc->set_tile_center( globals->get_scenery()->
1335                                           get_next_center() );
1336         }
1337     }
1338
1339     // END Tile Manager udpates
1340
1341     if (!scenery_loaded && globals->get_tile_mgr()->all_queues_empty() && cur_fdm_state->get_inited()) {
1342         fgSetBool("sim/sceneryloaded",true);
1343     }
1344
1345     if (fgGetBool("/sim/rendering/specular-highlight")) {
1346         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1347         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1348     } else {
1349         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1350         // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1351     }
1352
1353     fgRequestRedraw();
1354
1355     SG_LOG( SG_ALL, SG_DEBUG, "" );
1356 }
1357
1358
1359 // This is the top level master main function that is registered as
1360 // our idle funciton
1361
1362 // The first few passes take care of initialization things (a couple
1363 // per pass) and once everything has been initialized fgMainLoop from
1364 // then on.
1365
1366 static void fgIdleFunction ( void ) {
1367     // printf("idle state == %d\n", idle_state);
1368
1369     if ( idle_state == 0 ) {
1370         fgSetBool("sim/initialised", false);
1371
1372         // Initialize the splash screen right away
1373         if ( fgGetBool("/sim/startup/splash-screen") ) {
1374             fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1375         }
1376         
1377         idle_state++;
1378     } else if ( idle_state == 1 ) {
1379         // Initialize audio support
1380 #ifdef ENABLE_AUDIO_SUPPORT
1381
1382         // Start the intro music
1383         if ( fgGetBool("/sim/startup/intro-music") ) {
1384             SGPath mp3file( globals->get_fg_root() );
1385             mp3file.append( "Sounds/intro.mp3" );
1386
1387             SG_LOG( SG_GENERAL, SG_INFO, 
1388                 "Starting intro music: " << mp3file.str() );
1389
1390 #if defined( __CYGWIN__ )
1391             string command = "start /m `cygpath -w " + mp3file.str() + "`";
1392 #elif defined( WIN32 )
1393             string command = "start /m " + mp3file.str();
1394 #else
1395             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1396 #endif
1397
1398             system ( command.c_str() );
1399         }
1400 #endif
1401
1402         idle_state++;
1403     } else if ( idle_state == 2 ) {
1404         // These are a few miscellaneous things that aren't really
1405         // "subsystems" but still need to be initialized.
1406
1407 #ifdef USE_GLIDE
1408         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1409             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1410         }
1411 #endif
1412
1413         idle_state++;
1414     } else if ( idle_state == 3 ) {
1415         // This is the top level init routine which calls all the
1416         // other subsystem initialization routines.  If you are adding
1417         // a subsystem to flightgear, its initialization call should
1418         // located in this routine.
1419         if( !fgInitSubsystems()) {
1420             SG_LOG( SG_GENERAL, SG_ALERT,
1421                 "Subsystem initializations failed ..." );
1422             exit(-1);
1423         }
1424
1425         idle_state++;
1426     } else if ( idle_state == 4 ) {
1427         // Initialize the time offset (warp) after fgInitSubsystem
1428         // (which initializes the lighting interpolation tables.)
1429         fgInitTimeOffset();
1430
1431         // setup OpenGL view parameters
1432         fgInitVisuals();
1433
1434         // Read the list of available aircrafts
1435         fgReadAircraft();
1436
1437         idle_state++;
1438     } else if ( idle_state == 5 ) {
1439
1440         idle_state++;
1441     } else if ( idle_state == 6 ) {
1442         // sleep(1);
1443
1444         idle_state = 1000;
1445
1446         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1447         fgReshape( fgGetInt("/sim/startup/xsize"),
1448                fgGetInt("/sim/startup/ysize") );
1449
1450     } 
1451
1452     if ( idle_state == 1000 ) {
1453         // We've finished all our initialization steps, from now on we
1454         // run the main loop.
1455         fgSetBool("sim/initialised",true);
1456         fgSetBool("sim/sceneryloaded",false);
1457
1458         fgRegisterIdleHandler(fgMainLoop);
1459     } else {
1460         if ( fgGetBool("/sim/startup/splash-screen") ) {
1461             fgSplashUpdate(0.0, 1.0);
1462         }
1463     }
1464 }
1465
1466 // options.cxx needs to see this for toggle_panel()
1467 // Handle new window size or exposure
1468 void fgReshape( int width, int height ) {
1469     int view_h;
1470
1471     if ( (!fgGetBool("/sim/virtual-cockpit"))
1472          && fgPanelVisible() && idle_state == 1000 ) {
1473         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1474                              globals->get_current_panel()->getYOffset()) / 768.0);
1475     } else {
1476         view_h = height;
1477     }
1478
1479     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1480
1481     fgSetInt("/sim/startup/xsize", width);
1482     fgSetInt("/sim/startup/ysize", height);
1483     guiInitMouse(width, height);
1484
1485     // for all views
1486     FGViewMgr *viewmgr = globals->get_viewmgr();
1487     if (viewmgr) {
1488       for ( int i = 0; i < viewmgr->size(); ++i ) {
1489         viewmgr->get_view(i)->
1490           set_aspect_ratio((float)view_h / (float)width);
1491       }
1492
1493       ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1494                viewmgr->get_current_view()->get_v_fov() );
1495
1496 #ifdef FG_USE_CLOUDS_3D
1497       sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1498                viewmgr->get_current_view()->get_v_fov() );
1499 #endif
1500     }
1501
1502     fgHUDReshape();
1503
1504 }
1505
1506
1507 // do some clean up on exit.  Specifically we want to call alutExit()
1508 // which happens in the sound manager destructor.
1509 void fgExitCleanup() {
1510     fgSetMouseCursor(MOUSE_CURSOR_POINTER);
1511     delete globals;
1512 //    fgOSExit(0);
1513 }
1514
1515
1516 // Main top level initialization
1517 bool fgMainInit( int argc, char **argv ) {
1518
1519 #if defined( macintosh )
1520     freopen ("stdout.txt", "w", stdout );
1521     freopen ("stderr.txt", "w", stderr );
1522     argc = ccommand( &argv );
1523 #endif
1524
1525     // set default log levels
1526     sglog().setLogLevels( SG_ALL, SG_ALERT );
1527
1528     atexit(fgExitCleanup);
1529
1530     string version;
1531 #ifdef FLIGHTGEAR_VERSION
1532     version = FLIGHTGEAR_VERSION;
1533 #else
1534     version = "unknown version";
1535 #endif
1536     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1537             << version );
1538     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1539
1540     // Allocate global data structures.  This needs to happen before
1541     // we parse command line options
1542
1543     globals = new FGGlobals;
1544
1545     // seed the random number generater
1546     sg_srandom_time();
1547
1548     FGControls *controls = new FGControls;
1549     globals->set_controls( controls );
1550
1551     string_list *col = new string_list;
1552     globals->set_channel_options_list( col );
1553
1554     // Scan the config file(s) and command line options to see if
1555     // fg_root was specified (ignore all other options for now)
1556     fgInitFGRoot(argc, argv);
1557
1558     // Check for the correct base package version
1559     static char required_version[] = "0.9.5";
1560     string base_version = fgBasePackageVersion();
1561     if ( !(base_version == required_version) ) {
1562         // tell the operator how to use this application
1563
1564         SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1565         cerr << endl << "Base package check failed ... " \
1566              << "Found version " << base_version << " at: " \
1567              << globals->get_fg_root() << endl;
1568         cerr << "Please upgrade to version: " << required_version << endl;
1569 #ifdef _MSC_VER
1570         cerr << "Hit a key to continue..." << endl;
1571         cin.get();
1572 #endif
1573         exit(-1);
1574     }
1575
1576     // Initialize the Aircraft directory to "" (UIUC)
1577     aircraft_dir = "";
1578
1579     // Load the configuration parameters.  (Command line options
1580     // overrides config file options.  Config file options override
1581     // defaults.)
1582     if ( !fgInitConfig(argc, argv) ) {
1583         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1584         exit(-1);
1585     }
1586
1587     // Initialize the Window/Graphics environment.
1588 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1589     // Mac OS X command line ("non-bundle") applications call this
1590     // from main(), in bootstrap.cxx.  Andy doesn't know why, someone
1591     // feel free to add comments...
1592     fgOSInit(&argc, argv);
1593 #endif
1594
1595     fgRegisterWindowResizeHandler( fgReshape );
1596     fgRegisterIdleHandler( fgIdleFunction );
1597     fgRegisterDrawHandler( fgRenderFrame );
1598
1599 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1600     bool get_stencil_buffer = true;
1601 #else
1602     bool get_stencil_buffer = false;
1603 #endif
1604
1605     // Clouds3D requires an alpha channel
1606     // clouds may require stencil buffer
1607     fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1608                     fgGetInt("/sim/startup/ysize"),
1609                     fgGetInt("/sim/rendering/bits-per-pixel"),
1610                     fgGetBool("/sim/rendering/clouds3d"),
1611                     get_stencil_buffer,
1612                     fgGetBool("/sim/startup/fullscreen") );
1613
1614     // This seems to be the absolute earliest in the init sequence
1615     // that these calls will return valid info.  Too bad it's after
1616     // we've already created and sized out window. :-(
1617     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1618     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1619     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1620     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1621
1622     GLint tmp;
1623     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1624     general.set_glMaxTexSize( tmp );
1625     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1626
1627     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1628     general.set_glDepthBits( tmp );
1629     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1630
1631     // Initialize plib net interface
1632     netInit( &argc, argv );
1633
1634     // Initialize ssg (from plib).  Needs to come before we do any
1635     // other ssg stuff, but after opengl has been initialized.
1636     ssgInit();
1637
1638     // Initialize the user interface (we need to do this before
1639     // passing off control to the OS main loop and before
1640     // fgInitGeneral to get our fonts !!!
1641     guiInit();
1642
1643     // Read the list of available aircrafts
1644     fgReadAircraft();
1645
1646 #ifdef GL_EXT_texture_lod_bias
1647     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1648 #endif
1649
1650             // get the address of our OpenGL extensions
1651     if ( fgGetBool("/sim/rendering/distance-attenuation") )
1652     {
1653         if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1654             glPointParameterIsSupported = true;
1655             glPointParameterfPtr = (glPointParameterfProc)
1656                                    SGLookupFunction("glPointParameterfEXT");
1657             glPointParameterfvPtr = (glPointParameterfvProc)
1658                                     SGLookupFunction("glPointParameterfvEXT");
1659
1660         } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1661             glPointParameterIsSupported = true;
1662             glPointParameterfPtr = (glPointParameterfProc)
1663                                    SGLookupFunction("glPointParameterfARB");
1664             glPointParameterfvPtr = (glPointParameterfvProc)
1665                                     SGLookupFunction("glPointParameterfvARB");
1666         } else
1667             glPointParameterIsSupported = false;
1668    }
1669
1670     // based on the requested presets, calculate the true starting
1671     // lon, lat
1672     fgInitNav();
1673     fgInitPosition();
1674
1675     SGTime *t = fgInitTime();
1676     globals->set_time_params( t );
1677
1678     // Do some quick general initializations
1679     if( !fgInitGeneral()) {
1680         SG_LOG( SG_GENERAL, SG_ALERT, 
1681             "General initializations failed ..." );
1682         exit(-1);
1683     }
1684
1685     ////////////////////////////////////////////////////////////////////
1686     // Initialize the property-based built-in commands
1687     ////////////////////////////////////////////////////////////////////
1688     fgInitCommands();
1689
1690     ////////////////////////////////////////////////////////////////////
1691     // Initialize the material manager
1692     ////////////////////////////////////////////////////////////////////
1693     globals->set_matlib( new SGMaterialLib );
1694
1695     globals->set_model_lib(new SGModelLib);
1696
1697     ////////////////////////////////////////////////////////////////////
1698     // Initialize the TG scenery subsystem.
1699     ////////////////////////////////////////////////////////////////////
1700     globals->set_scenery( new FGScenery );
1701     globals->get_scenery()->init();
1702     globals->get_scenery()->bind();
1703     globals->set_tile_mgr( new FGTileMgr );
1704
1705     ////////////////////////////////////////////////////////////////////
1706     // Initialize the general model subsystem.
1707     ////////////////////////////////////////////////////////////////////
1708     globals->set_model_mgr(new FGModelMgr);
1709     globals->get_model_mgr()->init();
1710     globals->get_model_mgr()->bind();
1711
1712     ////////////////////////////////////////////////////////////////////
1713     // Initialize the 3D aircraft model subsystem (has a dependency on
1714     // the scenery subsystem.)
1715     ////////////////////////////////////////////////////////////////////
1716     globals->set_aircraft_model(new FGAircraftModel);
1717     globals->get_aircraft_model()->init();
1718     globals->get_aircraft_model()->bind();
1719
1720     ////////////////////////////////////////////////////////////////////
1721     // Initialize the view manager subsystem.
1722     ////////////////////////////////////////////////////////////////////
1723     FGViewMgr *viewmgr = new FGViewMgr;
1724     globals->set_viewmgr( viewmgr );
1725     viewmgr->init();
1726     viewmgr->bind();
1727
1728
1729     // Initialize the sky
1730     SGPath ephem_data_path( globals->get_fg_root() );
1731     ephem_data_path.append( "Astro" );
1732     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1733     ephem->update( globals->get_time_params()->getMjd(),
1734                    globals->get_time_params()->getLst(),
1735                    0.0 );
1736     globals->set_ephem( ephem );
1737
1738     // TODO: move to environment mgr
1739     thesky = new SGSky;
1740     SGPath texture_path(globals->get_fg_root());
1741     texture_path.append("Textures");
1742     texture_path.append("Sky");
1743     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1744         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1745         thesky->add_cloud_layer(layer);
1746     }
1747
1748     SGPath sky_tex_path( globals->get_fg_root() );
1749     sky_tex_path.append( "Textures" );
1750     sky_tex_path.append( "Sky" );
1751     thesky->texture_path( sky_tex_path.str() );
1752
1753     // The sun and moon diameters are scaled down numbers of the
1754     // actual diameters. This was needed to fit bot the sun and the
1755     // moon within the distance to the far clip plane.
1756     // Moon diameter:    3,476 kilometers
1757     // Sun diameter: 1,390,000 kilometers
1758     thesky->build( 80000.0, 80000.0,
1759                    463.3, 361.8,
1760                    globals->get_ephem()->getNumPlanets(), 
1761                    globals->get_ephem()->getPlanets(),
1762                    globals->get_ephem()->getNumStars(),
1763                    globals->get_ephem()->getStars() );
1764
1765     // Initialize MagVar model
1766     SGMagVar *magvar = new SGMagVar();
1767     globals->set_mag( magvar );
1768
1769
1770                                 // kludge to initialize mag compass
1771                                 // (should only be done for in-flight
1772                                 // startup)
1773     // update magvar model
1774     globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1775                                 * SGD_DEGREES_TO_RADIANS,
1776                                 fgGetDouble("/position/latitude-deg")
1777                                 * SGD_DEGREES_TO_RADIANS,
1778                                 fgGetDouble("/position/altitude-ft")
1779                                 * SG_FEET_TO_METER,
1780                                 globals->get_time_params()->getJD() );
1781     double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1782     fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1783
1784     // airport = new ssgBranch;
1785     // airport->setName( "Airport Lighting" );
1786     // lighting->addKid( airport );
1787
1788     // build our custom render states
1789     fgBuildRenderStates();
1790
1791     try {
1792         // pass control off to the master event handler
1793         fgOSMainLoop();
1794     } catch (...) {
1795         SG_LOG( SG_ALL, SG_ALERT,
1796             "Unknown exception in the main loop. Aborting..." );
1797     }
1798
1799     // we never actually get here ... but to avoid compiler warnings,
1800     // etc.
1801     return false;
1802 }
1803
1804
1805 // end of main.cxx