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