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