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