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