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