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