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