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