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