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