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