]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Reposition the sky modules only when the lat or long position is changed for 5 micro...
[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 double lat_curr = 9999.0;
599             static double long_curr = 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                 || (init != 0))
604             {
605                 if (init > 0)
606                    init--;
607
608                 sun_pos_angle = cur_light_params.sun_angle;
609                 sun_pos_rotation = cur_light_params.sun_rotation;
610
611                 thesky->repaint( cur_light_params.sky_color,
612                              cur_light_params.adj_fog_color,
613                              cur_light_params.sun_angle,
614                              cur_light_params.moon_angle,
615                              globals->get_ephem()->getNumPlanets(),
616                              globals->get_ephem()->getPlanets(),
617                              globals->get_ephem()->getNumStars(),
618                              globals->get_ephem()->getStars() );
619             }
620
621             /*
622             SG_LOG( SG_GENERAL, SG_BULK,
623                     "thesky->reposition( view_pos = " << view_pos[0] << " "
624              << view_pos[1] << " " << view_pos[2] );
625             SG_LOG( SG_GENERAL, SG_BULK,
626                     "    zero_elev = " << zero_elev[0] << " "
627              << zero_elev[1] << " " << zero_elev[2]
628              << " lon = " << cur_fdm_state->get_Longitude()
629              << " lat = " << cur_fdm_state->get_Latitude() );
630             SG_LOG( SG_GENERAL, SG_BULK,
631                     "    sun_rot = " << cur_light_params.sun_rotation
632              << " gst = " << SGTime::cur_time_params->getGst() );
633             SG_LOG( SG_GENERAL, SG_BULK,
634                  "    sun ra = " << globals->get_ephem()->getSunRightAscension()
635               << " sun dec = " << globals->get_ephem()->getSunDeclination()
636               << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
637               << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
638             */
639
640             if ((fabs(long_curr - current__view->getLongitude_deg()) > 5e-4)
641                 || (fabs(lat_curr - current__view->getLatitude_deg()) > 5e-4)
642                 || (init != 0))
643             {
644                 lat_curr = current__view->getLatitude_deg();
645                 long_curr = current__view->getLongitude_deg();
646
647                 thesky->reposition( current__view->get_view_pos(),
648                             current__view->get_zero_elev(),
649                             current__view->get_world_up(),
650                             current__view->getLongitude_deg()
651                                * SGD_DEGREES_TO_RADIANS,
652                             current__view->getLatitude_deg()
653                                * SGD_DEGREES_TO_RADIANS,
654                             current__view->getAltitudeASL_ft()
655                                * SG_FEET_TO_METER,
656                             cur_light_params.sun_rotation,
657                             globals->get_time_params()->getGst(),
658                             globals->get_ephem()->getSunRightAscension(),
659                             globals->get_ephem()->getSunDeclination(),
660                             50000.0,
661                             globals->get_ephem()->getMoonRightAscension(),
662                             globals->get_ephem()->getMoonDeclination(),
663                             50000.0 );
664             }
665         }
666
667         glEnable( GL_DEPTH_TEST );
668         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
669             glEnable( GL_FOG );
670             glFogi( GL_FOG_MODE, GL_EXP2 );
671             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
672         }
673
674         // set sun/lighting parameters
675         ssgGetLight( 0 ) -> setPosition( l->sun_vec );
676
677         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
678         // we only update GL_AMBIENT for our lights we will never get
679         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
680         // explicitely to black.
681         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
682
683         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
684         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
685         ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular );
686
687         // texture parameters
688         // glEnable( GL_TEXTURE_2D );
689         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
690         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
691
692         // glMatrixMode( GL_PROJECTION );
693         // glLoadIdentity();
694         ssgSetFOV( current__view->get_h_fov(),
695                    current__view->get_v_fov() );
696
697         double agl =
698             current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
699             - globals->get_scenery()->get_cur_elev();
700
701         if ( agl > 10.0 ) {
702             scene_nearplane = 10.0f;
703             scene_farplane = 120000.0f;
704         } else {
705             scene_nearplane = groundlevel_nearplane->getDoubleValue();
706             scene_farplane = 120000.0f;
707         }
708
709         ssgSetNearFar( scene_nearplane, scene_farplane );
710
711         // $$$ begin - added VS Renganthan 17 Oct 2K
712         if(objc)
713           fgUpdateDCS();
714         // $$$ end - added VS Renganthan 17 Oct 2K
715
716 # ifdef FG_NETWORK_OLK
717         if ( fgGetBool("/sim/networking/network-olk") ) {
718             sgCoord fgdpos;
719             other = head->next;             /* put listpointer to start  */
720             while ( other != tail) {        /* display all except myself */
721             if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
722                 other->fgd_sel->select(1);
723                 sgSetCoord( &fgdpos, other->sgFGD_COORD );
724                 other->fgd_pos->setTransform( &fgdpos );
725             }
726             other = other->next;
727             }
728
729             // fgd_sel->select(1);
730             // sgCopyMat4( sgTUX, current_view.sgVIEW);
731             // sgCoord fgdpos;
732             // sgSetCoord( &fgdpos, sgFGD_VIEW );
733             // fgd_pos->setTransform( &fgdpos);
734         }
735 # endif
736
737 #ifdef FG_MPLAYER_AS
738         // Update any multiplayer models
739         globals->get_multiplayer_rx_mgr()->Update();
740 #endif
741
742         if ( fgGetBool("/sim/rendering/skyblend") &&
743              fgGetBool("/sim/rendering/draw-otw") )
744         {
745             // draw the sky backdrop
746
747             // we need a white diffuse light for the phase of the moon
748             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
749
750             thesky->preDraw();
751
752             // return to the desired diffuse color
753             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
754         }
755
756         // draw the ssg scene
757         glEnable( GL_DEPTH_TEST );
758
759         ssgSetNearFar( scene_nearplane, scene_farplane );
760
761         if ( fgGetBool("/sim/rendering/wireframe") ) {
762             // draw wire frame
763             glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
764         }
765         if ( fgGetBool("/sim/rendering/draw-otw") ) {
766             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
767         }
768
769         // This is a bit kludgy.  Every 200 frames, do an extra
770         // traversal of the scene graph without drawing anything, but
771         // with the field-of-view set to 360x360 degrees.  This
772         // ensures that out-of-range random objects that are not in
773         // the current view frustum will still be freed properly.
774         static int counter = 0;
775         counter++;
776         if (counter == 200) {
777           sgFrustum f;
778           f.setFOV(360, 360);
779                             // No need to put the near plane too close;
780                             // this way, at least the aircraft can be
781                             // culled.
782           f.setNearFar(1000, 1000000);
783           sgMat4 m;
784           ssgGetModelviewMatrix(m);
785           globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
786           counter = 0;
787         }
788
789         // change state for lighting here
790
791         // draw runway lighting
792         glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
793         ssgSetNearFar( scene_nearplane, scene_farplane );
794
795 #ifdef FG_EXPERIMENTAL_POINT_LIGHTING
796         // Enable states for drawing points with GL_extension
797         glEnable(GL_POINT_SMOOTH);
798
799         if ( fgGetBool("/sim/rendering/distance-attenuation")
800              && glutExtensionSupported("GL_EXT_point_parameters") )
801         {
802             float quadratic[3] = {1.0, 0.001, 0.0000001};
803             // makes the points fade as they move away
804             glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
805             glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0); 
806         }
807         glPointSize(4.0);
808
809         // blending function for runway lights
810         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
811 #endif
812
813         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
814         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
815         glEnable(GL_TEXTURE_GEN_S);
816         glEnable(GL_TEXTURE_GEN_T);
817         glPolygonMode(GL_FRONT, GL_POINT);
818
819         // draw runway lighting
820         if ( fgGetBool("/sim/rendering/draw-otw") ) {
821             ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
822         }
823
824         // change punch through and then draw taxi lighting
825         glFogf ( GL_FOG_DENSITY, fog_exp2_density );
826         // sgVec3 taxi_fog;
827         // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
828         // glFogfv ( GL_FOG_COLOR, taxi_fog );
829         if ( fgGetBool("/sim/rendering/draw-otw") ) {
830             ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
831         }
832
833         // clean up lighting
834         glPolygonMode(GL_FRONT, GL_FILL);
835         glDisable(GL_TEXTURE_GEN_S);
836         glDisable(GL_TEXTURE_GEN_T);
837
838         //static int _frame_count = 0;
839         //if (_frame_count % 30 == 0) {
840         //  printf("SSG: %s\n", ssgShowStats());
841         //}
842         //else {
843         //  ssgShowStats();
844         //}
845         //_frame_count++;
846
847
848 #ifdef FG_EXPERIMENTAL_POINT_LIGHTING
849         if ( fgGetBool("/sim/rendering/distance-attenuation")
850              && glutExtensionSupported("GL_EXT_point_parameters") )
851         {
852             glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
853                                   default_attenuation);
854         }
855
856         glPointSize(1.0);
857         glDisable(GL_POINT_SMOOTH);
858 #endif
859
860         // draw ground lighting
861         glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
862         if ( fgGetBool("/sim/rendering/draw-otw") ) {
863             ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
864         }
865
866         if ( fgGetBool("/sim/rendering/skyblend") ) {
867             // draw the sky cloud layers
868             if ( fgGetBool("/environment/clouds/status") &&
869                  fgGetBool("/sim/rendering/draw-otw") )
870             {
871                 thesky->postDraw( cur_fdm_state->get_Altitude()
872                                   * SG_FEET_TO_METER );
873             }
874         }
875
876         if ( fgGetBool("/sim/rendering/clouds3d") &&
877              fgGetBool("/sim/rendering/draw-otw") )
878         {
879             glDisable( GL_FOG );
880             glDisable( GL_LIGHTING );
881             // cout << "drawing new clouds" << endl;
882
883             glEnable(GL_DEPTH_TEST);
884             glEnable(GL_BLEND);
885             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
886
887             /*
888             glEnable( GL_TEXTURE_2D );
889             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
890             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
891             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
892             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
893             */
894
895 #ifdef FG_USE_CLOUDS_3D
896             sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
897 #endif
898             glEnable( GL_FOG );
899             glEnable( GL_LIGHTING );
900             glEnable( GL_DEPTH_TEST );
901             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
902         }
903
904         if ( fgGetBool("/sim/rendering/draw-otw") ) {
905             globals->get_model_mgr()->draw();
906             globals->get_aircraft_model()->draw();
907         }
908
909         // display HUD && Panel
910         glDisable( GL_FOG );
911         glDisable( GL_DEPTH_TEST );
912         // glDisable( GL_CULL_FACE );
913         // glDisable( GL_TEXTURE_2D );
914
915         // update the controls subsystem
916         globals->get_controls()->update(delta_time_sec);
917
918         hud_and_panel->apply();
919         fgCockpitUpdate();
920
921         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
922         // This only works properly if called before the panel call
923         if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
924             globals->get_ATC_display()->update(delta_time_sec);
925
926         // update the panel subsystem
927         if ( globals->get_current_panel() != NULL ) {
928             globals->get_current_panel()->update(delta_time_sec);
929         }
930         fgUpdate3DPanels();
931
932         // We can do translucent menus, so why not. :-)
933         menus->apply();
934         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
935         puDisplay();
936         // glDisable ( GL_BLEND ) ;
937
938         glEnable( GL_DEPTH_TEST );
939         glEnable( GL_FOG );
940
941         // Fade out the splash screen over the first three seconds.
942         double t = globals->get_sim_time_sec();
943         if ( t <= 1.0 ) {
944             fgSplashUpdate(0.0, 1.0);
945         } else if ( t <= 3.0) {
946             fgSplashUpdate(0.0, (3.0 - t) / 2.0);
947         }
948     }
949
950     glutSwapBuffers();
951 }
952
953
954 // Update internal time dependent calculations (i.e. flight model)
955 // FIXME: this distinction is obsolete; all subsystems now get delta
956 // time on update.
957 void fgUpdateTimeDepCalcs() {
958     static bool inited = false;
959
960     //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
961
962     fgLIGHT *l = &cur_light_params;
963
964     // Initialize the FDM here if it hasn't been and if we have a
965     // scenery elevation hit.
966
967     // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited() 
968     //      << " cur_elev = " << scenery.get_cur_elev() << endl;
969
970     if ( !cur_fdm_state->get_inited() &&
971          globals->get_scenery()->get_cur_elev() > -9990 )
972     {
973         SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");  
974         cur_fdm_state->init();
975         if ( cur_fdm_state->get_bound() ) {
976             cur_fdm_state->unbind();
977         }
978         cur_fdm_state->bind();
979     }
980
981 #ifndef FG_WEATHERCM
982     globals->get_environment_mgr()->update(delta_time_sec);
983 #endif
984
985     // conceptually, the following block could be done for each fdm
986     // instance ...
987     if ( !cur_fdm_state->get_inited() ) {
988         // do nothing, fdm isn't inited yet
989     } else {
990         // we have been inited, and  we are good to go ...
991
992         if ( !inited ) {
993             inited = true;
994         }
995
996         globals->get_autopilot()->update(delta_time_sec);
997         cur_fdm_state->update(delta_time_sec);
998     }
999
1000     globals->get_model_mgr()->update(delta_time_sec);
1001     globals->get_aircraft_model()->update(delta_time_sec);
1002
1003     // update the view angle
1004     globals->get_viewmgr()->update(delta_time_sec);
1005
1006     l->UpdateAdjFog();
1007
1008     // Update solar system
1009     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
1010                               globals->get_time_params()->getLst(),
1011                               cur_fdm_state->get_Latitude() );
1012
1013     // Update radio stack model
1014     current_radiostack->update(delta_time_sec);
1015 }
1016
1017
1018 void fgInitTimeDepCalcs( void ) {
1019     // noop for now
1020 }
1021
1022
1023 static const double alt_adjust_ft = 3.758099;
1024 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1025
1026
1027 // What should we do when we have nothing else to do?  Let's get ready
1028 // for the next move and update the display?
1029 static void fgMainLoop( void ) {
1030
1031     static const SGPropertyNode *longitude
1032         = fgGetNode("/position/longitude-deg");
1033     static const SGPropertyNode *latitude
1034         = fgGetNode("/position/latitude-deg");
1035     static const SGPropertyNode *altitude
1036         = fgGetNode("/position/altitude-ft");
1037     static const SGPropertyNode *clock_freeze
1038         = fgGetNode("/sim/freeze/clock", true);
1039     static const SGPropertyNode *cur_time_override
1040         = fgGetNode("/sim/time/cur-time-override", true);
1041
1042     // Update the elapsed time.
1043     static bool first_time = true;
1044     if ( first_time ) {
1045         last_time_stamp.stamp();
1046         first_time = false;
1047     }
1048     current_time_stamp.stamp();
1049     delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
1050     if (clock_freeze->getBoolValue())
1051         delta_time_sec = 0;
1052     last_time_stamp = current_time_stamp;
1053     globals->inc_sim_time_sec( delta_time_sec );
1054
1055     static long remainder = 0;
1056     long elapsed;
1057 #ifdef FANCY_FRAME_COUNTER
1058     int i;
1059     double accum;
1060 #else
1061     static time_t last_time = 0;
1062     static int frames = 0;
1063 #endif // FANCY_FRAME_COUNTER
1064
1065     SGTime *t = globals->get_time_params();
1066
1067     sglog().setLogLevels( SG_ALL, (sgDebugPriority)fgGetInt("/sim/log-level") );
1068
1069     FGLocation * acmodel_location = 0;
1070     if(cur_fdm_state->getACModel() != 0) {
1071       acmodel_location = (FGLocation *)  cur_fdm_state->getACModel()->get3DModel()->getFGLocation();
1072     }
1073
1074     SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1075     SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1076
1077 #ifdef FG_NETWORK_OLK
1078     if ( fgGetBool("/sim/networking/network-olk") ) {
1079         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
1080             // printf("FGD: Netupdate\n");
1081             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
1082             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
1083         }
1084     }
1085 #endif
1086
1087 #if defined( ENABLE_PLIB_JOYSTICK )
1088     // Read joystick and update control settings
1089     // if ( fgGetString("/sim/control-mode") == "joystick" )
1090     // {
1091     //    fgJoystickRead();
1092     // }
1093 #elif defined( ENABLE_GLUT_JOYSTICK )
1094     // Glut joystick support works by feeding a joystick handler
1095     // function to glut.  This is taken care of once in the joystick
1096     // init routine and we don't have to worry about it again.
1097 #endif
1098
1099     // Fix elevation.  I'm just sticking this here for now, it should
1100     // probably move eventually
1101
1102     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
1103            scenery.get_cur_elev(),
1104            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1105            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1106
1107 // Curt is this code used?  I don't see any problems when I comment it out.
1108     if ( acmodel_location != 0 ) {
1109       if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
1110         if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER < 
1111              (acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0) ) {
1112             // now set aircraft altitude above ground
1113             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
1114                cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1115                acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0,
1116                acmodel_location->get_cur_elev_m() + alt_adjust_m );
1117             cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m() 
1118                                                 + alt_adjust_m) * SG_METER_TO_FEET );
1119             SG_LOG( SG_ALL, SG_DEBUG, 
1120                 "<*> resetting altitude to " 
1121                 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1122                 << " meters" );
1123         }
1124       }
1125     }
1126 // End of code in question. (see Curt is this code used? above)
1127
1128     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
1129            scenery.get_cur_elev(),
1130            cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1131            cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1132
1133     // cout << "Warp = " << globals->get_warp() << endl;
1134
1135     // update "time"
1136     static bool last_clock_freeze = false;
1137
1138     if ( clock_freeze->getBoolValue() ) {
1139         // clock freeze requested
1140         if ( cur_time_override->getLongValue() == 0 ) {
1141             fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1142             globals->set_warp( 0 );
1143         }
1144     } else {
1145         // no clock freeze requested
1146         if ( last_clock_freeze == true ) {
1147             // clock just unfroze, let's set warp as the difference
1148             // between frozen time and current time so we don't get a
1149             // time jump (and corresponding sky object and lighting
1150             // jump.)
1151             globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1152             fgSetLong( "/sim/time/cur-time-override", 0 );
1153         }
1154         if ( globals->get_warp_delta() != 0 ) {
1155             globals->inc_warp( globals->get_warp_delta() );
1156         }
1157     }
1158
1159     last_clock_freeze = clock_freeze->getBoolValue();
1160
1161     t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1162                latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1163                cur_time_override->getLongValue(),
1164                globals->get_warp() );
1165
1166     if ( globals->get_warp_delta() != 0 ) {
1167         fgUpdateSkyAndLightingParams();
1168     }
1169
1170     // update magvar model
1171     globals->get_mag()->update( longitude->getDoubleValue()
1172                               * SGD_DEGREES_TO_RADIANS,
1173                             latitude->getDoubleValue()
1174                               * SGD_DEGREES_TO_RADIANS,
1175                             altitude->getDoubleValue() * SG_FEET_TO_METER,
1176                             globals->get_time_params()->getJD() );
1177
1178     // Get elapsed time (in usec) for this past frame
1179     elapsed = fgGetTimeInterval();
1180     SG_LOG( SG_ALL, SG_DEBUG, 
1181             "Elapsed time interval is = " << elapsed 
1182             << ", previous remainder is = " << remainder );
1183
1184     // Calculate frame rate average
1185 #ifdef FANCY_FRAME_COUNTER
1186     /* old fps calculation */
1187     if ( elapsed > 0 ) {
1188         double tmp;
1189         accum = 0.0;
1190         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1191             tmp = general.get_frame(i);
1192             accum += tmp;
1193             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1194             general.set_frame(i+1,tmp);
1195         }
1196         tmp = 1000000.0 / (float)elapsed;
1197         general.set_frame(0,tmp);
1198         // printf("frame[0] = %.2f\n", general.frames[0]);
1199         accum += tmp;
1200         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1201         // printf("ave = %.2f\n", general.frame_rate);
1202     }
1203 #else
1204     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1205         general.set_frame_rate( frames );
1206         fgSetInt("/sim/frame-rate", frames);
1207         SG_LOG( SG_ALL, SG_DEBUG, 
1208             "--> Frame rate is = " << general.get_frame_rate() );
1209         frames = 0;
1210     }
1211     last_time = t->get_cur_time();
1212     ++frames;
1213 #endif
1214
1215     // Run ATC subsystem
1216     if (fgGetBool("/sim/ATC/enabled"))
1217         globals->get_ATC_mgr()->update(delta_time_sec);
1218
1219     // Run the AI subsystem
1220     if (fgGetBool("/sim/ai-traffic/enabled"))
1221         globals->get_AI_mgr()->update(delta_time_sec);
1222
1223     // Run flight model
1224
1225     // Calculate model iterations needed for next frame
1226     elapsed += remainder;
1227
1228     global_multi_loop = (long)(((double)elapsed * 0.000001) * 
1229                           fgGetInt("/sim/model-hz"));
1230     remainder = elapsed - ( (global_multi_loop*1000000) / 
1231                         fgGetInt("/sim/model-hz") );
1232     SG_LOG( SG_ALL, SG_DEBUG, 
1233             "Model iterations needed = " << global_multi_loop
1234             << ", new remainder = " << remainder );
1235         
1236     // chop max interations to something reasonable if the sim was
1237     // delayed for an excesive amount of time
1238     if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1239         global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1240         remainder = 0;
1241     }
1242
1243     // flight model
1244     if ( global_multi_loop > 0 ) {
1245         fgUpdateTimeDepCalcs();
1246     } else {
1247         SG_LOG( SG_ALL, SG_DEBUG, 
1248             "Elapsed time is zero ... we're zinging" );
1249     }
1250
1251     // Do any I/O channel work that might need to be done
1252     globals->get_io()->update( delta_time_sec );
1253
1254     // see if we need to load any deferred-load textures
1255     material_lib.load_next_deferred();
1256
1257     // Run audio scheduler
1258 #ifdef ENABLE_AUDIO_SUPPORT
1259     if ( fgGetBool("/sim/sound/audible")
1260            && globals->get_soundmgr()->is_working() ) {
1261         globals->get_soundmgr()->update( delta_time_sec );
1262     }
1263 #endif
1264
1265     globals->get_subsystem_mgr()->update(delta_time_sec);
1266
1267     //
1268     // Tile Manager updates - see if we need to load any new scenery tiles.
1269     //   this code ties together the fdm, viewer and scenery classes...
1270     //   we may want to move this to it's own class at some point
1271     //
1272     double visibility_meters = fgGetDouble("/environment/visibility-m");
1273     FGViewer *current_view = globals->get_current_view();
1274
1275     // update tile manager for FDM...
1276     // ...only if location is different than the viewer (to avoid duplicating effort)
1277     if( acmodel_location != current_view->getFGLocation() ) {
1278       if( acmodel_location != 0 ) {
1279         globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1280                                                  visibility_meters );
1281         globals->get_tile_mgr()->
1282             update( acmodel_location, visibility_meters,
1283                     acmodel_location->get_absolute_view_pos() );
1284         // save results of update in FGLocation for fdm...
1285         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1286           acmodel_location->
1287               set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1288         }
1289         acmodel_location->
1290             set_tile_center( globals->get_scenery()->get_next_center() );
1291       }
1292     }
1293
1294     globals->get_tile_mgr()->prep_ssg_nodes( current_view->getFGLocation(),
1295                                              visibility_meters );
1296     // update tile manager for view...
1297     // IMPORTANT!!! the tilemgr update for view location _must_ be done last 
1298     // after the FDM's until all of Flight Gear code references the viewer's location
1299     // for elevation instead of the "scenery's" current elevation.
1300     FGLocation *view_location = globals->get_current_view()->getFGLocation();
1301     globals->get_tile_mgr()->update( view_location, visibility_meters,
1302                                      current_view->get_absolute_view_pos() );
1303     // save results of update in FGLocation for fdm...
1304     if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1305       current_view->getFGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1306     }
1307     current_view->getFGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1308
1309     // If fdm location is same as viewer's then we didn't do the update for fdm location 
1310     //   above so we need to save the viewer results in the fdm FGLocation as well...
1311     if( acmodel_location == current_view->getFGLocation() ) {
1312       if( acmodel_location != 0 ) {
1313         if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1314           acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1315         }
1316         acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1317       }
1318     }
1319
1320     // END Tile Manager udpates
1321
1322     // redraw display
1323     fgRenderFrame();
1324
1325     SG_LOG( SG_ALL, SG_DEBUG, "" );
1326 }
1327
1328
1329 // This is the top level master main function that is registered as
1330 // our idle funciton
1331
1332 // The first few passes take care of initialization things (a couple
1333 // per pass) and once everything has been initialized fgMainLoop from
1334 // then on.
1335
1336 static void fgIdleFunction ( void ) {
1337     // printf("idle state == %d\n", idle_state);
1338
1339     if ( idle_state == 0 ) {
1340         // Initialize the splash screen right away
1341         if ( fgGetBool("/sim/startup/splash-screen") ) {
1342             fgSplashInit();
1343         }
1344         
1345         idle_state++;
1346     } else if ( idle_state == 1 ) {
1347         // Initialize audio support
1348 #ifdef ENABLE_AUDIO_SUPPORT
1349
1350         // Start the intro music
1351         if ( fgGetBool("/sim/startup/intro-music") ) {
1352             SGPath mp3file( globals->get_fg_root() );
1353             mp3file.append( "Sounds/intro.mp3" );
1354
1355             SG_LOG( SG_GENERAL, SG_INFO, 
1356                 "Starting intro music: " << mp3file.str() );
1357
1358 #if defined( __CYGWIN__ )
1359             string command = "start /m `cygpath -w " + mp3file.str() + "`";
1360 #elif defined( WIN32 )
1361             string command = "start /m " + mp3file.str();
1362 #else
1363             string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1364 #endif
1365
1366             system ( command.c_str() );
1367         }
1368 #endif
1369
1370         idle_state++;
1371     } else if ( idle_state == 2 ) {
1372         // These are a few miscellaneous things that aren't really
1373         // "subsystems" but still need to be initialized.
1374
1375 #ifdef USE_GLIDE
1376         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1377             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1378         }
1379 #endif
1380
1381         idle_state++;
1382     } else if ( idle_state == 3 ) {
1383         // This is the top level init routine which calls all the
1384         // other subsystem initialization routines.  If you are adding
1385         // a subsystem to flightgear, its initialization call should
1386         // located in this routine.
1387         if( !fgInitSubsystems()) {
1388             SG_LOG( SG_GENERAL, SG_ALERT,
1389                 "Subsystem initializations failed ..." );
1390             exit(-1);
1391         }
1392
1393         idle_state++;
1394     } else if ( idle_state == 4 ) {
1395         // setup OpenGL view parameters
1396         fgInitVisuals();
1397
1398         // Read the list of available aircrafts
1399         fgReadAircraft();
1400
1401         idle_state++;
1402     } else if ( idle_state == 5 ) {
1403
1404         idle_state++;
1405     } else if ( idle_state == 6 ) {
1406         // sleep(1);
1407         idle_state = 1000;
1408
1409         SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1410         fgReshape( fgGetInt("/sim/startup/xsize"),
1411                fgGetInt("/sim/startup/ysize") );
1412     } 
1413
1414     if ( idle_state == 1000 ) {
1415         // We've finished all our initialization steps, from now on we
1416         // run the main loop.
1417
1418         glutIdleFunc(fgMainLoop);
1419     } else {
1420         if ( fgGetBool("/sim/startup/splash-screen") ) {
1421             fgSplashUpdate(0.0, 1.0);
1422         }
1423     }
1424 }
1425
1426 // options.cxx needs to see this for toggle_panel()
1427 // Handle new window size or exposure
1428 void fgReshape( int width, int height ) {
1429     int view_h;
1430
1431     if ( (!fgGetBool("/sim/virtual-cockpit"))
1432          && fgPanelVisible() && idle_state == 1000 ) {
1433         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1434                              globals->get_current_panel()->getYOffset()) / 768.0);
1435     } else {
1436         view_h = height;
1437     }
1438
1439     // for all views
1440     FGViewMgr *viewmgr = globals->get_viewmgr();
1441     for ( int i = 0; i < viewmgr->size(); ++i ) {
1442       viewmgr->get_view(i)->
1443         set_aspect_ratio((float)view_h / (float)width);
1444     }
1445
1446     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1447
1448     fgSetInt("/sim/startup/xsize", width);
1449     fgSetInt("/sim/startup/ysize", height);
1450     guiInitMouse(width, height);
1451
1452     ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1453                viewmgr->get_current_view()->get_v_fov() );
1454
1455     fgHUDReshape();
1456
1457 #ifdef FG_USE_CLOUDS_3D
1458     sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1459                         viewmgr->get_current_view()->get_v_fov() );
1460 #endif
1461
1462 }
1463
1464 // Initialize GLUT and define a main window
1465 static bool fgGlutInit( int *argc, char **argv ) {
1466
1467 #if !defined( macintosh )
1468     // GLUT will extract all glut specific options so later on we only
1469     // need wory about our own.
1470     glutInit(argc, argv);
1471 #endif
1472
1473     // Define Display Parameters. Clouds3d works best with --bpp32 option
1474     if ( fgGetBool("/sim/rendering/clouds3d") ) {
1475         glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1476     } else {
1477         glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1478     }
1479
1480     SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1481             fgGetInt("/sim/startup/xsize") << "x"
1482             << fgGetInt("/sim/startup/ysize") );
1483
1484     // Define initial window size
1485     glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1486                     fgGetInt("/sim/startup/ysize") );
1487
1488     // Initialize windows
1489     if ( !fgGetBool("/sim/startup/game-mode")) {
1490         // Open the regular window
1491         glutCreateWindow("FlightGear");
1492 #ifndef GLUT_WRONG_VERSION
1493     } else {
1494         // Open the cool new 'game mode' window
1495         char game_mode_str[256];
1496 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1497 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1498 #ifndef ENUM_CURRENT_SETTINGS
1499 #define ENUM_CURRENT_SETTINGS       ((DWORD)-1)
1500 #define ENUM_REGISTRY_SETTINGS      ((DWORD)-2)
1501 #endif
1502
1503         DEVMODE dm;
1504         dm.dmSize = sizeof(DEVMODE);
1505         EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1506         fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1507         fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1508         glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1509                             fgGetInt("/sim/startup/ysize") );
1510         sprintf( game_mode_str, "%dx%d:%d@%d",
1511                      dm.dmPelsWidth,
1512                      dm.dmPelsHeight,
1513                      dm.dmBitsPerPel,
1514                      dm.dmDisplayFrequency );
1515 #else
1516         // Open the cool new 'game mode' window
1517         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1518              fgGetInt("/sim/startup/xsize"),
1519              fgGetInt("/sim/startup/ysize"),
1520              fgGetInt("/sim/rendering/bits-per-pixel"));
1521
1522 #endif // HAVE_WINDOWS_H
1523         SG_LOG( SG_GENERAL, SG_INFO, 
1524             "game mode params = " << game_mode_str );
1525         glutGameModeString( game_mode_str );
1526         glutEnterGameMode();
1527 #endif // GLUT_WRONG_VERSION
1528     }
1529
1530     // This seems to be the absolute earliest in the init sequence
1531     // that these calls will return valid info.  Too bad it's after
1532     // we've already created and sized out window. :-(
1533     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1534     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1535     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1536     SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1537
1538     GLint tmp;
1539     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1540     general.set_glMaxTexSize( tmp );
1541     SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1542
1543     glGetIntegerv( GL_DEPTH_BITS, &tmp );
1544     general.set_glDepthBits( tmp );
1545     SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1546
1547     return true;
1548 }
1549
1550
1551 // Initialize GLUT event handlers
1552 static bool fgGlutInitEvents( void ) {
1553     // call fgReshape() on window resizes
1554     glutReshapeFunc( fgReshape );
1555
1556     // keyboard and mouse callbacks are set in FGInput::init
1557
1558     // call fgMainLoop() whenever there is
1559     // nothing else to do
1560     glutIdleFunc( fgIdleFunction );
1561
1562     // draw the scene
1563     glutDisplayFunc( fgRenderFrame );
1564
1565     return true;
1566 }
1567
1568 // Main top level initialization
1569 static bool fgMainInit( int argc, char **argv ) {
1570
1571 #if defined( macintosh )
1572     freopen ("stdout.txt", "w", stdout );
1573     freopen ("stderr.txt", "w", stderr );
1574     argc = ccommand( &argv );
1575 #endif
1576
1577     // set default log levels
1578     sglog().setLogLevels( SG_ALL, SG_INFO );
1579
1580     string version;
1581 #ifdef FLIGHTGEAR_VERSION
1582     version = FLIGHTGEAR_VERSION;
1583 #else
1584     version = "unknown version";
1585 #endif
1586     SG_LOG( SG_GENERAL, SG_INFO, "FlightGear:  Version "
1587             << version );
1588     SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1589
1590     // Allocate global data structures.  This needs to happen before
1591     // we parse command line options
1592
1593     globals = new FGGlobals;
1594
1595 #ifndef FG_WEATHERCM
1596     globals->set_environment_mgr(new FGEnvironmentMgr);
1597 #endif
1598
1599     // seed the random number generater
1600     sg_srandom_time();
1601
1602     SGRoute *route = new SGRoute;
1603     globals->set_route( route );
1604
1605     FGControls *controls = new FGControls;
1606     globals->set_controls( controls );
1607
1608     string_list *col = new string_list;
1609     globals->set_channel_options_list( col );
1610
1611     // Scan the config file(s) and command line options to see if
1612     // fg_root was specified (ignore all other options for now)
1613     fgInitFGRoot(argc, argv);
1614
1615     // Check for the correct base package version
1616     static char required_version[] = "0.9.1";
1617     string base_version = fgBasePackageVersion();
1618     if ( !(base_version == required_version) ) {
1619         // tell the operator how to use this application
1620
1621         cerr << endl << "Base package check failed ... " \
1622              << "Found version " << base_version << " at: " \
1623              << globals->get_fg_root() << endl;
1624         cerr << "Please upgrade to version: " << required_version << endl;
1625         exit(-1);
1626     }
1627
1628     // Initialize the Aircraft directory to "" (UIUC)
1629     aircraft_dir = "";
1630
1631     // Load the configuration parameters.  (Command line options
1632     // overrides config file options.  Config file options override
1633     // defaults.)
1634     if ( !fgInitConfig(argc, argv) ) {
1635         SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1636         exit(-1);
1637     }
1638
1639     // Initialize the Window/Graphics environment.
1640     if( !fgGlutInit(&argc, argv) ) {
1641         SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1642         exit(-1);
1643     }
1644
1645     // Initialize the various GLUT Event Handlers.
1646     if( !fgGlutInitEvents() ) {
1647  SG_LOG( SG_GENERAL, SG_ALERT, 
1648                 "GLUT event handler initialization failed ..." );
1649         exit(-1);
1650     }
1651
1652     // Initialize plib net interface
1653     netInit( &argc, argv );
1654
1655     // Initialize ssg (from plib).  Needs to come before we do any
1656     // other ssg stuff, but after opengl/glut has been initialized.
1657     ssgInit();
1658
1659     // Initialize the user interface (we need to do this before
1660     // passing off control to glut and before fgInitGeneral to get our
1661     // fonts !!!
1662     guiInit();
1663
1664     // Read the list of available aircrafts
1665     fgReadAircraft();
1666
1667 #ifdef GL_EXT_texture_lod_bias
1668     glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1669 #endif
1670
1671 #ifdef FG_EXPERIMENTAL_POINT_LIGHTING
1672             // get the address of our OpenGL extensions
1673     if ( fgGetBool("/sim/rendering/distance-attenuation") )
1674     {
1675 #ifdef WIN32
1676         glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC) 
1677             wglGetProcAddress("glPointParameterfEXT");
1678         glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC) 
1679             wglGetProcAddress("glPointParameterfvEXT");
1680 #elif linux
1681         glPointParameterfEXT = (OpenGLFuncExt) 
1682             glXGetProcAddressARB((GLubyte *)"glPointParameterfEXT");
1683         glPointParameterfvEXT = (OpenGLFuncExtv) 
1684             glXGetProcAddressARB((GLubyte *)"glPointParameterfvEXT");
1685 #endif
1686    }
1687 #endif
1688
1689     // based on the requested presets, calculate the true starting
1690     // lon, lat
1691     fgInitNav();
1692     fgInitPosition();
1693
1694     SGTime *t = fgInitTime();
1695     globals->set_time_params( t );
1696
1697     // Do some quick general initializations
1698     if( !fgInitGeneral()) {
1699         SG_LOG( SG_GENERAL, SG_ALERT, 
1700             "General initializations failed ..." );
1701         exit(-1);
1702     }
1703
1704     SGPath modelpath( globals->get_fg_root() );
1705     ssgModelPath( (char *)modelpath.c_str() );
1706
1707     // Initialize the global scenery manager
1708     globals->set_scenery( new FGScenery );
1709     globals->get_scenery()->init();
1710     globals->get_scenery()->bind();
1711
1712     // Initialize the global tile manager
1713     globals->set_tile_mgr( new FGTileMgr );
1714
1715     ////////////////////////////////////////////////////////////////////
1716     // Initialize the property-based built-in commands
1717     ////////////////////////////////////////////////////////////////////
1718     fgInitCommands();
1719
1720     ////////////////////////////////////////////////////////////////////
1721     // Initialize the general model subsystem.
1722     ////////////////////////////////////////////////////////////////////
1723
1724     globals->set_model_loader(new FGModelLoader);
1725     globals->set_texture_loader(new FGTextureLoader);
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.
1732     ////////////////////////////////////////////////////////////////////
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     thesky->build( 550.0, 550.0,
1774                globals->get_ephem()->getNumPlanets(), 
1775                globals->get_ephem()->getPlanets(), 60000.0,
1776                globals->get_ephem()->getNumStars(),
1777                globals->get_ephem()->getStars(), 60000.0 );
1778
1779     // Initialize MagVar model
1780     SGMagVar *magvar = new SGMagVar();
1781     globals->set_mag( magvar );
1782
1783     // airport = new ssgBranch;
1784     // airport->setName( "Airport Lighting" );
1785     // lighting->addKid( airport );
1786
1787     // ADA
1788     fgLoadDCS();
1789     // ADA
1790
1791 #ifdef FG_NETWORK_OLK
1792     // Do the network intialization
1793     if ( fgGetBool("/sim/networking/network-olk") ) {
1794         printf("Multipilot mode %s\n",
1795                fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1796     }
1797 #endif
1798
1799     // build our custom render states
1800     fgBuildRenderStates();
1801     
1802     // pass control off to the master GLUT event handler
1803     glutMainLoop();
1804
1805     // we never actually get here ... but to avoid compiler warnings,
1806     // etc.
1807     return false;
1808 }
1809
1810
1811 // $$$ end - added VS Renganathan, 15 Oct 2K
1812 //         - added Venky         , 12 Nov 2K
1813
1814 #if defined(__linux__) && defined(__i386__)
1815
1816 static void handleFPE (int);
1817
1818 static void
1819 initFPE ()
1820 {
1821     fpu_control_t fpe_flags = 0;
1822     _FPU_GETCW(fpe_flags);
1823 //     fpe_flags &= ~_FPU_MASK_IM;      // invalid operation
1824 //     fpe_flags &= ~_FPU_MASK_DM;      // denormalized operand
1825 //     fpe_flags &= ~_FPU_MASK_ZM;      // zero-divide
1826 //     fpe_flags &= ~_FPU_MASK_OM;      // overflow
1827 //     fpe_flags &= ~_FPU_MASK_UM;      // underflow
1828 //     fpe_flags &= ~_FPU_MASK_PM;      // precision (inexact result)
1829     _FPU_SETCW(fpe_flags);
1830     signal(SIGFPE, handleFPE);
1831 }
1832
1833 static void
1834 handleFPE (int num)
1835 {
1836   initFPE();
1837   SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1838 }
1839 #endif
1840
1841 #ifdef __APPLE__
1842
1843 typedef struct
1844 {
1845   int  lo;
1846   int  hi;
1847 } PSN;
1848
1849 extern "C" {
1850   short CPSGetCurrentProcess(PSN *psn);
1851   short CPSSetProcessName (PSN *psn, char *processname);
1852   short CPSEnableForegroundOperation(PSN *psn, int _arg2, int _arg3, int _arg4, int _arg5);
1853   short CPSSetFrontProcess(PSN *psn);
1854 };
1855
1856 #define CPSEnableFG(psn) CPSEnableForegroundOperation(psn,0x03,0x3C,0x2C,0x1103)
1857
1858 #endif
1859
1860 // Main entry point; catch any exceptions that have made it this far.
1861 int main ( int argc, char **argv ) {
1862
1863     // Enable floating-point exceptions for Linux/x86
1864 #if defined(__linux__) && defined(__i386__)
1865     initFPE();
1866 #endif
1867
1868     // Enable floating-point exceptions for Windows
1869 #if defined( _MSC_VER ) && defined( DEBUG )
1870     // Christian, we should document what this does
1871     _control87( _EM_INEXACT, _MCW_EM );
1872 #endif
1873
1874 #if defined( HAVE_BC5PLUS )
1875     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1876 #endif
1877
1878     // Keyboard focus hack
1879 #ifdef __APPLE__
1880     {
1881       PSN psn;
1882
1883       glutInit (&argc, argv);
1884
1885       CPSGetCurrentProcess(&psn);
1886       CPSSetProcessName(&psn, "FlightGear");
1887       CPSEnableFG(&psn);
1888       CPSSetFrontProcess(&psn);
1889     }
1890 #endif
1891
1892     // FIXME: add other, more specific
1893     // exceptions.
1894     try {
1895         fgMainInit(argc, argv);
1896     } catch (sg_throwable &t) {
1897                             // We must use cerr rather than
1898                             // logging, since logging may be
1899                             // disabled.
1900         cerr << "Fatal error: " << t.getFormattedMessage()
1901              << "\n (received from " << t.getOrigin() << ')' << endl;
1902         exit(1);
1903     }
1904
1905     return 0;
1906 }
1907
1908
1909 void fgLoadDCS(void) {
1910
1911     ssgEntity *ship_obj = NULL;
1912
1913     char obj_filename[25];
1914
1915     for ( int k = 0; k < 32; k++ ) {
1916         ship_pos[k]=NULL;
1917     }
1918
1919     SGPath tile_path( globals->get_fg_root());
1920     tile_path.append( "Scenery" );
1921     tile_path.append( "Objects.txt" );
1922     sg_gzifstream in( tile_path.str() );
1923     if ( ! in.is_open() ) {
1924         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1925     } else {
1926
1927         SGPath modelpath( globals->get_fg_root() );
1928         modelpath.append( "Models" );
1929         modelpath.append( "Geometry" );
1930   
1931         SGPath texturepath( globals->get_fg_root() );
1932         texturepath.append( "Models" );
1933         texturepath.append( "Textures" );
1934  
1935         ssgModelPath( (char *)modelpath.c_str() );
1936         ssgTexturePath( (char *)texturepath.c_str() );
1937
1938         ship_sel = new ssgSelector;
1939
1940         char c;
1941         while ( ! in.eof() ) {
1942             in >> ::skipws;
1943             if ( in.get( c ) && c == '#' ) { 
1944                 in >> skipeol;
1945             } else { 
1946                 in.putback(c);
1947                 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1948                 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] <<  " " << obj_alt[objc] << endl;
1949                    int chj=getchar();*/
1950                 
1951                 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1952                 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1953                 
1954                 ship_pos[objc] = new ssgTransform;
1955        
1956                 // type "repeat" in objects.txt to load one more
1957                 // instance of the last object.
1958
1959                 if ( strcmp(obj_filename,"repeat") != 0) {
1960                     ship_obj =
1961                         globals->get_model_loader()->load_model( obj_filename );
1962                 }
1963       
1964                 if ( ship_obj != NULL ) {
1965                                 ship_obj->setName(obj_filename);
1966                             if (objc == 0)
1967                                         ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1968                                 else
1969                                         ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1970                     ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1971                     ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1972                     SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1973                             << obj_filename );
1974                 } else {
1975                     SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1976                             << obj_filename );
1977                 }
1978             
1979                             // temporary hack for deck lights - ultimately should move to PLib (when??)
1980                             //const char *extn = file_extension ( obj_filename ) ;
1981                             if ( objc == 1 ){
1982                                 ssgVertexArray *lights = new ssgVertexArray( 100 );
1983                                 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1984                                 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1985                                 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1986                                 int ltype[500], light_type;
1987                                 static int ltcount = 0;
1988                                 string token;
1989                                 sgVec3 rway_dir,rway_normal,lightpt;
1990                                 Point3D node;
1991                                 modelpath.append(obj_filename);
1992                                 sg_gzifstream in1( modelpath.str() );
1993                                 if ( ! in1.is_open() ) {
1994                                         SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1995                                 } else {
1996                                         while ( ! in1.eof() ) {
1997                                                         in1 >> ::skipws;
1998                                                 if ( in1.get( c ) && c == '#' ) { 
1999                                                         in1 >> skipeol;
2000                                                 } else { 
2001                                                         in1.putback(c);
2002                                                         in1 >> token;
2003                                                         //cout << token << endl;
2004                                                         if ( token == "runway" ) {
2005                                                                 in1 >> node;
2006                                                                 sgSetVec3 (rway_dir, node[0], node[1], node[2] );                        
2007                                                         } else if ( token == "edgelight" ) {
2008                                                                 in1 >> node;
2009                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2010                                                                 light_type = 1;
2011                                                         } else if ( token == "taxi" ) {
2012                                                                 in1 >> node;
2013                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
2014                                                                 light_type = 2;
2015                                                         } else if ( token == "vasi" ) {
2016                                                                 in1 >> node;
2017                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
2018                                                                 light_type = 3;
2019                                                         } else if ( token == "threshold" ) {
2020                                                                 in1 >> node;
2021                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );                     
2022                                                                 light_type = 4;
2023                                                         } else if ( token == "rabbit" ) {
2024                                                                 in1 >> node;
2025                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2026                                                                 light_type = 5;
2027                                                         } else if ( token == "ols" ) {
2028                                                                 in1 >> node;
2029                                                                 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
2030                                                                 light_type = 6;
2031                                                         } else if ( token == "red" ) {
2032                                                                 in1 >> node;
2033                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2034                                                                 light_type = 7;
2035                                                         } else if ( token == "green" ) {
2036                                                                 in1 >> node;
2037                                                                 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2038                                                                 light_type = 8;
2039                                                         } else if ( token == "lp" ) {
2040                                                                 in1 >> node;
2041                                                                 sgSetVec3 (lightpt, node[0], node[1], node[2] );
2042                                                                 lightpoints->add( lightpt );
2043                                                                 lightnormals->add( rway_normal );
2044                                                                 lightdir->add( rway_dir );
2045                                                                 ltype[ltcount]= light_type;
2046                                                                 ltcount++;
2047                                                         }
2048                                                         if (in1.eof()) break;
2049                                                 } 
2050                                         }  //while
2051         
2052                                         if ( lightpoints->getNum() ) {
2053                                                 ssgBranch *lightpoints_branch;
2054                                                 long int dummy = -999;
2055                                                 dummy_tile = new FGTileEntry((SGBucket)dummy);
2056                                                 dummy_tile->lightmaps_sequence = new ssgSelector;
2057                                                 dummy_tile->ols_transform = new ssgTransform;
2058
2059                                                 // call function to generate the runway lights
2060                                                 lightpoints_branch = 
2061                                                 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
2062                                                                                                                         lightdir, ltype);
2063                                                 lightpoints_brightness->addKid(lightpoints_branch);
2064                                                 lightpoints_transform->addKid(lightpoints_brightness);
2065                                             //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
2066                                                 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
2067                                                 lightpoints_transform->ref();
2068                                                 globals->get_scenery()->get_gnd_lights_root()->addKid( lightpoints_transform );
2069                                         } 
2070                                 } //if in1 
2071                 } //if objc
2072                             // end hack for deck lights
2073
2074                 objc++;
2075
2076                 if (in.eof()) break;
2077             }
2078         } // while
2079
2080         SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
2081
2082         globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node 
2083     }
2084
2085     return;
2086  }
2087
2088
2089 void fgUpdateDCS (void) {
2090
2091     // double eye_lat,eye_lon,eye_alt;
2092     // static double obj_head;
2093     double sl_radius,obj_latgc;
2094     // float nresultmat[4][4];
2095     // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
2096     double bz[3];
2097
2098     // Instantaneous Geodetic Lat/Lon/Alt of moving object
2099     FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
2100     
2101     // Deck should be the first object in objects.txt in case of fdm=ada
2102
2103     if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
2104             if ((fdm->get_iaux(1))==1)
2105             {
2106                     obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
2107                     obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
2108                     obj_alt[1] = fdm->get_daux(3);
2109                     obj_pitch[1] = fdm->get_faux(1);
2110                     obj_roll[1] = fdm->get_faux(2);
2111             }
2112     }
2113     
2114     for ( int m = 0; m < objc; m++ ) {
2115         //cout << endl <<  obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
2116         //int v=getchar();
2117
2118         //Geodetic to Geocentric angles for rotation
2119         sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
2120
2121         //moving object gbs-posn in cartesian coords
2122         Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
2123         Point3D obj_pos = sgGeodToCart( obj_posn );
2124
2125         // Translate moving object w.r.t eye
2126         Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
2127         bz[0]=Objtrans.x();
2128         bz[1]=Objtrans.y();
2129         bz[2]=Objtrans.z();
2130
2131        // rotate dynamic objects for lat,lon & alt and other motion about its axes
2132         
2133         sgMat4 sgTRANS;
2134         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
2135
2136         sgVec3 ship_fwd,ship_rt,ship_up;
2137         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
2138         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
2139         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
2140
2141         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
2142         sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
2143         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
2144         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
2145         sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
2146         sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2147         
2148         sgMat4 sgTUX;
2149         sgCopyMat4( sgTUX, sgROT_hdg );
2150         sgPostMultMat4( sgTUX, sgROT_pitch );
2151         sgPostMultMat4( sgTUX, sgROT_roll );
2152         sgPostMultMat4( sgTUX, sgROT_lat );
2153         sgPostMultMat4( sgTUX, sgROT_lon );
2154         sgPostMultMat4( sgTUX, sgTRANS );
2155
2156         sgCoord shippos;
2157         sgSetCoord(&shippos, sgTUX );
2158         ship_pos[m]->setTransform( &shippos );
2159         // temporary hack for deck lights - ultimately should move to PLib (when ??)
2160         if (m == 1) {
2161             if (lightpoints_transform) {
2162                     lightpoints_transform->setTransform( &shippos );
2163                     float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2164                     if ( sun_angle > 89 ) {
2165                             lightpoints_brightness->select(0x01);
2166                     } else {
2167                             lightpoints_brightness->select(0x00);
2168                     }
2169             }
2170
2171             float elev;
2172             sgVec3 rp,to;
2173             float *vp;
2174             float alt;
2175             float ref_elev;
2176             sgXformPnt3( rp, rway_ols, sgTUX );
2177             vp = globals->get_current_view()->get_view_pos();
2178             to[0] = rp[0]-vp[0];
2179             to[1] = rp[1]-vp[1];
2180             to[2] = rp[2]-vp[2];
2181             float dist = sgLengthVec3( to );
2182             alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2183
2184             elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2185
2186             ref_elev = elev - 3.75; // +ve above, -ve below
2187         
2188             unsigned int sel;
2189             sel = 0xFF;
2190 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2191 //              if (ref_elev > 0.51) sel = 0x21;
2192 //              if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2193 //              if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2194 //              if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2195 //              if (ref_elev < -0.51) sel = 0x30;
2196 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2197             dummy_tile->lightmaps_sequence->select(sel);
2198
2199             sgVec3 up;
2200             sgCopyVec3 (up, ship_up);
2201             if (dist > 750) 
2202                     sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2203             else
2204                     sgScaleVec3 (up, 4.0*ref_elev);
2205             dummy_tile->ols_transform->setTransform(up);
2206             //cout << "ref_elev  " << ref_elev << endl;
2207         }
2208     // end hack for deck lights
2209
2210     }
2211     if ( ship_sel != NULL ) {
2212         ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2213     }
2214 }
2215
2216 // $$$ end - added VS Renganathan, 15 Oct 2K
2217 //           added Venky         , 12 Nov 2K