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