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