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