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