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