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