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