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