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