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