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