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