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