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