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