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