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