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