]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
- added property-multiply command with argument 'factor'
[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/engine0/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     // update "time"
1028     if ( globals->get_warp_delta() != 0 ) {
1029         globals->inc_warp( globals->get_warp_delta() );
1030     }
1031
1032     t->update( cur_fdm_state->get_Longitude(),
1033                cur_fdm_state->get_Latitude(),
1034                globals->get_warp() );
1035
1036     if ( globals->get_warp_delta() != 0 ) {
1037         fgUpdateSkyAndLightingParams();
1038     }
1039
1040     // update magvar model
1041     globals->get_mag()->update( cur_fdm_state->get_Longitude(),
1042                                 cur_fdm_state->get_Latitude(),
1043                                 cur_fdm_state->get_Altitude()* SG_FEET_TO_METER,
1044                                 globals->get_time_params()->getJD() );
1045
1046     // Get elapsed time (in usec) for this past frame
1047     elapsed = fgGetTimeInterval();
1048     SG_LOG( SG_ALL, SG_DEBUG, 
1049             "Elapsed time interval is = " << elapsed 
1050             << ", previous remainder is = " << remainder );
1051
1052     // Calculate frame rate average
1053 #ifdef FANCY_FRAME_COUNTER
1054     /* old fps calculation */
1055     if ( elapsed > 0 ) {
1056         double tmp;
1057         accum = 0.0;
1058         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1059             tmp = general.get_frame(i);
1060             accum += tmp;
1061             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1062             general.set_frame(i+1,tmp);
1063         }
1064         tmp = 1000000.0 / (float)elapsed;
1065         general.set_frame(0,tmp);
1066         // printf("frame[0] = %.2f\n", general.frames[0]);
1067         accum += tmp;
1068         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1069         // printf("ave = %.2f\n", general.frame_rate);
1070     }
1071 #else
1072     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1073         general.set_frame_rate( frames );
1074         SG_LOG( SG_ALL, SG_DEBUG, 
1075                 "--> Frame rate is = " << general.get_frame_rate() );
1076         frames = 0;
1077     }
1078     last_time = t->get_cur_time();
1079     ++frames;
1080 #endif
1081
1082     // Run flight model
1083
1084     // Calculate model iterations needed for next frame
1085     elapsed += remainder;
1086
1087     global_multi_loop = (long)(((double)elapsed * 0.000001) * 
1088                               fgGetInt("/sim/model-hz"));
1089     remainder = elapsed - ( (global_multi_loop*1000000) / 
1090                             fgGetInt("/sim/model-hz") );
1091     SG_LOG( SG_ALL, SG_DEBUG, 
1092             "Model iterations needed = " << global_multi_loop
1093             << ", new remainder = " << remainder );
1094         
1095     // chop max interations to something reasonable if the sim was
1096     // delayed for an excesive amount of time
1097     if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1098         global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1099         remainder = 0;
1100     }
1101
1102     // flight model
1103     if ( global_multi_loop > 0 ) {
1104         fgUpdateTimeDepCalcs();
1105     } else {
1106         SG_LOG( SG_ALL, SG_DEBUG, 
1107                 "Elapsed time is zero ... we're zinging" );
1108     }
1109
1110 #if ! defined( macintosh )
1111     // Do any I/O channel work that might need to be done
1112     fgIOProcess();
1113 #endif
1114
1115     // see if we need to load any new scenery tiles
1116     global_tile_mgr.update( cur_fdm_state->get_Longitude()
1117                             * SGD_RADIANS_TO_DEGREES,
1118                             cur_fdm_state->get_Latitude()
1119                             * SGD_RADIANS_TO_DEGREES );
1120
1121     // see if we need to load any deferred-load textures
1122     material_lib.load_next_deferred();
1123
1124     // Process/manage pending events
1125     global_events.Process();
1126
1127     // Run audio scheduler
1128 #ifdef ENABLE_AUDIO_SUPPORT
1129     if ( fgGetBool("/sim/sound") && globals->get_soundmgr()->is_working() ) {
1130         if ( fgGetString("/sim/aircraft") == "c172" ) {
1131             // pitch corresponds to rpm
1132             // volume corresponds to manifold pressure
1133
1134             // cout << "AUDIO working = "
1135             //      << globals->get_soundmgr()->is_working() << endl;
1136
1137             double rpm_factor;
1138             if ( cur_fdm_state->get_engine(0) != NULL ) {
1139                 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1140             } else {
1141                 rpm_factor = 1.0;
1142             }
1143             // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1144             //      << endl;
1145
1146             double pitch = 0.3 + rpm_factor * 3.0;
1147         
1148             // don't run at absurdly slow rates -- not realistic
1149             // and sounds bad to boot.  :-)
1150             if (pitch < 0.7) { pitch = 0.7; }
1151             if (pitch > 5.0) { pitch = 5.0; }
1152
1153             double mp_factor;
1154             if ( cur_fdm_state->get_engine(0) != NULL ) {
1155                 mp_factor = 
1156                     cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1157             } else {
1158                 mp_factor = 0.3;
1159             }
1160             /* cout << "mp = " 
1161                  << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1162                  << endl; */
1163
1164             double volume = 0.15 + mp_factor / 2.0;
1165
1166             if ( volume < 0.15 ) { volume = 0.15; }
1167             if ( volume > 0.5 ) { volume = 0.5; }
1168             // cout << "volume = " << volume << endl;
1169
1170             s1->set_pitch( pitch );
1171             s1->set_volume( volume );
1172         } else {
1173             double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1174             s1->set_pitch( param );
1175             s1->set_volume( param );
1176         }
1177
1178         globals->get_soundmgr()->update();
1179     }
1180 #endif
1181
1182     // redraw display
1183     fgRenderFrame();
1184
1185     SG_LOG( SG_ALL, SG_DEBUG, "" );
1186 }
1187
1188
1189 // This is the top level master main function that is registered as
1190 // our idle funciton
1191 //
1192
1193 // The first few passes take care of initialization things (a couple
1194 // per pass) and once everything has been initialized fgMainLoop from
1195 // then on.
1196
1197 static void fgIdleFunction ( void ) {
1198     // printf("idle state == %d\n", idle_state);
1199
1200     if ( idle_state == 0 ) {
1201         // Initialize the splash screen right away
1202         if ( fgGetBool("/sim/startup/splash-screen") ) {
1203             fgSplashInit();
1204         }
1205         
1206         idle_state++;
1207     } else if ( idle_state == 1 ) {
1208         // Start the intro music
1209 #if !defined(WIN32)
1210         if ( fgGetBool("/sim/startup/intro-music") ) {
1211             string lockfile = "/tmp/mpg123.running";
1212             SGPath mp3file( globals->get_fg_root() );
1213             mp3file.append( "Sounds/intro.mp3" );
1214
1215             string command = "(touch " + lockfile + "; mpg123 "
1216                 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1217                 + lockfile + ") &";
1218             SG_LOG( SG_GENERAL, SG_INFO, 
1219                     "Starting intro music: " << mp3file.str() );
1220             system ( command.c_str() );
1221         }
1222 #endif
1223
1224         idle_state++;
1225     } else if ( idle_state == 2 ) {
1226         // These are a few miscellaneous things that aren't really
1227         // "subsystems" but still need to be initialized.
1228
1229 #ifdef USE_GLIDE
1230         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1231             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1232         }
1233 #endif
1234
1235         idle_state++;
1236     } else if ( idle_state == 3 ) {
1237         // This is the top level init routine which calls all the
1238         // other subsystem initialization routines.  If you are adding
1239         // a subsystem to flightgear, its initialization call should
1240         // located in this routine.
1241         if( !fgInitSubsystems()) {
1242             SG_LOG( SG_GENERAL, SG_ALERT,
1243                     "Subsystem initializations failed ..." );
1244             exit(-1);
1245         }
1246
1247         idle_state++;
1248     } else if ( idle_state == 4 ) {
1249         // setup OpenGL view parameters
1250         fgInitVisuals();
1251
1252         idle_state++;
1253     } else if ( idle_state == 5 ) {
1254
1255         idle_state++;
1256     } else if ( idle_state == 6 ) {
1257         // Initialize audio support
1258 #ifdef ENABLE_AUDIO_SUPPORT
1259
1260 #if !defined(WIN32)
1261         if ( fgGetBool("/sim/startup/intro-music") ) {
1262             // Let's wait for mpg123 to finish
1263             string lockfile = "/tmp/mpg123.running";
1264             struct stat stat_buf;
1265
1266             SG_LOG( SG_GENERAL, SG_INFO, 
1267                     "Waiting for mpg123 player to finish ..." );
1268             while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1269                 // file exist, wait ...
1270                 sleep(1);
1271                 SG_LOG( SG_GENERAL, SG_INFO, ".");
1272             }
1273             SG_LOG( SG_GENERAL, SG_INFO, "");
1274         }
1275 #endif // WIN32
1276
1277         if ( fgGetBool("/sim/sound") ) {
1278             globals->get_soundmgr()->init();
1279
1280             s1 = new FGSimpleSound( fgGetString("/sim/sounds/engine",
1281                                                 "Sounds/wasp.wav") );
1282             globals->get_soundmgr()->add( s1, "engine loop" );
1283             globals->get_soundmgr()->play_looped( "engine loop" );
1284             SG_LOG( SG_GENERAL, SG_INFO,
1285                     "Rate = " << s1->get_sample()->getRate()
1286                     << "  Bps = " << s1->get_sample()->getBps()
1287                     << "  Stereo = " << s1->get_sample()->getStereo() );
1288
1289             s2 = new FGSimpleSound( "Sounds/corflaps.wav" );
1290             // FGMorse mmm;
1291             // mmm.init();
1292             // s2 = mmm.make_ident( "JLI" );
1293             s2->set_volume( 0.3 );
1294             globals->get_soundmgr()->add( s2, "flaps" );
1295         }
1296 #endif
1297
1298         // sleep(1);
1299         idle_state = 1000;
1300
1301         cout << "Panel visible = " << fgPanelVisible() << endl;
1302         fgReshape( fgGetInt("/sim/startup/xsize"),
1303                    fgGetInt("/sim/startup/ysize") );
1304     } 
1305
1306     if ( idle_state == 1000 ) {
1307         // We've finished all our initialization steps, from now on we
1308         // run the main loop.
1309
1310         fgMainLoop();
1311     } else {
1312         if ( fgGetBool("/sim/startup/splash-screen") ) {
1313             fgSplashUpdate(0.0);
1314         }
1315     }
1316 }
1317
1318 // options.cxx needs to see this for toggle_panel()
1319 // Handle new window size or exposure
1320 void fgReshape( int width, int height ) {
1321     // for all views
1322     for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1323         if ( ! fgPanelVisible() || idle_state != 1000 ) {
1324             globals->get_viewmgr()->get_view(i)->
1325                 set_win_ratio( (float)height / (float)width );
1326         } else {
1327             int view_h =
1328                 int((current_panel->getViewHeight() -
1329                      current_panel->getYOffset())
1330                     * (height / 768.0)) + 1;
1331             globals->get_viewmgr()->get_view(i)->
1332                 set_win_ratio( (float)view_h / (float)width );
1333         }
1334     }
1335
1336     if ( ! fgPanelVisible() || idle_state != 1000 ) {
1337         glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1338     } else {
1339         int view_h =
1340             int((current_panel->getViewHeight() - current_panel->getYOffset())
1341                 * (height / 768.0)) + 1;
1342         glViewport(0, (GLint)(height - view_h),
1343                    (GLint)(width), (GLint)(view_h) );
1344     }
1345
1346     fgSetInt("/sim/startup/xsize", width);
1347     fgSetInt("/sim/startup/ysize", height);
1348
1349     float fov = globals->get_current_view()->get_fov();
1350     ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1351
1352     fgHUDReshape();
1353 }
1354
1355
1356 // Initialize GLUT and define a main window
1357 int fgGlutInit( int *argc, char **argv ) {
1358
1359 #if !defined( macintosh )
1360     // GLUT will extract all glut specific options so later on we only
1361     // need wory about our own.
1362     glutInit(argc, argv);
1363 #endif
1364
1365     // Define Display Parameters
1366     glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1367
1368     SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1369             fgGetInt("/sim/startup/xsize") << "x"
1370             << fgGetInt("/sim/startup/ysize") );
1371
1372     // Define initial window size
1373     glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1374                         fgGetInt("/sim/startup/ysize") );
1375
1376     // Initialize windows
1377     if ( !fgGetBool("/sim/startup/game-mode")) {
1378         // Open the regular window
1379         glutCreateWindow("FlightGear");
1380 #ifndef GLUT_WRONG_VERSION
1381     } else {
1382         // Open the cool new 'game mode' window
1383         char game_mode_str[256];
1384         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1385                  fgGetInt("/sim/startup/xsize"),
1386                  fgGetInt("/sim/startup/ysize"),
1387                  fgGetInt("/sim/rendering/bits-per-pixel"));
1388
1389         SG_LOG( SG_GENERAL, SG_INFO, 
1390                 "game mode params = " << game_mode_str );
1391         glutGameModeString( game_mode_str );
1392         glutEnterGameMode();
1393 #endif
1394     }
1395
1396     // This seems to be the absolute earliest in the init sequence
1397     // that these calls will return valid info.  Too bad it's after
1398     // we've already created and sized out window. :-(
1399     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1400     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1401     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1402     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1403
1404     GLint tmp;
1405     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1406     general.set_glMaxTexSize( tmp );
1407     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1408
1409     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1410     general.set_glDepthBits( tmp );
1411     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1412
1413     return 1;
1414 }
1415
1416
1417 // Initialize GLUT event handlers
1418 int fgGlutInitEvents( void ) {
1419     // call fgReshape() on window resizes
1420     glutReshapeFunc( fgReshape );
1421
1422     // call GLUTkey() on keyboard event
1423     glutKeyboardFunc(GLUTkey);
1424     glutKeyboardUpFunc(GLUTkeyup);
1425     glutSpecialFunc(GLUTspecialkey);
1426     glutSpecialUpFunc(GLUTspecialkeyup);
1427
1428     // call guiMouseFunc() whenever our little rodent is used
1429     glutMouseFunc ( guiMouseFunc );
1430     glutMotionFunc (guiMotionFunc );
1431     glutPassiveMotionFunc (guiMotionFunc );
1432
1433     // call fgMainLoop() whenever there is
1434     // nothing else to do
1435     glutIdleFunc( fgIdleFunction );
1436
1437     // draw the scene
1438     glutDisplayFunc( fgRenderFrame );
1439
1440     return(1);
1441 }
1442
1443
1444 // Main ...
1445 int main( int argc, char **argv ) {
1446
1447 #if defined( macintosh )
1448     freopen ("stdout.txt", "w", stdout );
1449     freopen ("stderr.txt", "w", stderr );
1450     argc = ccommand( &argv );
1451 #endif
1452
1453 #ifdef HAVE_BC5PLUS
1454     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1455 #endif
1456
1457     // set default log levels
1458     sglog().setLogLevels( SG_ALL, SG_INFO );
1459
1460     string version;
1461 #ifdef FLIGHTGEAR_VERSION
1462     version = FLIGHTGEAR_VERSION;
1463 #else
1464     version = "unknown version";
1465 #endif
1466     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1467             << version << endl );
1468
1469     // Allocate global data structures.  This needs to happen before
1470     // we parse command line options
1471
1472     globals = new FGGlobals;
1473
1474     // seed the random number generater
1475     sg_srandom_time();
1476
1477     SGRoute *route = new SGRoute;
1478     globals->set_route( route );
1479
1480 #ifdef ENABLE_AUDIO_SUPPORT
1481     FGSoundMgr *soundmgr = new FGSoundMgr;
1482     globals->set_soundmgr( soundmgr );
1483 #endif
1484
1485     FGViewMgr *viewmgr = new FGViewMgr;
1486     globals->set_viewmgr( viewmgr );
1487
1488     FGViewerRPH *pv = new FGViewerRPH;
1489     globals->get_viewmgr()->add_view( pv );
1490
1491     FGViewerLookAt *chase = new FGViewerLookAt;
1492     globals->get_viewmgr()->add_view( chase );
1493
1494     string_list *col = new string_list;
1495     globals->set_channel_options_list( col );
1496
1497     // set current view to 0 (first) which is our main pilot view
1498     globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1499
1500     // Scan the config file(s) and command line options to see if
1501     // fg_root was specified (ignore all other options for now)
1502     fgInitFGRoot(argc, argv);
1503
1504     // Initialize the Aircraft directory to "" (UIUC)
1505     aircraft_dir = "";
1506
1507     // Load the configuration parameters
1508     if ( !fgInitConfig(argc, argv) ) {
1509         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1510         exit(-1);
1511     }
1512
1513     // Initialize the Window/Graphics environment.
1514     if( !fgGlutInit(&argc, argv) ) {
1515         SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1516         exit(-1);
1517     }
1518
1519     // Initialize the various GLUT Event Handlers.
1520     if( !fgGlutInitEvents() ) {
1521         SG_LOG( SG_GENERAL, SG_ALERT, 
1522                 "GLUT event handler initialization failed ..." );
1523         exit(-1);
1524     }
1525  
1526     // Initialize ssg (from plib).  Needs to come before we do any
1527     // other ssg stuff, but after opengl/glut has been initialized.
1528     ssgInit();
1529
1530     // Initialize the user interface (we need to do this before
1531     // passing off control to glut and before fgInitGeneral to get our
1532     // fonts !!!
1533     guiInit();
1534
1535 #ifdef GL_EXT_texture_lod_bias
1536     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1537 #endif
1538
1539 #if 0
1540 #ifdef GL_EXT_texture_filter_anisotropic
1541     float max_anisotropy;
1542     glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy );
1543     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1544                      max_anisotropy );
1545     cout << "Max anisotropy = " << max_anisotropy << endl;
1546 #endif
1547 #endif
1548
1549     // set current_options lon/lat if an airport id is specified
1550     // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1551     if ( fgGetString("/sim/startup/airport-id").length() ) {
1552         // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1553         fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1554                                      fgGetDouble("/orientation/heading") );
1555     }
1556
1557     // Initialize time
1558     SGPath zone( globals->get_fg_root() );
1559     zone.append( "Timezone" );
1560     SGTime *t = new SGTime( fgGetDouble("/position/longitude") * SGD_DEGREES_TO_RADIANS,
1561                             fgGetDouble("/position/latitude") * SGD_DEGREES_TO_RADIANS,
1562                             zone.str() );
1563
1564     // Handle potential user specified time offsets
1565     time_t cur_time = t->get_cur_time();
1566     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1567     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1568     time_t aircraftLocalTime = 
1569         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1570
1571     // Okay, we now have six possible scenarios
1572     int offset = fgGetInt("/sim/startup/time-offset");
1573     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1574     if (offset_type == "system-offset") {
1575         globals->set_warp( offset );
1576     } else if (offset_type == "gmt-offset") {
1577         globals->set_warp( offset - (currGMT - systemLocalTime) );
1578     } else if (offset_type == "latitude-offset") {
1579         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1580     } else if (offset_type == "system") {
1581         globals->set_warp( offset - cur_time );
1582     } else if (offset_type == "gmt") {
1583         globals->set_warp( offset - currGMT );
1584     } else if (offset_type == "latitude") {
1585         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
1586                            cur_time ); 
1587     } else {
1588         SG_LOG( SG_GENERAL, SG_ALERT,
1589                 "Unsupported offset type " << offset_type );
1590         exit( -1 );
1591     }
1592
1593     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
1594             << globals->get_warp() );
1595
1596     globals->set_warp_delta( 0 );
1597
1598     t->update( 0.0, 0.0, globals->get_warp() );
1599
1600     globals->set_time_params( t );
1601
1602     // Do some quick general initializations
1603     if( !fgInitGeneral()) {
1604         SG_LOG( SG_GENERAL, SG_ALERT, 
1605                 "General initializations failed ..." );
1606         exit(-1);
1607     }
1608
1609     SGPath modelpath( globals->get_fg_root() );
1610     ssgModelPath( (char *)modelpath.c_str() );
1611   
1612     // Scene graph root
1613     scene = new ssgRoot;
1614     scene->setName( "Scene" );
1615
1616     lighting = new ssgRoot;
1617     lighting->setName( "Lighting" );
1618
1619     // Initialize the sky
1620     SGPath ephem_data_path( globals->get_fg_root() );
1621     ephem_data_path.append( "Astro" );
1622     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1623     ephem->update( globals->get_time_params()->getMjd(),
1624                    globals->get_time_params()->getLst(),
1625                    0.0 );
1626     globals->set_ephem( ephem );
1627
1628     thesky = new SGSky;
1629
1630     SGPath sky_tex_path( globals->get_fg_root() );
1631     sky_tex_path.append( "Textures" );
1632     sky_tex_path.append( "Sky" );
1633     thesky->texture_path( sky_tex_path.str() );
1634
1635     thesky->build( 550.0, 550.0,
1636                    globals->get_ephem()->getNumPlanets(), 
1637                    globals->get_ephem()->getPlanets(), 60000.0,
1638                    globals->get_ephem()->getNumStars(),
1639                    globals->get_ephem()->getStars(), 60000.0 );
1640
1641     if ( fgGetBool("/environment/clouds/status") ) {
1642         // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1643         //                          SG_CLOUD_OVERCAST );
1644         thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1645                                  SG_CLOUD_MOSTLY_CLOUDY );
1646         // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1647         //                          SG_CLOUD_MOSTLY_SUNNY );
1648         thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1649                                  SG_CLOUD_CIRRUS );
1650     }
1651
1652     // Initialize MagVar model
1653     SGMagVar *magvar = new SGMagVar();
1654     globals->set_mag( magvar );
1655
1656     // Terrain branch
1657     terrain = new ssgBranch;
1658     terrain->setName( "Terrain" );
1659     scene->addKid( terrain );
1660
1661     // Lighting
1662     ground = new ssgBranch;
1663     ground->setName( "Ground Lighting" );
1664     lighting->addKid( ground );
1665
1666     airport = new ssgBranch;
1667     airport->setName( "Airport Lighting" );
1668     lighting->addKid( airport );
1669
1670     // temporary visible aircraft "own ship"
1671     acmodel_selector = new ssgSelector;
1672     acmodel_pos = new ssgTransform;
1673
1674     // Get the model location, and load textures from the same
1675     // directory.  Use an absolute path for the model to avoid
1676     // incompatibilities in different versions of PLIB.
1677     string acmodel_path =
1678         fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1679     SGPath full_model = globals->get_fg_root();
1680     full_model.append(acmodel_path);
1681
1682 #if !defined( PLIB_1_2_X )
1683     // this should be redundant ... but it breaks for relative paths
1684     // ssgModelPath( (char *)full_model.dir().c_str() );
1685 #endif
1686
1687     ssgTexturePath( (char *)full_model.dir().c_str() );
1688     ssgEntity *acmodel_obj = ssgLoad( (char *)full_model.c_str() );
1689     if( !acmodel_obj ) {
1690         // fall back to default
1691         acmodel_obj = ssgLoad( (char *)"Models/Geometry/glider.ac" );
1692         if( !acmodel_obj ) {
1693             SG_LOG( SG_GENERAL, SG_ALERT, "FAILED to LOAD an AC model! ..." );
1694             exit(-1);
1695         }
1696     }
1697
1698     // find moving parts (if this is an MDL model)
1699     flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1700     prop_selector  = (ssgSelector*)fgFindNode( acmodel_obj, "PROP"  );
1701
1702     acmodel_npropsettings = 0;
1703     if (prop_selector != NULL) {
1704       for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1705            kid = prop_selector->getNextKid()) {
1706         int prop_low, prop_high;
1707         if ( sscanf(kid->getName(), "PROP_%d_%d", 
1708                     &prop_low, &prop_high) == 2 ) {
1709           prop_low  = (int)((float)prop_low  * (5000.0f / 32767.0f));
1710           prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1711           acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1712           acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1713           acmodel_npropsettings++;
1714
1715           SG_LOG( SG_GENERAL, SG_INFO, "PROPELLER SETTING " << prop_low <<
1716                   " " << prop_high );
1717         }
1718       }
1719     }
1720
1721     // align the model properly for FGFS
1722     ssgTransform *acmodel_align = new ssgTransform;
1723     acmodel_align->addKid(acmodel_obj);
1724     sgMat4 rot_matrix;
1725     sgMat4 off_matrix;
1726     sgMat4 res_matrix;
1727     float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1728     float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1729     float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1730     float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1731     float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1732     float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1733     sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1734     sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1735     sgMultMat4(res_matrix, off_matrix, rot_matrix);
1736     acmodel_align->setTransform(res_matrix);
1737
1738     acmodel_pos->addKid( acmodel_align );
1739     acmodel_selector->addKid( acmodel_pos );
1740     //ssgFlatten( acmodel_obj );
1741     //ssgStripify( acmodel_selector );
1742     acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1743     scene->addKid( acmodel_selector );
1744
1745     // $$$ begin - added VS Renganthan 17 Oct 2K
1746     fgLoadDCS();
1747     // $$$ end - added VS Renganthan 17 Oct 2K
1748
1749 #ifdef FG_NETWORK_OLK
1750     // Do the network intialization
1751     if ( fgGetBool("/sim/networking/network-olk") ) {
1752         printf("Multipilot mode %s\n", fg_net_init( scene ) );
1753     }
1754 #endif
1755
1756     // build our custom render states
1757     fgBuildRenderStates();
1758
1759     // pass control off to the master GLUT event handler
1760     glutMainLoop();
1761
1762     // we never actually get here ... but to avoid compiler warnings,
1763     // etc.
1764     return 0;
1765 }
1766
1767
1768 // $$$ end - added VS Renganathan, 15 Oct 2K
1769 //         - added Venky         , 12 Nov 2K
1770
1771 void fgLoadDCS(void) {
1772
1773     ssgEntity *ship_obj = NULL;
1774     // double bz[3];
1775     // int j=0;
1776     char obj_filename[25];
1777
1778     for ( int k = 0; k < 32; k++ ) {
1779         ship_pos[k]=NULL;
1780     }
1781
1782     SGPath tile_path( globals->get_fg_root());
1783     tile_path.append( "Scenery" );
1784     tile_path.append( "Objects.txt" );
1785     sg_gzifstream in( tile_path.str() );
1786     if ( ! in.is_open() ) {
1787         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1788     } else {
1789
1790         SGPath modelpath( globals->get_fg_root() );
1791         modelpath.append( "Models" );
1792         modelpath.append( "Geometry" );
1793   
1794         SGPath texturepath( globals->get_fg_root() );
1795         texturepath.append( "Models" );
1796         texturepath.append( "Textures" );
1797  
1798         ssgModelPath( (char *)modelpath.c_str() );
1799         ssgTexturePath( (char *)texturepath.c_str() );
1800
1801         ship_sel = new ssgSelector;
1802
1803         char c;
1804         while ( ! in.eof() ) {
1805             in >> ::skipws;
1806             if ( in.get( c ) && c == '#' ) { 
1807                 in >> skipeol;
1808             } else { 
1809                 in.putback(c);
1810                 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1811                 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] <<  " " << obj_alt[objc] << endl;
1812                    int chj=getchar();*/
1813                 
1814                 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1815                 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1816                 
1817                 ship_pos[objc] = new ssgTransform;
1818        
1819                 // type "repeat" in objects.txt to load one more
1820                 // instance of the last object.
1821
1822                 if ( strcmp(obj_filename,"repeat") != 0) {
1823                     ship_obj = ssgLoadOBJ( obj_filename );
1824                 }
1825       
1826                 if ( ship_obj != NULL ) {
1827                     ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1828                     ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1829                 } else {
1830                     SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1831                             << obj_filename );
1832                 }
1833             
1834                 objc++;
1835
1836                 if (in.eof()) break;
1837             }
1838         } // while
1839
1840         SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1841
1842         ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1843         scene->addKid( ship_sel ); //add selector node to root node 
1844     }
1845
1846     return;
1847  }
1848
1849
1850 void fgUpdateDCS (void) {
1851
1852     // double eye_lat,eye_lon,eye_alt;
1853     // static double obj_head;
1854     double sl_radius,obj_latgc;
1855     // float nresultmat[4][4];
1856     // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1857     double bz[3];
1858
1859     // Instantaneous Geodetic Lat/Lon/Alt of moving object
1860     FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1861     
1862     // Deck should be the first object in objects.txt in case of fdm=ada
1863
1864     if (fgGetString("/sim/flight-model") == "ada") {
1865         obj_lon[0] = fdm->get_aux5()*SGD_DEGREES_TO_RADIANS;
1866         obj_lat[0] = fdm->get_aux6()*SGD_DEGREES_TO_RADIANS;
1867         obj_alt[0] = fdm->get_aux7();
1868     }
1869     
1870     for ( int m = 0; m < objc; m++ ) {
1871         //cout << endl <<  obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1872         //int v=getchar();
1873
1874         //Geodetic to Geocentric angles for rotation
1875         sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1876
1877         //moving object gbs-posn in cartesian coords
1878         Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1879         Point3D obj_pos = sgGeodToCart( obj_posn );
1880
1881         // Translate moving object w.r.t eye
1882         Point3D Objtrans = obj_pos-scenery.center;
1883         bz[0]=Objtrans.x();
1884         bz[1]=Objtrans.y();
1885         bz[2]=Objtrans.z();
1886
1887        // rotate dynamic objects for lat,lon & alt and other motion about its axes
1888         
1889         sgMat4 sgTRANS;
1890         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1891
1892         sgVec3 ship_fwd,ship_rt,ship_up;
1893         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1894         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1895         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1896
1897         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1898         sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1899         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1900         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1901         
1902         sgMat4 sgTUX;
1903         sgCopyMat4( sgTUX, sgROT_hdg );
1904         sgPostMultMat4( sgTUX, sgROT_lat );
1905         sgPostMultMat4( sgTUX, sgROT_lon );
1906         sgPostMultMat4( sgTUX, sgTRANS );
1907
1908         sgCoord shippos;
1909         sgSetCoord(&shippos, sgTUX );
1910         ship_pos[m]->setTransform( &shippos );
1911     }
1912     if ( ship_sel != NULL ) {
1913         ship_sel->select(0xFFFFFFFF);
1914     }
1915 }
1916
1917 // $$$ end - added VS Renganathan, 15 Oct 2K
1918 //           added Venky         , 12 Nov 2K