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