]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Remove the last traces of metakit (hopefully) :-)
[flightgear.git] / src / Main / main.cxx
1 // main.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997 - 2002  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
30 #if defined(__linux__) && defined(__i386__)
31 #  include <fpu_control.h>
32 #  include <signal.h>
33 #endif
34
35 #ifdef SG_MATH_EXCEPTION_CLASH
36 #  include <math.h>
37 #endif
38
39 #ifdef HAVE_WINDOWS_H
40 #  include <windows.h>
41 #  include <float.h>
42 #endif
43
44 #include <plib/ssg.h>
45 #include <plib/pu.h>
46 #include <plib/netSocket.h>
47
48 #include <simgear/screen/extensions.hxx>
49 #include <simgear/scene/material/matlib.hxx>
50 #include <simgear/props/props.hxx>
51 #include <simgear/scene/sky/sky.hxx>
52 #include <simgear/timing/sg_time.hxx>
53 #include <simgear/scene/model/animation.hxx>
54 #include <simgear/ephemeris/ephemeris.hxx>
55 #include <simgear/scene/model/placement.hxx>
56 #include <simgear/math/sg_random.h>
57 #include <simgear/route/route.hxx>
58 #include <simgear/scene/model/modellib.hxx>
59
60 #ifdef FG_USE_CLOUDS_3D
61 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
62 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
63 #endif
64
65 #include <Include/general.hxx>
66 #include <Scenery/tileentry.hxx>
67 #include <Time/FGEventMgr.hxx>
68 #include <Time/light.hxx>
69 #include <Time/light.hxx>
70 #include <Aircraft/aircraft.hxx>
71 #include <Cockpit/panel.hxx>
72 #include <Cockpit/cockpit.hxx>
73 #include <Cockpit/radiostack.hxx>
74 #include <Cockpit/hud.hxx>
75 #include <Model/panelnode.hxx>
76 #include <Model/modelmgr.hxx>
77 #include <Model/acmodel.hxx>
78 #include <Scenery/scenery.hxx>
79 #include <Scenery/tilemgr.hxx>
80 #include <FDM/flight.hxx>
81 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
82 #include <FDM/ADA.hxx>
83 #include <ATC/ATCdisplay.hxx>
84 #include <ATC/ATCmgr.hxx>
85 #include <ATC/AIMgr.hxx>
86 #include <Autopilot/newauto.hxx>
87 #include <Replay/replay.hxx>
88 #include <Time/tmp.hxx>
89 #include <Time/fg_timer.hxx>
90 #include <Environment/environment_mgr.hxx>
91
92 #ifdef FG_NETWORK_OLK
93 #include <NetworkOLK/network.h>
94 #endif
95
96 #ifdef FG_MPLAYER_AS
97 #include <MultiPlayer/multiplaytxmgr.hxx>
98 #include <MultiPlayer/multiplayrxmgr.hxx>
99 #endif
100
101 #include "splash.hxx"
102 #include "fg_commands.hxx"
103 #include "fg_io.hxx"
104
105
106 glPointParameterfProc glPointParameterfPtr = 0;
107 glPointParameterfvProc glPointParameterfvPtr = 0;
108 bool glPointParameterIsSupported = false;
109
110 float default_attenuation[3] = {1.0, 0.0, 0.0};
111 //Required for using GL_extensions
112 void fgLoadDCS (void);
113 void fgUpdateDCS (void);
114 ssgSelector *ship_sel=NULL;
115 // upto 32 instances of a same object can be loaded.
116 ssgTransform *ship_pos[32];
117 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
118 int objc=0;
119 ssgSelector *lightpoints_brightness = new ssgSelector;
120 ssgTransform *lightpoints_transform = new ssgTransform;
121 FGTileEntry *dummy_tile;
122 sgVec3 rway_ols;
123 // ADA
124 // Clip plane settings...
125 float scene_nearplane = 0.5f;
126 float scene_farplane = 120000.0f;
127
128 static double delta_time_sec = 0.0;
129
130
131 #ifdef FG_WEATHERCM
132 #  include <WeatherCM/FGLocalWeatherDatabase.h>
133 #endif
134
135 #ifdef macintosh
136 #  include <console.h>          // -dw- for command line dialog
137 #endif
138
139 FGEventMgr global_events;
140
141 // This is a record containing a bit of global housekeeping information
142 FGGeneral general;
143
144 // Specify our current idle function state.  This is used to run all
145 // our initializations out of the glutIdleLoop() so that we can get a
146 // splash screen up and running right away.
147 static int idle_state = 0;
148 static long global_multi_loop;
149
150 // fog constants.  I'm a little nervous about putting actual code out
151 // here but it seems to work (?)
152 static const double m_log01 = -log( 0.01 );
153 static const double sqrt_m_log01 = sqrt( m_log01 );
154 static GLfloat fog_exp_density;
155 static GLfloat fog_exp2_density;
156 static GLfloat rwy_exp2_punch_through;
157 static GLfloat taxi_exp2_punch_through;
158 static GLfloat ground_exp2_punch_through;
159
160 #ifdef FG_NETWORK_OLK
161 ssgSelector *fgd_sel = NULL;
162 ssgTransform *fgd_pos = NULL;
163 #endif
164
165 // Sky structures
166 SGSky *thesky;
167
168 #ifdef FG_USE_CLOUDS_3D
169   SkySceneLoader *sgClouds3d;
170   bool _bcloud_orig = true;
171 #endif
172
173 // hack
174 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
175 {
176   {  1.0f,  0.0f,  0.0f,  0.0f },
177   {  0.0f,  0.0f, -1.0f,  0.0f },
178   {  0.0f,  1.0f,  0.0f,  0.0f },
179   {  0.0f,  0.0f,  0.0f,  1.0f }
180 };
181
182 // The following defines flightgear options. Because glutlib will also
183 // want to parse its own options, those options must not be included here
184 // or they will get parsed by the main program option parser. Hence case
185 // is significant for any option added that might be in conflict with
186 // glutlib's parser.
187 //
188 // glutlib parses for:
189 //    -display
190 //    -direct   (invalid in Win32)
191 //    -geometry
192 //    -gldebug
193 //    -iconized
194 //    -indirect (invalid in Win32)
195 //    -synce
196 //
197 // Note that glutlib depends upon strings while this program's
198 // option parser wants only initial characters followed by numbers
199 // or pathnames.
200 //
201
202
203 ssgSimpleState *cloud3d_imposter_state;
204 ssgSimpleState *default_state;
205 ssgSimpleState *hud_and_panel;
206 ssgSimpleState *menus;
207
208 SGTimeStamp last_time_stamp;
209 SGTimeStamp current_time_stamp;
210
211
212 void fgBuildRenderStates( void ) {
213     default_state = new ssgSimpleState;
214     default_state->ref();
215     default_state->disable( GL_TEXTURE_2D );
216     default_state->enable( GL_CULL_FACE );
217     default_state->enable( GL_COLOR_MATERIAL );
218     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
219     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
220     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
221     default_state->disable( GL_BLEND );
222     default_state->disable( GL_ALPHA_TEST );
223     default_state->disable( GL_LIGHTING );
224
225     cloud3d_imposter_state = new ssgSimpleState;
226     cloud3d_imposter_state->ref();
227     cloud3d_imposter_state->enable( GL_TEXTURE_2D );
228     cloud3d_imposter_state->enable( GL_CULL_FACE );
229     cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
230     cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
231     cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
232     cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
233     cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
234     cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
235     cloud3d_imposter_state->enable( GL_BLEND );
236     cloud3d_imposter_state->enable( GL_ALPHA_TEST );
237     cloud3d_imposter_state->disable( GL_LIGHTING );
238
239     hud_and_panel = new ssgSimpleState;
240     hud_and_panel->ref();
241     hud_and_panel->disable( GL_CULL_FACE );
242     hud_and_panel->disable( GL_TEXTURE_2D );
243     hud_and_panel->disable( GL_LIGHTING );
244     hud_and_panel->enable( GL_BLEND );
245
246     menus = new ssgSimpleState;
247     menus->ref();
248     menus->disable( GL_CULL_FACE );
249     menus->disable( GL_TEXTURE_2D );
250     menus->enable( GL_BLEND );
251 }
252
253
254 // fgInitVisuals() -- Initialize various GL/view parameters
255 void fgInitVisuals( void ) {
256     fgLIGHT *l;
257
258     l = &cur_light_params;
259
260 #ifndef GLUT_WRONG_VERSION
261     // Go full screen if requested ...
262     if ( fgGetBool("/sim/startup/fullscreen") ) {
263         glutFullScreen();
264     }
265 #endif
266
267     // If enabled, normal vectors specified with glNormal are scaled
268     // to unit length after transformation.  Enabling this has
269     // performance implications.  See the docs for glNormal.
270     // glEnable( GL_NORMALIZE );
271
272     glEnable( GL_LIGHTING );
273     glEnable( GL_LIGHT0 );
274     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
275
276     sgVec3 sunpos;
277     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
278     ssgGetLight( 0 ) -> setPosition( sunpos );
279
280     glFogi (GL_FOG_MODE, GL_EXP2);
281     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
282          (!fgGetBool("/sim/rendering/shading"))) {
283         // if fastest fog requested, or if flat shading force fastest
284         glHint ( GL_FOG_HINT, GL_FASTEST );
285     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
286         glHint ( GL_FOG_HINT, GL_NICEST );
287     }
288     if ( fgGetBool("/sim/rendering/wireframe") ) {
289         // draw wire frame
290         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
291     }
292
293     // This is the default anyways, but it can't hurt
294     glFrontFace ( GL_CCW );
295
296     // Just testing ...
297     // glEnable(GL_POINT_SMOOTH);
298     // glEnable(GL_LINE_SMOOTH);
299     // glEnable(GL_POLYGON_SMOOTH);      
300 }
301
302
303 // For HiRes screen Dumps using Brian Pauls TR Library
304 void trRenderFrame( void ) {
305
306     if ( fgPanelVisible() ) {
307         GLfloat height = fgGetInt("/sim/startup/ysize");
308         GLfloat view_h =
309             (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
310             * (height / 768.0) + 1;
311         glTranslatef( 0.0, view_h, 0.0 );
312     }
313
314     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
315     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
316
317     fgLIGHT *l = &cur_light_params;
318
319     glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
320                  l->adj_fog_color[2], l->adj_fog_color[3]);
321
322     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
323
324     // set the opengl state to known default values
325     default_state->force();
326
327     glEnable( GL_FOG );
328     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
329     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
330     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color );
331
332     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
333     // we only update GL_AMBIENT for our lights we will never get
334     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
335     // explicitely to black.
336     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
337     glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
338
339     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
340
341     // texture parameters
342     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
343     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
344
345     // we need a white diffuse light for the phase of the moon
346     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
347     thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
348
349     // draw the ssg scene
350     // return to the desired diffuse color
351     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
352     glEnable( GL_DEPTH_TEST );
353     ssgSetNearFar( scene_nearplane, scene_farplane );
354     ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
355
356     // draw the lights
357     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
358     ssgSetNearFar( scene_nearplane, scene_farplane );
359     ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
360
361     ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
362
363     if (fgGetBool("/environment/clouds/status"))
364         thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
365
366     globals->get_model_mgr()->draw();
367     globals->get_aircraft_model()->draw();
368 }
369
370
371 // Update all Visuals (redraws anything graphics related)
372 void fgRenderFrame() {
373     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
374     bool skyblend = fgGetBool("/sim/rendering/skyblend");
375     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
376     bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
377
378     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
379     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
380
381     // Process/manage pending events
382     global_events.update( delta_time_sec );
383
384     // static const SGPropertyNode *longitude
385     //     = fgGetNode("/position/longitude-deg");
386     // static const SGPropertyNode *latitude
387     //     = fgGetNode("/position/latitude-deg");
388     // static const SGPropertyNode *altitude
389     //     = fgGetNode("/position/altitude-ft");
390     static const SGPropertyNode *groundlevel_nearplane
391         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
392
393     // Update the default (kludged) properties.
394     fgUpdateProps();
395
396     FGViewer *current__view = globals->get_current_view();
397
398     fgLIGHT *l = &cur_light_params;
399     static double last_visibility = -9999;
400
401     // update fog params
402     double actual_visibility;
403     if (fgGetBool("/environment/clouds/status"))
404         actual_visibility = thesky->get_visibility();
405     else
406         actual_visibility = fgGetDouble("/environment/visibility-m");
407     if ( actual_visibility != last_visibility ) {
408         last_visibility = actual_visibility;
409
410         fog_exp_density = m_log01 / actual_visibility;
411         fog_exp2_density = sqrt_m_log01 / actual_visibility;
412         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
413         if ( actual_visibility < 8000 ) {
414             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
415             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
416         } else {
417             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
418             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
419         }
420     }
421
422     // double angle;
423     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
424     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
425     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
426     // GLfloat mat_shininess[] = { 10.0 };
427     GLbitfield clear_mask;
428
429     if ( idle_state != 1000 ) {
430         // still initializing, draw the splash screen
431         if ( fgGetBool("/sim/startup/splash-screen") ) {
432             fgSplashUpdate(0.0, 1.0);
433         }
434         // Keep resetting sim time while the sim is initializing
435         globals->set_sim_time_sec( 0.0 );
436         SGAnimation::set_sim_time_sec( 0.0 );
437     } else {
438         // idle_state is now 1000 meaning we've finished all our
439         // initializations and are running the main loop, so this will
440         // now work without seg faulting the system.
441
442         // calculate our current position in cartesian space
443         globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
444
445         // update view port
446         fgReshape( fgGetInt("/sim/startup/xsize"),
447                    fgGetInt("/sim/startup/ysize") );
448
449         if ( fgGetBool("/sim/rendering/clouds3d") ) {
450             glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
451             cloud3d_imposter_state->force();
452             glDisable( GL_FOG );
453             glColor4f( 1.0, 1.0, 1.0, 1.0 );
454             glEnable(GL_DEPTH_TEST);
455             glEnable(GL_BLEND);
456             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
457
458 #ifdef FG_USE_CLOUDS_3D
459             if ( _bcloud_orig ) {
460                 Point3D c = globals->get_scenery()->get_center();
461                 sgClouds3d->Set_Cloud_Orig( &c );
462                 _bcloud_orig = false;
463             }
464             sgClouds3d->Update( current__view->get_absolute_view_pos() );
465 #endif
466             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
467             glDisable(GL_DEPTH_TEST);
468         }
469
470         clear_mask = GL_DEPTH_BUFFER_BIT;
471         if ( fgGetBool("/sim/rendering/wireframe") ) {
472             clear_mask |= GL_COLOR_BUFFER_BIT;
473         }
474
475         if ( skyblend ) {
476             if ( fgGetBool("/sim/rendering/textures") ) {
477             // glClearColor(black[0], black[1], black[2], black[3]);
478             glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
479                          l->adj_fog_color[2], l->adj_fog_color[3]);
480             clear_mask |= GL_COLOR_BUFFER_BIT;
481             }
482         } else {
483             glClearColor(l->sky_color[0], l->sky_color[1],
484                      l->sky_color[2], l->sky_color[3]);
485             clear_mask |= GL_COLOR_BUFFER_BIT;
486         }
487         glClear( clear_mask );
488
489         // Tell GL we are switching to model view parameters
490
491         // I really should create a derived ssg node or use a call
492         // back or something so that I can draw the sky within the
493         // ssgCullAndDraw() function, but for now I just mimic what
494         // ssg does to set up the model view matrix
495         glMatrixMode(GL_MODELVIEW);
496         glLoadIdentity();
497         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
498
499         // set the opengl state to known default values
500         default_state->force();
501
502         // update fog params if visibility has changed
503         double visibility_meters = fgGetDouble("/environment/visibility-m");
504         thesky->set_visibility(visibility_meters);
505
506         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
507                             ( global_multi_loop * fgGetInt("/sim/speed-up") )
508                             / (double)fgGetInt("/sim/model-hz") );
509
510         // Set correct opengl fog density
511         glFogf (GL_FOG_DENSITY, fog_exp2_density);
512
513         // update the sky dome
514         if ( skyblend ) {
515             /*
516              SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
517              << cur_light_params.sky_color[0] << " "
518              << cur_light_params.sky_color[1] << " "
519              << cur_light_params.sky_color[2] << " "
520              << cur_light_params.sky_color[3] );
521             SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
522              << cur_light_params.fog_color[0] << " "
523              << cur_light_params.fog_color[1] << " "
524              << cur_light_params.fog_color[2] << " "
525              << cur_light_params.fog_color[3] ); 
526             SG_LOG( SG_GENERAL, SG_BULK,
527                     "    sun_angle = " << cur_light_params.sun_angle
528              << "    moon_angle = " << cur_light_params.moon_angle );
529             */
530
531             static SGSkyColor scolor;
532
533             scolor.sky_color   = cur_light_params.sky_color;
534             scolor.fog_color   = cur_light_params.adj_fog_color;
535             scolor.cloud_color = cur_light_params.cloud_color;
536             scolor.sun_angle   = cur_light_params.sun_angle;
537             scolor.moon_angle  = cur_light_params.moon_angle;
538             scolor.nplanets    = globals->get_ephem()->getNumPlanets();
539             scolor.nstars      = globals->get_ephem()->getNumStars();
540             scolor.planet_data = globals->get_ephem()->getPlanets();
541             scolor.star_data   = globals->get_ephem()->getStars();
542
543             thesky->repaint( scolor );
544
545             /*
546             SG_LOG( SG_GENERAL, SG_BULK,
547                     "thesky->reposition( view_pos = " << view_pos[0] << " "
548              << view_pos[1] << " " << view_pos[2] );
549             SG_LOG( SG_GENERAL, SG_BULK,
550                     "    zero_elev = " << zero_elev[0] << " "
551              << zero_elev[1] << " " << zero_elev[2]
552              << " lon = " << cur_fdm_state->get_Longitude()
553              << " lat = " << cur_fdm_state->get_Latitude() );
554             SG_LOG( SG_GENERAL, SG_BULK,
555                     "    sun_rot = " << cur_light_params.sun_rotation
556              << " gst = " << SGTime::cur_time_params->getGst() );
557             SG_LOG( SG_GENERAL, SG_BULK,
558                  "    sun ra = " << globals->get_ephem()->getSunRightAscension()
559               << " sun dec = " << globals->get_ephem()->getSunDeclination()
560               << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
561               << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
562             */
563
564             // The sun and moon distances are scaled down versions
565             // of the actual distance to get both the moon and the sun
566             // within the range of the far clip plane.
567             // Moon distance:    384,467 kilometers
568             // Sun distance: 150,000,000 kilometers
569             double sun_horiz_eff, moon_horiz_eff;
570             if (fgGetBool("/sim/rendering/horizon-effect")) {
571             sun_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.sun_angle*2)/2,0.33)/3;
572             moon_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.moon_angle*2)/2,0.33)/3;
573             } else {
574                sun_horiz_eff = moon_horiz_eff = 1.0;
575             }
576
577             static SGSkyState sstate;
578
579             sstate.view_pos  = current__view->get_view_pos();
580             sstate.zero_elev = current__view->get_zero_elev();
581             sstate.view_up   = current__view->get_world_up();
582             sstate.lon       = current__view->getLongitude_deg()
583                                 * SGD_DEGREES_TO_RADIANS;
584             sstate.lat       = current__view->getLatitude_deg()
585                                 * SGD_DEGREES_TO_RADIANS;
586             sstate.alt       = current__view->getAltitudeASL_ft()
587                                 * SG_FEET_TO_METER;
588             sstate.spin      = cur_light_params.sun_rotation;
589             sstate.gst       = globals->get_time_params()->getGst();
590             sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
591             sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
592             sstate.sun_dist  = 50000.0 * sun_horiz_eff;
593             sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
594             sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
595             sstate.moon_dist = 40000.0 * moon_horiz_eff;
596
597             thesky->reposition( sstate, delta_time_sec );
598         }
599
600         glEnable( GL_DEPTH_TEST );
601         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
602             glEnable( GL_FOG );
603             glFogi( GL_FOG_MODE, GL_EXP2 );
604             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
605         }
606
607         // set sun/lighting parameters
608         ssgGetLight( 0 ) -> setPosition( l->sun_vec );
609
610         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
611         // we only update GL_AMBIENT for our lights we will never get
612         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
613         // explicitely to black.
614         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
615
616         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
617         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
618         ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular );
619
620         // texture parameters
621         // glEnable( GL_TEXTURE_2D );
622         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
623         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
624
625         // glMatrixMode( GL_PROJECTION );
626         // glLoadIdentity();
627         ssgSetFOV( current__view->get_h_fov(),
628                    current__view->get_v_fov() );
629
630         double agl =
631             current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
632             - globals->get_scenery()->get_cur_elev();
633
634         if ( agl > 10.0 ) {
635             scene_nearplane = 10.0f;
636             scene_farplane = 120000.0f;
637         } else {
638             scene_nearplane = groundlevel_nearplane->getDoubleValue();
639             scene_farplane = 120000.0f;
640         }
641
642         ssgSetNearFar( scene_nearplane, scene_farplane );
643
644         // $$$ begin - added VS Renganthan 17 Oct 2K
645         if(objc)
646           fgUpdateDCS();
647         // $$$ end - added VS Renganthan 17 Oct 2K
648
649 # ifdef FG_NETWORK_OLK
650         if ( fgGetBool("/sim/networking/network-olk") ) {
651             sgCoord fgdpos;
652             other = head->next;             /* put listpointer to start  */
653             while ( other != tail) {        /* display all except myself */
654             if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
655                 other->fgd_sel->select(1);
656                 sgSetCoord( &fgdpos, other->sgFGD_COORD );
657                 other->fgd_pos->setTransform( &fgdpos );
658             }
659             other = other->next;
660             }
661
662             // fgd_sel->select(1);
663             // sgCopyMat4( sgTUX, current_view.sgVIEW);
664             // sgCoord fgdpos;
665             // sgSetCoord( &fgdpos, sgFGD_VIEW );
666             // fgd_pos->setTransform( &fgdpos);
667         }
668 # endif
669
670 #ifdef FG_MPLAYER_AS
671         // Update any multiplayer models
672         globals->get_multiplayer_rx_mgr()->Update();
673 #endif
674
675         if ( draw_otw && skyblend )
676         {
677             // draw the sky backdrop
678
679             // we need a white diffuse light for the phase of the moon
680             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
681
682             thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
683
684             // return to the desired diffuse color
685             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
686
687             // FIXME: This should not be needed, but at this time (08/15/2003)
688             //        certain NVidia drivers don't seem to implement
689             //        fgPushAttrib(FG_FOG_BIT) properly. The result is that
690             //        there is not fog when looking at the sun.
691             glFogf ( GL_FOG_DENSITY, fog_exp2_density );
692         }
693
694         // draw the ssg scene
695         glEnable( GL_DEPTH_TEST );
696
697         ssgSetNearFar( scene_nearplane, scene_farplane );
698
699         if ( fgGetBool("/sim/rendering/wireframe") ) {
700             // draw wire frame
701             glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
702         }
703         if ( draw_otw ) {
704             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
705         }
706
707         // This is a bit kludgy.  Every 200 frames, do an extra
708         // traversal of the scene graph without drawing anything, but
709         // with the field-of-view set to 360x360 degrees.  This
710         // ensures that out-of-range random objects that are not in
711         // the current view frustum will still be freed properly.
712         static int counter = 0;
713         counter++;
714         if (counter == 200) {
715           sgFrustum f;
716           f.setFOV(360, 360);
717                             // No need to put the near plane too close;
718                             // this way, at least the aircraft can be
719                             // culled.
720           f.setNearFar(1000, 1000000);
721           sgMat4 m;
722           ssgGetModelviewMatrix(m);
723           globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
724           counter = 0;
725         }
726
727         // change state for lighting here
728
729         // draw runway lighting
730         glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
731         ssgSetNearFar( scene_nearplane, scene_farplane );
732
733         if ( enhanced_lighting ) {
734
735             // Enable states for drawing points with GL_extension
736             glEnable(GL_POINT_SMOOTH);
737
738             if ( distance_attenuation && glPointParameterIsSupported )
739             {
740                 // Enable states for drawing points with GL_extension
741                 glEnable(GL_POINT_SMOOTH);
742
743                 float quadratic[3] = {1.0, 0.001, 0.0000001};
744                 // makes the points fade as they move away
745                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
746                 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
747             }
748
749             glPointSize(4.0);
750
751             // blending function for runway lights
752             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
753         }
754
755         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
756         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
757         glEnable(GL_TEXTURE_GEN_S);
758         glEnable(GL_TEXTURE_GEN_T);
759         glPolygonMode(GL_FRONT, GL_POINT);
760
761         // draw runway lighting
762         if ( draw_otw ) {
763             ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
764         }
765
766         // change punch through and then draw taxi lighting
767         glFogf ( GL_FOG_DENSITY, fog_exp2_density );
768         // sgVec3 taxi_fog;
769         // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
770         // glFogfv ( GL_FOG_COLOR, taxi_fog );
771         if ( draw_otw ) {
772             ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
773         }
774
775         // clean up lighting
776         glPolygonMode(GL_FRONT, GL_FILL);
777         glDisable(GL_TEXTURE_GEN_S);
778         glDisable(GL_TEXTURE_GEN_T);
779
780         //static int _frame_count = 0;
781         //if (_frame_count % 30 == 0) {
782         //  printf("SSG: %s\n", ssgShowStats());
783         //}
784         //else {
785         //  ssgShowStats();
786         //}
787         //_frame_count++;
788
789
790         if ( enhanced_lighting ) {
791             if ( distance_attenuation && glPointParameterIsSupported )
792             {
793                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
794                                       default_attenuation);
795             }
796
797             glPointSize(1.0);
798             glDisable(GL_POINT_SMOOTH);
799         }
800
801         // draw ground lighting
802         glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
803         if ( draw_otw ) {
804             ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
805         }
806
807         if ( skyblend ) {
808             // draw the sky cloud layers
809             if ( draw_otw && fgGetBool("/environment/clouds/status") )
810             {
811                 thesky->postDraw( cur_fdm_state->get_Altitude()
812                                   * SG_FEET_TO_METER );
813             }
814         }
815
816         if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") )
817         {
818             glDisable( GL_FOG );
819             glDisable( GL_LIGHTING );
820             // cout << "drawing new clouds" << endl;
821
822             glEnable(GL_DEPTH_TEST);
823             glEnable(GL_BLEND);
824             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
825
826             /*
827             glEnable( GL_TEXTURE_2D );
828             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
829             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
830             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
831             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
832             */
833
834 #ifdef FG_USE_CLOUDS_3D
835             sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
836 #endif
837             glEnable( GL_FOG );
838             glEnable( GL_LIGHTING );
839             glEnable( GL_DEPTH_TEST );
840             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
841         }
842
843         if ( draw_otw ) {
844             globals->get_model_mgr()->draw();
845             globals->get_aircraft_model()->draw();
846         }
847
848         // display HUD && Panel
849         glDisable( GL_FOG );
850         glDisable( GL_DEPTH_TEST );
851         // glDisable( GL_CULL_FACE );
852         // glDisable( GL_TEXTURE_2D );
853
854         // update the controls subsystem
855         globals->get_controls()->update(delta_time_sec);
856
857         hud_and_panel->apply();
858         fgCockpitUpdate();
859
860         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
861         // This only works properly if called before the panel call
862         if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
863             globals->get_ATC_display()->update(delta_time_sec);
864
865         // update the panel subsystem
866         if ( globals->get_current_panel() != NULL ) {
867             globals->get_current_panel()->update(delta_time_sec);
868         }
869         fgUpdate3DPanels();
870
871         // We can do translucent menus, so why not. :-)
872         menus->apply();
873         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
874         puDisplay();
875         // glDisable ( GL_BLEND ) ;
876
877         glEnable( GL_DEPTH_TEST );
878         glEnable( GL_FOG );
879
880         // Fade out the splash screen over the first three seconds.
881         double t = globals->get_sim_time_sec();
882         if ( t <= 1.0 ) {
883             fgSplashUpdate(0.0, 1.0);
884         } else if ( t <= 3.0) {
885             fgSplashUpdate(0.0, (3.0 - t) / 2.0);
886         }
887     }
888
889     glutSwapBuffers();
890 }
891
892
893 // Update internal time dependent calculations (i.e. flight model)
894 // FIXME: this distinction is obsolete; all subsystems now get delta
895 // time on update.
896 void fgUpdateTimeDepCalcs() {
897     static bool inited = false;
898
899     static const SGPropertyNode *replay_master
900         = fgGetNode( "/sim/freeze/replay", true );
901     static SGPropertyNode *replay_time
902         = fgGetNode( "/sim/replay/time", true );
903     static const SGPropertyNode *replay_end_time
904         = fgGetNode( "/sim/replay/end-time", true );
905
906     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
907
908     fgLIGHT *l = &cur_light_params;
909
910     // Initialize the FDM here if it hasn't been and if we have a
911     // scenery elevation hit.
912
913     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
914     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
915
916     if ( !cur_fdm_state->get_inited() &&
917          globals->get_scenery()->get_cur_elev() > -9990 )
918     {
919         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
920         cur_fdm_state->init();
921         if ( cur_fdm_state->get_bound() ) {
922             cur_fdm_state->unbind();
923         }
924         cur_fdm_state->bind();
925     }
926
927     // conceptually, the following block could be done for each fdm
928     // instance ...
929     if ( cur_fdm_state->get_inited() ) {
930         // we have been inited, and  we are good to go ...
931
932         if ( !inited ) {
933             inited = true;
934         }
935
936         if ( ! replay_master->getBoolValue() ) {
937             globals->get_autopilot()->update( delta_time_sec );
938             cur_fdm_state->update( delta_time_sec );
939         } else {
940             FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
941             r->replay( replay_time->getDoubleValue() );
942             replay_time->setDoubleValue( replay_time->getDoubleValue()
943                                          + ( delta_time_sec
944                                              * fgGetInt("/sim/speed-up") ) );
945         }
946     } else {
947         // do nothing, fdm isn't inited yet
948     }
949
950     globals->get_model_mgr()->update(delta_time_sec);
951     globals->get_aircraft_model()->update(delta_time_sec);
952
953     // update the view angle
954     globals->get_viewmgr()->update(delta_time_sec);
955
956     l->UpdateAdjFog();
957
958     // Update solar system
959     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
960                               globals->get_time_params()->getLst(),
961                               cur_fdm_state->get_Latitude() );
962
963     // Update radio stack model
964     current_radiostack->update(delta_time_sec);
965 }
966
967
968 void fgInitTimeDepCalcs( void ) {
969     // noop for now
970 }
971
972
973 static const double alt_adjust_ft = 3.758099;
974 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
975
976
977 // What should we do when we have nothing else to do?  Let's get ready
978 // for the next move and update the display?
979 static void fgMainLoop( void ) {
980     int model_hz = fgGetInt("/sim/model-hz");
981
982     static const SGPropertyNode *longitude
983         = fgGetNode("/position/longitude-deg");
984     static const SGPropertyNode *latitude
985         = fgGetNode("/position/latitude-deg");
986     static const SGPropertyNode *altitude
987         = fgGetNode("/position/altitude-ft");
988     static const SGPropertyNode *clock_freeze
989         = fgGetNode("/sim/freeze/clock", true);
990     static const SGPropertyNode *cur_time_override
991         = fgGetNode("/sim/time/cur-time-override", true);
992     static const SGPropertyNode *replay_master
993         = fgGetNode("/sim/freeze/replay", true);
994
995     // Update the elapsed time.
996     static bool first_time = true;
997     if ( first_time ) {
998         last_time_stamp.stamp();
999         first_time = false;
1000     }
1001
1002     double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1003     if ( throttle_hz > 0.0 ) {
1004         // simple frame rate throttle
1005         double dt = 1000000.0 / throttle_hz;
1006         current_time_stamp.stamp();
1007         while ( current_time_stamp - last_time_stamp < dt ) {
1008             current_time_stamp.stamp();
1009         }
1010     } else {
1011         // run as fast as the app will go
1012         current_time_stamp.stamp();
1013     }
1014
1015     delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
1016     if ( clock_freeze->getBoolValue() ) {
1017         delta_time_sec = 0;
1018     } 
1019     last_time_stamp = current_time_stamp;
1020     globals->inc_sim_time_sec( delta_time_sec );
1021     SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1022
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     sglog().setLogLevels( SG_ALL, (sgDebugPriority)fgGetInt("/sim/log-level") );
1036     sglog().setLogLevels( SG_ALL, SG_INFO );
1037
1038     SGLocation * acmodel_location = 0;
1039     if(cur_fdm_state->getACModel() != 0) {
1040       acmodel_location = (SGLocation *)  cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
1041     }
1042
1043     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1044     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1045
1046 #ifdef FG_NETWORK_OLK
1047     if ( fgGetBool("/sim/networking/network-olk") ) {
1048         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
1049             // printf("FGD: Netupdate\n");
1050             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
1051             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
1052         }
1053     }
1054 #endif
1055
1056 #if defined( ENABLE_PLIB_JOYSTICK )
1057     // Read joystick and update control settings
1058     // if ( fgGetString("/sim/control-mode") == "joystick" )
1059     // {
1060     //    fgJoystickRead();
1061     // }
1062 #elif defined( ENABLE_GLUT_JOYSTICK )
1063     // Glut joystick support works by feeding a joystick handler
1064     // function to glut.  This is taken care of once in the joystick
1065     // init routine and we don't have to worry about it again.
1066 #endif
1067
1068     // Fix elevation.  I'm just sticking this here for now, it should
1069     // probably move eventually
1070
1071     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
1072            scenery.get_cur_elev(),
1073            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1074            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1075
1076 #if 0
1077 // This code is used by LaRCsim/UIUC to position the aircraft at a proper
1078 // place. This code should eventually go into the LaRCsim directory.
1079 // Commented out at Jul 27 2003 because tests show it is not needed.
1080 // Can probbaly be safely removed after Spet. 2003 - EMH
1081
1082     if ( acmodel_location != 0 ) {
1083       if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
1084         if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER < 
1085              (acmodel_location->get_cur_elev_m() + alt_adjust_m - 130.0) ) {
1086             // now set aircraft altitude above ground
1087             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
1088                cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1089                acmodel_location->get_cur_elev_m() + alt_adjust_m - 130.0,
1090                acmodel_location->get_cur_elev_m() + alt_adjust_m );
1091             cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m() 
1092                                                 + alt_adjust_m) * SG_METER_TO_FEET );
1093             SG_LOG( SG_ALL, SG_DEBUG, 
1094                 "<*> resetting altitude to " 
1095                 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1096                 << " meters" );
1097         }
1098       }
1099     }
1100 // End of code in question. (see Curt is this code used? above)
1101 #endif
1102
1103     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
1104            scenery.get_cur_elev(),
1105            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1106            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1107
1108     // cout << "Warp = " << globals->get_warp() << endl;
1109
1110     // update "time"
1111     static bool last_clock_freeze = false;
1112
1113     if ( clock_freeze->getBoolValue() ) {
1114         // clock freeze requested
1115         if ( cur_time_override->getLongValue() == 0 ) {
1116             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1117             globals->set_warp( 0 );
1118         }
1119     } else {
1120         // no clock freeze requested
1121         if ( last_clock_freeze == true ) {
1122             // clock just unfroze, let's set warp as the difference
1123             // between frozen time and current time so we don't get a
1124             // time jump (and corresponding sky object and lighting
1125             // jump.)
1126             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1127             fgSetLong( "/sim/time/cur-time-override", 0 );
1128         }
1129         if ( globals->get_warp_delta() != 0 ) {
1130             globals->inc_warp( globals->get_warp_delta() );
1131         }
1132     }
1133
1134     last_clock_freeze = clock_freeze->getBoolValue();
1135
1136     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1137                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1138                cur_time_override->getLongValue(),
1139                globals->get_warp() );
1140
1141     if ( globals->get_warp_delta() != 0 ) {
1142         fgUpdateSkyAndLightingParams();
1143     }
1144
1145     // update magvar model
1146     globals->get_mag()->update( longitude->getDoubleValue()
1147                               * SGD_DEGREES_TO_RADIANS,
1148                             latitude->getDoubleValue()
1149                               * SGD_DEGREES_TO_RADIANS,
1150                             altitude->getDoubleValue() * SG_FEET_TO_METER,
1151                             globals->get_time_params()->getJD() );
1152
1153     // Get elapsed time (in usec) for this past frame
1154     elapsed = fgGetTimeInterval();
1155     SG_LOG( SG_ALL, SG_DEBUG, 
1156             "Elapsed time interval is = " << elapsed 
1157             << ", previous remainder is = " << remainder );
1158
1159     // Calculate frame rate average
1160 #ifdef FANCY_FRAME_COUNTER
1161     /* old fps calculation */
1162     if ( elapsed > 0 ) {
1163         double tmp;
1164         accum = 0.0;
1165         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1166             tmp = general.get_frame(i);
1167             accum += tmp;
1168             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1169             general.set_frame(i+1,tmp);
1170         }
1171         tmp = 1000000.0 / (float)elapsed;
1172         general.set_frame(0,tmp);
1173         // printf("frame[0] = %.2f\n", general.frames[0]);
1174         accum += tmp;
1175         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1176         // printf("ave = %.2f\n", general.frame_rate);
1177     }
1178 #else
1179     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1180         general.set_frame_rate( frames );
1181         fgSetInt("/sim/frame-rate", frames);
1182         SG_LOG( SG_ALL, SG_DEBUG, 
1183             "--> Frame rate is = " << general.get_frame_rate() );
1184         frames = 0;
1185     }
1186     last_time = t->get_cur_time();
1187     ++frames;
1188 #endif
1189
1190     // Run ATC subsystem
1191     if (fgGetBool("/sim/ATC/enabled"))
1192         globals->get_ATC_mgr()->update(delta_time_sec);
1193
1194     // Run the AI subsystem
1195     if (fgGetBool("/sim/ai-traffic/enabled"))
1196         globals->get_AI_mgr()->update(delta_time_sec);
1197
1198     // Run flight model
1199
1200     // Calculate model iterations needed for next frame
1201     elapsed += remainder;
1202
1203     global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1204     remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1205     SG_LOG( SG_ALL, SG_DEBUG, 
1206             "Model iterations needed = " << global_multi_loop
1207             << ", new remainder = " << remainder );
1208         
1209     // chop max interations to something reasonable if the sim was
1210     // delayed for an excesive amount of time
1211     if ( global_multi_loop > 2.0 * model_hz ) {
1212         global_multi_loop = (int)(2.0 * model_hz );
1213         remainder = 0;
1214     }
1215
1216     // flight model
1217     if ( global_multi_loop > 0 ) {
1218         fgUpdateTimeDepCalcs();
1219     } else {
1220         SG_LOG( SG_ALL, SG_DEBUG, 
1221             "Elapsed time is zero ... we're zinging" );
1222     }
1223
1224     // Do any I/O channel work that might need to be done
1225     globals->get_io()->update( delta_time_sec );
1226
1227     // see if we need to load any deferred-load textures
1228     globals->get_matlib()->load_next_deferred();
1229
1230     // Run audio scheduler
1231 #ifdef ENABLE_AUDIO_SUPPORT
1232     if ( fgGetBool("/sim/sound/audible")
1233            && globals->get_soundmgr()->is_working() ) {
1234         globals->get_soundmgr()->update( delta_time_sec );
1235     }
1236 #endif
1237
1238     globals->get_subsystem_mgr()->update(delta_time_sec);
1239
1240     //
1241     // Tile Manager updates - see if we need to load any new scenery tiles.
1242     //   this code ties together the fdm, viewer and scenery classes...
1243     //   we may want to move this to it's own class at some point
1244     //
1245     double visibility_meters = fgGetDouble("/environment/visibility-m");
1246     FGViewer *current_view = globals->get_current_view();
1247
1248     // update tile manager for FDM...
1249     // ...only if location is different than the viewer (to avoid duplicating effort)
1250     if( acmodel_location != current_view->getSGLocation() ) {
1251       if( acmodel_location != 0 ) {
1252         globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1253                                                  visibility_meters );
1254         globals->get_tile_mgr()->
1255             update( acmodel_location, visibility_meters,
1256                     acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1257         // save results of update in SGLocation for fdm...
1258         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1259           acmodel_location->
1260               set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1261         }
1262         acmodel_location->
1263             set_tile_center( globals->get_scenery()->get_next_center() );
1264       }
1265     }
1266
1267     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1268                                              visibility_meters );
1269     // update tile manager for view...
1270     // IMPORTANT!!! the tilemgr update for view location _must_ be done last 
1271     // after the FDM's until all of Flight Gear code references the viewer's location
1272     // for elevation instead of the "scenery's" current elevation.
1273     SGLocation *view_location = globals->get_current_view()->getSGLocation();
1274     globals->get_tile_mgr()->update( view_location, visibility_meters,
1275                                      current_view->get_absolute_view_pos() );
1276     // save results of update in SGLocation for fdm...
1277     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1278       current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1279     }
1280     current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1281
1282     // If fdm location is same as viewer's then we didn't do the update for fdm location 
1283     //   above so we need to save the viewer results in the fdm SGLocation as well...
1284     if( acmodel_location == current_view->getSGLocation() ) {
1285       if( acmodel_location != 0 ) {
1286         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1287           acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1288         }
1289         acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1290       }
1291     }
1292
1293     // END Tile Manager udpates
1294
1295     // redraw display
1296     fgRenderFrame();
1297
1298     SG_LOG( SG_ALL, SG_DEBUG, "" );
1299 }
1300
1301
1302 // This is the top level master main function that is registered as
1303 // our idle funciton
1304
1305 // The first few passes take care of initialization things (a couple
1306 // per pass) and once everything has been initialized fgMainLoop from
1307 // then on.
1308
1309 static void fgIdleFunction ( void ) {
1310     // printf("idle state == %d\n", idle_state);
1311
1312     if ( idle_state == 0 ) {
1313         // Initialize the splash screen right away
1314         if ( fgGetBool("/sim/startup/splash-screen") ) {
1315             fgSplashInit();
1316         }
1317         
1318         idle_state++;
1319     } else if ( idle_state == 1 ) {
1320         // Initialize audio support
1321 #ifdef ENABLE_AUDIO_SUPPORT
1322
1323         // Start the intro music
1324         if ( fgGetBool("/sim/startup/intro-music") ) {
1325             SGPath mp3file( globals->get_fg_root() );
1326             mp3file.append( "Sounds/intro.mp3" );
1327
1328             SG_LOG( SG_GENERAL, SG_INFO, 
1329                 "Starting intro music: " << mp3file.str() );
1330
1331 #if defined( __CYGWIN__ )
1332             string command = "start /m `cygpath -w " + mp3file.str() + "`";
1333 #elif defined( WIN32 )
1334             string command = "start /m " + mp3file.str();
1335 #else
1336             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1337 #endif
1338
1339             system ( command.c_str() );
1340         }
1341 #endif
1342
1343         idle_state++;
1344     } else if ( idle_state == 2 ) {
1345         // These are a few miscellaneous things that aren't really
1346         // "subsystems" but still need to be initialized.
1347
1348 #ifdef USE_GLIDE
1349         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1350             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1351         }
1352 #endif
1353
1354         idle_state++;
1355     } else if ( idle_state == 3 ) {
1356         // This is the top level init routine which calls all the
1357         // other subsystem initialization routines.  If you are adding
1358         // a subsystem to flightgear, its initialization call should
1359         // located in this routine.
1360         if( !fgInitSubsystems()) {
1361             SG_LOG( SG_GENERAL, SG_ALERT,
1362                 "Subsystem initializations failed ..." );
1363             exit(-1);
1364         }
1365
1366         idle_state++;
1367     } else if ( idle_state == 4 ) {
1368         // setup OpenGL view parameters
1369         fgInitVisuals();
1370
1371         // Read the list of available aircrafts
1372         fgReadAircraft();
1373
1374         idle_state++;
1375     } else if ( idle_state == 5 ) {
1376
1377         idle_state++;
1378     } else if ( idle_state == 6 ) {
1379         // sleep(1);
1380         idle_state = 1000;
1381
1382         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1383         fgReshape( fgGetInt("/sim/startup/xsize"),
1384                fgGetInt("/sim/startup/ysize") );
1385     } 
1386
1387     if ( idle_state == 1000 ) {
1388         // We've finished all our initialization steps, from now on we
1389         // run the main loop.
1390
1391         glutIdleFunc(fgMainLoop);
1392     } else {
1393         if ( fgGetBool("/sim/startup/splash-screen") ) {
1394             fgSplashUpdate(0.0, 1.0);
1395         }
1396     }
1397 }
1398
1399 // options.cxx needs to see this for toggle_panel()
1400 // Handle new window size or exposure
1401 void fgReshape( int width, int height ) {
1402     int view_h;
1403
1404     if ( (!fgGetBool("/sim/virtual-cockpit"))
1405          && fgPanelVisible() && idle_state == 1000 ) {
1406         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1407                              globals->get_current_panel()->getYOffset()) / 768.0);
1408     } else {
1409         view_h = height;
1410     }
1411
1412     // for all views
1413     FGViewMgr *viewmgr = globals->get_viewmgr();
1414     for ( int i = 0; i < viewmgr->size(); ++i ) {
1415       viewmgr->get_view(i)->
1416         set_aspect_ratio((float)view_h / (float)width);
1417     }
1418
1419     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1420
1421     fgSetInt("/sim/startup/xsize", width);
1422     fgSetInt("/sim/startup/ysize", height);
1423     guiInitMouse(width, height);
1424
1425     ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1426                viewmgr->get_current_view()->get_v_fov() );
1427
1428     fgHUDReshape();
1429
1430 #ifdef FG_USE_CLOUDS_3D
1431     sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1432                         viewmgr->get_current_view()->get_v_fov() );
1433 #endif
1434
1435 }
1436
1437 // Initialize GLUT and define a main window
1438 static bool fgGlutInit( int *argc, char **argv ) {
1439
1440 #if !defined( macintosh )
1441     // GLUT will extract all glut specific options so later on we only
1442     // need wory about our own.
1443     glutInit(argc, argv);
1444 #endif
1445
1446     // Define Display Parameters. Clouds3d works best with --bpp32 option
1447     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1448         glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1449     } else {
1450         glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1451     }
1452
1453     SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1454             fgGetInt("/sim/startup/xsize") << "x"
1455             << fgGetInt("/sim/startup/ysize") );
1456
1457     // Define initial window size
1458     glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1459                     fgGetInt("/sim/startup/ysize") );
1460
1461     // Initialize windows
1462     if ( !fgGetBool("/sim/startup/game-mode")) {
1463         // Open the regular window
1464         glutCreateWindow("FlightGear");
1465 #ifndef GLUT_WRONG_VERSION
1466     } else {
1467         // Open the cool new 'game mode' window
1468         char game_mode_str[256];
1469 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1470 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1471 #ifndef ENUM_CURRENT_SETTINGS
1472 #define ENUM_CURRENT_SETTINGS       ((DWORD)-1)
1473 #define ENUM_REGISTRY_SETTINGS      ((DWORD)-2)
1474 #endif
1475
1476         DEVMODE dm;
1477         dm.dmSize = sizeof(DEVMODE);
1478         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1479         fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1480         fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1481         glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1482                             fgGetInt("/sim/startup/ysize") );
1483         sprintf( game_mode_str, "%dx%d:%d@%d",
1484                      dm.dmPelsWidth,
1485                      dm.dmPelsHeight,
1486                      dm.dmBitsPerPel,
1487                      dm.dmDisplayFrequency );
1488 #else
1489         // Open the cool new 'game mode' window
1490         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1491              fgGetInt("/sim/startup/xsize"),
1492              fgGetInt("/sim/startup/ysize"),
1493              fgGetInt("/sim/rendering/bits-per-pixel"));
1494
1495 #endif // HAVE_WINDOWS_H
1496         SG_LOG( SG_GENERAL, SG_INFO, 
1497             "game mode params = " << game_mode_str );
1498         glutGameModeString( game_mode_str );
1499         glutEnterGameMode();
1500 #endif // GLUT_WRONG_VERSION
1501     }
1502
1503     // This seems to be the absolute earliest in the init sequence
1504     // that these calls will return valid info.  Too bad it's after
1505     // we've already created and sized out window. :-(
1506     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1507     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1508     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1509     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1510
1511     GLint tmp;
1512     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1513     general.set_glMaxTexSize( tmp );
1514     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1515
1516     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1517     general.set_glDepthBits( tmp );
1518     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1519
1520     return true;
1521 }
1522
1523
1524 // Initialize GLUT event handlers
1525 static bool fgGlutInitEvents( void ) {
1526     // call fgReshape() on window resizes
1527     glutReshapeFunc( fgReshape );
1528
1529     // keyboard and mouse callbacks are set in FGInput::init
1530
1531     // call fgMainLoop() whenever there is
1532     // nothing else to do
1533     glutIdleFunc( fgIdleFunction );
1534
1535     // draw the scene
1536     glutDisplayFunc( fgRenderFrame );
1537
1538     return true;
1539 }
1540
1541 // Main top level initialization
1542 bool fgMainInit( int argc, char **argv ) {
1543
1544 #if defined( macintosh )
1545     freopen ("stdout.txt", "w", stdout );
1546     freopen ("stderr.txt", "w", stderr );
1547     argc = ccommand( &argv );
1548 #endif
1549
1550     // set default log levels
1551     sglog().setLogLevels( SG_ALL, SG_INFO );
1552
1553     string version;
1554 #ifdef FLIGHTGEAR_VERSION
1555     version = FLIGHTGEAR_VERSION;
1556 #else
1557     version = "unknown version";
1558 #endif
1559     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1560             << version );
1561     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1562
1563     // Allocate global data structures.  This needs to happen before
1564     // we parse command line options
1565
1566     globals = new FGGlobals;
1567
1568     // seed the random number generater
1569     sg_srandom_time();
1570
1571     SGRoute *route = new SGRoute;
1572     globals->set_route( route );
1573
1574     FGControls *controls = new FGControls;
1575     globals->set_controls( controls );
1576
1577     string_list *col = new string_list;
1578     globals->set_channel_options_list( col );
1579
1580     // Scan the config file(s) and command line options to see if
1581     // fg_root was specified (ignore all other options for now)
1582     fgInitFGRoot(argc, argv);
1583
1584     // Check for the correct base package version
1585     static char required_version[] = "0.9.2";
1586     string base_version = fgBasePackageVersion();
1587     if ( !(base_version == required_version) ) {
1588         // tell the operator how to use this application
1589
1590         cerr << endl << "Base package check failed ... " \
1591              << "Found version " << base_version << " at: " \
1592              << globals->get_fg_root() << endl;
1593         cerr << "Please upgrade to version: " << required_version << endl;
1594         exit(-1);
1595     }
1596
1597     // Initialize the Aircraft directory to "" (UIUC)
1598     aircraft_dir = "";
1599
1600     // Load the configuration parameters.  (Command line options
1601     // overrides config file options.  Config file options override
1602     // defaults.)
1603     if ( !fgInitConfig(argc, argv) ) {
1604         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1605         exit(-1);
1606     }
1607
1608     // Initialize the Window/Graphics environment.
1609     if( !fgGlutInit(&argc, argv) ) {
1610         SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1611         exit(-1);
1612     }
1613
1614     // Initialize the various GLUT Event Handlers.
1615     if( !fgGlutInitEvents() ) {
1616         SG_LOG( SG_GENERAL, SG_ALERT, 
1617                 "GLUT event handler initialization failed ..." );
1618         exit(-1);
1619     }
1620
1621     // Initialize plib net interface
1622     netInit( &argc, argv );
1623
1624     // Initialize ssg (from plib).  Needs to come before we do any
1625     // other ssg stuff, but after opengl/glut has been initialized.
1626     ssgInit();
1627
1628     // Initialize the user interface (we need to do this before
1629     // passing off control to glut and before fgInitGeneral to get our
1630     // fonts !!!
1631     guiInit();
1632
1633     // Read the list of available aircrafts
1634     fgReadAircraft();
1635
1636 #ifdef GL_EXT_texture_lod_bias
1637     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1638 #endif
1639
1640             // get the address of our OpenGL extensions
1641     if ( fgGetBool("/sim/rendering/distance-attenuation") )
1642     {
1643         if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1644             glPointParameterIsSupported = true;
1645             glPointParameterfPtr = (glPointParameterfProc)
1646                                    SGLookupFunction("glPointParameterfEXT");
1647             glPointParameterfvPtr = (glPointParameterfvProc)
1648                                     SGLookupFunction("glPointParameterfvEXT");
1649
1650         } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1651             glPointParameterIsSupported = true;
1652             glPointParameterfPtr = (glPointParameterfProc)
1653                                    SGLookupFunction("glPointParameterfARB");
1654             glPointParameterfvPtr = (glPointParameterfvProc)
1655                                     SGLookupFunction("glPointParameterfvARB");
1656         } else
1657             glPointParameterIsSupported = false;
1658    }
1659
1660     // based on the requested presets, calculate the true starting
1661     // lon, lat
1662     fgInitNav();
1663     fgInitPosition();
1664
1665     SGTime *t = fgInitTime();
1666     globals->set_time_params( t );
1667
1668     // Do some quick general initializations
1669     if( !fgInitGeneral()) {
1670         SG_LOG( SG_GENERAL, SG_ALERT, 
1671             "General initializations failed ..." );
1672         exit(-1);
1673     }
1674
1675     SGPath modelpath( globals->get_fg_root() );
1676     ssgModelPath( (char *)modelpath.c_str() );
1677
1678     ////////////////////////////////////////////////////////////////////
1679     // Initialize the property-based built-in commands
1680     ////////////////////////////////////////////////////////////////////
1681     fgInitCommands();
1682
1683     ////////////////////////////////////////////////////////////////////
1684     // Initialize the material manager
1685     ////////////////////////////////////////////////////////////////////
1686     globals->set_matlib( new SGMaterialLib );
1687
1688     globals->set_model_lib(new SGModelLib);
1689
1690     ////////////////////////////////////////////////////////////////////
1691     // Initialize the TG scenery subsystem.
1692     ////////////////////////////////////////////////////////////////////
1693     globals->set_scenery( new FGScenery );
1694     globals->get_scenery()->init();
1695     globals->get_scenery()->bind();
1696     globals->set_tile_mgr( new FGTileMgr );
1697
1698     ////////////////////////////////////////////////////////////////////
1699     // Initialize the general model subsystem.
1700     ////////////////////////////////////////////////////////////////////
1701     globals->set_model_mgr(new FGModelMgr);
1702     globals->get_model_mgr()->init();
1703     globals->get_model_mgr()->bind();
1704
1705     ////////////////////////////////////////////////////////////////////
1706     // Initialize the 3D aircraft model subsystem (has a dependency on
1707     // the scenery subsystem.)
1708     ////////////////////////////////////////////////////////////////////
1709     globals->set_aircraft_model(new FGAircraftModel);
1710     globals->get_aircraft_model()->init();
1711     globals->get_aircraft_model()->bind();
1712
1713     ////////////////////////////////////////////////////////////////////
1714     // Initialize the view manager subsystem.
1715     ////////////////////////////////////////////////////////////////////
1716     FGViewMgr *viewmgr = new FGViewMgr;
1717     globals->set_viewmgr( viewmgr );
1718     viewmgr->init();
1719     viewmgr->bind();
1720
1721
1722     // Initialize the sky
1723     SGPath ephem_data_path( globals->get_fg_root() );
1724     ephem_data_path.append( "Astro" );
1725     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1726     ephem->update( globals->get_time_params()->getMjd(),
1727                globals->get_time_params()->getLst(),
1728                0.0 );
1729     globals->set_ephem( ephem );
1730
1731                             // TODO: move to environment mgr
1732     thesky = new SGSky;
1733     SGPath texture_path(globals->get_fg_root());
1734     texture_path.append("Textures");
1735     texture_path.append("Sky");
1736     for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1737         SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1738         thesky->add_cloud_layer(layer);
1739     }
1740
1741
1742     SGPath sky_tex_path( globals->get_fg_root() );
1743     sky_tex_path.append( "Textures" );
1744     sky_tex_path.append( "Sky" );
1745     thesky->texture_path( sky_tex_path.str() );
1746
1747     // The sun and moon diameters are scaled down numbers of the
1748     // actual diameters. This was needed to fit bot the sun and the
1749     // moon within the distance to the far clip plane.
1750     // Moon diameter:    3,476 kilometers
1751     // Sun diameter: 1,390,000 kilometers
1752     thesky->build( 80000.0, 80000.0,
1753                    463.3, 361.8,
1754                    globals->get_ephem()->getNumPlanets(), 
1755                    globals->get_ephem()->getPlanets(),
1756                    globals->get_ephem()->getNumStars(),
1757                    globals->get_ephem()->getStars() );
1758
1759     // Initialize MagVar model
1760     SGMagVar *magvar = new SGMagVar();
1761     globals->set_mag( magvar );
1762
1763
1764                                 // kludge to initialize mag compass
1765                                 // (should only be done for in-flight
1766                                 // startup)
1767     // update magvar model
1768     globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1769                                 * SGD_DEGREES_TO_RADIANS,
1770                                 fgGetDouble("/position/latitude-deg")
1771                                 * SGD_DEGREES_TO_RADIANS,
1772                                 fgGetDouble("/position/altitude-ft")
1773                                 * SG_FEET_TO_METER,
1774                                 globals->get_time_params()->getJD() );
1775     double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1776     fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1777
1778     // airport = new ssgBranch;
1779     // airport->setName( "Airport Lighting" );
1780     // lighting->addKid( airport );
1781
1782     // ADA
1783     fgLoadDCS();
1784     // ADA
1785
1786 #ifdef FG_NETWORK_OLK
1787     // Do the network intialization
1788     if ( fgGetBool("/sim/networking/network-olk") ) {
1789         printf("Multipilot mode %s\n",
1790                fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1791     }
1792 #endif
1793
1794     // build our custom render states
1795     fgBuildRenderStates();
1796     
1797     // pass control off to the master GLUT event handler
1798     glutMainLoop();
1799
1800     // we never actually get here ... but to avoid compiler warnings,
1801     // etc.
1802     return false;
1803 }
1804
1805
1806 // $$$ end - added VS Renganathan, 15 Oct 2K
1807 //         - added Venky         , 12 Nov 2K
1808
1809
1810 void fgLoadDCS(void) {
1811
1812     ssgEntity *ship_obj = NULL;
1813
1814     char obj_filename[25];
1815
1816     for ( int k = 0; k < 32; k++ ) {
1817         ship_pos[k]=NULL;
1818     }
1819
1820     SGPath tile_path( globals->get_fg_root());
1821     tile_path.append( "Scenery" );
1822     tile_path.append( "Objects.txt" );
1823     sg_gzifstream in( tile_path.str() );
1824     if ( ! in.is_open() ) {
1825         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1826     } else {
1827
1828         SGPath modelpath( globals->get_fg_root() );
1829         modelpath.append( "Models" );
1830         modelpath.append( "Geometry" );
1831   
1832         SGPath texturepath( globals->get_fg_root() );
1833         texturepath.append( "Models" );
1834         texturepath.append( "Textures" );
1835  
1836         ssgModelPath( (char *)modelpath.c_str() );
1837         ssgTexturePath( (char *)texturepath.c_str() );
1838
1839         ship_sel = new ssgSelector;
1840
1841         char c;
1842         while ( ! in.eof() ) {
1843             in >> ::skipws;
1844             if ( in.get( c ) && c == '#' ) { 
1845                 in >> skipeol;
1846             } else { 
1847                 in.putback(c);
1848                 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1849                 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] <<  " " << obj_alt[objc] << endl;
1850                    int chj=getchar();*/
1851                 
1852                 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1853                 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1854                 
1855                 ship_pos[objc] = new ssgTransform;
1856        
1857                 // type "repeat" in objects.txt to load one more
1858                 // instance of the last object.
1859
1860                 if ( strcmp(obj_filename,"repeat") != 0) {
1861                     ship_obj =
1862                       globals->get_model_lib()->load_model( globals->get_fg_root(), obj_filename, globals->get_props(), globals->get_sim_time_sec() );
1863                 }
1864       
1865                 if ( ship_obj != NULL ) {
1866                                 ship_obj->setName(obj_filename);
1867                             if (objc == 0)
1868                                         ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1869                                 else
1870                                         ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1871                     ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1872                     ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1873                     SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1874                             << obj_filename );
1875                 } else {
1876                     SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1877                             << obj_filename );
1878                 }
1879             
1880                             // temporary hack for deck lights - ultimately should move to PLib (when??)
1881                             //const char *extn = file_extension ( obj_filename ) ;
1882                             if ( objc == 1 ){
1883                                 // ssgVertexArray *lights = new ssgVertexArray( 100 );
1884                                 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1885                                 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1886                                 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1887                                 int ltype[500], light_type = 0;
1888                                 static int ltcount = 0;
1889                                 string token;
1890                                 sgVec3 rway_dir,rway_normal,lightpt;
1891                                 Point3D node;
1892                                 modelpath.append(obj_filename);
1893                                 sg_gzifstream in1( modelpath.str() );
1894                                 if ( ! in1.is_open() ) {
1895                                         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1896                                 } else {
1897                                         while ( ! in1.eof() ) {
1898                                                         in1 >> ::skipws;
1899                                                 if ( in1.get( c ) && c == '#' ) { 
1900                                                         in1 >> skipeol;
1901                                                 } else { 
1902                                                         in1.putback(c);
1903                                                         in1 >> token;
1904                                                         //cout << token << endl;
1905                                                         if ( token == "runway" ) {
1906                                                                 in1 >> node;
1907                                                                 sgSetVec3 (rway_dir, node[0], node[1], node[2] );                        
1908                                                         } else if ( token == "edgelight" ) {
1909                                                                 in1 >> node;
1910                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1911                                                                 light_type = 1;
1912                                                         } else if ( token == "taxi" ) {
1913                                                                 in1 >> node;
1914                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
1915                                                                 light_type = 2;
1916                                                         } else if ( token == "vasi" ) {
1917                                                                 in1 >> node;
1918                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
1919                                                                 light_type = 3;
1920                                                         } else if ( token == "threshold" ) {
1921                                                                 in1 >> node;
1922                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
1923                                                                 light_type = 4;
1924                                                         } else if ( token == "rabbit" ) {
1925                                                                 in1 >> node;
1926                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1927                                                                 light_type = 5;
1928                                                         } else if ( token == "ols" ) {
1929                                                                 in1 >> node;
1930                                                                 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1931                                                                 light_type = 6;
1932                                                         } else if ( token == "red" ) {
1933                                                                 in1 >> node;
1934                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1935                                                                 light_type = 7;
1936                                                         } else if ( token == "green" ) {
1937                                                                 in1 >> node;
1938                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1939                                                                 light_type = 8;
1940                                                         } else if ( token == "lp" ) {
1941                                                                 in1 >> node;
1942                                                                 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1943                                                                 lightpoints->add( lightpt );
1944                                                                 lightnormals->add( rway_normal );
1945                                                                 lightdir->add( rway_dir );
1946                                                                 ltype[ltcount]= light_type;
1947                                                                 ltcount++;
1948                                                         }
1949                                                         if (in1.eof()) break;
1950                                                 } 
1951                                         }  //while
1952
1953 #if 0        
1954                                         if ( lightpoints->getNum() ) {
1955                                                 ssgBranch *lightpoints_branch;
1956                                                 long int dummy = -999;
1957                                                 dummy_tile = new FGTileEntry((SGBucket)dummy);
1958                                                 dummy_tile->lightmaps_sequence = new ssgSelector;
1959                                                 dummy_tile->ols_transform = new ssgTransform;
1960
1961                                                 // call function to generate the runway lights
1962                                                 lightpoints_branch = 
1963                                                 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1964                                                                                                                         lightdir, ltype);
1965                                                 lightpoints_brightness->addKid(lightpoints_branch);
1966                                                 lightpoints_transform->addKid(lightpoints_brightness);
1967                                             //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1968                                                 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1969                                                 lightpoints_transform->ref();
1970                                                 globals->get_scenery()->get_gnd_lights_root()->addKid( lightpoints_transform );
1971                                         } 
1972 #endif
1973                                 } //if in1 
1974                 } //if objc
1975                             // end hack for deck lights
1976
1977                 objc++;
1978
1979                 if (in.eof()) break;
1980             }
1981         } // while
1982
1983         SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1984
1985         globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node 
1986     }
1987
1988     return;
1989  }
1990
1991
1992 void fgUpdateDCS (void) {
1993
1994     // double eye_lat,eye_lon,eye_alt;
1995     // static double obj_head;
1996     double sl_radius,obj_latgc;
1997     // float nresultmat[4][4];
1998     // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1999     double bz[3];
2000
2001     // Instantaneous Geodetic Lat/Lon/Alt of moving object
2002     FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
2003     
2004     // Deck should be the first object in objects.txt in case of fdm=ada
2005
2006     if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
2007             if ((fdm->get_iaux(1))==1)
2008             {
2009                     obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
2010                     obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
2011                     obj_alt[1] = fdm->get_daux(3);
2012                     obj_pitch[1] = fdm->get_faux(1);
2013                     obj_roll[1] = fdm->get_faux(2);
2014             }
2015     }
2016     
2017     for ( int m = 0; m < objc; m++ ) {
2018         //cout << endl <<  obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
2019         //int v=getchar();
2020
2021         //Geodetic to Geocentric angles for rotation
2022         sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
2023
2024         //moving object gbs-posn in cartesian coords
2025         Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
2026         Point3D obj_pos = sgGeodToCart( obj_posn );
2027
2028         // Translate moving object w.r.t eye
2029         Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
2030         bz[0]=Objtrans.x();
2031         bz[1]=Objtrans.y();
2032         bz[2]=Objtrans.z();
2033
2034        // rotate dynamic objects for lat,lon & alt and other motion about its axes
2035         
2036         sgMat4 sgTRANS;
2037         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
2038
2039         sgVec3 ship_fwd,ship_rt,ship_up;
2040         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
2041         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
2042         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
2043
2044         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
2045         sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
2046         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
2047         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
2048         sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
2049         sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2050         
2051         sgMat4 sgTUX;
2052         sgCopyMat4( sgTUX, sgROT_hdg );
2053         sgPostMultMat4( sgTUX, sgROT_pitch );
2054         sgPostMultMat4( sgTUX, sgROT_roll );
2055         sgPostMultMat4( sgTUX, sgROT_lat );
2056         sgPostMultMat4( sgTUX, sgROT_lon );
2057         sgPostMultMat4( sgTUX, sgTRANS );
2058
2059         sgCoord shippos;
2060         sgSetCoord(&shippos, sgTUX );
2061         ship_pos[m]->setTransform( &shippos );
2062         // temporary hack for deck lights - ultimately should move to PLib (when ??)
2063         if (m == 1) {
2064             if (lightpoints_transform) {
2065                     lightpoints_transform->setTransform( &shippos );
2066                     float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2067                     if ( sun_angle > 89 ) {
2068                             lightpoints_brightness->select(0x01);
2069                     } else {
2070                             lightpoints_brightness->select(0x00);
2071                     }
2072             }
2073
2074             float elev;
2075             sgVec3 rp,to;
2076             float *vp;
2077             float alt;
2078             float ref_elev;
2079             sgXformPnt3( rp, rway_ols, sgTUX );
2080             vp = globals->get_current_view()->get_view_pos();
2081             to[0] = rp[0]-vp[0];
2082             to[1] = rp[1]-vp[1];
2083             to[2] = rp[2]-vp[2];
2084             float dist = sgLengthVec3( to );
2085             alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2086
2087             elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2088
2089             ref_elev = elev - 3.75; // +ve above, -ve below
2090         
2091             unsigned int sel;
2092             sel = 0xFF;
2093 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2094 //              if (ref_elev > 0.51) sel = 0x21;
2095 //              if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2096 //              if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2097 //              if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2098 //              if (ref_elev < -0.51) sel = 0x30;
2099 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2100             // dummy_tile->lightmaps_sequence->select(sel);
2101
2102             sgVec3 up;
2103             sgCopyVec3 (up, ship_up);
2104             if (dist > 750) 
2105                     sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2106             else
2107                     sgScaleVec3 (up, 4.0*ref_elev);
2108             // dummy_tile->ols_transform->setTransform(up);
2109             //cout << "ref_elev  " << ref_elev << endl;
2110         }
2111     // end hack for deck lights
2112
2113     }
2114     if ( ship_sel != NULL ) {
2115         ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2116     }
2117 }
2118
2119 // $$$ end - added VS Renganathan, 15 Oct 2K
2120 //           added Venky         , 12 Nov 2K