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