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