]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Frederic Bouvier:
[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/pu.h>
46 #include <plib/netSocket.h>
47
48 #include <simgear/screen/extensions.hxx>
49 #include <simgear/scene/material/matlib.hxx>
50 #include <simgear/props/props.hxx>
51 #include <simgear/scene/sky/sky.hxx>
52 #include <simgear/timing/sg_time.hxx>
53 #include <simgear/scene/model/animation.hxx>
54 #include <simgear/ephemeris/ephemeris.hxx>
55 #include <simgear/scene/model/placement.hxx>
56 #include <simgear/math/sg_random.h>
57 #include <simgear/route/route.hxx>
58 #include <simgear/scene/model/modellib.hxx>
59
60 #ifdef FG_USE_CLOUDS_3D
61 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
62 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
63 #endif
64
65 #include <Include/general.hxx>
66 #include <Scenery/tileentry.hxx>
67 #include <Time/FGEventMgr.hxx>
68 #include <Time/light.hxx>
69 #include <Time/light.hxx>
70 #include <Aircraft/aircraft.hxx>
71 #include <Cockpit/panel.hxx>
72 #include <Cockpit/cockpit.hxx>
73 #include <Cockpit/radiostack.hxx>
74 #include <Cockpit/hud.hxx>
75 #include <Model/panelnode.hxx>
76 #include <Model/modelmgr.hxx>
77 #include <Model/acmodel.hxx>
78 #include <Scenery/scenery.hxx>
79 #include <Scenery/tilemgr.hxx>
80 #include <FDM/flight.hxx>
81 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
82 #include <FDM/ADA.hxx>
83 #include <ATC/ATCdisplay.hxx>
84 #include <ATC/ATCmgr.hxx>
85 #include <ATC/AIMgr.hxx>
86 #include <Autopilot/newauto.hxx>
87 #include <Replay/replay.hxx>
88 #include <Time/tmp.hxx>
89 #include <Time/fg_timer.hxx>
90 #include <Environment/environment_mgr.hxx>
91
92 #ifdef FG_NETWORK_OLK
93 #include <NetworkOLK/network.h>
94 #endif
95
96 #ifdef FG_MPLAYER_AS
97 #include <MultiPlayer/multiplaytxmgr.hxx>
98 #include <MultiPlayer/multiplayrxmgr.hxx>
99 #endif
100
101 #include "splash.hxx"
102 #include "fg_commands.hxx"
103 #include "fg_io.hxx"
104 #include "main.hxx"
105
106 float default_attenuation[3] = {1.0, 0.0, 0.0};
107 ssgSelector *ship_sel=NULL;
108 // upto 32 instances of a same object can be loaded.
109 ssgTransform *ship_pos[32];
110 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
111 int objc=0;
112 ssgSelector *lightpoints_brightness = new ssgSelector;
113 ssgTransform *lightpoints_transform = new ssgTransform;
114 FGTileEntry *dummy_tile;
115 sgVec3 rway_ols;
116 // ADA
117 // Clip plane settings...
118 float scene_nearplane = 0.5f;
119 float scene_farplane = 120000.0f;
120
121 static double delta_time_sec = 0.0;
122
123 glPointParameterfProc glPointParameterfPtr = 0;
124 glPointParameterfvProc glPointParameterfvPtr = 0;
125 bool glPointParameterIsSupported = false;
126
127
128 #ifdef FG_WEATHERCM
129 #  include <WeatherCM/FGLocalWeatherDatabase.h>
130 #endif
131
132 #ifdef macintosh
133 #  include <console.h>          // -dw- for command line dialog
134 #endif
135
136 FGEventMgr global_events;
137
138 // This is a record containing a bit of global housekeeping information
139 FGGeneral general;
140
141 // Specify our current idle function state.  This is used to run all
142 // our initializations out of the glutIdleLoop() so that we can get a
143 // splash screen up and running right away.
144 static int idle_state = 0;
145 static long global_multi_loop;
146
147 // fog constants.  I'm a little nervous about putting actual code out
148 // here but it seems to work (?)
149 static const double m_log01 = -log( 0.01 );
150 static const double sqrt_m_log01 = sqrt( m_log01 );
151 static GLfloat fog_exp_density;
152 static GLfloat fog_exp2_density;
153 static GLfloat rwy_exp2_punch_through;
154 static GLfloat taxi_exp2_punch_through;
155 static GLfloat ground_exp2_punch_through;
156
157 #ifdef FG_NETWORK_OLK
158 ssgSelector *fgd_sel = NULL;
159 ssgTransform *fgd_pos = NULL;
160 #endif
161
162 // Sky structures
163 SGSky *thesky;
164
165 #ifdef FG_USE_CLOUDS_3D
166   SkySceneLoader *sgClouds3d;
167   bool _bcloud_orig = true;
168 #endif
169
170 // hack
171 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
172 {
173   {  1.0f,  0.0f,  0.0f,  0.0f },
174   {  0.0f,  0.0f, -1.0f,  0.0f },
175   {  0.0f,  1.0f,  0.0f,  0.0f },
176   {  0.0f,  0.0f,  0.0f,  1.0f }
177 };
178
179 // The following defines flightgear options. Because glutlib will also
180 // want to parse its own options, those options must not be included here
181 // or they will get parsed by the main program option parser. Hence case
182 // is significant for any option added that might be in conflict with
183 // glutlib's parser.
184 //
185 // glutlib parses for:
186 //    -display
187 //    -direct   (invalid in Win32)
188 //    -geometry
189 //    -gldebug
190 //    -iconized
191 //    -indirect (invalid in Win32)
192 //    -synce
193 //
194 // Note that glutlib depends upon strings while this program's
195 // option parser wants only initial characters followed by numbers
196 // or pathnames.
197 //
198
199
200 ssgSimpleState *cloud3d_imposter_state;
201 ssgSimpleState *default_state;
202 ssgSimpleState *hud_and_panel;
203 ssgSimpleState *menus;
204
205 SGTimeStamp last_time_stamp;
206 SGTimeStamp current_time_stamp;
207
208
209 void fgBuildRenderStates( void ) {
210     default_state = new ssgSimpleState;
211     default_state->ref();
212     default_state->disable( GL_TEXTURE_2D );
213     default_state->enable( GL_CULL_FACE );
214     default_state->enable( GL_COLOR_MATERIAL );
215     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
216     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
217     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
218     default_state->disable( GL_BLEND );
219     default_state->disable( GL_ALPHA_TEST );
220     default_state->disable( GL_LIGHTING );
221
222     cloud3d_imposter_state = new ssgSimpleState;
223     cloud3d_imposter_state->ref();
224     cloud3d_imposter_state->enable( GL_TEXTURE_2D );
225     cloud3d_imposter_state->enable( GL_CULL_FACE );
226     cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
227     cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
228     cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
229     cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
230     cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
231     cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
232     cloud3d_imposter_state->enable( GL_BLEND );
233     cloud3d_imposter_state->enable( GL_ALPHA_TEST );
234     cloud3d_imposter_state->disable( GL_LIGHTING );
235
236     hud_and_panel = new ssgSimpleState;
237     hud_and_panel->ref();
238     hud_and_panel->disable( GL_CULL_FACE );
239     hud_and_panel->disable( GL_TEXTURE_2D );
240     hud_and_panel->disable( GL_LIGHTING );
241     hud_and_panel->enable( GL_BLEND );
242
243     menus = new ssgSimpleState;
244     menus->ref();
245     menus->disable( GL_CULL_FACE );
246     menus->disable( GL_TEXTURE_2D );
247     menus->enable( GL_BLEND );
248 }
249
250
251 // fgInitVisuals() -- Initialize various GL/view parameters
252 void fgInitVisuals( void ) {
253     fgLIGHT *l;
254
255     l = &cur_light_params;
256
257 #ifndef GLUT_WRONG_VERSION
258     // Go full screen if requested ...
259     if ( fgGetBool("/sim/startup/fullscreen") ) {
260         glutFullScreen();
261     }
262 #endif
263
264     // If enabled, normal vectors specified with glNormal are scaled
265     // to unit length after transformation.  Enabling this has
266     // performance implications.  See the docs for glNormal.
267     // glEnable( GL_NORMALIZE );
268
269     glEnable( GL_LIGHTING );
270     glEnable( GL_LIGHT0 );
271     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
272
273     sgVec3 sunpos;
274     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
275     ssgGetLight( 0 ) -> setPosition( sunpos );
276
277     glFogi (GL_FOG_MODE, GL_EXP2);
278     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
279          (!fgGetBool("/sim/rendering/shading"))) {
280         // if fastest fog requested, or if flat shading force fastest
281         glHint ( GL_FOG_HINT, GL_FASTEST );
282     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
283         glHint ( GL_FOG_HINT, GL_NICEST );
284     }
285     if ( fgGetBool("/sim/rendering/wireframe") ) {
286         // draw wire frame
287         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
288     }
289
290     // This is the default anyways, but it can't hurt
291     glFrontFace ( GL_CCW );
292
293     // Just testing ...
294     // glEnable(GL_POINT_SMOOTH);
295     // glEnable(GL_LINE_SMOOTH);
296     // glEnable(GL_POLYGON_SMOOTH);      
297 }
298
299
300 // For HiRes screen Dumps using Brian Pauls TR Library
301 void trRenderFrame( void ) {
302
303     if ( fgPanelVisible() ) {
304         GLfloat height = fgGetInt("/sim/startup/ysize");
305         GLfloat view_h =
306             (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
307             * (height / 768.0) + 1;
308         glTranslatef( 0.0, view_h, 0.0 );
309     }
310
311     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
312     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
313
314     fgLIGHT *l = &cur_light_params;
315
316     glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
317                  l->adj_fog_color[2], l->adj_fog_color[3]);
318
319     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
320
321     // set the opengl state to known default values
322     default_state->force();
323
324     glEnable( GL_FOG );
325     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
326     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
327     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color );
328
329     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
330     // we only update GL_AMBIENT for our lights we will never get
331     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
332     // explicitely to black.
333     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
334     glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
335
336     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
337
338     // texture parameters
339     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
340     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
341
342     // we need a white diffuse light for the phase of the moon
343     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
344     thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
345
346     // draw the ssg scene
347     // return to the desired diffuse color
348     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
349     glEnable( GL_DEPTH_TEST );
350     ssgSetNearFar( scene_nearplane, scene_farplane );
351     ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
352
353     // draw the lights
354     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
355     ssgSetNearFar( scene_nearplane, scene_farplane );
356     ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
357
358     ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
359
360     if (fgGetBool("/environment/clouds/status"))
361         thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
362
363     globals->get_model_mgr()->draw();
364     globals->get_aircraft_model()->draw();
365 }
366
367
368 // Update all Visuals (redraws anything graphics related)
369 void fgRenderFrame() {
370     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
371     bool skyblend = fgGetBool("/sim/rendering/skyblend");
372     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
373     bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
374
375     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
376     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
377
378     // Process/manage pending events
379     global_events.update( delta_time_sec );
380
381     // static const SGPropertyNode *longitude
382     //     = fgGetNode("/position/longitude-deg");
383     // static const SGPropertyNode *latitude
384     //     = fgGetNode("/position/latitude-deg");
385     // static const SGPropertyNode *altitude
386     //     = fgGetNode("/position/altitude-ft");
387     static const SGPropertyNode *groundlevel_nearplane
388         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
389
390     // Update the default (kludged) properties.
391     fgUpdateProps();
392
393     FGViewer *current__view = globals->get_current_view();
394
395     fgLIGHT *l = &cur_light_params;
396     static double last_visibility = -9999;
397
398     // update fog params
399     double actual_visibility;
400     if (fgGetBool("/environment/clouds/status"))
401         actual_visibility = thesky->get_visibility();
402     else
403         actual_visibility = fgGetDouble("/environment/visibility-m");
404     if ( actual_visibility != last_visibility ) {
405         last_visibility = actual_visibility;
406
407         fog_exp_density = m_log01 / actual_visibility;
408         fog_exp2_density = sqrt_m_log01 / actual_visibility;
409         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
410         if ( actual_visibility < 8000 ) {
411             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
412             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
413         } else {
414             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
415             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
416         }
417     }
418
419     // double angle;
420     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
421     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
422     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
423     // GLfloat mat_shininess[] = { 10.0 };
424     GLbitfield clear_mask;
425
426     if ( idle_state != 1000 ) {
427         // still initializing, draw the splash screen
428         if ( fgGetBool("/sim/startup/splash-screen") ) {
429             fgSplashUpdate(0.0, 1.0);
430         }
431         // Keep resetting sim time while the sim is initializing
432         globals->set_sim_time_sec( 0.0 );
433         SGAnimation::set_sim_time_sec( 0.0 );
434     } else {
435         // idle_state is now 1000 meaning we've finished all our
436         // initializations and are running the main loop, so this will
437         // now work without seg faulting the system.
438
439         // calculate our current position in cartesian space
440         globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
441
442         // update view port
443         fgReshape( fgGetInt("/sim/startup/xsize"),
444                    fgGetInt("/sim/startup/ysize") );
445
446         if ( fgGetBool("/sim/rendering/clouds3d") ) {
447             glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
448             cloud3d_imposter_state->force();
449             glDisable( GL_FOG );
450             glColor4f( 1.0, 1.0, 1.0, 1.0 );
451             glEnable(GL_DEPTH_TEST);
452             glEnable(GL_BLEND);
453             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
454
455 #ifdef FG_USE_CLOUDS_3D
456             if ( _bcloud_orig ) {
457                 Point3D c = globals->get_scenery()->get_center();
458                 sgClouds3d->Set_Cloud_Orig( &c );
459                 _bcloud_orig = false;
460             }
461             sgClouds3d->Update( current__view->get_absolute_view_pos() );
462 #endif
463             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
464             glDisable(GL_DEPTH_TEST);
465         }
466
467         clear_mask = GL_DEPTH_BUFFER_BIT;
468         if ( fgGetBool("/sim/rendering/wireframe") ) {
469             clear_mask |= GL_COLOR_BUFFER_BIT;
470         }
471
472         if ( skyblend ) {
473             if ( fgGetBool("/sim/rendering/textures") ) {
474             // glClearColor(black[0], black[1], black[2], black[3]);
475             glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
476                          l->adj_fog_color[2], l->adj_fog_color[3]);
477             clear_mask |= GL_COLOR_BUFFER_BIT;
478             }
479         } else {
480             glClearColor(l->sky_color[0], l->sky_color[1],
481                      l->sky_color[2], l->sky_color[3]);
482             clear_mask |= GL_COLOR_BUFFER_BIT;
483         }
484         glClear( clear_mask );
485
486         // Tell GL we are switching to model view parameters
487
488         // I really should create a derived ssg node or use a call
489         // back or something so that I can draw the sky within the
490         // ssgCullAndDraw() function, but for now I just mimic what
491         // ssg does to set up the model view matrix
492         glMatrixMode(GL_MODELVIEW);
493         glLoadIdentity();
494         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
495
496         // set the opengl state to known default values
497         default_state->force();
498
499         // update fog params if visibility has changed
500         double visibility_meters = fgGetDouble("/environment/visibility-m");
501         thesky->set_visibility(visibility_meters);
502
503         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
504                             ( global_multi_loop * fgGetInt("/sim/speed-up") )
505                             / (double)fgGetInt("/sim/model-hz") );
506
507         // Set correct opengl fog density
508         glFogf (GL_FOG_DENSITY, fog_exp2_density);
509
510         // update the sky dome
511         if ( skyblend ) {
512             /*
513              SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
514              << cur_light_params.sky_color[0] << " "
515              << cur_light_params.sky_color[1] << " "
516              << cur_light_params.sky_color[2] << " "
517              << cur_light_params.sky_color[3] );
518             SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
519              << cur_light_params.fog_color[0] << " "
520              << cur_light_params.fog_color[1] << " "
521              << cur_light_params.fog_color[2] << " "
522              << cur_light_params.fog_color[3] ); 
523             SG_LOG( SG_GENERAL, SG_BULK,
524                     "    sun_angle = " << cur_light_params.sun_angle
525              << "    moon_angle = " << cur_light_params.moon_angle );
526             */
527
528             static SGSkyColor scolor;
529
530             scolor.sky_color   = cur_light_params.sky_color;
531             scolor.fog_color   = cur_light_params.adj_fog_color;
532             scolor.cloud_color = cur_light_params.cloud_color;
533             scolor.sun_angle   = cur_light_params.sun_angle;
534             scolor.moon_angle  = cur_light_params.moon_angle;
535             scolor.nplanets    = globals->get_ephem()->getNumPlanets();
536             scolor.nstars      = globals->get_ephem()->getNumStars();
537             scolor.planet_data = globals->get_ephem()->getPlanets();
538             scolor.star_data   = globals->get_ephem()->getStars();
539
540             thesky->repaint( scolor );
541
542             /*
543             SG_LOG( SG_GENERAL, SG_BULK,
544                     "thesky->reposition( view_pos = " << view_pos[0] << " "
545              << view_pos[1] << " " << view_pos[2] );
546             SG_LOG( SG_GENERAL, SG_BULK,
547                     "    zero_elev = " << zero_elev[0] << " "
548              << zero_elev[1] << " " << zero_elev[2]
549              << " lon = " << cur_fdm_state->get_Longitude()
550              << " lat = " << cur_fdm_state->get_Latitude() );
551             SG_LOG( SG_GENERAL, SG_BULK,
552                     "    sun_rot = " << cur_light_params.sun_rotation
553              << " gst = " << SGTime::cur_time_params->getGst() );
554             SG_LOG( SG_GENERAL, SG_BULK,
555                  "    sun ra = " << globals->get_ephem()->getSunRightAscension()
556               << " sun dec = " << globals->get_ephem()->getSunDeclination()
557               << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
558               << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
559             */
560
561             // The sun and moon distances are scaled down versions
562             // of the actual distance to get both the moon and the sun
563             // within the range of the far clip plane.
564             // Moon distance:    384,467 kilometers
565             // Sun distance: 150,000,000 kilometers
566             double sun_horiz_eff, moon_horiz_eff;
567             if (fgGetBool("/sim/rendering/horizon-effect")) {
568             sun_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.sun_angle*2)/2,0.33)/3;
569             moon_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.moon_angle*2)/2,0.33)/3;
570             } else {
571                sun_horiz_eff = moon_horiz_eff = 1.0;
572             }
573
574             static SGSkyState sstate;
575
576             sstate.view_pos  = current__view->get_view_pos();
577             sstate.zero_elev = current__view->get_zero_elev();
578             sstate.view_up   = current__view->get_world_up();
579             sstate.lon       = current__view->getLongitude_deg()
580                                 * SGD_DEGREES_TO_RADIANS;
581             sstate.lat       = current__view->getLatitude_deg()
582                                 * SGD_DEGREES_TO_RADIANS;
583             sstate.alt       = current__view->getAltitudeASL_ft()
584                                 * SG_FEET_TO_METER;
585             sstate.spin      = cur_light_params.sun_rotation;
586             sstate.gst       = globals->get_time_params()->getGst();
587             sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
588             sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
589             sstate.sun_dist  = 50000.0 * sun_horiz_eff;
590             sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
591             sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
592             sstate.moon_dist = 40000.0 * moon_horiz_eff;
593
594             thesky->reposition( sstate, delta_time_sec );
595         }
596
597         glEnable( GL_DEPTH_TEST );
598         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
599             glEnable( GL_FOG );
600             glFogi( GL_FOG_MODE, GL_EXP2 );
601             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
602         }
603
604         // set sun/lighting parameters
605         ssgGetLight( 0 ) -> setPosition( l->sun_vec );
606
607         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
608         // we only update GL_AMBIENT for our lights we will never get
609         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
610         // explicitely to black.
611         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
612
613         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
614         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
615         ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular );
616
617         // texture parameters
618         // glEnable( GL_TEXTURE_2D );
619         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
620         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
621
622         // glMatrixMode( GL_PROJECTION );
623         // glLoadIdentity();
624         ssgSetFOV( current__view->get_h_fov(),
625                    current__view->get_v_fov() );
626
627         double agl =
628             current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
629             - globals->get_scenery()->get_cur_elev();
630
631         if ( agl > 10.0 ) {
632             scene_nearplane = 10.0f;
633             scene_farplane = 120000.0f;
634         } else {
635             scene_nearplane = groundlevel_nearplane->getDoubleValue();
636             scene_farplane = 120000.0f;
637         }
638
639         ssgSetNearFar( scene_nearplane, scene_farplane );
640
641         // $$$ begin - added VS Renganthan 17 Oct 2K
642         if(objc)
643           fgUpdateDCS();
644         // $$$ end - added VS Renganthan 17 Oct 2K
645
646 # ifdef FG_NETWORK_OLK
647         if ( fgGetBool("/sim/networking/network-olk") ) {
648             sgCoord fgdpos;
649             other = head->next;             /* put listpointer to start  */
650             while ( other != tail) {        /* display all except myself */
651             if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
652                 other->fgd_sel->select(1);
653                 sgSetCoord( &fgdpos, other->sgFGD_COORD );
654                 other->fgd_pos->setTransform( &fgdpos );
655             }
656             other = other->next;
657             }
658
659             // fgd_sel->select(1);
660             // sgCopyMat4( sgTUX, current_view.sgVIEW);
661             // sgCoord fgdpos;
662             // sgSetCoord( &fgdpos, sgFGD_VIEW );
663             // fgd_pos->setTransform( &fgdpos);
664         }
665 # endif
666
667 #ifdef FG_MPLAYER_AS
668         // Update any multiplayer models
669         globals->get_multiplayer_rx_mgr()->Update();
670 #endif
671
672         if ( draw_otw && skyblend )
673         {
674             // draw the sky backdrop
675
676             // we need a white diffuse light for the phase of the moon
677             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
678
679             thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
680
681             // return to the desired diffuse color
682             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
683
684             // FIXME: This should not be needed, but at this time (08/15/2003)
685             //        certain NVidia drivers don't seem to implement
686             //        fgPushAttrib(FG_FOG_BIT) properly. The result is that
687             //        there is not fog when looking at the sun.
688             glFogf ( GL_FOG_DENSITY, fog_exp2_density );
689         }
690
691         // draw the ssg scene
692         glEnable( GL_DEPTH_TEST );
693
694         ssgSetNearFar( scene_nearplane, scene_farplane );
695
696         if ( fgGetBool("/sim/rendering/wireframe") ) {
697             // draw wire frame
698             glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
699         }
700         if ( draw_otw ) {
701             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
702         }
703
704         // This is a bit kludgy.  Every 200 frames, do an extra
705         // traversal of the scene graph without drawing anything, but
706         // with the field-of-view set to 360x360 degrees.  This
707         // ensures that out-of-range random objects that are not in
708         // the current view frustum will still be freed properly.
709         static int counter = 0;
710         counter++;
711         if (counter == 200) {
712           sgFrustum f;
713           f.setFOV(360, 360);
714                             // No need to put the near plane too close;
715                             // this way, at least the aircraft can be
716                             // culled.
717           f.setNearFar(1000, 1000000);
718           sgMat4 m;
719           ssgGetModelviewMatrix(m);
720           globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
721           counter = 0;
722         }
723
724         // change state for lighting here
725
726         // draw runway lighting
727         glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
728         ssgSetNearFar( scene_nearplane, scene_farplane );
729
730         if ( enhanced_lighting ) {
731
732             // Enable states for drawing points with GL_extension
733             glEnable(GL_POINT_SMOOTH);
734
735             if ( distance_attenuation && glPointParameterIsSupported )
736             {
737                 // Enable states for drawing points with GL_extension
738                 glEnable(GL_POINT_SMOOTH);
739
740                 float quadratic[3] = {1.0, 0.001, 0.0000001};
741                 // makes the points fade as they move away
742                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
743                 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
744             }
745
746             glPointSize(4.0);
747
748             // blending function for runway lights
749             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
750         }
751
752         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
753         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
754         glEnable(GL_TEXTURE_GEN_S);
755         glEnable(GL_TEXTURE_GEN_T);
756         glPolygonMode(GL_FRONT, GL_POINT);
757
758         // draw runway lighting
759         if ( draw_otw ) {
760             ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
761         }
762
763         // change punch through and then draw taxi lighting
764         glFogf ( GL_FOG_DENSITY, fog_exp2_density );
765         // sgVec3 taxi_fog;
766         // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
767         // glFogfv ( GL_FOG_COLOR, taxi_fog );
768         if ( draw_otw ) {
769             ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
770         }
771
772         // clean up lighting
773         glPolygonMode(GL_FRONT, GL_FILL);
774         glDisable(GL_TEXTURE_GEN_S);
775         glDisable(GL_TEXTURE_GEN_T);
776
777         //static int _frame_count = 0;
778         //if (_frame_count % 30 == 0) {
779         //  printf("SSG: %s\n", ssgShowStats());
780         //}
781         //else {
782         //  ssgShowStats();
783         //}
784         //_frame_count++;
785
786
787         if ( enhanced_lighting ) {
788             if ( distance_attenuation && glPointParameterIsSupported )
789             {
790                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
791                                       default_attenuation);
792             }
793
794             glPointSize(1.0);
795             glDisable(GL_POINT_SMOOTH);
796         }
797
798         // draw ground lighting
799         glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
800         if ( draw_otw ) {
801             ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
802         }
803
804         if ( skyblend ) {
805             // draw the sky cloud layers
806             if ( draw_otw && fgGetBool("/environment/clouds/status") )
807             {
808                 thesky->postDraw( cur_fdm_state->get_Altitude()
809                                   * SG_FEET_TO_METER );
810             }
811         }
812
813         if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") )
814         {
815             glDisable( GL_FOG );
816             glDisable( GL_LIGHTING );
817             // cout << "drawing new clouds" << endl;
818
819             glEnable(GL_DEPTH_TEST);
820             glEnable(GL_BLEND);
821             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
822
823             /*
824             glEnable( GL_TEXTURE_2D );
825             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
826             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
827             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
828             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
829             */
830
831 #ifdef FG_USE_CLOUDS_3D
832             sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
833 #endif
834             glEnable( GL_FOG );
835             glEnable( GL_LIGHTING );
836             glEnable( GL_DEPTH_TEST );
837             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
838         }
839
840         if ( draw_otw ) {
841             globals->get_model_mgr()->draw();
842             globals->get_aircraft_model()->draw();
843         }
844
845         // display HUD && Panel
846         glDisable( GL_FOG );
847         glDisable( GL_DEPTH_TEST );
848         // glDisable( GL_CULL_FACE );
849         // glDisable( GL_TEXTURE_2D );
850
851         // update the controls subsystem
852         globals->get_controls()->update(delta_time_sec);
853
854         hud_and_panel->apply();
855         fgCockpitUpdate();
856
857         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
858         // This only works properly if called before the panel call
859         if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
860             globals->get_ATC_display()->update(delta_time_sec);
861
862         // update the panel subsystem
863         if ( globals->get_current_panel() != NULL ) {
864             globals->get_current_panel()->update(delta_time_sec);
865         }
866         fgUpdate3DPanels();
867
868         // We can do translucent menus, so why not. :-)
869         menus->apply();
870         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
871         puDisplay();
872         // glDisable ( GL_BLEND ) ;
873
874         glEnable( GL_DEPTH_TEST );
875         glEnable( GL_FOG );
876
877         // Fade out the splash screen over the first three seconds.
878         double t = globals->get_sim_time_sec();
879         if ( t <= 1.0 ) {
880             fgSplashUpdate(0.0, 1.0);
881         } else if ( t <= 3.0) {
882             fgSplashUpdate(0.0, (3.0 - t) / 2.0);
883         }
884     }
885
886     glutSwapBuffers();
887 }
888
889
890 // Update internal time dependent calculations (i.e. flight model)
891 // FIXME: this distinction is obsolete; all subsystems now get delta
892 // time on update.
893 void fgUpdateTimeDepCalcs() {
894     static bool inited = false;
895
896     static const SGPropertyNode *replay_master
897         = fgGetNode( "/sim/freeze/replay", true );
898     static SGPropertyNode *replay_time
899         = fgGetNode( "/sim/replay/time", true );
900     static const SGPropertyNode *replay_end_time
901         = fgGetNode( "/sim/replay/end-time", true );
902
903     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
904
905     fgLIGHT *l = &cur_light_params;
906
907     // Initialize the FDM here if it hasn't been and if we have a
908     // scenery elevation hit.
909
910     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
911     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
912
913     if ( !cur_fdm_state->get_inited() &&
914          globals->get_scenery()->get_cur_elev() > -9990 )
915     {
916         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
917         cur_fdm_state->init();
918         if ( cur_fdm_state->get_bound() ) {
919             cur_fdm_state->unbind();
920         }
921         cur_fdm_state->bind();
922     }
923
924     // conceptually, the following block could be done for each fdm
925     // instance ...
926     if ( cur_fdm_state->get_inited() ) {
927         // we have been inited, and  we are good to go ...
928
929         if ( !inited ) {
930             inited = true;
931         }
932
933         if ( ! replay_master->getBoolValue() ) {
934             globals->get_autopilot()->update( delta_time_sec );
935             cur_fdm_state->update( delta_time_sec );
936         } else {
937             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
938             r->replay( replay_time->getDoubleValue() );
939             replay_time->setDoubleValue( replay_time->getDoubleValue()
940                                          + ( delta_time_sec
941                                              * fgGetInt("/sim/speed-up") ) );
942         }
943     } else {
944         // do nothing, fdm isn't inited yet
945     }
946
947     globals->get_model_mgr()->update(delta_time_sec);
948     globals->get_aircraft_model()->update(delta_time_sec);
949
950     // update the view angle
951     globals->get_viewmgr()->update(delta_time_sec);
952
953     l->UpdateAdjFog();
954
955     // Update solar system
956     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
957                               globals->get_time_params()->getLst(),
958                               cur_fdm_state->get_Latitude() );
959
960     // Update radio stack model
961     current_radiostack->update(delta_time_sec);
962 }
963
964
965 void fgInitTimeDepCalcs( void ) {
966     // noop for now
967 }
968
969
970 static const double alt_adjust_ft = 3.758099;
971 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
972
973
974 // What should we do when we have nothing else to do?  Let's get ready
975 // for the next move and update the display?
976 static void fgMainLoop( void ) {
977     int model_hz = fgGetInt("/sim/model-hz");
978
979     static const SGPropertyNode *longitude
980         = fgGetNode("/position/longitude-deg");
981     static const SGPropertyNode *latitude
982         = fgGetNode("/position/latitude-deg");
983     static const SGPropertyNode *altitude
984         = fgGetNode("/position/altitude-ft");
985     static const SGPropertyNode *clock_freeze
986         = fgGetNode("/sim/freeze/clock", true);
987     static const SGPropertyNode *cur_time_override
988         = fgGetNode("/sim/time/cur-time-override", true);
989     static const SGPropertyNode *replay_master
990         = fgGetNode("/sim/freeze/replay", true);
991
992     // Update the elapsed time.
993     static bool first_time = true;
994     if ( first_time ) {
995         last_time_stamp.stamp();
996         first_time = false;
997     }
998
999     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1000     if ( throttle_hz > 0.0 ) {
1001         // simple frame rate throttle
1002         double dt = 1000000.0 / throttle_hz;
1003         current_time_stamp.stamp();
1004         while ( current_time_stamp - last_time_stamp < dt ) {
1005             current_time_stamp.stamp();
1006         }
1007     } else {
1008         // run as fast as the app will go
1009         current_time_stamp.stamp();
1010     }
1011
1012     delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
1013     if ( clock_freeze->getBoolValue() ) {
1014         delta_time_sec = 0;
1015     } 
1016     last_time_stamp = current_time_stamp;
1017     globals->inc_sim_time_sec( delta_time_sec );
1018     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1019
1020     static long remainder = 0;
1021     long elapsed;
1022 #ifdef FANCY_FRAME_COUNTER
1023     int i;
1024     double accum;
1025 #else
1026     static time_t last_time = 0;
1027     static int frames = 0;
1028 #endif // FANCY_FRAME_COUNTER
1029
1030     SGTime *t = globals->get_time_params();
1031
1032     sglog().setLogLevels( SG_ALL, (sgDebugPriority)fgGetInt("/sim/log-level") );
1033     sglog().setLogLevels( SG_ALL, SG_INFO );
1034
1035     SGLocation * acmodel_location = 0;
1036     if(cur_fdm_state->getACModel() != 0) {
1037       acmodel_location = (SGLocation *)  cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
1038     }
1039
1040     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1041     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1042
1043 #ifdef FG_NETWORK_OLK
1044     if ( fgGetBool("/sim/networking/network-olk") ) {
1045         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
1046             // printf("FGD: Netupdate\n");
1047             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
1048             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
1049         }
1050     }
1051 #endif
1052
1053 #if defined( ENABLE_PLIB_JOYSTICK )
1054     // Read joystick and update control settings
1055     // if ( fgGetString("/sim/control-mode") == "joystick" )
1056     // {
1057     //    fgJoystickRead();
1058     // }
1059 #elif defined( ENABLE_GLUT_JOYSTICK )
1060     // Glut joystick support works by feeding a joystick handler
1061     // function to glut.  This is taken care of once in the joystick
1062     // init routine and we don't have to worry about it again.
1063 #endif
1064
1065     // Fix elevation.  I'm just sticking this here for now, it should
1066     // probably move eventually
1067
1068     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
1069            scenery.get_cur_elev(),
1070            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1071            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1072
1073 #if 0
1074 // This code is used by LaRCsim/UIUC to position the aircraft at a proper
1075 // place. This code should eventually go into the LaRCsim directory.
1076 // Commented out at Jul 27 2003 because tests show it is not needed.
1077 // Can probbaly be safely removed after Spet. 2003 - EMH
1078
1079     if ( acmodel_location != 0 ) {
1080       if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
1081         if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER < 
1082              (acmodel_location->get_cur_elev_m() + alt_adjust_m - 130.0) ) {
1083             // now set aircraft altitude above ground
1084             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
1085                cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1086                acmodel_location->get_cur_elev_m() + alt_adjust_m - 130.0,
1087                acmodel_location->get_cur_elev_m() + alt_adjust_m );
1088             cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m() 
1089                                                 + alt_adjust_m) * SG_METER_TO_FEET );
1090             SG_LOG( SG_ALL, SG_DEBUG, 
1091                 "<*> resetting altitude to " 
1092                 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1093                 << " meters" );
1094         }
1095       }
1096     }
1097 // End of code in question. (see Curt is this code used? above)
1098 #endif
1099
1100     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
1101            scenery.get_cur_elev(),
1102            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1103            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1104
1105     // cout << "Warp = " << globals->get_warp() << endl;
1106
1107     // update "time"
1108     static bool last_clock_freeze = false;
1109
1110     if ( clock_freeze->getBoolValue() ) {
1111         // clock freeze requested
1112         if ( cur_time_override->getLongValue() == 0 ) {
1113             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1114             globals->set_warp( 0 );
1115         }
1116     } else {
1117         // no clock freeze requested
1118         if ( last_clock_freeze == true ) {
1119             // clock just unfroze, let's set warp as the difference
1120             // between frozen time and current time so we don't get a
1121             // time jump (and corresponding sky object and lighting
1122             // jump.)
1123             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1124             fgSetLong( "/sim/time/cur-time-override", 0 );
1125         }
1126         if ( globals->get_warp_delta() != 0 ) {
1127             globals->inc_warp( globals->get_warp_delta() );
1128         }
1129     }
1130
1131     last_clock_freeze = clock_freeze->getBoolValue();
1132
1133     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1134                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1135                cur_time_override->getLongValue(),
1136                globals->get_warp() );
1137
1138     if ( globals->get_warp_delta() != 0 ) {
1139         fgUpdateSkyAndLightingParams();
1140     }
1141
1142     // update magvar model
1143     globals->get_mag()->update( longitude->getDoubleValue()
1144                               * SGD_DEGREES_TO_RADIANS,
1145                             latitude->getDoubleValue()
1146                               * SGD_DEGREES_TO_RADIANS,
1147                             altitude->getDoubleValue() * SG_FEET_TO_METER,
1148                             globals->get_time_params()->getJD() );
1149
1150     // Get elapsed time (in usec) for this past frame
1151     elapsed = fgGetTimeInterval();
1152     SG_LOG( SG_ALL, SG_DEBUG, 
1153             "Elapsed time interval is = " << elapsed 
1154             << ", previous remainder is = " << remainder );
1155
1156     // Calculate frame rate average
1157 #ifdef FANCY_FRAME_COUNTER
1158     /* old fps calculation */
1159     if ( elapsed > 0 ) {
1160         double tmp;
1161         accum = 0.0;
1162         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1163             tmp = general.get_frame(i);
1164             accum += tmp;
1165             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1166             general.set_frame(i+1,tmp);
1167         }
1168         tmp = 1000000.0 / (float)elapsed;
1169         general.set_frame(0,tmp);
1170         // printf("frame[0] = %.2f\n", general.frames[0]);
1171         accum += tmp;
1172         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1173         // printf("ave = %.2f\n", general.frame_rate);
1174     }
1175 #else
1176     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1177         general.set_frame_rate( frames );
1178         fgSetInt("/sim/frame-rate", frames);
1179         SG_LOG( SG_ALL, SG_DEBUG, 
1180             "--> Frame rate is = " << general.get_frame_rate() );
1181         frames = 0;
1182     }
1183     last_time = t->get_cur_time();
1184     ++frames;
1185 #endif
1186
1187     // Run ATC subsystem
1188     if (fgGetBool("/sim/ATC/enabled"))
1189         globals->get_ATC_mgr()->update(delta_time_sec);
1190
1191     // Run the AI subsystem
1192     if (fgGetBool("/sim/ai-traffic/enabled"))
1193         globals->get_AI_mgr()->update(delta_time_sec);
1194
1195     // Run flight model
1196
1197     // Calculate model iterations needed for next frame
1198     elapsed += remainder;
1199
1200     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1201     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1202     SG_LOG( SG_ALL, SG_DEBUG, 
1203             "Model iterations needed = " << global_multi_loop
1204             << ", new remainder = " << remainder );
1205         
1206     // chop max interations to something reasonable if the sim was
1207     // delayed for an excesive amount of time
1208     if ( global_multi_loop > 2.0 * model_hz ) {
1209         global_multi_loop = (int)(2.0 * model_hz );
1210         remainder = 0;
1211     }
1212
1213     // flight model
1214     if ( global_multi_loop > 0 ) {
1215         fgUpdateTimeDepCalcs();
1216     } else {
1217         SG_LOG( SG_ALL, SG_DEBUG, 
1218             "Elapsed time is zero ... we're zinging" );
1219     }
1220
1221     // Do any I/O channel work that might need to be done
1222     globals->get_io()->update( delta_time_sec );
1223
1224     // see if we need to load any deferred-load textures
1225     globals->get_matlib()->load_next_deferred();
1226
1227     // Run audio scheduler
1228 #ifdef ENABLE_AUDIO_SUPPORT
1229     if ( fgGetBool("/sim/sound/audible")
1230            && globals->get_soundmgr()->is_working() ) {
1231         globals->get_soundmgr()->update( delta_time_sec );
1232     }
1233 #endif
1234
1235     globals->get_subsystem_mgr()->update(delta_time_sec);
1236
1237     //
1238     // Tile Manager updates - see if we need to load any new scenery tiles.
1239     //   this code ties together the fdm, viewer and scenery classes...
1240     //   we may want to move this to it's own class at some point
1241     //
1242     double visibility_meters = fgGetDouble("/environment/visibility-m");
1243     FGViewer *current_view = globals->get_current_view();
1244
1245     // update tile manager for FDM...
1246     // ...only if location is different than the viewer (to avoid duplicating effort)
1247     if( acmodel_location != current_view->getSGLocation() ) {
1248       if( acmodel_location != 0 ) {
1249         globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1250                                                  visibility_meters );
1251         globals->get_tile_mgr()->
1252             update( acmodel_location, visibility_meters,
1253                     acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1254         // save results of update in SGLocation for fdm...
1255         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1256           acmodel_location->
1257               set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1258         }
1259         acmodel_location->
1260             set_tile_center( globals->get_scenery()->get_next_center() );
1261       }
1262     }
1263
1264     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1265                                              visibility_meters );
1266     // update tile manager for view...
1267     // IMPORTANT!!! the tilemgr update for view location _must_ be done last 
1268     // after the FDM's until all of Flight Gear code references the viewer's location
1269     // for elevation instead of the "scenery's" current elevation.
1270     SGLocation *view_location = globals->get_current_view()->getSGLocation();
1271     globals->get_tile_mgr()->update( view_location, visibility_meters,
1272                                      current_view->get_absolute_view_pos() );
1273     // save results of update in SGLocation for fdm...
1274     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1275       current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1276     }
1277     current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1278
1279     // If fdm location is same as viewer's then we didn't do the update for fdm location 
1280     //   above so we need to save the viewer results in the fdm SGLocation as well...
1281     if( acmodel_location == current_view->getSGLocation() ) {
1282       if( acmodel_location != 0 ) {
1283         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1284           acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1285         }
1286         acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1287       }
1288     }
1289
1290     // END Tile Manager udpates
1291
1292     if (fgGetBool("/sim/rendering/specular-highlight")) {
1293         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);        glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1294     } else {
1295         glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1296          glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1297     }
1298
1299     // redraw display
1300     fgRenderFrame();
1301
1302     SG_LOG( SG_ALL, SG_DEBUG, "" );
1303 }
1304
1305
1306 // This is the top level master main function that is registered as
1307 // our idle funciton
1308
1309 // The first few passes take care of initialization things (a couple
1310 // per pass) and once everything has been initialized fgMainLoop from
1311 // then on.
1312
1313 static void fgIdleFunction ( void ) {
1314     // printf("idle state == %d\n", idle_state);
1315
1316     if ( idle_state == 0 ) {
1317         // Initialize the splash screen right away
1318         if ( fgGetBool("/sim/startup/splash-screen") ) {
1319             fgSplashInit();
1320         }
1321         
1322         idle_state++;
1323     } else if ( idle_state == 1 ) {
1324         // Initialize audio support
1325 #ifdef ENABLE_AUDIO_SUPPORT
1326
1327         // Start the intro music
1328         if ( fgGetBool("/sim/startup/intro-music") ) {
1329             SGPath mp3file( globals->get_fg_root() );
1330             mp3file.append( "Sounds/intro.mp3" );
1331
1332             SG_LOG( SG_GENERAL, SG_INFO, 
1333                 "Starting intro music: " << mp3file.str() );
1334
1335 #if defined( __CYGWIN__ )
1336             string command = "start /m `cygpath -w " + mp3file.str() + "`";
1337 #elif defined( WIN32 )
1338             string command = "start /m " + mp3file.str();
1339 #else
1340             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1341 #endif
1342
1343             system ( command.c_str() );
1344         }
1345 #endif
1346
1347         idle_state++;
1348     } else if ( idle_state == 2 ) {
1349         // These are a few miscellaneous things that aren't really
1350         // "subsystems" but still need to be initialized.
1351
1352 #ifdef USE_GLIDE
1353         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1354             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1355         }
1356 #endif
1357
1358         idle_state++;
1359     } else if ( idle_state == 3 ) {
1360         // This is the top level init routine which calls all the
1361         // other subsystem initialization routines.  If you are adding
1362         // a subsystem to flightgear, its initialization call should
1363         // located in this routine.
1364         if( !fgInitSubsystems()) {
1365             SG_LOG( SG_GENERAL, SG_ALERT,
1366                 "Subsystem initializations failed ..." );
1367             exit(-1);
1368         }
1369
1370         idle_state++;
1371     } else if ( idle_state == 4 ) {
1372         // setup OpenGL view parameters
1373         fgInitVisuals();
1374
1375         // Read the list of available aircrafts
1376         fgReadAircraft();
1377
1378         idle_state++;
1379     } else if ( idle_state == 5 ) {
1380
1381         idle_state++;
1382     } else if ( idle_state == 6 ) {
1383         // sleep(1);
1384         idle_state = 1000;
1385
1386         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1387         fgReshape( fgGetInt("/sim/startup/xsize"),
1388                fgGetInt("/sim/startup/ysize") );
1389     } 
1390
1391     if ( idle_state == 1000 ) {
1392         // We've finished all our initialization steps, from now on we
1393         // run the main loop.
1394
1395         glutIdleFunc(fgMainLoop);
1396     } else {
1397         if ( fgGetBool("/sim/startup/splash-screen") ) {
1398             fgSplashUpdate(0.0, 1.0);
1399         }
1400     }
1401 }
1402
1403 // options.cxx needs to see this for toggle_panel()
1404 // Handle new window size or exposure
1405 void fgReshape( int width, int height ) {
1406     int view_h;
1407
1408     if ( (!fgGetBool("/sim/virtual-cockpit"))
1409          && fgPanelVisible() && idle_state == 1000 ) {
1410         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1411                              globals->get_current_panel()->getYOffset()) / 768.0);
1412     } else {
1413         view_h = height;
1414     }
1415
1416     // for all views
1417     FGViewMgr *viewmgr = globals->get_viewmgr();
1418     for ( int i = 0; i < viewmgr->size(); ++i ) {
1419       viewmgr->get_view(i)->
1420         set_aspect_ratio((float)view_h / (float)width);
1421     }
1422
1423     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1424
1425     fgSetInt("/sim/startup/xsize", width);
1426     fgSetInt("/sim/startup/ysize", height);
1427     guiInitMouse(width, height);
1428
1429     ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1430                viewmgr->get_current_view()->get_v_fov() );
1431
1432     fgHUDReshape();
1433
1434 #ifdef FG_USE_CLOUDS_3D
1435     sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1436                         viewmgr->get_current_view()->get_v_fov() );
1437 #endif
1438
1439 }
1440
1441 // Initialize GLUT and define a main window
1442 static bool fgGlutInit( int *argc, char **argv ) {
1443
1444 #if !defined( macintosh )
1445     // GLUT will extract all glut specific options so later on we only
1446     // need wory about our own.
1447     glutInit(argc, argv);
1448 #endif
1449
1450     // Define Display Parameters. Clouds3d works best with --bpp32 option
1451     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1452         glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1453     } else {
1454         glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1455     }
1456
1457     SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1458             fgGetInt("/sim/startup/xsize") << "x"
1459             << fgGetInt("/sim/startup/ysize") );
1460
1461     // Define initial window size
1462     glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1463                     fgGetInt("/sim/startup/ysize") );
1464
1465     // Initialize windows
1466     if ( !fgGetBool("/sim/startup/game-mode")) {
1467         // Open the regular window
1468         glutCreateWindow("FlightGear");
1469 #ifndef GLUT_WRONG_VERSION
1470     } else {
1471         // Open the cool new 'game mode' window
1472         char game_mode_str[256];
1473 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1474 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1475 #ifndef ENUM_CURRENT_SETTINGS
1476 #define ENUM_CURRENT_SETTINGS       ((DWORD)-1)
1477 #define ENUM_REGISTRY_SETTINGS      ((DWORD)-2)
1478 #endif
1479
1480         DEVMODE dm;
1481         dm.dmSize = sizeof(DEVMODE);
1482         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1483         fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1484         fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1485         glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1486                             fgGetInt("/sim/startup/ysize") );
1487         sprintf( game_mode_str, "%dx%d:%d@%d",
1488                      dm.dmPelsWidth,
1489                      dm.dmPelsHeight,
1490                      dm.dmBitsPerPel,
1491                      dm.dmDisplayFrequency );
1492 #else
1493         // Open the cool new 'game mode' window
1494         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1495              fgGetInt("/sim/startup/xsize"),
1496              fgGetInt("/sim/startup/ysize"),
1497              fgGetInt("/sim/rendering/bits-per-pixel"));
1498
1499 #endif // HAVE_WINDOWS_H
1500         SG_LOG( SG_GENERAL, SG_INFO, 
1501             "game mode params = " << game_mode_str );
1502         glutGameModeString( game_mode_str );
1503         glutEnterGameMode();
1504 #endif // GLUT_WRONG_VERSION
1505     }
1506
1507     // This seems to be the absolute earliest in the init sequence
1508     // that these calls will return valid info.  Too bad it's after
1509     // we've already created and sized out window. :-(
1510     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1511     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1512     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1513     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1514
1515     GLint tmp;
1516     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1517     general.set_glMaxTexSize( tmp );
1518     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1519
1520     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1521     general.set_glDepthBits( tmp );
1522     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1523
1524     return true;
1525 }
1526
1527
1528 // Initialize GLUT event handlers
1529 static bool fgGlutInitEvents( void ) {
1530     // call fgReshape() on window resizes
1531     glutReshapeFunc( fgReshape );
1532
1533     // keyboard and mouse callbacks are set in FGInput::init
1534
1535     // call fgMainLoop() whenever there is
1536     // nothing else to do
1537     glutIdleFunc( fgIdleFunction );
1538
1539     // draw the scene
1540     glutDisplayFunc( fgRenderFrame );
1541
1542     return true;
1543 }
1544
1545 // Main top level initialization
1546 bool fgMainInit( int argc, char **argv ) {
1547
1548 #if defined( macintosh )
1549     freopen ("stdout.txt", "w", stdout );
1550     freopen ("stderr.txt", "w", stderr );
1551     argc = ccommand( &argv );
1552 #endif
1553
1554     // set default log levels
1555     sglog().setLogLevels( SG_ALL, SG_INFO );
1556
1557     string version;
1558 #ifdef FLIGHTGEAR_VERSION
1559     version = FLIGHTGEAR_VERSION;
1560 #else
1561     version = "unknown version";
1562 #endif
1563     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1564             << version );
1565     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1566
1567     // Allocate global data structures.  This needs to happen before
1568     // we parse command line options
1569
1570     globals = new FGGlobals;
1571
1572     // seed the random number generater
1573     sg_srandom_time();
1574
1575     SGRoute *route = new SGRoute;
1576     globals->set_route( route );
1577
1578     FGControls *controls = new FGControls;
1579     globals->set_controls( controls );
1580
1581     string_list *col = new string_list;
1582     globals->set_channel_options_list( col );
1583
1584     // Scan the config file(s) and command line options to see if
1585     // fg_root was specified (ignore all other options for now)
1586     fgInitFGRoot(argc, argv);
1587
1588     // Check for the correct base package version
1589     static char required_version[] = "0.9.2";
1590     string base_version = fgBasePackageVersion();
1591     if ( !(base_version == required_version) ) {
1592         // tell the operator how to use this application
1593
1594         cerr << endl << "Base package check failed ... " \
1595              << "Found version " << base_version << " at: " \
1596              << globals->get_fg_root() << endl;
1597         cerr << "Please upgrade to version: " << required_version << endl;
1598         exit(-1);
1599     }
1600
1601     // Initialize the Aircraft directory to "" (UIUC)
1602     aircraft_dir = "";
1603
1604     // Load the configuration parameters.  (Command line options
1605     // overrides config file options.  Config file options override
1606     // defaults.)
1607     if ( !fgInitConfig(argc, argv) ) {
1608         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1609         exit(-1);
1610     }
1611
1612     // Initialize the Window/Graphics environment.
1613     if( !fgGlutInit(&argc, argv) ) {
1614         SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1615         exit(-1);
1616     }
1617
1618     // Initialize the various GLUT Event Handlers.
1619     if( !fgGlutInitEvents() ) {
1620         SG_LOG( SG_GENERAL, SG_ALERT, 
1621                 "GLUT event handler initialization failed ..." );
1622         exit(-1);
1623     }
1624
1625     // Initialize plib net interface
1626     netInit( &argc, argv );
1627
1628     // Initialize ssg (from plib).  Needs to come before we do any
1629     // other ssg stuff, but after opengl/glut has been initialized.
1630     ssgInit();
1631
1632     // Initialize the user interface (we need to do this before
1633     // passing off control to glut and before fgInitGeneral to get our
1634     // fonts !!!
1635     guiInit();
1636
1637     // Read the list of available aircrafts
1638     fgReadAircraft();
1639
1640 #ifdef GL_EXT_texture_lod_bias
1641     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1642 #endif
1643
1644             // get the address of our OpenGL extensions
1645     if ( fgGetBool("/sim/rendering/distance-attenuation") )
1646     {
1647         if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1648             glPointParameterIsSupported = true;
1649             glPointParameterfPtr = (glPointParameterfProc)
1650                                    SGLookupFunction("glPointParameterfEXT");
1651             glPointParameterfvPtr = (glPointParameterfvProc)
1652                                     SGLookupFunction("glPointParameterfvEXT");
1653
1654         } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1655             glPointParameterIsSupported = true;
1656             glPointParameterfPtr = (glPointParameterfProc)
1657                                    SGLookupFunction("glPointParameterfARB");
1658             glPointParameterfvPtr = (glPointParameterfvProc)
1659                                     SGLookupFunction("glPointParameterfvARB");
1660         } else
1661             glPointParameterIsSupported = false;
1662    }
1663
1664     // based on the requested presets, calculate the true starting
1665     // lon, lat
1666     fgInitNav();
1667     fgInitPosition();
1668
1669     SGTime *t = fgInitTime();
1670     globals->set_time_params( t );
1671
1672     // Do some quick general initializations
1673     if( !fgInitGeneral()) {
1674         SG_LOG( SG_GENERAL, SG_ALERT, 
1675             "General initializations failed ..." );
1676         exit(-1);
1677     }
1678
1679     ////////////////////////////////////////////////////////////////////
1680     // Initialize the property-based built-in commands
1681     ////////////////////////////////////////////////////////////////////
1682     fgInitCommands();
1683
1684     ////////////////////////////////////////////////////////////////////
1685     // Initialize the material manager
1686     ////////////////////////////////////////////////////////////////////
1687     globals->set_matlib( new SGMaterialLib );
1688
1689     globals->set_model_lib(new SGModelLib);
1690
1691     ////////////////////////////////////////////////////////////////////
1692     // Initialize the TG scenery subsystem.
1693     ////////////////////////////////////////////////////////////////////
1694     globals->set_scenery( new FGScenery );
1695     globals->get_scenery()->init();
1696     globals->get_scenery()->bind();
1697     globals->set_tile_mgr( new FGTileMgr );
1698
1699     ////////////////////////////////////////////////////////////////////
1700     // Initialize the general model subsystem.
1701     ////////////////////////////////////////////////////////////////////
1702     globals->set_model_mgr(new FGModelMgr);
1703     globals->get_model_mgr()->init();
1704     globals->get_model_mgr()->bind();
1705
1706     ////////////////////////////////////////////////////////////////////
1707     // Initialize the 3D aircraft model subsystem (has a dependency on
1708     // the scenery subsystem.)
1709     ////////////////////////////////////////////////////////////////////
1710     globals->set_aircraft_model(new FGAircraftModel);
1711     globals->get_aircraft_model()->init();
1712     globals->get_aircraft_model()->bind();
1713
1714     ////////////////////////////////////////////////////////////////////
1715     // Initialize the view manager subsystem.
1716     ////////////////////////////////////////////////////////////////////
1717     FGViewMgr *viewmgr = new FGViewMgr;
1718     globals->set_viewmgr( viewmgr );
1719     viewmgr->init();
1720     viewmgr->bind();
1721
1722
1723     // Initialize the sky
1724     SGPath ephem_data_path( globals->get_fg_root() );
1725     ephem_data_path.append( "Astro" );
1726     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1727     ephem->update( globals->get_time_params()->getMjd(),
1728                globals->get_time_params()->getLst(),
1729                0.0 );
1730     globals->set_ephem( ephem );
1731
1732                             // TODO: move to environment mgr
1733     thesky = new SGSky;
1734     SGPath texture_path(globals->get_fg_root());
1735     texture_path.append("Textures");
1736     texture_path.append("Sky");
1737     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1738         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1739         thesky->add_cloud_layer(layer);
1740     }
1741
1742
1743     SGPath sky_tex_path( globals->get_fg_root() );
1744     sky_tex_path.append( "Textures" );
1745     sky_tex_path.append( "Sky" );
1746     thesky->texture_path( sky_tex_path.str() );
1747
1748     // The sun and moon diameters are scaled down numbers of the
1749     // actual diameters. This was needed to fit bot the sun and the
1750     // moon within the distance to the far clip plane.
1751     // Moon diameter:    3,476 kilometers
1752     // Sun diameter: 1,390,000 kilometers
1753     thesky->build( 80000.0, 80000.0,
1754                    463.3, 361.8,
1755                    globals->get_ephem()->getNumPlanets(), 
1756                    globals->get_ephem()->getPlanets(),
1757                    globals->get_ephem()->getNumStars(),
1758                    globals->get_ephem()->getStars() );
1759
1760     // Initialize MagVar model
1761     SGMagVar *magvar = new SGMagVar();
1762     globals->set_mag( magvar );
1763
1764
1765                                 // kludge to initialize mag compass
1766                                 // (should only be done for in-flight
1767                                 // startup)
1768     // update magvar model
1769     globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1770                                 * SGD_DEGREES_TO_RADIANS,
1771                                 fgGetDouble("/position/latitude-deg")
1772                                 * SGD_DEGREES_TO_RADIANS,
1773                                 fgGetDouble("/position/altitude-ft")
1774                                 * SG_FEET_TO_METER,
1775                                 globals->get_time_params()->getJD() );
1776     double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1777     fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1778
1779     // airport = new ssgBranch;
1780     // airport->setName( "Airport Lighting" );
1781     // lighting->addKid( airport );
1782
1783     // ADA
1784     fgLoadDCS();
1785     // ADA
1786
1787 #ifdef FG_NETWORK_OLK
1788     // Do the network intialization
1789     if ( fgGetBool("/sim/networking/network-olk") ) {
1790         printf("Multipilot mode %s\n",
1791                fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1792     }
1793 #endif
1794
1795     // build our custom render states
1796     fgBuildRenderStates();
1797     
1798     // pass control off to the master GLUT event handler
1799     glutMainLoop();
1800
1801     // we never actually get here ... but to avoid compiler warnings,
1802     // etc.
1803     return false;
1804 }
1805
1806
1807 // $$$ end - added VS Renganathan, 15 Oct 2K
1808 //         - added Venky         , 12 Nov 2K
1809
1810
1811 void fgLoadDCS(void) {
1812
1813     ssgEntity *ship_obj = NULL;
1814
1815     char obj_filename[25];
1816
1817     for ( int k = 0; k < 32; k++ ) {
1818         ship_pos[k]=NULL;
1819     }
1820
1821     SGPath tile_path( globals->get_fg_root());
1822     tile_path.append( "Scenery" );
1823     tile_path.append( "Objects.txt" );
1824     sg_gzifstream in( tile_path.str() );
1825     if ( ! in.is_open() ) {
1826         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1827     } else {
1828
1829         SGPath modelpath( globals->get_fg_root() );
1830         modelpath.append( "Models" );
1831         modelpath.append( "Geometry" );
1832   
1833         SGPath texturepath( globals->get_fg_root() );
1834         texturepath.append( "Models" );
1835         texturepath.append( "Textures" );
1836  
1837         ssgModelPath( (char *)modelpath.c_str() );
1838         ssgTexturePath( (char *)texturepath.c_str() );
1839
1840         ship_sel = new ssgSelector;
1841
1842         char c;
1843         while ( ! in.eof() ) {
1844             in >> ::skipws;
1845             if ( in.get( c ) && c == '#' ) { 
1846                 in >> skipeol;
1847             } else { 
1848                 in.putback(c);
1849                 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1850                 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] <<  " " << obj_alt[objc] << endl;
1851                    int chj=getchar();*/
1852                 
1853                 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1854                 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1855                 
1856                 ship_pos[objc] = new ssgTransform;
1857        
1858                 // type "repeat" in objects.txt to load one more
1859                 // instance of the last object.
1860
1861                 if ( strcmp(obj_filename,"repeat") != 0) {
1862                     ship_obj =
1863                       globals->get_model_lib()->load_model( globals->get_fg_root(), obj_filename, globals->get_props(), globals->get_sim_time_sec() );
1864                 }
1865       
1866                 if ( ship_obj != NULL ) {
1867                                 ship_obj->setName(obj_filename);
1868                             if (objc == 0)
1869                                         ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1870                                 else
1871                                         ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1872                     ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1873                     ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1874                     SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1875                             << obj_filename );
1876                 } else {
1877                     SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1878                             << obj_filename );
1879                 }
1880             
1881                             // temporary hack for deck lights - ultimately should move to PLib (when??)
1882                             //const char *extn = file_extension ( obj_filename ) ;
1883                             if ( objc == 1 ){
1884                                 // ssgVertexArray *lights = new ssgVertexArray( 100 );
1885                                 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1886                                 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1887                                 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1888                                 int ltype[500], light_type = 0;
1889                                 static int ltcount = 0;
1890                                 string token;
1891                                 sgVec3 rway_dir,rway_normal,lightpt;
1892                                 Point3D node;
1893                                 modelpath.append(obj_filename);
1894                                 sg_gzifstream in1( modelpath.str() );
1895                                 if ( ! in1.is_open() ) {
1896                                         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1897                                 } else {
1898                                         while ( ! in1.eof() ) {
1899                                                         in1 >> ::skipws;
1900                                                 if ( in1.get( c ) && c == '#' ) { 
1901                                                         in1 >> skipeol;
1902                                                 } else { 
1903                                                         in1.putback(c);
1904                                                         in1 >> token;
1905                                                         //cout << token << endl;
1906                                                         if ( token == "runway" ) {
1907                                                                 in1 >> node;
1908                                                                 sgSetVec3 (rway_dir, node[0], node[1], node[2] );                        
1909                                                         } else if ( token == "edgelight" ) {
1910                                                                 in1 >> node;
1911                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1912                                                                 light_type = 1;
1913                                                         } else if ( token == "taxi" ) {
1914                                                                 in1 >> node;
1915                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
1916                                                                 light_type = 2;
1917                                                         } else if ( token == "vasi" ) {
1918                                                                 in1 >> node;
1919                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
1920                                                                 light_type = 3;
1921                                                         } else if ( token == "threshold" ) {
1922                                                                 in1 >> node;
1923                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
1924                                                                 light_type = 4;
1925                                                         } else if ( token == "rabbit" ) {
1926                                                                 in1 >> node;
1927                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1928                                                                 light_type = 5;
1929                                                         } else if ( token == "ols" ) {
1930                                                                 in1 >> node;
1931                                                                 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1932                                                                 light_type = 6;
1933                                                         } else if ( token == "red" ) {
1934                                                                 in1 >> node;
1935                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1936                                                                 light_type = 7;
1937                                                         } else if ( token == "green" ) {
1938                                                                 in1 >> node;
1939                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1940                                                                 light_type = 8;
1941                                                         } else if ( token == "lp" ) {
1942                                                                 in1 >> node;
1943                                                                 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1944                                                                 lightpoints->add( lightpt );
1945                                                                 lightnormals->add( rway_normal );
1946                                                                 lightdir->add( rway_dir );
1947                                                                 ltype[ltcount]= light_type;
1948                                                                 ltcount++;
1949                                                         }
1950                                                         if (in1.eof()) break;
1951                                                 } 
1952                                         }  //while
1953
1954 #if 0        
1955                                         if ( lightpoints->getNum() ) {
1956                                                 ssgBranch *lightpoints_branch;
1957                                                 long int dummy = -999;
1958                                                 dummy_tile = new FGTileEntry((SGBucket)dummy);
1959                                                 dummy_tile->lightmaps_sequence = new ssgSelector;
1960                                                 dummy_tile->ols_transform = new ssgTransform;
1961
1962                                                 // call function to generate the runway lights
1963                                                 lightpoints_branch = 
1964                                                 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1965                                                                                                                         lightdir, ltype);
1966                                                 lightpoints_brightness->addKid(lightpoints_branch);
1967                                                 lightpoints_transform->addKid(lightpoints_brightness);
1968                                             //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1969                                                 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1970                                                 lightpoints_transform->ref();
1971                                                 globals->get_scenery()->get_gnd_lights_root()->addKid( lightpoints_transform );
1972                                         } 
1973 #endif
1974                                 } //if in1 
1975                 } //if objc
1976                             // end hack for deck lights
1977
1978                 objc++;
1979
1980                 if (in.eof()) break;
1981             }
1982         } // while
1983
1984         SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1985
1986         globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node 
1987     }
1988
1989     return;
1990  }
1991
1992
1993 void fgUpdateDCS (void) {
1994
1995     // double eye_lat,eye_lon,eye_alt;
1996     // static double obj_head;
1997     double sl_radius,obj_latgc;
1998     // float nresultmat[4][4];
1999     // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
2000     double bz[3];
2001
2002     // Instantaneous Geodetic Lat/Lon/Alt of moving object
2003     FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
2004     
2005     // Deck should be the first object in objects.txt in case of fdm=ada
2006
2007     if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
2008             if ((fdm->get_iaux(1))==1)
2009             {
2010                     obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
2011                     obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
2012                     obj_alt[1] = fdm->get_daux(3);
2013                     obj_pitch[1] = fdm->get_faux(1);
2014                     obj_roll[1] = fdm->get_faux(2);
2015             }
2016     }
2017     
2018     for ( int m = 0; m < objc; m++ ) {
2019         //cout << endl <<  obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
2020         //int v=getchar();
2021
2022         //Geodetic to Geocentric angles for rotation
2023         sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
2024
2025         //moving object gbs-posn in cartesian coords
2026         Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
2027         Point3D obj_pos = sgGeodToCart( obj_posn );
2028
2029         // Translate moving object w.r.t eye
2030         Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
2031         bz[0]=Objtrans.x();
2032         bz[1]=Objtrans.y();
2033         bz[2]=Objtrans.z();
2034
2035        // rotate dynamic objects for lat,lon & alt and other motion about its axes
2036         
2037         sgMat4 sgTRANS;
2038         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
2039
2040         sgVec3 ship_fwd,ship_rt,ship_up;
2041         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
2042         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
2043         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
2044
2045         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
2046         sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
2047         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
2048         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
2049         sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
2050         sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2051         
2052         sgMat4 sgTUX;
2053         sgCopyMat4( sgTUX, sgROT_hdg );
2054         sgPostMultMat4( sgTUX, sgROT_pitch );
2055         sgPostMultMat4( sgTUX, sgROT_roll );
2056         sgPostMultMat4( sgTUX, sgROT_lat );
2057         sgPostMultMat4( sgTUX, sgROT_lon );
2058         sgPostMultMat4( sgTUX, sgTRANS );
2059
2060         sgCoord shippos;
2061         sgSetCoord(&shippos, sgTUX );
2062         ship_pos[m]->setTransform( &shippos );
2063         // temporary hack for deck lights - ultimately should move to PLib (when ??)
2064         if (m == 1) {
2065             if (lightpoints_transform) {
2066                     lightpoints_transform->setTransform( &shippos );
2067                     float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2068                     if ( sun_angle > 89 ) {
2069                             lightpoints_brightness->select(0x01);
2070                     } else {
2071                             lightpoints_brightness->select(0x00);
2072                     }
2073             }
2074
2075             float elev;
2076             sgVec3 rp,to;
2077             float *vp;
2078             float alt;
2079             float ref_elev;
2080             sgXformPnt3( rp, rway_ols, sgTUX );
2081             vp = globals->get_current_view()->get_view_pos();
2082             to[0] = rp[0]-vp[0];
2083             to[1] = rp[1]-vp[1];
2084             to[2] = rp[2]-vp[2];
2085             float dist = sgLengthVec3( to );
2086             alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2087
2088             elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2089
2090             ref_elev = elev - 3.75; // +ve above, -ve below
2091         
2092             unsigned int sel;
2093             sel = 0xFF;
2094 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2095 //              if (ref_elev > 0.51) sel = 0x21;
2096 //              if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2097 //              if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2098 //              if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2099 //              if (ref_elev < -0.51) sel = 0x30;
2100 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2101             // dummy_tile->lightmaps_sequence->select(sel);
2102
2103             sgVec3 up;
2104             sgCopyVec3 (up, ship_up);
2105             if (dist > 750) 
2106                     sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2107             else
2108                     sgScaleVec3 (up, 4.0*ref_elev);
2109             // dummy_tile->ols_transform->setTransform(up);
2110             //cout << "ref_elev  " << ref_elev << endl;
2111         }
2112     // end hack for deck lights
2113
2114     }
2115     if ( ship_sel != NULL ) {
2116         ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2117     }
2118 }
2119
2120 // $$$ end - added VS Renganathan, 15 Oct 2K
2121 //           added Venky         , 12 Nov 2K