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