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