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