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