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