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