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