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