]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
MacOS changes contributed by Darrell Walisser (12/13/2000)
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson for OpenGL, started May 1997.
4 //
5 // Copyright (C) 1997 - 1999  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #ifdef FG_MATH_EXCEPTION_CLASH
29 #  include <math.h>
30 #endif
31
32 #ifdef HAVE_WINDOWS_H
33 #  include <windows.h>                     
34 #  include <float.h>                    
35 #endif
36
37 #include <GL/glut.h>
38 #include <simgear/xgl/xgl.h>
39
40 #include <stdio.h>
41 #include <string.h>
42 #include <string>
43
44 #ifdef HAVE_STDLIB_H
45 #   include <stdlib.h>
46 #endif
47
48 #ifdef HAVE_SYS_STAT_H
49 #  include <sys/stat.h>         // for stat()
50 #endif
51
52 #ifdef HAVE_UNISTD_H
53 #  include <unistd.h>           // for stat()
54 #endif
55
56 #include <plib/pu.h>
57 #include <plib/ssg.h>
58
59 #ifdef ENABLE_AUDIO_SUPPORT
60 #  include <plib/sl.h>
61 #  include <plib/sm.h>
62 #endif
63
64 #include <simgear/constants.h>  // for VERSION
65 #include <simgear/debug/logstream.hxx>
66 #include <simgear/math/polar3d.hxx>
67 #include <simgear/math/sg_random.h>
68 #include <simgear/misc/fgpath.hxx>
69 #include <simgear/sky/sky.hxx>
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/timing/lowleveltime.h>
72
73 #include <Include/general.hxx>
74
75 #include <Aircraft/aircraft.hxx>
76
77 #include <Autopilot/newauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/radiostack.hxx>
80 #include <Cockpit/steam.hxx>
81
82 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
83 #include <GUI/gui.h>
84 #include <Joystick/joystick.hxx>
85 #ifdef FG_NETWORK_OLK
86 #include <NetworkOLK/network.h>
87 #endif
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/tilemgr.hxx>
90 #include <Time/event.hxx>
91 #include <Time/fg_timer.hxx>
92 #include <Time/light.hxx>
93 #include <Time/sunpos.hxx>
94 #include <Time/tmp.hxx>
95
96 // begin - added Venky
97 //    $$$ begin - added VS Renganathan
98 #include <simgear/misc/fgstream.hxx>
99 #include <FDM/flight.hxx>
100 #include <FDM/ADA.hxx>
101 void fgLoadDCS (void);
102 void fgUpdateDCS (void);
103 ssgSelector *ship_sel=NULL;
104 // upto 32 instances of a same object can be loaded.
105 ssgTransform *ship_pos[32];
106 double obj_lat[32],obj_lon[32],obj_alt[32];
107 int objc=0;
108 //    $$$ end - added VS Renganathan
109 // end - added Venky
110
111 #ifndef FG_OLD_WEATHER
112 #  include <WeatherCM/FGLocalWeatherDatabase.h>
113 #else
114 #  include <Weather/weather.hxx>
115 #endif
116
117 #include "version.h"
118
119 #include "bfi.hxx"
120 #include "fg_init.hxx"
121 #include "fg_io.hxx"
122 #include "globals.hxx"
123 #include "keyboard.hxx"
124 #include "splash.hxx"
125
126 #ifdef macintosh
127 #  include <console.h>          // -dw- for command line dialog
128 #endif
129
130
131 // This is a record containing a bit of global housekeeping information
132 FGGeneral general;
133
134 // Specify our current idle function state.  This is used to run all
135 // our initializations out of the glutIdleLoop() so that we can get a
136 // splash screen up and running right away.
137 static int idle_state = 0;
138 static int global_multi_loop;
139
140 // attempt to avoid a large bounce at startup
141 static bool initial_freeze = true;
142
143 // Another hack
144 int use_signals = 0;
145
146 // forward declaration
147 void fgReshape( int width, int height );
148
149 // Global structures for the Audio library
150 #ifdef ENABLE_AUDIO_SUPPORT
151 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
152 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
153 slScheduler *audio_sched;
154 smMixer *audio_mixer;
155 slSample *s1;
156 slSample *s2;
157 #endif
158
159
160 // ssg variables
161 ssgRoot *scene = NULL;
162 ssgBranch *terrain = NULL;
163 ssgSelector *penguin_sel = NULL;
164 ssgTransform *penguin_pos = NULL;
165
166 ssgRoot *lighting = NULL;
167 ssgBranch *ground = NULL;
168 ssgBranch *airport = NULL;
169
170 #ifdef FG_NETWORK_OLK
171 ssgSelector *fgd_sel = NULL;
172 ssgTransform *fgd_pos = NULL;
173 //sgMat4 sgTUX;
174 #endif
175
176 // current fdm/position used for view
177 FGInterface cur_view_fdm;
178
179 // Sky structures
180 SGSky *thesky;
181
182 // hack
183 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
184 {
185   {  1.0f,  0.0f,  0.0f,  0.0f },
186   {  0.0f,  0.0f, -1.0f,  0.0f },
187   {  0.0f,  1.0f,  0.0f,  0.0f },
188   {  0.0f,  0.0f,  0.0f,  1.0f }
189 } ;
190
191 // The following defines flightgear options. Because glutlib will also
192 // want to parse its own options, those options must not be included here
193 // or they will get parsed by the main program option parser. Hence case
194 // is significant for any option added that might be in conflict with
195 // glutlib's parser.
196 //
197 // glutlib parses for:
198 //    -display
199 //    -direct   (invalid in Win32)
200 //    -geometry
201 //    -gldebug
202 //    -iconized
203 //    -indirect (invalid in Win32)
204 //    -synce
205 //
206 // Note that glutlib depends upon strings while this program's
207 // option parser wants only initial characters followed by numbers
208 // or pathnames.
209 //
210
211
212 ssgSimpleState *default_state;
213 ssgSimpleState *hud_and_panel;
214 ssgSimpleState *menus;
215
216 void fgBuildRenderStates( void ) {
217     default_state = new ssgSimpleState;
218     default_state->ref();
219     default_state->disable( GL_TEXTURE_2D );
220     default_state->enable( GL_CULL_FACE );
221     default_state->enable( GL_COLOR_MATERIAL );
222     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
223     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
224     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
225     default_state->disable( GL_BLEND );
226     default_state->disable( GL_ALPHA_TEST );
227     default_state->disable( GL_LIGHTING );
228
229     hud_and_panel = new ssgSimpleState;
230     hud_and_panel->ref();
231     hud_and_panel->disable( GL_CULL_FACE );
232     hud_and_panel->disable( GL_TEXTURE_2D );
233     hud_and_panel->disable( GL_LIGHTING );
234     hud_and_panel->enable( GL_BLEND );
235
236     menus = new ssgSimpleState;
237     menus->ref();
238     menus->disable( GL_CULL_FACE );
239     menus->disable( GL_TEXTURE_2D );
240     menus->enable( GL_BLEND );
241 }
242
243
244 // fgInitVisuals() -- Initialize various GL/view parameters
245 void fgInitVisuals( void ) {
246     fgLIGHT *l;
247
248     l = &cur_light_params;
249
250 #ifndef GLUT_WRONG_VERSION
251     // Go full screen if requested ...
252     if ( globals->get_options()->get_fullscreen() ) {
253         glutFullScreen();
254     }
255 #endif
256
257     // If enabled, normal vectors specified with glNormal are scaled
258     // to unit length after transformation.  See glNormal.
259     // glEnable( GL_NORMALIZE );
260
261     glEnable( GL_LIGHTING );
262     glEnable( GL_LIGHT0 );
263     glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
264
265     sgVec3 sunpos;
266     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
267     ssgGetLight( 0 ) -> setPosition( sunpos );
268
269     // glFogi (GL_FOG_MODE, GL_LINEAR);
270     glFogi (GL_FOG_MODE, GL_EXP2);
271     if ( (globals->get_options()->get_fog() == 1) || 
272          (globals->get_options()->get_shading() == 0) ) {
273         // if fastest fog requested, or if flat shading force fastest
274         glHint ( GL_FOG_HINT, GL_FASTEST );
275     } else if ( globals->get_options()->get_fog() == 2 ) {
276         glHint ( GL_FOG_HINT, GL_NICEST );
277     }
278     if ( globals->get_options()->get_wireframe() ) {
279         // draw wire frame
280         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
281     }
282
283     // This is the default anyways, but it can't hurt
284     glFrontFace ( GL_CCW );
285
286     // Just testing ...
287     // glEnable(GL_POINT_SMOOTH);
288     // glEnable(GL_LINE_SMOOTH);
289     // glEnable(GL_POLYGON_SMOOTH);      
290 }
291
292
293 // Update all Visuals (redraws anything graphics related)
294 void fgRenderFrame( void ) {
295     // Update the BFI.
296     FGBFI::update();
297
298     fgLIGHT *l = &cur_light_params;
299     static double last_visibility = -9999;
300
301     static GLfloat fog_exp_density;
302     static GLfloat fog_exp2_density;
303     static GLfloat fog_exp2_punch_through;
304     
305     // double angle;
306     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
307     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
308     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
309     // GLfloat mat_shininess[] = { 10.0 };
310     GLbitfield clear_mask;
311     
312     if ( idle_state != 1000 ) {
313         // still initializing, draw the splash screen
314         if ( globals->get_options()->get_splash_screen() == 1 ) {
315             fgSplashUpdate(0.0);
316         }
317     } else {
318         // idle_state is now 1000 meaning we've finished all our
319         // initializations and are running the main loop, so this will
320         // now work without seg faulting the system.
321
322         // printf("Ground = %.2f  Altitude = %.2f\n", scenery.cur_elev, 
323         //        FG_Altitude * FEET_TO_METER);
324     
325         // this is just a temporary hack, to make me understand Pui
326         // timerText -> setLabel (ctime (&t->cur_time));
327         // end of hack
328
329         // calculate our current position in cartesian space
330         scenery.center = scenery.next_center;
331         // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
332         //        scenery.center.y(), scenery.center.z());
333
334         FGViewerRPH *pilot_view =
335             (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
336
337         pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
338                                        cur_fdm_state->get_Lat_geocentric(), 
339                                        cur_fdm_state->get_Altitude() *
340                                        FEET_TO_METER );
341         pilot_view->set_sea_level_radius( cur_fdm_state->
342                                           get_Sea_level_radius() *
343                                           FEET_TO_METER ); 
344         pilot_view->set_rph( cur_fdm_state->get_Phi(),
345                              cur_fdm_state->get_Theta(),
346                              cur_fdm_state->get_Psi() );
347
348         FGViewerLookAt *chase_view =
349             (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
350
351         sgVec3 po;              // chase view pilot_offset
352         sgVec3 wup;             // chase view world up
353         sgSetVec3( po, 0.0, 0.0, 50.0 );
354         sgCopyVec3( wup, pilot_view->get_world_up() );
355         sgMat4 CXFM;            // chase view + pilot offset xform
356         sgMakeRotMat4( CXFM,
357                        chase_view->get_view_offset() * RAD_TO_DEG -
358                        cur_fdm_state->get_Psi() * RAD_TO_DEG,
359                        wup );
360         sgVec3 npo;             // new pilot offset after rotation
361         sgXformVec3( po, po, pilot_view->get_UP() );
362         sgXformVec3( npo, po, CXFM );
363
364         chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
365                                        cur_fdm_state->get_Lat_geocentric(), 
366                                        cur_fdm_state->get_Altitude() *
367                                        FEET_TO_METER );
368         chase_view->set_sea_level_radius( cur_fdm_state->
369                                           get_Sea_level_radius() *
370                                           FEET_TO_METER );
371         chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
372         chase_view->set_view_forward( pilot_view->get_view_pos() ); 
373         chase_view->set_view_up( wup );
374
375 #if 0
376         sgMat4 rph;
377         sgCopyMat4( rph, pilot_view->get_VIEW() );
378         cout << "RPH Matrix = " << endl;
379         int i, j;
380         for ( i = 0; i < 4; i++ ) {
381             for ( j = 0; j < 4; j++ ) {
382                 printf("%10.4f ", rph[i][j]);
383             }
384             cout << endl;
385         }
386
387         sgMat4 la;
388         sgCopyMat4( la, chase_view->get_VIEW() );
389         cout << "LookAt Matrix = " << endl;
390         for ( i = 0; i < 4; i++ ) {
391             for ( j = 0; j < 4; j++ ) {
392                 printf("%10.4f ", la[i][j]);
393             }
394             cout << endl;
395         }
396 #endif
397
398         // update view port
399         fgReshape( globals->get_options()->get_xsize(),
400                    globals->get_options()->get_ysize() );
401
402 #if 0
403         // swing and a miss
404
405         if ( ! fgPanelVisible() ) {
406             xglViewport( 0, 0 ,
407                          (GLint)(globals->get_options()->get_xsize()),
408                          (GLint)(globals->get_options()->get_ysize()) );
409         } else {
410             int view_h =
411                 int( (current_panel->getViewHeight() -
412                       current_panel->getYOffset())
413                      * (globals->get_options()->get_ysize() / 768.0) );
414             glViewport( 0, 
415                         (GLint)(globals->get_options()->get_ysize() - view_h),
416                         (GLint)(globals->get_options()->get_xsize()),
417                         (GLint)(view_h) );
418         }
419 #endif
420
421         // set the sun position
422         glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
423
424         clear_mask = GL_DEPTH_BUFFER_BIT;
425         if ( globals->get_options()->get_wireframe() ) {
426             clear_mask |= GL_COLOR_BUFFER_BIT;
427         }
428
429         if ( globals->get_options()->get_skyblend() ) {
430             if ( globals->get_options()->get_textures() ) {
431                 // glClearColor(black[0], black[1], black[2], black[3]);
432                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
433                              l->adj_fog_color[2], l->adj_fog_color[3]);
434                 clear_mask |= GL_COLOR_BUFFER_BIT;
435             }
436         } else {
437             glClearColor(l->sky_color[0], l->sky_color[1], 
438                          l->sky_color[2], l->sky_color[3]);
439             clear_mask |= GL_COLOR_BUFFER_BIT;
440         }
441         glClear( clear_mask );
442
443         // Tell GL we are switching to model view parameters
444
445         // I really should create a derived ssg node or use a call
446         // back or something so that I can draw the sky within the
447         // ssgCullAndDraw() function, but for now I just mimic what
448         // ssg does to set up the model view matrix
449         glMatrixMode(GL_MODELVIEW);
450         glLoadIdentity();
451         ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
452
453         // set the opengl state to known default values
454         default_state->force();
455
456         // update fog params if visibility has changed
457 #ifndef FG_OLD_WEATHER
458         thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
459 #else
460         thesky->set_visibility( current_weather.get_visibility() );
461 #endif
462
463         thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
464                                 
465                             ( global_multi_loop * 
466                               globals->get_options()->get_speed_up() ) /
467                             (double)globals->get_options()->get_model_hz() );
468
469         double actual_visibility = thesky->get_visibility();
470         // cout << "actual visibility = " << actual_visibility << endl;
471
472         if ( actual_visibility != last_visibility ) {
473             last_visibility = actual_visibility;
474
475             // cout << "----> updating fog params" << endl;
476                 
477             // for GL_FOG_EXP
478             fog_exp_density = -log(0.01 / actual_visibility);
479     
480             // for GL_FOG_EXP2
481             fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
482             fog_exp2_punch_through = sqrt( -log(0.01) ) / 
483                 ( actual_visibility * 1.5 );
484         }
485
486         // Set correct opengl fog density
487         glFogf (GL_FOG_DENSITY, fog_exp2_density);
488
489         // update the sky dome
490         if ( globals->get_options()->get_skyblend() ) {
491             /* cout << "thesky->repaint() sky_color = "
492                  << cur_light_params.sky_color[0] << " "
493                  << cur_light_params.sky_color[1] << " "
494                  << cur_light_params.sky_color[2] << " "
495                  << cur_light_params.sky_color[3] << endl;
496             cout << "    fog = "
497                  << cur_light_params.fog_color[0] << " "
498                  << cur_light_params.fog_color[1] << " "
499                  << cur_light_params.fog_color[2] << " "
500                  << cur_light_params.fog_color[3] << endl;
501             cout << "    sun_angle = " << cur_light_params.sun_angle
502                  << "    moon_angle = " << cur_light_params.moon_angle
503                  << endl; */
504             thesky->repaint( cur_light_params.sky_color,
505                              cur_light_params.adj_fog_color,
506                              cur_light_params.sun_angle,
507                              cur_light_params.moon_angle,
508                              globals->get_ephem()->getNumPlanets(),
509                              globals->get_ephem()->getPlanets(),
510                              globals->get_ephem()->getNumStars(),
511                              globals->get_ephem()->getStars() );
512  
513             /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
514                  << view_pos[1] << " " << view_pos[2] << endl;
515             cout << "    zero_elev = " << zero_elev[0] << " "
516                  << zero_elev[1] << " " << zero_elev[2]
517                  << " lon = " << cur_fdm_state->get_Longitude()
518                  << " lat = " << cur_fdm_state->get_Latitude() << endl;
519             cout << "    sun_rot = " << cur_light_params.sun_rotation
520                  << " gst = " << SGTime::cur_time_params->getGst() << endl;
521             cout << "    sun ra = " << globals->get_ephem()->getSunRightAscension()
522                  << " sun dec = " << globals->get_ephem()->getSunDeclination() 
523                  << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
524                  << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
525
526             thesky->reposition( globals->get_current_view()->get_view_pos(),
527                                 globals->get_current_view()->get_zero_elev(),
528                                 globals->get_current_view()->get_world_up(),
529                                 cur_fdm_state->get_Longitude(),
530                                 cur_fdm_state->get_Latitude(),
531                                 cur_fdm_state->get_Altitude() * FEET_TO_METER,
532                                 cur_light_params.sun_rotation,
533                                 globals->get_time_params()->getGst(),
534                                 globals->get_ephem()->getSunRightAscension(),
535                                 globals->get_ephem()->getSunDeclination(),
536                                 50000.0,
537                                 globals->get_ephem()->getMoonRightAscension(),
538                                 globals->get_ephem()->getMoonDeclination(),
539                                 50000.0 );
540         }
541
542         glEnable( GL_DEPTH_TEST );
543         if ( globals->get_options()->get_fog() > 0 ) {
544             glEnable( GL_FOG );
545             glFogi( GL_FOG_MODE, GL_EXP2 );
546             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
547         }
548
549         // set lighting parameters
550         GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
551         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
552         glLightfv( GL_LIGHT0, GL_AMBIENT, black );
553         glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
554         // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
555
556         // texture parameters
557         // glEnable( GL_TEXTURE_2D );
558         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
559         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
560         // set base color (I don't think this is doing anything here)
561         // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
562         //  (GL_FRONT, GL_DIFFUSE, white);
563         // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
564         // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
565
566         sgVec3 sunpos;
567         sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
568         ssgGetLight( 0 ) -> setPosition( sunpos );
569
570         // glMatrixMode( GL_PROJECTION );
571         // glLoadIdentity();
572         float fov = globals->get_current_view()->get_fov();
573         ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
574
575         double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
576             - scenery.cur_elev;
577
578         // FG_LOG( FG_ALL, FG_INFO, "visibility is " 
579         //         << current_weather.get_visibility() );
580             
581         if ( agl > 10.0 ) {
582             ssgSetNearFar( 10.0f, 120000.0f );
583         } else {
584             ssgSetNearFar( 0.5f, 120000.0f );
585         }
586
587         if ( globals->get_viewmgr()->get_current() == 0 ) {
588             // disable TuX
589             penguin_sel->select(0);
590         } else { 
591             // enable TuX and set up his position and orientation
592             penguin_sel->select(1);
593
594             FGViewerRPH *pilot_view =
595                 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
596
597             sgMat4 sgTRANS;
598             sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
599
600             sgVec3 ownship_up;
601             sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
602
603             sgMat4 sgROT;
604             sgMakeRotMat4( sgROT, -90.0, ownship_up );
605
606             // sgMat4 sgTMP;
607             // sgMat4 sgTUX;
608             // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
609             // sgMultMat4( sgTUX, sgTMP, sgTRANS );
610
611             // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
612             sgMat4 sgTUX;
613             sgCopyMat4( sgTUX, sgROT );
614             sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
615             sgPostMultMat4( sgTUX, sgTRANS );
616         
617             sgCoord tuxpos;
618             sgSetCoord( &tuxpos, sgTUX );
619             penguin_pos->setTransform( &tuxpos );
620         }
621
622         // $$$ begin - added VS Renganthan 17 Oct 2K
623         fgUpdateDCS();
624         // $$$ end - added VS Renganthan 17 Oct 2K
625
626 # ifdef FG_NETWORK_OLK
627         if ( globals->get_options()->get_network_olk() ) {
628             sgCoord fgdpos;
629             other = head->next;             /* put listpointer to start  */
630             while ( other != tail) {        /* display all except myself */
631                 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
632                     other->fgd_sel->select(1);
633                     sgSetCoord( &fgdpos, other->sgFGD_COORD );
634                     other->fgd_pos->setTransform( &fgdpos );
635                 }
636                 other = other->next;
637             }
638
639             // fgd_sel->select(1);
640             // sgCopyMat4( sgTUX, current_view.sgVIEW);
641             // sgCoord fgdpos;
642             // sgSetCoord( &fgdpos, sgFGD_VIEW );
643             // fgd_pos->setTransform( &fgdpos);
644         }
645 # endif
646
647         // position tile nodes and update range selectors
648         global_tile_mgr.prep_ssg_nodes();
649
650         // draw the sky backdrop
651         thesky->preDraw();
652
653         // draw the ssg scene
654         glEnable( GL_DEPTH_TEST );
655         ssgCullAndDraw( scene );
656
657         // change state for lighting here
658
659         // draw lighting
660         // Set punch through fog density
661         glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
662
663         ssgCullAndDraw( lighting );
664
665         // draw the sky cloud layers
666         thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
667
668         // display HUD && Panel
669         glDisable( GL_FOG );
670         glDisable( GL_DEPTH_TEST );
671         // glDisable( GL_CULL_FACE );
672         // glDisable( GL_TEXTURE_2D );
673         hud_and_panel->apply();
674         fgCockpitUpdate();
675
676         // We can do translucent menus, so why not. :-)
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     FG_LOG( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1272
1273     GLint tmp;
1274     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1275     general.set_glMaxTexSize( tmp );
1276     FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1277
1278     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1279     general.set_glDepthBits( tmp );
1280     FG_LOG ( FG_GENERAL, FG_INFO, "Depth buffer bits = " << tmp );
1281
1282 #if 0
1283     // try to determine if we should adjust the initial default
1284     // display resolution.  The options class defaults (is
1285     // initialized) to 640x480.
1286     string renderer = general.glRenderer;
1287
1288     // currently we only know how to deal with Mesa/Glide/Voodoo cards
1289     if ( renderer.find( "Glide" ) != string::npos ) {
1290         FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1291         if ( renderer.find( "FB/8" ) != string::npos ) {
1292             // probably a voodoo-2
1293             if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1294                 // probably two SLI'd Voodoo-2's
1295                 globals->get_options()->set_xsize( 1024 );
1296                 globals->get_options()->set_ysize( 768 );
1297                 FG_LOG( FG_GENERAL, FG_INFO,
1298                         "It looks like you have two sli'd voodoo-2's." << endl
1299                         << "upgrading your win resolution to 1024 x 768" );
1300                 glutReshapeWindow(1024, 768);
1301             } else {
1302                 // probably a single non-SLI'd Voodoo-2
1303                 globals->get_options()->set_xsize( 800 );
1304                 globals->get_options()->set_ysize( 600 );
1305                 FG_LOG( FG_GENERAL, FG_INFO,
1306                         "It looks like you have a voodoo-2." << endl
1307                         << "upgrading your win resolution to 800 x 600" );
1308                 glutReshapeWindow(800, 600);
1309             }
1310         } else if ( renderer.find( "FB/2" ) != string::npos ) {
1311             // probably a voodoo-1, stick with the default
1312         }
1313     } else {
1314         // we have no special knowledge of this card, stick with the default
1315     }
1316 #endif
1317
1318     return(1);
1319 }
1320
1321
1322 // Initialize GLUT event handlers
1323 int fgGlutInitEvents( void ) {
1324     // call fgReshape() on window resizes
1325     glutReshapeFunc( fgReshape );
1326
1327     // call GLUTkey() on keyboard event
1328     glutKeyboardFunc( GLUTkey );
1329     glutSpecialFunc( GLUTspecialkey );
1330
1331     // call guiMouseFunc() whenever our little rodent is used
1332     glutMouseFunc ( guiMouseFunc );
1333     glutMotionFunc (guiMotionFunc );
1334     glutPassiveMotionFunc (guiMotionFunc );
1335
1336     // call fgMainLoop() whenever there is
1337     // nothing else to do
1338     glutIdleFunc( fgIdleFunction );
1339
1340     // draw the scene
1341     glutDisplayFunc( fgRenderFrame );
1342
1343     return(1);
1344 }
1345
1346
1347 // Main ...
1348 int main( int argc, char **argv ) {
1349
1350 #if defined( macintosh )
1351     freopen ("stdout.txt", "w", stdout );
1352     freopen ("stderr.txt", "w", stderr );
1353     argc = ccommand( &argv );
1354 #endif
1355
1356 #ifdef HAVE_BC5PLUS
1357     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1358 #endif
1359
1360     // set default log levels
1361     fglog().setLogLevels( FG_ALL, FG_INFO );
1362
1363     FG_LOG( FG_GENERAL, FG_INFO, "FlightGear:  Version "
1364             << FLIGHTGEAR_VERSION << endl );
1365
1366     // seed the random number generater
1367     sg_srandom_time();
1368
1369     // Allocate global data structures.  This needs to happen before
1370     // we parse command line options
1371     globals = new FGGlobals;
1372
1373     SGRoute *route = new SGRoute;
1374     globals->set_route( route );
1375
1376     FGOptions *options = new FGOptions;
1377     globals->set_options( options );
1378
1379     FGViewMgr *viewmgr = new FGViewMgr;
1380     globals->set_viewmgr( viewmgr );
1381
1382     FGViewerRPH *pv = new FGViewerRPH;
1383     globals->get_viewmgr()->add_view( pv );
1384
1385     FGViewerLookAt *chase = new FGViewerLookAt;
1386     globals->get_viewmgr()->add_view( chase );
1387
1388     // set current view to 0 (first) which is our main pilot view
1389     globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1390
1391     // Scan the config file(s) and command line options to see if
1392     // fg_root was specified (ignore all other options for now)
1393     fgInitFGRoot(argc, argv);
1394
1395     // cout << "1. airport_id = " << globals->get_options()->get_airport_id() << endl;
1396
1397     // Read global preferences from $FG_ROOT/preferences.xml
1398     FGPath props_path(globals->get_options()->get_fg_root());
1399     props_path.append("preferences.xml");
1400     FG_LOG(FG_INPUT, FG_INFO, "Reading global preferences");
1401     if (!readPropertyList(props_path.str(), &current_properties)) {
1402       FG_LOG(FG_INPUT, FG_ALERT, "Failed to read global preferences from "
1403              << props_path.str());
1404     } else {
1405       FG_LOG(FG_INPUT, FG_INFO, "Finished Reading global preferences");
1406     }
1407
1408     // cout << "2. airport_id = " << globals->get_options()->get_airport_id() << endl;
1409
1410     // Initialize the Aircraft directory to "" (UIUC)
1411     aircraft_dir = "";
1412
1413     // Load the configuration parameters
1414     if ( !fgInitConfig(argc, argv) ) {
1415         FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1416         exit(-1);
1417     }
1418
1419     // Initialize the Window/Graphics environment.
1420     if( !fgGlutInit(&argc, argv) ) {
1421         FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1422         exit(-1);
1423     }
1424
1425     // Initialize the various GLUT Event Handlers.
1426     if( !fgGlutInitEvents() ) {
1427         FG_LOG( FG_GENERAL, FG_ALERT, 
1428                 "GLUT event handler initialization failed ..." );
1429         exit(-1);
1430     }
1431  
1432     // Initialize ssg (from plib).  Needs to come before we do any
1433     // other ssg stuff, but after opengl/glut has been initialized.
1434     ssgInit();
1435
1436     // Initialize the user interface (we need to do this before
1437     // passing off control to glut and before fgInitGeneral to get our
1438     // fonts !!!
1439     guiInit();
1440
1441     // set current_options lon/lat if an airport id is specified
1442     // cout << "3. airport_id = " << globals->get_options()->get_airport_id() << endl;
1443     if ( globals->get_options()->get_airport_id().length() ) {
1444         // fgSetPosFromAirportID( globals->get_options()->get_airport_id() );
1445         fgSetPosFromAirportIDandHdg( globals->get_options()->get_airport_id(),
1446                                      globals->get_options()->get_heading() );
1447     }
1448
1449     // Initialize time
1450     FGPath zone( globals->get_options()->get_fg_root() );
1451     zone.append( "Timezone" );
1452     SGTime *t = new SGTime( globals->get_options()->get_lon() * DEG_TO_RAD,
1453                             globals->get_options()->get_lat() * DEG_TO_RAD,
1454                             zone.str() );
1455
1456     // Handle potential user specified time offsets
1457     time_t cur_time = t->get_cur_time();
1458     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1459     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1460     time_t aircraftLocalTime = 
1461         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1462
1463     // Okay, we now have six possible scenarios
1464     switch ( globals->get_options()->get_time_offset_type() ) {
1465     case FGOptions::FG_TIME_SYS_OFFSET:
1466         globals->set_warp( globals->get_options()->get_time_offset() );
1467         break;
1468     case FGOptions::FG_TIME_GMT_OFFSET:
1469         globals->set_warp( globals->get_options()->get_time_offset() - 
1470                            (currGMT - systemLocalTime) );
1471         break;
1472     case FGOptions::FG_TIME_LAT_OFFSET:
1473         globals->set_warp( globals->get_options()->get_time_offset() - 
1474                            (aircraftLocalTime - systemLocalTime) );
1475         break;
1476     case FGOptions::FG_TIME_SYS_ABSOLUTE:
1477         globals->set_warp( globals->get_options()->get_time_offset() -
1478                            cur_time );
1479         //printf("warp = %d\n", warp); 
1480         break;
1481     case FGOptions::FG_TIME_GMT_ABSOLUTE:
1482         globals->set_warp( globals->get_options()->get_time_offset() -
1483                            currGMT );
1484         break;
1485     case FGOptions::FG_TIME_LAT_ABSOLUTE:
1486         globals->set_warp( globals->get_options()->get_time_offset() - 
1487                            (aircraftLocalTime - systemLocalTime) - 
1488                            cur_time ); 
1489         break;
1490     default:
1491         FG_LOG( FG_GENERAL, FG_ALERT, "Unsupported type" );
1492         exit( -1 );
1493     }
1494
1495     FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = " 
1496             << globals->get_warp() );
1497
1498     globals->set_warp_delta( 0 );
1499
1500     t->update( 0.0, 0.0, globals->get_warp() );
1501
1502     globals->set_time_params( t );
1503
1504     // Do some quick general initializations
1505     if( !fgInitGeneral()) {
1506         FG_LOG( FG_GENERAL, FG_ALERT, 
1507                 "General initializations failed ..." );
1508         exit(-1);
1509     }
1510
1511     //
1512     // some ssg test stuff (requires data from the plib source
1513     // distribution) specifically from the ssg tux example
1514     //
1515
1516     FGPath modelpath( globals->get_options()->get_fg_root() );
1517     // modelpath.append( "Models" );
1518     // modelpath.append( "Geometry" );
1519   
1520     FGPath texturepath( globals->get_options()->get_fg_root() );
1521     texturepath.append( "Models" );
1522     texturepath.append( "Textures" );
1523   
1524     ssgModelPath( (char *)modelpath.c_str() );
1525     ssgTexturePath( (char *)texturepath.c_str() );
1526
1527     // Scene graph root
1528     scene = new ssgRoot;
1529     scene->setName( "Scene" );
1530
1531     lighting = new ssgRoot;
1532     lighting->setName( "Lighting" );
1533
1534     // Initialize the sky
1535     FGPath ephem_data_path( globals->get_options()->get_fg_root() );
1536     ephem_data_path.append( "Astro" );
1537     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1538     ephem->update( globals->get_time_params()->getMjd(),
1539                    globals->get_time_params()->getLst(),
1540                    0.0 );
1541     globals->set_ephem( ephem );
1542
1543     FGPath sky_tex_path( globals->get_options()->get_fg_root() );
1544     sky_tex_path.append( "Textures" );
1545     sky_tex_path.append( "Sky" );
1546     thesky = new SGSky;
1547     thesky->texture_path( sky_tex_path.str() );
1548
1549     thesky->build( 550.0, 550.0,
1550                    globals->get_ephem()->getNumPlanets(), 
1551                    globals->get_ephem()->getPlanets(), 60000.0,
1552                    globals->get_ephem()->getNumStars(),
1553                    globals->get_ephem()->getStars(), 60000.0 );
1554
1555     if ( globals->get_options()->get_clouds() == true ) {
1556         thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1557                                  SG_CLOUD_MOSTLY_SUNNY );
1558         thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1559                                  SG_CLOUD_CIRRUS );
1560         // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1561         //                          SG_CLOUD_MOSTLY_SUNNY );
1562         // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1563         // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1564     }
1565
1566     // Initialize MagVar model
1567     SGMagVar *magvar = new SGMagVar();
1568     globals->set_mag( magvar );
1569
1570     // Terrain branch
1571     terrain = new ssgBranch;
1572     terrain->setName( "Terrain" );
1573     scene->addKid( terrain );
1574
1575     // Lighting
1576     ground = new ssgBranch;
1577     ground->setName( "Ground Lighting" );
1578     lighting->addKid( ground );
1579
1580     airport = new ssgBranch;
1581     airport->setName( "Airport Lighting" );
1582     lighting->addKid( airport );
1583
1584     // temporary visible aircraft "own ship"
1585     penguin_sel = new ssgSelector;
1586     penguin_pos = new ssgTransform;
1587     string tux_path =
1588       current_properties.getStringValue("/sim/model/path",
1589                                         "Models/Geometry/glider.ac");
1590     ssgEntity *tux_obj = ssgLoad((char *)(tux_path.c_str()));
1591
1592     // align the model properly for FGFS
1593     ssgTransform *tux_align = new ssgTransform;
1594     tux_align->addKid(tux_obj);
1595     sgMat4 rot_matrix;
1596     sgMat4 off_matrix;
1597     sgMat4 res_matrix;
1598     float h_rot =
1599       current_properties.getFloatValue("/sim/model/h-rotation", 0.0);
1600     float p_rot =
1601       current_properties.getFloatValue("/sim/model/p-rotation", 0.0);
1602     float r_rot =
1603       current_properties.getFloatValue("/sim/model/r-rotation", 0.0);
1604     float x_off =
1605       current_properties.getFloatValue("/sim/model/x-offset", 0.0);
1606     float y_off =
1607       current_properties.getFloatValue("/sim/model/y-offset", 0.0);
1608     float z_off =
1609       current_properties.getFloatValue("/sim/model/z-offset", 0.0);
1610     sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1611     sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1612     sgMultMat4(res_matrix, off_matrix, rot_matrix);
1613     tux_align->setTransform(res_matrix);
1614
1615     penguin_pos->addKid( tux_align );
1616     penguin_sel->addKid( penguin_pos );
1617     ssgFlatten( tux_obj );
1618     ssgStripify( penguin_sel );
1619     penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1620     scene->addKid( penguin_sel );
1621
1622     // $$$ begin - added VS Renganthan 17 Oct 2K
1623     fgLoadDCS();
1624     // $$$ end - added VS Renganthan 17 Oct 2K
1625
1626 #ifdef FG_NETWORK_OLK
1627     // Do the network intialization
1628     if ( globals->get_options()->get_network_olk() ) {
1629         printf("Multipilot mode %s\n", fg_net_init( scene ) );
1630     }
1631 #endif
1632
1633     // build our custom render states
1634     fgBuildRenderStates();
1635
1636     // pass control off to the master GLUT event handler
1637     glutMainLoop();
1638
1639     // we never actually get here ... but to avoid compiler warnings,
1640     // etc.
1641     return 0;
1642 }
1643
1644
1645 // $$$ end - added VS Renganathan, 15 Oct 2K
1646 //         - added Venky         , 12 Nov 2K
1647
1648 void fgLoadDCS(void) {
1649
1650     ssgEntity *ship_obj;
1651     double bz[3];
1652     int j=0;
1653     char obj_filename[25];
1654
1655     for (int k=0;k<32;k++)
1656     {
1657         ship_pos[k]=NULL;
1658     }
1659
1660     FGPath tile_path( globals->get_options()->get_fg_root());
1661     tile_path.append( "Scenery" );
1662     tile_path.append( "Objects.txt" );
1663     fg_gzifstream in( tile_path.str() );
1664     if ( ! in.is_open() ) {
1665         FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1666     }
1667
1668     FGPath modelpath( globals->get_options()->get_fg_root() );
1669     modelpath.append( "Models" );
1670     modelpath.append( "Geometry" );
1671   
1672     FGPath texturepath( globals->get_options()->get_fg_root() );
1673     texturepath.append( "Models" );
1674     texturepath.append( "Textures" );
1675  
1676     ssgModelPath( (char *)modelpath.c_str() );
1677     ssgTexturePath( (char *)texturepath.c_str() );
1678
1679     ship_sel = new ssgSelector;
1680
1681     char c;
1682     while ( ! in.eof() ) 
1683     {
1684        in >> ::skipws;
1685        if ( in.get( c ) && c == '#' )
1686        { 
1687             in >> skipeol;
1688        }
1689        else 
1690        { 
1691         in.putback(c);
1692                 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1693 /*              cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] <<  " " << obj_alt[objc] << endl;
1694         int chj=getchar();*/
1695                 
1696               obj_lon[objc] *=DEG_TO_RAD;
1697         obj_lat[objc] *=DEG_TO_RAD;
1698     
1699             ship_pos[objc] = new ssgTransform;
1700        
1701        
1702         // type "repeat" in objects.txt to load one more instance of the last object.
1703
1704         if ( strcmp(obj_filename,"repeat") != 0)
1705                   ship_obj = ssgLoadOBJ( obj_filename );
1706       
1707               if ( ship_obj != NULL ) 
1708             {
1709                         ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1710                         ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1711                         }
1712         else
1713                 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << obj_filename );
1714             
1715         if (in.eof()) break;
1716             objc++;
1717          }
1718      } // while
1719
1720     ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1721     scene->addKid( ship_sel ); //add selector node to root node
1722     return;
1723  }
1724
1725
1726 void fgUpdateDCS (void) {
1727
1728     double eye_lat,eye_lon,eye_alt;
1729     static double obj_head;
1730     double sl_radius,obj_latgc;
1731     float nresultmat[4][4];
1732     sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1733     double bz[3];
1734
1735     // Instantaneous Geodetic Lat/Lon/Alt of moving object
1736     FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1737     
1738     // Deck should be the first object in objects.txt in case of fdm=ada
1739
1740     if ((globals->get_options()->get_flight_model()) == 4 )
1741     {
1742       obj_lon[0] = fdm->get_aux5()*DEG_TO_RAD;
1743       obj_lat[0] = fdm->get_aux6()*DEG_TO_RAD;
1744       obj_alt[0] = fdm->get_aux7();
1745     }
1746     
1747     for (int m=0; m<=objc; m++)
1748     {
1749         //cout << endl <<  obj_lat[m]*RAD_TO_DEG << " " << obj_lon[m]*RAD_TO_DEG << " " << obj_alt[m] << " " << objc << endl;
1750         //int v=getchar();
1751
1752         //Geodetic to Geocentric angles for rotation
1753         sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1754
1755         //moving object gbs-posn in cartesian coords
1756         Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1757         Point3D obj_pos = sgGeodToCart( obj_posn );
1758
1759         // Translate moving object w.r.t eye
1760         Point3D Objtrans = obj_pos-scenery.center;
1761         bz[0]=Objtrans.x();
1762         bz[1]=Objtrans.y();
1763         bz[2]=Objtrans.z();
1764
1765        // rotate dynamic objects for lat,lon & alt and other motion about its axes
1766         
1767         sgMat4 sgTRANS;
1768         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1769
1770         sgVec3 ship_fwd,ship_rt,ship_up;
1771         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1772         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1773         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1774
1775         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1776         sgMakeRotMat4( sgROT_lon, obj_lon[m]*RAD_TO_DEG, ship_up );
1777         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1778         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1779         
1780         sgMat4 sgTUX;
1781         sgCopyMat4( sgTUX, sgROT_hdg );
1782         sgPostMultMat4( sgTUX, sgROT_lat );
1783         sgPostMultMat4( sgTUX, sgROT_lon );
1784         sgPostMultMat4( sgTUX, sgTRANS );
1785
1786         sgCoord shippos;
1787         sgSetCoord(&shippos, sgTUX );
1788         ship_pos[m]->setTransform( &shippos );
1789     }
1790    if ( ship_sel != NULL ) 
1791         ship_sel->select(0xFFFFFFFF);
1792   }
1793
1794 // $$$ end - added VS Renganathan, 15 Oct 2K
1795 //           added Venky         , 12 Nov 2K