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