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