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