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