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