]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Various MSVC patches.
[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 #include <simgear/compiler.h>
29 #include <simgear/misc/exception.hxx>
30
31 #ifdef SG_MATH_EXCEPTION_CLASH
32 #  include <math.h>
33 #endif
34
35 #ifdef HAVE_WINDOWS_H
36 #  include <windows.h>
37 #  include <float.h>
38 #endif
39
40 #include <GL/glut.h>
41 #include <GL/gl.h>
42
43 #include <stdio.h>
44 #include <string.h>
45 #include <string>
46
47 #ifdef HAVE_STDLIB_H
48 #   include <stdlib.h>
49 #endif
50
51 #ifdef HAVE_SYS_STAT_H
52 #  include <sys/stat.h>         // for stat()
53 #endif
54
55 #ifdef HAVE_UNISTD_H
56 #  include <unistd.h>           // for stat()
57 #endif
58
59 // #ifdef HAVE_LIBX11
60 // #  include <GL/glext.h>
61 // #endif
62
63 #include <plib/netChat.h>
64 #include <plib/pu.h>
65 #include <plib/ssg.h>
66
67 #include <simgear/constants.h>  // for VERSION
68 #include <simgear/debug/logstream.hxx>
69 #include <simgear/math/polar3d.hxx>
70 #include <simgear/math/sg_random.h>
71 #include <simgear/misc/sg_path.hxx>
72 #include <simgear/sky/sky.hxx>
73 #include <simgear/timing/sg_time.hxx>
74 #include <simgear/timing/lowleveltime.h>
75
76 #include <Include/general.hxx>
77
78 #include <Aircraft/aircraft.hxx>
79
80 #include <Autopilot/newauto.hxx>
81 #include <Cockpit/cockpit.hxx>
82 #include <Cockpit/radiostack.hxx>
83 #include <Cockpit/steam.hxx>
84
85 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
86 #include <GUI/gui.h>
87 #include <GUI/sgVec3Slider.hxx>
88 // #include <Joystick/joystick.hxx>
89 #ifdef FG_NETWORK_OLK
90 #include <NetworkOLK/network.h>
91 #endif
92 #include <Objects/matlib.hxx>
93 #include <Scenery/scenery.hxx>
94 #include <Scenery/tilemgr.hxx>
95 #ifdef ENABLE_AUDIO_SUPPORT
96 #  include <Sound/soundmgr.hxx>
97 #  include <Sound/morse.hxx>
98 #endif
99 #include <Time/event.hxx>
100 #include <Time/fg_timer.hxx>
101 #include <Time/light.hxx>
102 #include <Time/sunpos.hxx>
103 #include <Time/tmp.hxx>
104
105 #include <Input/input.hxx>
106
107 // ADA
108 #include <simgear/misc/sgstream.hxx>
109 #include <simgear/math/point3d.hxx>
110 #include <FDM/flight.hxx>
111 #include <FDM/ADA.hxx>
112 #include <Scenery/tileentry.hxx>
113 // Should already be inlcluded by gl.h if needed by your platform so
114 // we shouldn't include this here.
115 // #include <GL/glext.h>
116 // PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
117 // PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
118 float default_attenuation[3] = {1.0, 0.0, 0.0};
119 //Required for using GL_extensions
120 void fgLoadDCS (void);
121 void fgUpdateDCS (void);
122 ssgSelector *ship_sel=NULL;
123 // upto 32 instances of a same object can be loaded.
124 ssgTransform *ship_pos[32];
125 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
126 int objc=0;
127 ssgSelector *lightpoints_brightness = new ssgSelector;
128 ssgTransform *lightpoints_transform = new ssgTransform;
129 FGTileEntry *dummy_tile;
130 sgVec3 rway_ols;
131 // ADA
132
133 #ifndef FG_OLD_WEATHER
134 #  include <WeatherCM/FGLocalWeatherDatabase.h>
135 #else
136 #  include <Weather/weather.hxx>
137 #endif
138
139 #include "version.h"
140
141 #include "fg_init.hxx"
142 #include "fg_io.hxx"
143 #include "fg_props.hxx"
144 #include "globals.hxx"
145 #include "splash.hxx"
146 #include "viewmgr.hxx"
147
148 #ifdef macintosh
149 #  include <console.h>          // -dw- for command line dialog
150 #endif
151
152
153 // This is a record containing a bit of global housekeeping information
154 FGGeneral general;
155
156 // Specify our current idle function state.  This is used to run all
157 // our initializations out of the glutIdleLoop() so that we can get a
158 // splash screen up and running right away.
159 static int idle_state = 0;
160 static long global_multi_loop;
161
162 // attempt to avoid a large bounce at startup
163 static bool initial_freeze = true;
164
165 // forward declaration
166 void fgReshape( int width, int height );
167
168 // Global structures for the Audio library
169 #ifdef ENABLE_AUDIO_SUPPORT
170    static FGSimpleSound *s1;
171    static FGSimpleSound *s2;
172 #endif
173
174
175 // ssg variables
176 ssgRoot *scene = NULL;
177 ssgBranch *terrain = NULL;
178
179 // aircraft model stuff
180 ssgSelector *acmodel_selector = NULL;
181 ssgTransform *acmodel_pos = NULL;
182 ssgSelector *prop_selector = NULL;
183 ssgSelector *flaps_selector = NULL;
184 int acmodel_npropsettings;
185 int acmodel_proprpms[4][2];  // different propeller settings
186
187 ssgRoot *lighting = NULL;
188 ssgBranch *ground = NULL;
189 ssgBranch *airport = NULL;
190
191 #ifdef FG_NETWORK_OLK
192 ssgSelector *fgd_sel = NULL;
193 ssgTransform *fgd_pos = NULL;
194 #endif
195
196 // current fdm/position used for view
197 FGInterface cur_view_fdm;
198
199 // Sky structures
200 SGSky *thesky;
201
202 // hack
203 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
204 {
205   {  1.0f,  0.0f,  0.0f,  0.0f },
206   {  0.0f,  0.0f, -1.0f,  0.0f },
207   {  0.0f,  1.0f,  0.0f,  0.0f },
208   {  0.0f,  0.0f,  0.0f,  1.0f }
209 } ;
210
211 // The following defines flightgear options. Because glutlib will also
212 // want to parse its own options, those options must not be included here
213 // or they will get parsed by the main program option parser. Hence case
214 // is significant for any option added that might be in conflict with
215 // glutlib's parser.
216 //
217 // glutlib parses for:
218 //    -display
219 //    -direct   (invalid in Win32)
220 //    -geometry
221 //    -gldebug
222 //    -iconized
223 //    -indirect (invalid in Win32)
224 //    -synce
225 //
226 // Note that glutlib depends upon strings while this program's
227 // option parser wants only initial characters followed by numbers
228 // or pathnames.
229 //
230
231
232 ssgSimpleState *default_state;
233 ssgSimpleState *hud_and_panel;
234 ssgSimpleState *menus;
235
236 void fgBuildRenderStates( void ) {
237     default_state = new ssgSimpleState;
238     default_state->ref();
239     default_state->disable( GL_TEXTURE_2D );
240     default_state->enable( GL_CULL_FACE );
241     default_state->enable( GL_COLOR_MATERIAL );
242     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
243     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
244     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
245     default_state->disable( GL_BLEND );
246     default_state->disable( GL_ALPHA_TEST );
247     default_state->disable( GL_LIGHTING );
248
249     hud_and_panel = new ssgSimpleState;
250     hud_and_panel->ref();
251     hud_and_panel->disable( GL_CULL_FACE );
252     hud_and_panel->disable( GL_TEXTURE_2D );
253     hud_and_panel->disable( GL_LIGHTING );
254     hud_and_panel->enable( GL_BLEND );
255
256     menus = new ssgSimpleState;
257     menus->ref();
258     menus->disable( GL_CULL_FACE );
259     menus->disable( GL_TEXTURE_2D );
260     menus->enable( GL_BLEND );
261 }
262
263 // fgFindNode -- a function that finds a named node in an ssg graph
264 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
265   if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
266     return node;
267   } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
268     ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
269     while (kid != NULL) {
270       ssgEntity *n = fgFindNode(kid, name);
271       if (n != NULL)
272         return n;
273
274       kid = ((ssgBranch*)node)->getNextKid();
275     }
276   }
277
278   return NULL;
279 }
280
281 // fgInitVisuals() -- Initialize various GL/view parameters
282 void fgInitVisuals( void ) {
283     fgLIGHT *l;
284
285     l = &cur_light_params;
286
287 #ifndef GLUT_WRONG_VERSION
288     // Go full screen if requested ...
289     if ( fgGetBool("/sim/startup/fullscreen") ) {
290         glutFullScreen();
291     }
292 #endif
293
294     // If enabled, normal vectors specified with glNormal are scaled
295     // to unit length after transformation.  See glNormal.
296     // glEnable( GL_NORMALIZE );
297
298     glEnable( GL_LIGHTING );
299     glEnable( GL_LIGHT0 );
300     glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
301
302     sgVec3 sunpos;
303     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
304     ssgGetLight( 0 ) -> setPosition( sunpos );
305
306     // glFogi (GL_FOG_MODE, GL_LINEAR);
307     glFogi (GL_FOG_MODE, GL_EXP2);
308     if ( (fgGetString("/sim/rendering/fog") == "disabled") || 
309          (!fgGetBool("/sim/rendering/shading"))) {
310         // if fastest fog requested, or if flat shading force fastest
311         glHint ( GL_FOG_HINT, GL_FASTEST );
312     } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
313         glHint ( GL_FOG_HINT, GL_NICEST );
314     }
315     if ( fgGetBool("/sim/rendering/wireframe") ) {
316         // draw wire frame
317         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
318     }
319
320     // This is the default anyways, but it can't hurt
321     glFrontFace ( GL_CCW );
322
323     // Just testing ...
324     // glEnable(GL_POINT_SMOOTH);
325     // glEnable(GL_LINE_SMOOTH);
326     // glEnable(GL_POLYGON_SMOOTH);      
327 }
328
329
330 // For HiRes screen Dumps using Brian Pauls TR Library
331 void trRenderFrame( void ) {
332
333     if ( fgPanelVisible() ) {
334         GLfloat height = fgGetInt("/sim/startup/ysize");
335         GLfloat view_h =
336             (current_panel->getViewHeight() - current_panel->getYOffset())
337             * (height / 768.0) + 1;
338         glTranslatef( 0.0, view_h, 0.0 );
339     }
340
341     static double m_log01      = -log( 0.01 );
342     static double sqrt_m_log01 = sqrt( m_log01 );
343
344     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
345     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
346
347     fgLIGHT *l = &cur_light_params;
348
349     glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
350                  l->adj_fog_color[2], l->adj_fog_color[3]);
351
352     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
353
354     // set the opengl state to known default values
355     default_state->force();
356
357     // update fog params
358     double actual_visibility       = thesky->get_visibility();
359     // GLfloat fog_exp_density        = m_log01 / actual_visibility;
360     GLfloat fog_exp2_density       = sqrt_m_log01 / actual_visibility;
361     GLfloat fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 1.5 );
362
363     glEnable( GL_FOG );
364     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
365     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
366     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color );
367
368     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
369     // we only update GL_AMBIENT for our lights we will never get
370     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
371     // explicitely to black.
372     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
373
374     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
375
376     // texture parameters
377     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
378     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
379
380     // we need a white diffuse light for the phase of the moon
381     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
382     thesky->preDraw();
383
384     // draw the ssg scene
385     // return to the desired diffuse color
386     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
387     glEnable( GL_DEPTH_TEST );
388     ssgCullAndDraw( scene );
389
390     // draw the lights
391     glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
392     ssgCullAndDraw( lighting );
393
394     thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
395
396     // need to do this here as hud_and_panel state is static to
397     // main.cxx  and HUD and Panel routines have to be called with
398     // knowledge of the the TR struct < see gui.cxx::HighResDump()
399     hud_and_panel->apply();
400 }
401
402
403 // Update all Visuals (redraws anything graphics related)
404 void fgRenderFrame( void ) {
405     // Update the default (kludged) properties.
406     fgUpdateProps();
407
408     fgLIGHT *l = &cur_light_params;
409     static double last_visibility = -9999;
410
411     static GLfloat fog_exp_density;
412     static GLfloat fog_exp2_density;
413     static GLfloat fog_exp2_punch_through;
414     
415     // double angle;
416     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
417     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
418     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
419     // GLfloat mat_shininess[] = { 10.0 };
420     GLbitfield clear_mask;
421     
422     if ( idle_state != 1000 ) {
423         // still initializing, draw the splash screen
424         if ( fgGetBool("/sim/startup/splash-screen") ) {
425             fgSplashUpdate(0.0);
426         }
427     } else {
428         // idle_state is now 1000 meaning we've finished all our
429         // initializations and are running the main loop, so this will
430         // now work without seg faulting the system.
431
432         // printf("Ground = %.2f  Altitude = %.2f\n", scenery.cur_elev, 
433         //        FG_Altitude * SG_FEET_TO_METER);
434     
435         // this is just a temporary hack, to make me understand Pui
436         // timerText -> setLabel (ctime (&t->cur_time));
437         // end of hack
438
439         // calculate our current position in cartesian space
440         scenery.center = scenery.next_center;
441         // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
442         //        scenery.center.y(), scenery.center.z());
443
444         FGViewerRPH *pilot_view =
445             (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
446
447         pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
448                                        cur_fdm_state->get_Lat_geocentric(), 
449                                        cur_fdm_state->get_Altitude() *
450                                        SG_FEET_TO_METER );
451         pilot_view->set_sea_level_radius( cur_fdm_state->
452                                           get_Sea_level_radius() *
453                                           SG_FEET_TO_METER ); 
454         pilot_view->set_rph( cur_fdm_state->get_Phi(),
455                              cur_fdm_state->get_Theta(),
456                              cur_fdm_state->get_Psi() );
457
458         if (fgGetString("/sim/flight-model") == "ada") {
459             //+ve x is aft, +ve z is up (see viewer.hxx)
460             pilot_view->set_pilot_offset( -5.0, 0.0, 1.0 ); 
461         }
462
463         FGViewerLookAt *chase_view =
464             (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
465
466         sgVec3 po;              // chase view pilot_offset
467         sgVec3 wup;             // chase view world up
468         sgSetVec3( po, 0.0, 0.0, 100.0 );
469         sgCopyVec3( wup, pilot_view->get_world_up() );
470         sgMat4 CXFM;            // chase view + pilot offset xform
471         sgMakeRotMat4( CXFM,
472                        chase_view->get_view_offset() * SGD_RADIANS_TO_DEGREES -
473                        cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES,
474                        wup );
475         sgVec3 npo;             // new pilot offset after rotation
476         sgVec3 *pPO = PilotOffsetGet();
477         sgXformVec3( po, *pPO, pilot_view->get_UP() );
478         sgXformVec3( npo, po, CXFM );
479
480         chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(), 
481                                        cur_fdm_state->get_Lat_geocentric(), 
482                                        cur_fdm_state->get_Altitude() *
483                                        SG_FEET_TO_METER );
484         chase_view->set_sea_level_radius( cur_fdm_state->
485                                           get_Sea_level_radius() *
486                                           SG_FEET_TO_METER );
487         chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
488         chase_view->set_view_forward( pilot_view->get_view_pos() ); 
489         chase_view->set_view_up( wup );
490
491 #if 0
492         sgMat4 rph;
493         sgCopyMat4( rph, pilot_view->get_VIEW() );
494         cout << "RPH Matrix = " << endl;
495         int i, j;
496         for ( i = 0; i < 4; i++ ) {
497             for ( j = 0; j < 4; j++ ) {
498                 printf("%10.4f ", rph[i][j]);
499             }
500             cout << endl;
501         }
502
503         sgMat4 la;
504         sgCopyMat4( la, chase_view->get_VIEW() );
505         cout << "LookAt Matrix = " << endl;
506         for ( i = 0; i < 4; i++ ) {
507             for ( j = 0; j < 4; j++ ) {
508                 printf("%10.4f ", la[i][j]);
509             }
510             cout << endl;
511         }
512 #endif
513
514         // update view port
515         fgReshape( fgGetInt("/sim/startup/xsize"),
516                    fgGetInt("/sim/startup/ysize") );
517
518 #if 0
519         // swing and a miss
520
521         if ( ! fgPanelVisible() ) {
522             xglViewport( 0, 0 ,
523                          (GLint)(fgGetInt("/sim/startup/xsize")),
524                          (GLint)(fgGetInt("/sim/startup/ysize")) );
525         } else {
526             int view_h =
527                 int( (current_panel->getViewHeight() -
528                       current_panel->getYOffset())
529                      * (fgGetInt("/sim/startup/ysize") / 768.0) );
530             glViewport( 0, 
531                         (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
532                         (GLint)(fgGetInt("/sim/startup/xsize")),
533                         (GLint)(view_h) );
534         }
535 #endif
536
537         // set the sun position
538         glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
539
540         clear_mask = GL_DEPTH_BUFFER_BIT;
541         if ( fgGetBool("/sim/rendering/wireframe") ) {
542             clear_mask |= GL_COLOR_BUFFER_BIT;
543         }
544
545         if ( fgGetBool("/sim/rendering/skyblend") ) {
546             if ( fgGetBool("/sim/rendering/textures") ) {
547                 // glClearColor(black[0], black[1], black[2], black[3]);
548                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
549                              l->adj_fog_color[2], l->adj_fog_color[3]);
550                 clear_mask |= GL_COLOR_BUFFER_BIT;
551             }
552         } else {
553             glClearColor(l->sky_color[0], l->sky_color[1], 
554                          l->sky_color[2], l->sky_color[3]);
555             clear_mask |= GL_COLOR_BUFFER_BIT;
556         }
557         glClear( clear_mask );
558
559         // Tell GL we are switching to model view parameters
560
561         // I really should create a derived ssg node or use a call
562         // back or something so that I can draw the sky within the
563         // ssgCullAndDraw() function, but for now I just mimic what
564         // ssg does to set up the model view matrix
565         glMatrixMode(GL_MODELVIEW);
566         glLoadIdentity();
567         ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
568
569         // set the opengl state to known default values
570         default_state->force();
571
572         // update fog params if visibility has changed
573 #ifndef FG_OLD_WEATHER
574         thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
575 #else
576         thesky->set_visibility( current_weather.get_visibility() );
577 #endif
578
579         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
580                             ( global_multi_loop * 
581                               fgGetInt("/sim/speed-up") ) /
582                             (double)fgGetInt("/sim/model-hz") );
583
584         double actual_visibility = thesky->get_visibility();
585         // cout << "actual visibility = " << actual_visibility << endl;
586
587         if ( actual_visibility != last_visibility ) {
588             last_visibility = actual_visibility;
589
590             // cout << "----> updating fog params" << endl;
591                 
592             // for GL_FOG_EXP
593             fog_exp_density = -log(0.01) / actual_visibility;
594     
595             // for GL_FOG_EXP2
596             fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
597             fog_exp2_punch_through = sqrt( -log(0.01) ) / 
598                 ( actual_visibility * 1.5 );
599         }
600
601         // Set correct opengl fog density
602         glFogf (GL_FOG_DENSITY, fog_exp2_density);
603
604         // update the sky dome
605         if ( fgGetBool("/sim/rendering/skyblend") ) {
606             /* cout << "thesky->repaint() sky_color = "
607                  << cur_light_params.sky_color[0] << " "
608                  << cur_light_params.sky_color[1] << " "
609                  << cur_light_params.sky_color[2] << " "
610                  << cur_light_params.sky_color[3] << endl;
611             cout << "    fog = "
612                  << cur_light_params.fog_color[0] << " "
613                  << cur_light_params.fog_color[1] << " "
614                  << cur_light_params.fog_color[2] << " "
615                  << cur_light_params.fog_color[3] << endl;
616             cout << "    sun_angle = " << cur_light_params.sun_angle
617                  << "    moon_angle = " << cur_light_params.moon_angle
618                  << endl; */
619             thesky->repaint( cur_light_params.sky_color,
620                              cur_light_params.adj_fog_color,
621                              cur_light_params.sun_angle,
622                              cur_light_params.moon_angle,
623                              globals->get_ephem()->getNumPlanets(),
624                              globals->get_ephem()->getPlanets(),
625                              globals->get_ephem()->getNumStars(),
626                              globals->get_ephem()->getStars() );
627  
628             /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
629                  << view_pos[1] << " " << view_pos[2] << endl;
630             cout << "    zero_elev = " << zero_elev[0] << " "
631                  << zero_elev[1] << " " << zero_elev[2]
632                  << " lon = " << cur_fdm_state->get_Longitude()
633                  << " lat = " << cur_fdm_state->get_Latitude() << endl;
634             cout << "    sun_rot = " << cur_light_params.sun_rotation
635                  << " gst = " << SGTime::cur_time_params->getGst() << endl;
636             cout << "    sun ra = " << globals->get_ephem()->getSunRightAscension()
637                  << " sun dec = " << globals->get_ephem()->getSunDeclination() 
638                  << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
639                  << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
640
641             thesky->reposition( globals->get_current_view()->get_view_pos(),
642                                 globals->get_current_view()->get_zero_elev(),
643                                 globals->get_current_view()->get_world_up(),
644                                 cur_fdm_state->get_Longitude(),
645                                 cur_fdm_state->get_Latitude(),
646                                 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
647                                 cur_light_params.sun_rotation,
648                                 globals->get_time_params()->getGst(),
649                                 globals->get_ephem()->getSunRightAscension(),
650                                 globals->get_ephem()->getSunDeclination(),
651                                 50000.0,
652                                 globals->get_ephem()->getMoonRightAscension(),
653                                 globals->get_ephem()->getMoonDeclination(),
654                                 50000.0 );
655         }
656
657         glEnable( GL_DEPTH_TEST );
658         if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
659             glEnable( GL_FOG );
660             glFogi( GL_FOG_MODE, GL_EXP2 );
661             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
662         }
663
664         // set sun/lighting parameters
665         ssgGetLight( 0 ) -> setPosition( l->sun_vec );
666
667         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
668         // we only update GL_AMBIENT for our lights we will never get
669         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
670         // explicitely to black.
671         GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
672         GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
673         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
674
675         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
676         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
677         // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
678
679         // texture parameters
680         // glEnable( GL_TEXTURE_2D );
681         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
682         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
683
684         // glMatrixMode( GL_PROJECTION );
685         // glLoadIdentity();
686         float fov = globals->get_current_view()->get_fov();
687         ssgSetFOV(fov, fov * globals->get_current_view()->get_fov_ratio());
688
689         double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
690             - scenery.cur_elev;
691
692         // SG_LOG( SG_ALL, SG_INFO, "visibility is " 
693         //         << current_weather.get_visibility() );
694             
695         if ( agl > 10.0 ) {
696             ssgSetNearFar( 10.0f, 120000.0f );
697         } else {
698             ssgSetNearFar( 0.5f, 120000.0f );
699         }
700
701         if ( globals->get_viewmgr()->get_current() == 0 ) {
702             // disable aircraft model
703             acmodel_selector->select(0);
704         } else { 
705             // enable aircraft model and set up its position and orientation
706             acmodel_selector->select(1);
707
708             FGViewerRPH *pilot_view =
709                 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
710
711             sgMat4 sgTRANS;
712             sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
713
714             sgVec3 ownship_up;
715             sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
716
717             sgMat4 sgROT;
718             sgMakeRotMat4( sgROT, -90.0, ownship_up );
719
720             // sgMat4 sgTMP;
721             // sgMat4 sgTUX;
722             // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
723             // sgMultMat4( sgTUX, sgTMP, sgTRANS );
724
725             // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
726             sgMat4 sgTUX;
727             sgCopyMat4( sgTUX, sgROT );
728             sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
729             sgPostMultMat4( sgTUX, sgTRANS );
730         
731             sgCoord tuxpos;
732             sgSetCoord( &tuxpos, sgTUX );
733             acmodel_pos->setTransform( &tuxpos );
734
735             // set up moving parts
736             if (flaps_selector != NULL) {
737                 flaps_selector->select( (globals->get_controls()->get_flaps() > 0.5f) ? 1 : 2 );
738             }
739
740             if (prop_selector != NULL) {
741               int propsel_mask = 0;
742               double rpm = fgGetDouble("/engines/engine[0]/rpm");
743               for (int i = 0; i < acmodel_npropsettings; i++) {
744                 if (rpm >= acmodel_proprpms[i][0] &&
745                     rpm <= acmodel_proprpms[i][1]) {
746                   propsel_mask |= 1 << i;
747                 }
748               }
749               prop_selector->select(propsel_mask);
750             }
751         }
752
753         // $$$ begin - added VS Renganthan 17 Oct 2K
754         fgUpdateDCS();
755         // $$$ end - added VS Renganthan 17 Oct 2K
756
757 # ifdef FG_NETWORK_OLK
758         if ( fgGetBool("/sim/networking/network-olk") ) {
759             sgCoord fgdpos;
760             other = head->next;             /* put listpointer to start  */
761             while ( other != tail) {        /* display all except myself */
762                 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
763                     other->fgd_sel->select(1);
764                     sgSetCoord( &fgdpos, other->sgFGD_COORD );
765                     other->fgd_pos->setTransform( &fgdpos );
766                 }
767                 other = other->next;
768             }
769
770             // fgd_sel->select(1);
771             // sgCopyMat4( sgTUX, current_view.sgVIEW);
772             // sgCoord fgdpos;
773             // sgSetCoord( &fgdpos, sgFGD_VIEW );
774             // fgd_pos->setTransform( &fgdpos);
775         }
776 # endif
777
778         // position tile nodes and update range selectors
779         global_tile_mgr.prep_ssg_nodes();
780
781         if ( fgGetBool("/sim/rendering/skyblend") ) {
782             // draw the sky backdrop
783
784             // we need a white diffuse light for the phase of the moon
785             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
786
787             thesky->preDraw();
788
789             // return to the desired diffuse color
790             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
791         }
792
793         // draw the ssg scene
794         glEnable( GL_DEPTH_TEST );
795         ssgCullAndDraw( scene );
796
797         // change state for lighting here
798
799         // draw lighting
800         // Set punch through fog density
801         glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
802
803 #ifdef FG_EXPERIMENTAL_LIGHTING
804         // Enable states for drawing points with GL_extension
805         if (glutExtensionSupported("GL_EXT_point_parameters")) {
806             glEnable(GL_POINT_SMOOTH);
807             float quadratic[3] = {1.0, 0.01, 0.0001};
808             // get the address of our OpenGL extensions
809             glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC) 
810                 wglGetProcAddress("glPointParameterfEXT");
811             glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC) 
812                 wglGetProcAddress("glPointParameterfvEXT");
813             // makes the points fade as they move away
814             glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
815             glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0); 
816             glPointSize(4.0);
817
818             // Enable states for drawing runway lights with spherical mapping
819             glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
820             glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
821             glEnable(GL_TEXTURE_GEN_S);
822             glEnable(GL_TEXTURE_GEN_T);
823
824             //Maybe this is not the best way, but it works !!
825             glPolygonMode(GL_FRONT, GL_POINT);
826             glCullFace(GL_BACK);
827             glEnable(GL_CULL_FACE);
828         }
829
830         glDisable( GL_LIGHTING );
831         // blending function for runway lights
832         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
833         glEnable(GL_BLEND);
834 #endif
835
836         ssgCullAndDraw( lighting );
837
838 #ifdef FG_EXPERIMENTAL_LIGHTING
839         if (glutExtensionSupported("GL_EXT_point_parameters")) {
840             // Disable states used for runway lighting
841             glPolygonMode(GL_FRONT, GL_FILL);
842
843             glDisable(GL_TEXTURE_GEN_S);
844             glDisable(GL_TEXTURE_GEN_T);
845             glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
846                                   default_attenuation);
847         }
848
849         glPointSize(1.0);
850 #endif
851
852         if ( fgGetBool("/sim/rendering/skyblend") ) {
853             // draw the sky cloud layers
854             thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
855         }
856
857         // display HUD && Panel
858         glDisable( GL_FOG );
859         glDisable( GL_DEPTH_TEST );
860         // glDisable( GL_CULL_FACE );
861         // glDisable( GL_TEXTURE_2D );
862
863         // update the input subsystem
864         current_input.update();
865
866         // update the controls subsystem
867         globals->get_controls()->update();
868
869         hud_and_panel->apply();
870         fgCockpitUpdate();
871
872         // update the panel subsystem
873         if (current_panel != 0)
874           current_panel->update();
875
876         // We can do translucent menus, so why not. :-)
877         menus->apply();
878         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
879         puDisplay();
880         // glDisable ( GL_BLEND ) ;
881
882         // glEnable( GL_FOG );
883     }
884
885     glutSwapBuffers();
886 }
887
888
889 // Update internal time dependent calculations (i.e. flight model)
890 void fgUpdateTimeDepCalcs() {
891     static bool inited = false;
892
893     fgLIGHT *l = &cur_light_params;
894     int i;
895
896     long multi_loop = 1;
897
898     if ( !globals->get_freeze() && !initial_freeze ) {
899         // conceptually, this could be done for each fdm instance ...
900
901         if ( !inited ) {
902             cur_fdm_state->stamp();
903             inited = true;
904         }
905
906         SGTimeStamp current;
907         current.stamp();
908         long elapsed = current - cur_fdm_state->get_time_stamp();
909         cur_fdm_state->set_time_stamp( current );
910         elapsed += cur_fdm_state->get_remainder();
911         // cout << "elapsed = " << elapsed << endl;
912         // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
913         multi_loop = (long)(((double)elapsed * 0.000001) /
914                                cur_fdm_state->get_delta_t() );
915         cur_fdm_state->set_multi_loop( multi_loop );
916         long remainder = elapsed - (long)( (multi_loop*1000000) *
917                                      cur_fdm_state->get_delta_t() );
918         cur_fdm_state->set_remainder( remainder );
919         // cout << "remainder = " << remainder << endl;
920
921         // chop max interations to something reasonable if the sim was
922         // delayed for an excesive amount of time
923         if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
924             multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
925             cur_fdm_state->set_remainder( 0 );
926         }
927
928         // cout << "multi_loop = " << multi_loop << endl;
929         for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
930             // run Autopilot system
931             current_autopilot->run();
932
933             // update autopilot
934             cur_fdm_state->update( 1 );
935         }
936         FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
937     } else {
938         cur_fdm_state->update( 0 );
939         FGSteam::update( 0 );
940
941         //if ( global_tile_mgr.queue_size() == 0 ) {
942             initial_freeze = false;
943             //}
944     }
945
946     if ( fgGetString("/sim/view-mode") == "pilot" ) {
947         cur_view_fdm = *cur_fdm_state;
948         // do nothing
949     }
950
951     // update the view angle
952     FGViewer *v = globals->get_current_view();
953     for ( i = 0; i < multi_loop; i++ ) {
954         if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
955             v->set_view_offset( v->get_goal_view_offset() );
956             break;
957         } else {
958             // move current_view.view_offset towards
959             // current_view.goal_view_offset
960             if ( v->get_goal_view_offset() > v->get_view_offset() )
961             {
962                 if ( v->get_goal_view_offset() - v->get_view_offset() < SGD_PI ){
963                     v->inc_view_offset( 0.01 );
964                 } else {
965                     v->inc_view_offset( -0.01 );
966                 }
967             } else {
968                 if ( v->get_view_offset() - v->get_goal_view_offset() < SGD_PI ){
969                     v->inc_view_offset( -0.01 );
970                 } else {
971                     v->inc_view_offset( 0.01 );
972                 }
973             }
974             if ( v->get_view_offset() > SGD_2PI ) {
975                 v->inc_view_offset( -SGD_2PI );
976             } else if ( v->get_view_offset() < 0 ) {
977                 v->inc_view_offset( SGD_2PI );
978             }
979         }
980     }
981
982     double tmp = -(l->sun_rotation + SGD_PI) 
983         - (cur_fdm_state->get_Psi() -
984            globals->get_current_view()->get_view_offset() );
985     while ( tmp < 0.0 ) {
986         tmp += SGD_2PI;
987     }
988     while ( tmp > SGD_2PI ) {
989         tmp -= SGD_2PI;
990     }
991     /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
992            FG_Psi * SGD_RADIANS_TO_DEGREES, current_view.view_offset * SGD_RADIANS_TO_DEGREES, 
993            -(l->sun_rotation+SGD_PI) * SGD_RADIANS_TO_DEGREES, tmp * SGD_RADIANS_TO_DEGREES); */
994     l->UpdateAdjFog();
995
996     // Update solar system
997     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
998                                   globals->get_time_params()->getLst(),
999                                   cur_fdm_state->get_Latitude() );
1000
1001     // Update radio stack model
1002     current_radiostack->update();
1003 }
1004
1005
1006 void fgInitTimeDepCalcs( void ) {
1007     // initialize timer
1008
1009     // #ifdef HAVE_SETITIMER
1010     //   fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"), 
1011     //                fgUpdateTimeDepCalcs );
1012     // #endif HAVE_SETITIMER
1013 }
1014
1015
1016 static const double alt_adjust_ft = 3.758099;
1017 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1018
1019
1020 // What should we do when we have nothing else to do?  Let's get ready
1021 // for the next move and update the display?
1022 static void fgMainLoop( void ) {
1023     static long remainder = 0;
1024     long elapsed;
1025 #ifdef FANCY_FRAME_COUNTER
1026     int i;
1027     double accum;
1028 #else
1029     static time_t last_time = 0;
1030     static int frames = 0;
1031 #endif // FANCY_FRAME_COUNTER
1032
1033     SGTime *t = globals->get_time_params();
1034
1035     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1036     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1037
1038 #ifdef FG_NETWORK_OLK
1039     if ( fgGetBool("/sim/networking/network-olk") ) {
1040         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
1041             // printf("FGD: Netupdate\n");
1042             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
1043             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
1044         }
1045     }
1046 #endif
1047
1048 #if defined( ENABLE_PLIB_JOYSTICK )
1049     // Read joystick and update control settings
1050     // if ( fgGetString("/sim/control-mode") == "joystick" )
1051     // {
1052     //    fgJoystickRead();
1053     // }
1054 #elif defined( ENABLE_GLUT_JOYSTICK )
1055     // Glut joystick support works by feeding a joystick handler
1056     // function to glut.  This is taken care of once in the joystick
1057     // init routine and we don't have to worry about it again.
1058 #endif
1059
1060 #ifdef FG_OLD_WEATHER
1061     current_weather.Update();
1062 #endif
1063
1064     // Fix elevation.  I'm just sticking this here for now, it should
1065     // probably move eventually
1066
1067     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
1068            scenery.cur_elev,
1069            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1070            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1071
1072     if ( scenery.cur_elev > -9990 ) {
1073         if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER < 
1074              (scenery.cur_elev + alt_adjust_m - 3.0) ) {
1075             // now set aircraft altitude above ground
1076             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
1077                    cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1078                    scenery.cur_elev + alt_adjust_m - 3.0,
1079                    scenery.cur_elev + alt_adjust_m );
1080             fgFDMForceAltitude( fgGetString("/sim/flight-model"), 
1081                                 scenery.cur_elev + alt_adjust_m );
1082
1083             SG_LOG( SG_ALL, SG_DEBUG, 
1084                     "<*> resetting altitude to " 
1085                     << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1086                     << " meters" );
1087         }
1088     }
1089
1090     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
1091            scenery.cur_elev,
1092            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1093            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1094
1095     // cout << "Warp = " << globals->get_warp() << endl;
1096
1097     // update "time"
1098     if ( globals->get_warp_delta() != 0 ) {
1099         globals->inc_warp( globals->get_warp_delta() );
1100     }
1101
1102     t->update( cur_fdm_state->get_Longitude(),
1103                cur_fdm_state->get_Latitude(),
1104                globals->get_warp() );
1105
1106     if ( globals->get_warp_delta() != 0 ) {
1107         fgUpdateSkyAndLightingParams();
1108     }
1109
1110     // update magvar model
1111     globals->get_mag()->update( cur_fdm_state->get_Longitude(),
1112                                 cur_fdm_state->get_Latitude(),
1113                                 cur_fdm_state->get_Altitude()* SG_FEET_TO_METER,
1114                                 globals->get_time_params()->getJD() );
1115
1116     // Get elapsed time (in usec) for this past frame
1117     elapsed = fgGetTimeInterval();
1118     SG_LOG( SG_ALL, SG_DEBUG, 
1119             "Elapsed time interval is = " << elapsed 
1120             << ", previous remainder is = " << remainder );
1121
1122     // Calculate frame rate average
1123 #ifdef FANCY_FRAME_COUNTER
1124     /* old fps calculation */
1125     if ( elapsed > 0 ) {
1126         double tmp;
1127         accum = 0.0;
1128         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1129             tmp = general.get_frame(i);
1130             accum += tmp;
1131             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1132             general.set_frame(i+1,tmp);
1133         }
1134         tmp = 1000000.0 / (float)elapsed;
1135         general.set_frame(0,tmp);
1136         // printf("frame[0] = %.2f\n", general.frames[0]);
1137         accum += tmp;
1138         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1139         // printf("ave = %.2f\n", general.frame_rate);
1140     }
1141 #else
1142     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1143         general.set_frame_rate( frames );
1144         SG_LOG( SG_ALL, SG_DEBUG, 
1145                 "--> Frame rate is = " << general.get_frame_rate() );
1146         frames = 0;
1147     }
1148     last_time = t->get_cur_time();
1149     ++frames;
1150 #endif
1151
1152     // Run flight model
1153
1154     // Calculate model iterations needed for next frame
1155     elapsed += remainder;
1156
1157     global_multi_loop = (long)(((double)elapsed * 0.000001) * 
1158                               fgGetInt("/sim/model-hz"));
1159     remainder = elapsed - ( (global_multi_loop*1000000) / 
1160                             fgGetInt("/sim/model-hz") );
1161     SG_LOG( SG_ALL, SG_DEBUG, 
1162             "Model iterations needed = " << global_multi_loop
1163             << ", new remainder = " << remainder );
1164         
1165     // chop max interations to something reasonable if the sim was
1166     // delayed for an excesive amount of time
1167     if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1168         global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1169         remainder = 0;
1170     }
1171
1172     // flight model
1173     if ( global_multi_loop > 0 ) {
1174         fgUpdateTimeDepCalcs();
1175     } else {
1176         SG_LOG( SG_ALL, SG_DEBUG, 
1177                 "Elapsed time is zero ... we're zinging" );
1178     }
1179
1180 #if ! defined( macintosh )
1181     // Do any I/O channel work that might need to be done
1182     fgIOProcess();
1183 #endif
1184
1185     // see if we need to load any new scenery tiles
1186     global_tile_mgr.update( cur_fdm_state->get_Longitude()
1187                             * SGD_RADIANS_TO_DEGREES,
1188                             cur_fdm_state->get_Latitude()
1189                             * SGD_RADIANS_TO_DEGREES );
1190
1191     // see if we need to load any deferred-load textures
1192     material_lib.load_next_deferred();
1193
1194     // Process/manage pending events
1195     global_events.Process();
1196
1197     // Run audio scheduler
1198 #ifdef ENABLE_AUDIO_SUPPORT
1199     static bool bCranking;
1200     if ( fgGetBool("/sim/sound") && globals->get_soundmgr()->is_working() ) {
1201         if ( fgGetString("/sim/aircraft") == "c172" ) {
1202             if(fgGetBool("/engines/engine[0]/running")) {
1203                 // pitch corresponds to rpm
1204                 // volume corresponds to manifold pressure
1205
1206                 // cout << "AUDIO working = "
1207                 //      << globals->get_soundmgr()->is_working() << endl;
1208
1209                 double rpm_factor;
1210                 if ( cur_fdm_state->get_engine(0) != NULL ) {
1211                     rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1212                 } else {
1213                     rpm_factor = 1.0;
1214                 }
1215                 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1216                 //      << endl;
1217
1218                 double pitch = 0.3 + rpm_factor * 3.0;
1219         
1220                 // don't run at absurdly slow rates -- not realistic
1221                 // and sounds bad to boot.  :-)
1222                 if (pitch < 0.7) { pitch = 0.7; }
1223                 if (pitch > 5.0) { pitch = 5.0; }
1224
1225                 double mp_factor;
1226                 if ( cur_fdm_state->get_engine(0) != NULL ) {
1227                     mp_factor = cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1228                 } else {
1229                     mp_factor = 0.3;
1230                 }
1231                 /* cout << "mp = " 
1232                     << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1233                     << endl; */
1234
1235                 double volume = 0.15 + mp_factor / 2.0;
1236
1237                 if ( volume < 0.15 ) { volume = 0.15; }
1238                 if ( volume > 0.5 ) { volume = 0.5; }
1239                 // cout << "volume = " << volume << endl;
1240
1241                 s1->set_pitch( pitch );
1242                 s1->set_volume( volume );
1243             } else {
1244                 s1->set_pitch(0.0);
1245                 s1->set_volume(0.0);
1246             }
1247             if(fgGetBool("/engines/engine[0]/cranking")) {
1248                 if(!bCranking) {
1249                     globals->get_soundmgr()->play_looped("cranking");
1250                     bCranking = true;
1251                 }
1252             } else {
1253                 if(bCranking) {
1254                     globals->get_soundmgr()->stop("cranking");
1255                     bCranking = false;
1256                 }
1257             }
1258         } else {    // Not C172
1259             double param
1260                 = globals->get_controls()->get_throttle( 0 ) * 2.0 + 1.0;
1261             s1->set_pitch( param );
1262             s1->set_volume( param );
1263         }
1264
1265         globals->get_soundmgr()->update();
1266     }
1267 #endif
1268
1269     // redraw display
1270     fgRenderFrame();
1271
1272     SG_LOG( SG_ALL, SG_DEBUG, "" );
1273 }
1274
1275
1276 // This is the top level master main function that is registered as
1277 // our idle funciton
1278 //
1279
1280 // The first few passes take care of initialization things (a couple
1281 // per pass) and once everything has been initialized fgMainLoop from
1282 // then on.
1283
1284 static void fgIdleFunction ( void ) {
1285     // printf("idle state == %d\n", idle_state);
1286
1287     if ( idle_state == 0 ) {
1288         // Initialize the splash screen right away
1289         if ( fgGetBool("/sim/startup/splash-screen") ) {
1290             fgSplashInit();
1291         }
1292         
1293         idle_state++;
1294     } else if ( idle_state == 1 ) {
1295         // Initialize audio support
1296 #ifdef ENABLE_AUDIO_SUPPORT
1297
1298         // Start the intro music
1299 #if !defined(WIN32)
1300         if ( fgGetBool("/sim/startup/intro-music") ) {
1301             SGPath mp3file( globals->get_fg_root() );
1302             mp3file.append( "Sounds/intro.mp3" );
1303
1304             SG_LOG( SG_GENERAL, SG_INFO, 
1305                     "Starting intro music: " << mp3file.str() );
1306
1307             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1308             system ( command.c_str() );
1309         }
1310 #endif // !WIN32
1311
1312         FGSoundMgr *soundmgr = new FGSoundMgr;
1313         globals->set_soundmgr( soundmgr );
1314
1315         if ( fgGetBool("/sim/sound") ) {
1316             globals->get_soundmgr()->init();
1317
1318             s1 = new FGSimpleSound( fgGetString("/sim/sounds/engine",
1319                                                 "Sounds/wasp.wav") );
1320             globals->get_soundmgr()->add( s1, "engine loop" );
1321             globals->get_soundmgr()->play_looped( "engine loop" );
1322             SG_LOG( SG_GENERAL, SG_INFO,
1323                     "Rate = " << s1->get_sample()->getRate()
1324                     << "  Bps = " << s1->get_sample()->getBps()
1325                     << "  Stereo = " << s1->get_sample()->getStereo() );
1326
1327             // s2 = new FGSimpleSound( "Sounds/corflaps.wav" );
1328             // s2->set_volume( 0.3 );
1329             // globals->get_soundmgr()->add( s2, "flaps" );
1330             s2 = new FGSimpleSound( fgGetString("/sim/sounds/engine",
1331                                                 "Sounds/cranking.wav") );
1332             globals->get_soundmgr()->add( s2, "cranking" );
1333             s2->set_pitch(1.5);
1334             s2->set_volume(0.25);
1335         }
1336 #endif
1337
1338         idle_state++;
1339     } else if ( idle_state == 2 ) {
1340         // These are a few miscellaneous things that aren't really
1341         // "subsystems" but still need to be initialized.
1342
1343 #ifdef USE_GLIDE
1344         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1345             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1346         }
1347 #endif
1348
1349         idle_state++;
1350     } else if ( idle_state == 3 ) {
1351         // This is the top level init routine which calls all the
1352         // other subsystem initialization routines.  If you are adding
1353         // a subsystem to flightgear, its initialization call should
1354         // located in this routine.
1355         if( !fgInitSubsystems()) {
1356             SG_LOG( SG_GENERAL, SG_ALERT,
1357                     "Subsystem initializations failed ..." );
1358             exit(-1);
1359         }
1360
1361         idle_state++;
1362     } else if ( idle_state == 4 ) {
1363         // setup OpenGL view parameters
1364         fgInitVisuals();
1365
1366         idle_state++;
1367     } else if ( idle_state == 5 ) {
1368
1369         idle_state++;
1370     } else if ( idle_state == 6 ) {
1371         // sleep(1);
1372         idle_state = 1000;
1373
1374         cout << "Panel visible = " << fgPanelVisible() << endl;
1375         fgReshape( fgGetInt("/sim/startup/xsize"),
1376                    fgGetInt("/sim/startup/ysize") );
1377     } 
1378
1379     if ( idle_state == 1000 ) {
1380         // We've finished all our initialization steps, from now on we
1381         // run the main loop.
1382
1383         fgMainLoop();
1384     } else {
1385         if ( fgGetBool("/sim/startup/splash-screen") ) {
1386             fgSplashUpdate(0.0);
1387         }
1388     }
1389 }
1390
1391 // options.cxx needs to see this for toggle_panel()
1392 // Handle new window size or exposure
1393 void fgReshape( int width, int height ) {
1394     int view_h;
1395
1396     if ( fgPanelVisible() && idle_state == 1000 ) {
1397         view_h = (int)(height * (current_panel->getViewHeight() -
1398                                  current_panel->getYOffset()) / 768.0);
1399     } else {
1400         view_h = height;
1401     }
1402
1403     // for all views
1404     for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1405         globals->get_viewmgr()->get_view(i)->
1406             set_aspect_ratio((float)view_h / (float)width);
1407     }
1408
1409     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1410
1411     fgSetInt("/sim/startup/xsize", width);
1412     fgSetInt("/sim/startup/ysize", height);
1413
1414     float fov = globals->get_current_view()->get_fov();
1415     ssgSetFOV(fov, fov * globals->get_current_view()->get_fov_ratio());
1416
1417     fgHUDReshape();
1418 }
1419
1420
1421 // Initialize GLUT and define a main window
1422 int fgGlutInit( int *argc, char **argv ) {
1423
1424 #if !defined( macintosh )
1425     // GLUT will extract all glut specific options so later on we only
1426     // need wory about our own.
1427     glutInit(argc, argv);
1428 #endif
1429
1430     // Define Display Parameters
1431     glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1432
1433     SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1434             fgGetInt("/sim/startup/xsize") << "x"
1435             << fgGetInt("/sim/startup/ysize") );
1436
1437     // Define initial window size
1438     glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1439                         fgGetInt("/sim/startup/ysize") );
1440
1441     // Initialize windows
1442     if ( !fgGetBool("/sim/startup/game-mode")) {
1443         // Open the regular window
1444         glutCreateWindow("FlightGear");
1445 #ifndef GLUT_WRONG_VERSION
1446     } else {
1447         // Open the cool new 'game mode' window
1448         char game_mode_str[256];
1449         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1450                  fgGetInt("/sim/startup/xsize"),
1451                  fgGetInt("/sim/startup/ysize"),
1452                  fgGetInt("/sim/rendering/bits-per-pixel"));
1453
1454         SG_LOG( SG_GENERAL, SG_INFO, 
1455                 "game mode params = " << game_mode_str );
1456         glutGameModeString( game_mode_str );
1457         glutEnterGameMode();
1458 #endif
1459     }
1460
1461     // This seems to be the absolute earliest in the init sequence
1462     // that these calls will return valid info.  Too bad it's after
1463     // we've already created and sized out window. :-(
1464     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1465     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1466     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1467     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1468
1469     GLint tmp;
1470     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1471     general.set_glMaxTexSize( tmp );
1472     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1473
1474     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1475     general.set_glDepthBits( tmp );
1476     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1477
1478     return 1;
1479 }
1480
1481
1482 // Initialize GLUT event handlers
1483 int fgGlutInitEvents( void ) {
1484     // call fgReshape() on window resizes
1485     glutReshapeFunc( fgReshape );
1486
1487     // call GLUTkey() on keyboard event
1488     glutKeyboardFunc(GLUTkey);
1489     glutKeyboardUpFunc(GLUTkeyup);
1490     glutSpecialFunc(GLUTspecialkey);
1491     glutSpecialUpFunc(GLUTspecialkeyup);
1492
1493     // call guiMouseFunc() whenever our little rodent is used
1494     glutMouseFunc ( guiMouseFunc );
1495     glutMotionFunc (guiMotionFunc );
1496     glutPassiveMotionFunc (guiMotionFunc );
1497
1498     // call fgMainLoop() whenever there is
1499     // nothing else to do
1500     glutIdleFunc( fgIdleFunction );
1501
1502     // draw the scene
1503     glutDisplayFunc( fgRenderFrame );
1504
1505     return(1);
1506 }
1507
1508
1509 // Main loop
1510 int mainLoop( int argc, char **argv ) {
1511
1512 #if defined( macintosh )
1513     freopen ("stdout.txt", "w", stdout );
1514     freopen ("stderr.txt", "w", stderr );
1515     argc = ccommand( &argv );
1516 #endif
1517
1518     // set default log levels
1519     sglog().setLogLevels( SG_ALL, SG_INFO );
1520
1521     string version;
1522 #ifdef FLIGHTGEAR_VERSION
1523     version = FLIGHTGEAR_VERSION;
1524 #else
1525     version = "unknown version";
1526 #endif
1527     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1528             << version << endl );
1529
1530     // Allocate global data structures.  This needs to happen before
1531     // we parse command line options
1532
1533     globals = new FGGlobals;
1534
1535     // seed the random number generater
1536     sg_srandom_time();
1537
1538     SGRoute *route = new SGRoute;
1539     globals->set_route( route );
1540
1541     FGControls *controls = new FGControls;
1542     globals->set_controls( controls );
1543
1544     FGViewMgr *viewmgr = new FGViewMgr;
1545     globals->set_viewmgr( viewmgr );
1546
1547     FGViewerRPH *pv = new FGViewerRPH;
1548     globals->get_viewmgr()->add_view( pv );
1549
1550     FGViewerLookAt *chase = new FGViewerLookAt;
1551     globals->get_viewmgr()->add_view( chase );
1552
1553     string_list *col = new string_list;
1554     globals->set_channel_options_list( col );
1555
1556     // set current view to 0 (first) which is our main pilot view
1557     globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1558
1559     // Scan the config file(s) and command line options to see if
1560     // fg_root was specified (ignore all other options for now)
1561     fgInitFGRoot(argc, argv);
1562
1563     // Check for the correct base package version
1564     string base_version = fgBasePackageVersion();
1565     if ( !(base_version == "0.7.9") ) {
1566         SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1567                 << "Found version " << base_version );
1568         SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1569         exit(-1);
1570     }
1571
1572     // Initialize the Aircraft directory to "" (UIUC)
1573     aircraft_dir = "";
1574
1575     // Load the configuration parameters
1576     if ( !fgInitConfig(argc, argv) ) {
1577         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1578         exit(-1);
1579     }
1580
1581     // Initialize the Window/Graphics environment.
1582     if( !fgGlutInit(&argc, argv) ) {
1583         SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1584         exit(-1);
1585     }
1586
1587     // Initialize the various GLUT Event Handlers.
1588     if( !fgGlutInitEvents() ) {
1589         SG_LOG( SG_GENERAL, SG_ALERT, 
1590                 "GLUT event handler initialization failed ..." );
1591         exit(-1);
1592     }
1593
1594     // Initialize plib net interface
1595     netInit( &argc, argv );
1596
1597     // Initialize ssg (from plib).  Needs to come before we do any
1598     // other ssg stuff, but after opengl/glut has been initialized.
1599     ssgInit();
1600
1601     // Initialize the user interface (we need to do this before
1602     // passing off control to glut and before fgInitGeneral to get our
1603     // fonts !!!
1604     guiInit();
1605
1606 #ifdef GL_EXT_texture_lod_bias
1607     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1608 #endif
1609
1610 #if 0
1611 #ifdef GL_EXT_texture_filter_anisotropic
1612     float max_anisotropy;
1613     glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy );
1614     glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1615                      max_anisotropy );
1616     cout << "Max anisotropy = " << max_anisotropy << endl;
1617 #endif
1618 #endif
1619
1620     // set current_options lon/lat if an airport id is specified
1621     // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1622     if ( fgGetString("/sim/startup/airport-id").length() ) {
1623         // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1624         fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1625                                      fgGetDouble("/orientation/heading-deg") );
1626     }
1627
1628     // Initialize time
1629     SGPath zone( globals->get_fg_root() );
1630     zone.append( "Timezone" );
1631     SGTime *t = new SGTime( fgGetDouble("/position/longitude-deg") * SGD_DEGREES_TO_RADIANS,
1632                             fgGetDouble("/position/latitude-deg") * SGD_DEGREES_TO_RADIANS,
1633                             zone.str() );
1634
1635     // Handle potential user specified time offsets
1636     time_t cur_time = t->get_cur_time();
1637     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1638     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1639     time_t aircraftLocalTime = 
1640         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1641
1642     // Okay, we now have six possible scenarios
1643     int offset = fgGetInt("/sim/startup/time-offset");
1644     const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1645     if (offset_type == "system-offset") {
1646         globals->set_warp( offset );
1647     } else if (offset_type == "gmt-offset") {
1648         globals->set_warp( offset - (currGMT - systemLocalTime) );
1649     } else if (offset_type == "latitude-offset") {
1650         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1651     } else if (offset_type == "system") {
1652         globals->set_warp( offset - cur_time );
1653     } else if (offset_type == "gmt") {
1654         globals->set_warp( offset - currGMT );
1655     } else if (offset_type == "latitude") {
1656         globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) - 
1657                            cur_time ); 
1658     } else {
1659         SG_LOG( SG_GENERAL, SG_ALERT,
1660                 "Unsupported offset type " << offset_type );
1661         exit( -1 );
1662     }
1663
1664     SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = " 
1665             << globals->get_warp() );
1666
1667     globals->set_warp_delta( 0 );
1668
1669     t->update( 0.0, 0.0, globals->get_warp() );
1670
1671     globals->set_time_params( t );
1672
1673     // Do some quick general initializations
1674     if( !fgInitGeneral()) {
1675         SG_LOG( SG_GENERAL, SG_ALERT, 
1676                 "General initializations failed ..." );
1677         exit(-1);
1678     }
1679
1680     SGPath modelpath( globals->get_fg_root() );
1681     ssgModelPath( (char *)modelpath.c_str() );
1682   
1683     // Scene graph root
1684     scene = new ssgRoot;
1685     scene->setName( "Scene" );
1686
1687     lighting = new ssgRoot;
1688     lighting->setName( "Lighting" );
1689
1690     // Initialize the sky
1691     SGPath ephem_data_path( globals->get_fg_root() );
1692     ephem_data_path.append( "Astro" );
1693     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1694     ephem->update( globals->get_time_params()->getMjd(),
1695                    globals->get_time_params()->getLst(),
1696                    0.0 );
1697     globals->set_ephem( ephem );
1698
1699     thesky = new SGSky;
1700
1701     SGPath sky_tex_path( globals->get_fg_root() );
1702     sky_tex_path.append( "Textures" );
1703     sky_tex_path.append( "Sky" );
1704     thesky->texture_path( sky_tex_path.str() );
1705
1706     thesky->build( 550.0, 550.0,
1707                    globals->get_ephem()->getNumPlanets(), 
1708                    globals->get_ephem()->getPlanets(), 60000.0,
1709                    globals->get_ephem()->getNumStars(),
1710                    globals->get_ephem()->getStars(), 60000.0 );
1711
1712     if ( fgGetBool("/environment/clouds/status") ) {
1713         // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1714         //                          SG_CLOUD_OVERCAST );
1715         thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1716                                  SG_CLOUD_MOSTLY_CLOUDY );
1717         // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1718         //                          SG_CLOUD_MOSTLY_SUNNY );
1719         thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1720                                  SG_CLOUD_CIRRUS );
1721     }
1722
1723     // Initialize MagVar model
1724     SGMagVar *magvar = new SGMagVar();
1725     globals->set_mag( magvar );
1726
1727     // Terrain branch
1728     terrain = new ssgBranch;
1729     terrain->setName( "Terrain" );
1730     scene->addKid( terrain );
1731
1732     // Lighting
1733     ground = new ssgBranch;
1734     ground->setName( "Ground Lighting" );
1735     lighting->addKid( ground );
1736
1737     airport = new ssgBranch;
1738     airport->setName( "Airport Lighting" );
1739     lighting->addKid( airport );
1740
1741     // ADA
1742     fgLoadDCS();
1743     // ADA
1744
1745     // temporary visible aircraft "own ship"
1746     acmodel_selector = new ssgSelector;
1747     acmodel_pos = new ssgTransform;
1748
1749     ssgEntity *acmodel_obj = NULL;
1750     if (fgGetString("/sim/flight-model") == "ada") {
1751         // ada exteranl aircraft model loading
1752         if( !ship_pos[0]->getKid(0) ) {
1753             // fall back to default
1754             ssgEntity *acmodel_obj = ssgLoad( (char *)"glider.ac" );
1755             if( !acmodel_obj ) {
1756                 SG_LOG( SG_GENERAL, SG_ALERT, "FAILED to LOAD an AC model! ..." );
1757                 exit(-1);
1758             }
1759             acmodel_pos->addKid( acmodel_obj );
1760         } else {
1761             acmodel_obj = ship_pos[0]->getKid(0);
1762         }
1763     } else {
1764         // default aircraft model loading
1765
1766         // Get the model location, and load textures from the same
1767         // directory.  Use an absolute path for the model to avoid
1768         // incompatibilities in different versions of PLIB.
1769         string acmodel_path =
1770             fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1771         SGPath full_model = globals->get_fg_root();
1772         full_model.append(acmodel_path);
1773
1774         ssgTexturePath( (char *)full_model.dir().c_str() );
1775         acmodel_obj = ssgLoad( (char *)full_model.c_str() );
1776         if( !acmodel_obj ) {
1777             // fall back to default
1778             acmodel_obj = ssgLoad( (char *)"Models/Geometry/glider.ac" );
1779             if( !acmodel_obj ) {
1780                 SG_LOG( SG_GENERAL, SG_ALERT, "FAILED to LOAD an AC model! ..." );
1781                 exit(-1);
1782             }
1783         }
1784     }
1785
1786     // find moving parts (if this is an MDL model)
1787     flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1788     prop_selector  = (ssgSelector*)fgFindNode( acmodel_obj, "PROP"  );
1789
1790     acmodel_npropsettings = 0;
1791     if (prop_selector != NULL) {
1792       for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1793            kid = prop_selector->getNextKid()) {
1794         int prop_low, prop_high;
1795         if ( sscanf(kid->getName(), "PROP_%d_%d", 
1796                     &prop_low, &prop_high) == 2 ) {
1797           prop_low  = (int)((float)prop_low  * (5000.0f / 32767.0f));
1798           prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1799           acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1800           acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1801           acmodel_npropsettings++;
1802
1803           SG_LOG( SG_GENERAL, SG_INFO, "PROPELLER SETTING " << prop_low <<
1804                   " " << prop_high );
1805         }
1806       }
1807     }
1808
1809     // align the model properly for FGFS
1810     ssgTransform *acmodel_align = new ssgTransform;
1811     acmodel_align->addKid(acmodel_obj);
1812     sgMat4 rot_matrix;
1813     sgMat4 off_matrix;
1814     sgMat4 res_matrix;
1815     float h_rot = fgGetFloat("/sim/model/heading-offset-deg", 0.0);
1816     float p_rot = fgGetFloat("/sim/model/roll-offset-deg", 0.0);
1817     float r_rot = fgGetFloat("/sim/model/pitch-offset-deg", 0.0);
1818     float x_off = fgGetFloat("/sim/model/x-offset-m", 0.0);
1819     float y_off = fgGetFloat("/sim/model/y-offset-m", 0.0);
1820     float z_off = fgGetFloat("/sim/model/z-offset-m", 0.0);
1821     sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1822     sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1823     sgMultMat4(res_matrix, off_matrix, rot_matrix);
1824     acmodel_align->setTransform(res_matrix);
1825
1826     acmodel_pos->addKid( acmodel_align );
1827     acmodel_selector->addKid( acmodel_pos );
1828     //ssgFlatten( acmodel_obj );
1829     //ssgStripify( acmodel_selector );
1830     acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1831     scene->addKid( acmodel_selector );
1832
1833 #ifdef FG_NETWORK_OLK
1834     // Do the network intialization
1835     if ( fgGetBool("/sim/networking/network-olk") ) {
1836         printf("Multipilot mode %s\n", fg_net_init( scene ) );
1837     }
1838 #endif
1839
1840     // build our custom render states
1841     fgBuildRenderStates();
1842
1843     // pass control off to the master GLUT event handler
1844     glutMainLoop();
1845
1846     // we never actually get here ... but to avoid compiler warnings,
1847     // etc.
1848     return 0;
1849 }
1850
1851
1852 // $$$ end - added VS Renganathan, 15 Oct 2K
1853 //         - added Venky         , 12 Nov 2K
1854
1855 // Main entry point; catch any exceptions that have made it this far.
1856 int main ( int argc, char **argv ) {
1857
1858 #if defined( _MSC_VER ) && defined( DEBUG )
1859     // Christian, we should document what this does
1860     _control87( _EM_INEXACT, _MCW_EM );
1861 #endif
1862
1863 #if defined( HAVE_BC5PLUS )
1864     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1865 #endif
1866
1867     // FIXME: add other, more specific
1868     // exceptions.
1869     try {
1870         mainLoop(argc, argv);
1871     } catch (sg_throwable &t) {
1872         SG_LOG(SG_GENERAL, SG_ALERT,
1873                "Fatal error: " << t.getFormattedMessage()
1874                << "\n (received from " << t.getOrigin() << ')');
1875         exit(1);
1876     }
1877
1878     return 0;
1879 }
1880
1881
1882 void fgLoadDCS(void) {
1883
1884     ssgEntity *ship_obj = NULL;
1885
1886     char obj_filename[25];
1887
1888     for ( int k = 0; k < 32; k++ ) {
1889         ship_pos[k]=NULL;
1890     }
1891
1892     SGPath tile_path( globals->get_fg_root());
1893     tile_path.append( "Scenery" );
1894     tile_path.append( "Objects.txt" );
1895     sg_gzifstream in( tile_path.str() );
1896     if ( ! in.is_open() ) {
1897         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1898     } else {
1899
1900         SGPath modelpath( globals->get_fg_root() );
1901         modelpath.append( "Models" );
1902         modelpath.append( "Geometry" );
1903   
1904         SGPath texturepath( globals->get_fg_root() );
1905         texturepath.append( "Models" );
1906         texturepath.append( "Textures" );
1907  
1908         ssgModelPath( (char *)modelpath.c_str() );
1909         ssgTexturePath( (char *)texturepath.c_str() );
1910
1911         ship_sel = new ssgSelector;
1912
1913         char c;
1914         while ( ! in.eof() ) {
1915             in >> ::skipws;
1916             if ( in.get( c ) && c == '#' ) { 
1917                 in >> skipeol;
1918             } else { 
1919                 in.putback(c);
1920                 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1921                 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] <<  " " << obj_alt[objc] << endl;
1922                    int chj=getchar();*/
1923                 
1924                 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1925                 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1926                 
1927                 ship_pos[objc] = new ssgTransform;
1928        
1929                 // type "repeat" in objects.txt to load one more
1930                 // instance of the last object.
1931
1932                 if ( strcmp(obj_filename,"repeat") != 0) {
1933                     ship_obj = ssgLoad( obj_filename );
1934                 }
1935       
1936                 if ( ship_obj != NULL ) {
1937                                         ship_obj->setName(obj_filename);
1938                                 if (objc == 0)
1939                                                 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1940                                         else
1941                                                 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1942                     ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1943                     ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1944                     SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1945                             << obj_filename );
1946                 } else {
1947                     SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1948                             << obj_filename );
1949                 }
1950             
1951                                 // temporary hack for deck lights - ultimately should move to PLib (when??)
1952                                 //const char *extn = file_extension ( obj_filename ) ;
1953                                 if ( objc == 1 ){
1954                                     ssgVertexArray *lights = new ssgVertexArray( 100 );
1955                                         ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1956                                         ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1957                                         ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1958                                         int ltype[500], light_type;
1959                                         static int ltcount = 0;
1960                                     string token;
1961                                         sgVec3 rway_dir,rway_normal,lightpt;
1962                                         Point3D node;
1963                                         modelpath.append(obj_filename);
1964                                         sg_gzifstream in1( modelpath.str() );
1965                                         if ( ! in1.is_open() ) {
1966                                                 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1967                                         } else {
1968                                                 while ( ! in1.eof() ) {
1969                                                         in1 >> ::skipws;
1970                                                         if ( in1.get( c ) && c == '#' ) { 
1971                                                                 in1 >> skipeol;
1972                                                         } else { 
1973                                                                 in1.putback(c);
1974                                                                 in1 >> token;
1975                                                                 //cout << token << endl;
1976                                                                 if ( token == "runway" ) {
1977                                                                         in1 >> node;
1978                                                                         sgSetVec3 (rway_dir, node[0], node[1], node[2] );                        
1979                                                                 } else if ( token == "edgelight" ) {
1980                                                                         in1 >> node;
1981                                                                         sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1982                                                                         light_type = 1;
1983                                                                 } else if ( token == "taxi" ) {
1984                                                                         in1 >> node;
1985                                                                         sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
1986                                                                         light_type = 2;
1987                                                                 } else if ( token == "vasi" ) {
1988                                                                         in1 >> node;
1989                                                                         sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
1990                                                                         light_type = 3;
1991                                                                 } else if ( token == "threshold" ) {
1992                                                                         in1 >> node;
1993                                                                         sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
1994                                                                         light_type = 4;
1995                                                                 } else if ( token == "rabbit" ) {
1996                                                                         in1 >> node;
1997                                                                         sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1998                                                                         light_type = 5;
1999                                                                 } else if ( token == "ols" ) {
2000                                                                         in1 >> node;
2001                                                                         sgSetVec3 (rway_ols, node[0], node[1], node[2] );
2002                                                                         light_type = 6;
2003                                                                 } else if ( token == "red" ) {
2004                                                                         in1 >> node;
2005                                                                         sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2006                                                                         light_type = 7;
2007                                                                 } else if ( token == "green" ) {
2008                                                                         in1 >> node;
2009                                                                         sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2010                                                                         light_type = 8;
2011                                                                 } else if ( token == "lp" ) {
2012                                                                         in1 >> node;
2013                                                                         sgSetVec3 (lightpt, node[0], node[1], node[2] );
2014                                                                         lightpoints->add( lightpt );
2015                                                                         lightnormals->add( rway_normal );
2016                                                                         lightdir->add( rway_dir );
2017                                                                         ltype[ltcount]= light_type;
2018                                                                         ltcount++;
2019                                                                 }
2020                                                                 if (in1.eof()) break;
2021                                                         } 
2022                                                 }  //while
2023         
2024                                                 if ( lightpoints->getNum() ) {
2025                                                         ssgBranch *lightpoints_branch;
2026                                                         long int dummy = -999;
2027                                                         dummy_tile = new FGTileEntry((SGBucket)dummy);
2028                                                         dummy_tile->lightmaps_sequence = new ssgSelector;
2029                                                         dummy_tile->ols_transform = new ssgTransform;
2030
2031                                                         // call function to generate the runway lights
2032                                                         lightpoints_branch = 
2033                                                         dummy_tile->gen_runway_lights( lightpoints, lightnormals,
2034                                                                                                                                 lightdir, ltype);
2035                                                         lightpoints_brightness->addKid(lightpoints_branch);
2036                                                         lightpoints_transform->addKid(lightpoints_brightness);
2037                                                     //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
2038                                                         lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
2039                                                         lightpoints_transform->ref();
2040                                                         ground->addKid( lightpoints_transform );
2041                                                 } 
2042                                         } //if in1 
2043                 } //if objc
2044                                 // end hack for deck lights
2045
2046                 objc++;
2047
2048                 if (in.eof()) break;
2049             }
2050         } // while
2051
2052         SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
2053
2054         terrain->addKid( ship_sel ); //add selector node to root node 
2055     }
2056
2057     return;
2058  }
2059
2060
2061 void fgUpdateDCS (void) {
2062
2063     // double eye_lat,eye_lon,eye_alt;
2064     // static double obj_head;
2065     double sl_radius,obj_latgc;
2066     // float nresultmat[4][4];
2067     // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
2068     double bz[3];
2069
2070     // Instantaneous Geodetic Lat/Lon/Alt of moving object
2071     FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
2072     
2073     // Deck should be the first object in objects.txt in case of fdm=ada
2074
2075     if (fgGetString("/sim/flight-model") == "ada") {
2076                 if ((fdm->get_iaux(1))==1)
2077                 {
2078                         obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
2079                         obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
2080                         obj_alt[1] = fdm->get_daux(3);
2081                         obj_pitch[1] = fdm->get_faux(1);
2082                         obj_roll[1] = fdm->get_faux(2);
2083                 }
2084     }
2085     
2086     for ( int m = 0; m < objc; m++ ) {
2087         //cout << endl <<  obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
2088         //int v=getchar();
2089
2090         //Geodetic to Geocentric angles for rotation
2091         sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
2092
2093         //moving object gbs-posn in cartesian coords
2094         Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
2095         Point3D obj_pos = sgGeodToCart( obj_posn );
2096
2097         // Translate moving object w.r.t eye
2098         Point3D Objtrans = obj_pos-scenery.center;
2099         bz[0]=Objtrans.x();
2100         bz[1]=Objtrans.y();
2101         bz[2]=Objtrans.z();
2102
2103        // rotate dynamic objects for lat,lon & alt and other motion about its axes
2104         
2105         sgMat4 sgTRANS;
2106         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
2107
2108         sgVec3 ship_fwd,ship_rt,ship_up;
2109         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
2110         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
2111         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
2112
2113         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
2114         sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
2115         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
2116         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
2117         sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
2118         sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2119         
2120         sgMat4 sgTUX;
2121         sgCopyMat4( sgTUX, sgROT_hdg );
2122         sgPostMultMat4( sgTUX, sgROT_pitch );
2123         sgPostMultMat4( sgTUX, sgROT_roll );
2124         sgPostMultMat4( sgTUX, sgROT_lat );
2125         sgPostMultMat4( sgTUX, sgROT_lon );
2126         sgPostMultMat4( sgTUX, sgTRANS );
2127
2128         sgCoord shippos;
2129         sgSetCoord(&shippos, sgTUX );
2130         ship_pos[m]->setTransform( &shippos );
2131         // temporary hack for deck lights - ultimately should move to PLib (when ??)
2132         if (m == 1) {
2133                 if (lightpoints_transform) {
2134                         lightpoints_transform->setTransform( &shippos );
2135                         float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2136                         if ( sun_angle > 89 ) {
2137                                 lightpoints_brightness->select(0x01);
2138                         } else {
2139                                 lightpoints_brightness->select(0x00);
2140                         }
2141                 }
2142
2143                 float elev;
2144                 sgVec3 rp,to;
2145                 float *vp;
2146                 float alt;
2147                 float ref_elev;
2148                 sgXformPnt3( rp, rway_ols, sgTUX );
2149                 vp = globals->get_current_view()->get_view_pos();
2150             to[0] = rp[0]-vp[0];
2151             to[1] = rp[1]-vp[1];
2152             to[2] = rp[2]-vp[2];
2153                 float dist = sgLengthVec3( to );
2154                 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2155
2156                 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2157
2158             ref_elev = elev - 3.75; // +ve above, -ve below
2159         
2160                 unsigned int sel;
2161                 sel = 0xFF;
2162 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2163 //              if (ref_elev > 0.51) sel = 0x21;
2164 //              if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2165 //              if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2166 //              if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2167 //              if (ref_elev < -0.51) sel = 0x30;
2168 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2169                 dummy_tile->lightmaps_sequence->select(sel);
2170
2171                 sgVec3 up;
2172                 sgCopyVec3 (up, ship_up);
2173                 if (dist > 750) 
2174                         sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2175                 else
2176                         sgScaleVec3 (up, 4.0*ref_elev);
2177                 dummy_tile->ols_transform->setTransform(up);
2178                 //cout << "ref_elev  " << ref_elev << endl;
2179         }
2180     // end hack for deck lights
2181
2182     }
2183     if ( ship_sel != NULL ) {
2184         ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2185     }
2186 }
2187
2188 // $$$ end - added VS Renganathan, 15 Oct 2K
2189 //           added Venky         , 12 Nov 2K