]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
7c7b798be2bb2d1b58fd9c595fd55c49e60fa857
[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 #ifdef FG_MATH_EXCEPTION_CLASH
29 #  include <math.h>
30 #endif
31
32 #ifdef HAVE_WINDOWS_H
33 #  include <windows.h>                     
34 #  include <float.h>                    
35 #endif
36
37 #include <GL/glut.h>
38 #include <simgear/xgl/xgl.h>
39
40 #include <stdio.h>
41 #include <string.h>
42 #include <string>
43
44 #ifdef HAVE_STDLIB_H
45 #   include <stdlib.h>
46 #endif
47
48 #ifdef HAVE_SYS_STAT_H
49 #  include <sys/stat.h> /* for stat() */
50 #endif
51
52 #ifdef HAVE_UNISTD_H
53 #  include <unistd.h>    /* for stat() */
54 #endif
55
56 #include <plib/pu.h>                    // plib include
57 #include <plib/ssg.h>           // plib include
58
59 #ifdef ENABLE_AUDIO_SUPPORT
60 #  include <plib/sl.h>          // plib include
61 #  include <plib/sm.h>          // plib include
62 #endif
63
64 #include <simgear/constants.h>  // for VERSION
65 #include <simgear/debug/logstream.hxx>
66 #include <simgear/math/polar3d.hxx>
67 #include <simgear/math/fg_random.h>
68 #include <simgear/misc/fgpath.hxx>
69 #include <simgear/sky/sky.hxx>
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/timing/lowleveltime.h>
72
73 #include <Include/general.hxx>
74
75 #include <Aircraft/aircraft.hxx>
76
77 #include <Autopilot/newauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/radiostack.hxx>
80 #include <Cockpit/steam.hxx>
81
82 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
83 #include <GUI/gui.h>
84 #include <Joystick/joystick.hxx>
85 #ifdef FG_NETWORK_OLK
86 #include <NetworkOLK/network.h>
87 #endif
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/tilemgr.hxx>
90 #include <Time/event.hxx>
91 #include <Time/fg_timer.hxx>
92 #include <Time/sunpos.hxx>
93 #include <Time/tmp.hxx>
94
95 // $$$ begin - added VS Renganathan
96 #include <simgear/misc/fgstream.hxx>
97 #include <FDM/flight.hxx>
98 void fgLoadDCS (void);
99 void fgUpdateDCS (void);
100 ssgSelector *ship_sel = NULL;
101 ssgTransform *ship_pos = NULL;
102 //int totalDCSobj = 0;
103 // $$$ end - added VS Renganathan
104
105 #ifndef FG_OLD_WEATHER
106 #  include <WeatherCM/FGLocalWeatherDatabase.h>
107 #else
108 #  include <Weather/weather.hxx>
109 #endif
110
111 #include "version.h"
112
113 #include "bfi.hxx"
114 #include "fg_init.hxx"
115 #include "fg_io.hxx"
116 #include "globals.hxx"
117 #include "keyboard.hxx"
118 #include "splash.hxx"
119
120
121 // -dw- use custom sioux settings so I can see output window
122 #ifdef macintosh
123 #  ifndef FG_NDEBUG
124 #    include <sioux.h> // settings for output window
125 #  endif
126 #  include <console.h>
127 #endif
128
129
130 // This is a record containing a bit of global housekeeping information
131 FGGeneral general;
132
133 // Specify our current idle function state.  This is used to run all
134 // our initializations out of the glutIdleLoop() so that we can get a
135 // splash screen up and running right away.
136 static int idle_state = 0;
137 static int global_multi_loop;
138
139 // attempt to avoid a large bounce at startup
140 static bool initial_freeze = true;
141
142 // Another hack
143 int use_signals = 0;
144
145 // forward declaration
146 void fgReshape( int width, int height );
147
148 // Global structures for the Audio library
149 #ifdef ENABLE_AUDIO_SUPPORT
150 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
151 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
152 slScheduler *audio_sched;
153 smMixer *audio_mixer;
154 slSample *s1;
155 slSample *s2;
156 #endif
157
158
159 // ssg variables
160 ssgRoot *scene = NULL;
161 ssgBranch *terrain = NULL;
162 ssgSelector *penguin_sel = NULL;
163 ssgTransform *penguin_pos = NULL;
164
165 #ifdef FG_NETWORK_OLK
166 ssgSelector *fgd_sel = NULL;
167 ssgTransform *fgd_pos = NULL;
168 //sgMat4 sgTUX;
169 #endif
170
171 // current fdm/position used for view
172 FGInterface cur_view_fdm;
173
174 // Sky structures
175 SGSky *thesky;
176
177 // hack
178 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
179 {
180   {  1.0f,  0.0f,  0.0f,  0.0f },
181   {  0.0f,  0.0f, -1.0f,  0.0f },
182   {  0.0f,  1.0f,  0.0f,  0.0f },
183   {  0.0f,  0.0f,  0.0f,  1.0f }
184 } ;
185
186 // The following defines flightgear options. Because glutlib will also
187 // want to parse its own options, those options must not be included here
188 // or they will get parsed by the main program option parser. Hence case
189 // is significant for any option added that might be in conflict with
190 // glutlib's parser.
191 //
192 // glutlib parses for:
193 //    -display
194 //    -direct   (invalid in Win32)
195 //    -geometry
196 //    -gldebug
197 //    -iconized
198 //    -indirect (invalid in Win32)
199 //    -synce
200 //
201 // Note that glutlib depends upon strings while this program's
202 // option parser wants only initial characters followed by numbers
203 // or pathnames.
204 //
205
206
207 ssgSimpleState *default_state;
208 ssgSimpleState *hud_and_panel;
209 ssgSimpleState *menus;
210
211 void fgBuildRenderStates( void ) {
212     default_state = new ssgSimpleState;
213     default_state->ref();
214     default_state->disable( GL_TEXTURE_2D );
215     default_state->enable( GL_CULL_FACE );
216     default_state->enable( GL_COLOR_MATERIAL );
217     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
218     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
219     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
220     default_state->disable( GL_BLEND );
221     default_state->disable( GL_ALPHA_TEST );
222     default_state->disable( GL_LIGHTING );
223
224     hud_and_panel = new ssgSimpleState;
225     hud_and_panel->ref();
226     hud_and_panel->disable( GL_CULL_FACE );
227     hud_and_panel->disable( GL_TEXTURE_2D );
228     hud_and_panel->disable( GL_LIGHTING );
229     hud_and_panel->enable( GL_BLEND );
230
231     menus = new ssgSimpleState;
232     menus->ref();
233     menus->disable( GL_CULL_FACE );
234     menus->disable( GL_TEXTURE_2D );
235     menus->enable( GL_BLEND );
236 }
237
238
239 // fgInitVisuals() -- Initialize various GL/view parameters
240 void fgInitVisuals( void ) {
241     fgLIGHT *l;
242
243     l = &cur_light_params;
244
245 #ifndef GLUT_WRONG_VERSION
246     // Go full screen if requested ...
247     if ( globals->get_options()->get_fullscreen() ) {
248         glutFullScreen();
249     }
250 #endif
251
252     // If enabled, normal vectors specified with glNormal are scaled
253     // to unit length after transformation.  See glNormal.
254     // glEnable( GL_NORMALIZE );
255
256     glEnable( GL_LIGHTING );
257     glEnable( GL_LIGHT0 );
258     glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
259
260     sgVec3 sunpos;
261     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
262     ssgGetLight( 0 ) -> setPosition( sunpos );
263
264     // glFogi (GL_FOG_MODE, GL_LINEAR);
265     glFogi (GL_FOG_MODE, GL_EXP2);
266     if ( (globals->get_options()->get_fog() == 1) || 
267          (globals->get_options()->get_shading() == 0) ) {
268         // if fastest fog requested, or if flat shading force fastest
269         glHint ( GL_FOG_HINT, GL_FASTEST );
270     } else if ( globals->get_options()->get_fog() == 2 ) {
271         glHint ( GL_FOG_HINT, GL_NICEST );
272     }
273     if ( globals->get_options()->get_wireframe() ) {
274         // draw wire frame
275         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
276     }
277
278     // This is the default anyways, but it can't hurt
279     glFrontFace ( GL_CCW );
280
281     // Just testing ...
282     // glEnable(GL_POINT_SMOOTH);
283     // glEnable(GL_LINE_SMOOTH);
284     // glEnable(GL_POLYGON_SMOOTH);      
285 }
286
287
288 // Update all Visuals (redraws anything graphics related)
289 void fgRenderFrame( void ) {
290     // Update the BFI.
291     FGBFI::update();
292
293     fgLIGHT *l = &cur_light_params;
294     static double last_visibility = -9999;
295
296     // double angle;
297     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
298     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
299     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
300     // GLfloat mat_shininess[] = { 10.0 };
301     GLbitfield clear_mask;
302     
303     if ( idle_state != 1000 ) {
304         // still initializing, draw the splash screen
305         if ( globals->get_options()->get_splash_screen() == 1 ) {
306             fgSplashUpdate(0.0);
307         }
308     } else {
309         // idle_state is now 1000 meaning we've finished all our
310         // initializations and are running the main loop, so this will
311         // now work without seg faulting the system.
312
313         // printf("Ground = %.2f  Altitude = %.2f\n", scenery.cur_elev, 
314         //        FG_Altitude * FEET_TO_METER);
315     
316         // this is just a temporary hack, to make me understand Pui
317         // timerText -> setLabel (ctime (&t->cur_time));
318         // end of hack
319
320         // calculate our current position in cartesian space
321         scenery.center = scenery.next_center;
322         // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
323         //        scenery.center.y(), scenery.center.z());
324
325         globals->get_current_view()->
326             set_geod_view_pos( cur_fdm_state->get_Longitude(), 
327                                cur_fdm_state->get_Lat_geocentric(), 
328                                cur_fdm_state->get_Altitude() *
329                                FEET_TO_METER );
330         globals->get_current_view()->
331             set_sea_level_radius( cur_fdm_state->get_Sea_level_radius() *
332                                   FEET_TO_METER ); 
333         globals->get_current_view()->
334             set_rph( cur_fdm_state->get_Phi(),
335                      cur_fdm_state->get_Theta(),
336                      cur_fdm_state->get_Psi() );
337
338         // update view volume parameters
339         // cout << "before pilot_view update" << endl;
340         if ( globals->get_options()->get_view_mode() ==
341              FGOptions::FG_VIEW_FOLLOW )
342         {
343             float * offset = globals->get_current_view()->get_pilot_offset();
344             globals->get_current_view()->set_pilot_offset( offset[0],
345                                                            offset[1],
346                                                            offset[2] );
347         } else {
348             globals->get_current_view()->set_pilot_offset(0.0, 0.0, 0.0);
349         }
350
351         if ( ! fgPanelVisible() ) {
352             xglViewport( 0, 0 ,
353                          (GLint)(globals->get_options()->get_xsize()),
354                          (GLint)(globals->get_options()->get_ysize()) );
355         } else {
356             int view_h =
357                 int( (current_panel->getViewHeight() -
358                       current_panel->getYOffset())
359                      * (globals->get_options()->get_ysize() / 768.0) );
360             glViewport( 0, 
361                         (GLint)(globals->get_options()->get_ysize() - view_h),
362                         (GLint)(globals->get_options()->get_xsize()),
363                         (GLint)(view_h) );
364         }
365
366         // set the sun position
367         glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
368
369         clear_mask = GL_DEPTH_BUFFER_BIT;
370         if ( globals->get_options()->get_wireframe() ) {
371             clear_mask |= GL_COLOR_BUFFER_BIT;
372         }
373
374         if ( globals->get_options()->get_skyblend() ) {
375             if ( globals->get_options()->get_textures() ) {
376                 // glClearColor(black[0], black[1], black[2], black[3]);
377                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
378                              l->adj_fog_color[2], l->adj_fog_color[3]);
379                 clear_mask |= GL_COLOR_BUFFER_BIT;
380             }
381         } else {
382             glClearColor(l->sky_color[0], l->sky_color[1], 
383                          l->sky_color[2], l->sky_color[3]);
384             clear_mask |= GL_COLOR_BUFFER_BIT;
385         }
386         glClear( clear_mask );
387
388         // Tell GL we are switching to model view parameters
389
390         // I really should create a derived ssg node or use a call
391         // back or something so that I can draw the sky within the
392         // ssgCullAndDraw() function, but for now I just mimic what
393         // ssg does to set up the model view matrix
394         glMatrixMode(GL_MODELVIEW);
395         glLoadIdentity();
396         ssgSetCamera( (sgMat4)globals->get_current_view()->get_VIEW() );
397
398         /*
399         sgMat4 vm_tmp, view_mat;
400         sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
401         sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
402         sgPreMultMat4( view_mat, vm_tmp ) ;
403         glLoadMatrixf( (float *)view_mat );
404         */
405
406         // set the opengl state to known default values
407         default_state->force();
408
409         // update fog params if visibility has changed
410 #ifndef FG_OLD_WEATHER
411         thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
412 #else
413         thesky->set_visibility( current_weather.get_visibility() );
414 #endif
415
416         thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
417                                 
418                             ( global_multi_loop * 
419                               globals->get_options()->get_speed_up() ) /
420                             (double)globals->get_options()->get_model_hz() );
421
422         double actual_visibility = thesky->get_visibility();
423         // cout << "actual visibility = " << actual_visibility << endl;
424
425         if ( actual_visibility != last_visibility ) {
426             last_visibility = actual_visibility;
427
428             // cout << "----> updating fog params" << endl;
429                 
430             GLfloat fog_exp_density;
431             GLfloat fog_exp2_density;
432     
433             // for GL_FOG_EXP
434             fog_exp_density = -log(0.01 / actual_visibility);
435     
436             // for GL_FOG_EXP2
437             fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
438     
439             // Set correct opengl fog density
440             glFogf (GL_FOG_DENSITY, fog_exp2_density);
441         }
442  
443         // update the sky dome
444         if ( globals->get_options()->get_skyblend() ) {
445             sgVec3 zero_elev;
446             sgSetVec3( zero_elev,
447                        globals->get_current_view()->get_cur_zero_elev().x(),
448                        globals->get_current_view()->get_cur_zero_elev().y(),
449                        globals->get_current_view()->get_cur_zero_elev().z() );
450
451             /* cout << "thesky->repaint() sky_color = "
452                  << cur_light_params.sky_color[0] << " "
453                  << cur_light_params.sky_color[1] << " "
454                  << cur_light_params.sky_color[2] << " "
455                  << cur_light_params.sky_color[3] << endl;
456             cout << "    fog = "
457                  << cur_light_params.fog_color[0] << " "
458                  << cur_light_params.fog_color[1] << " "
459                  << cur_light_params.fog_color[2] << " "
460                  << cur_light_params.fog_color[3] << endl;
461             cout << "    sun_angle = " << cur_light_params.sun_angle
462                  << "    moon_angle = " << cur_light_params.moon_angle
463                  << endl; */
464             thesky->repaint( cur_light_params.sky_color,
465                              cur_light_params.adj_fog_color,
466                              cur_light_params.sun_angle,
467                              cur_light_params.moon_angle,
468                              globals->get_ephem()->getNumPlanets(),
469                              globals->get_ephem()->getPlanets(),
470                              globals->get_ephem()->getNumStars(),
471                              globals->get_ephem()->getStars() );
472  
473             /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
474                  << view_pos[1] << " " << view_pos[2] << endl;
475             cout << "    zero_elev = " << zero_elev[0] << " "
476                  << zero_elev[1] << " " << zero_elev[2]
477                  << " lon = " << cur_fdm_state->get_Longitude()
478                  << " lat = " << cur_fdm_state->get_Latitude() << endl;
479             cout << "    sun_rot = " << cur_light_params.sun_rotation
480                  << " gst = " << SGTime::cur_time_params->getGst() << endl;
481             cout << "    sun ra = " << globals->get_ephem()->getSunRightAscension()
482                  << " sun dec = " << globals->get_ephem()->getSunDeclination() 
483                  << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
484                  << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
485
486             thesky->reposition( globals->get_current_view()->get_view_pos(),
487                                 zero_elev,
488                                 globals->get_current_view()->get_local_up(),
489                                 cur_fdm_state->get_Longitude(),
490                                 cur_fdm_state->get_Latitude(),
491                                 cur_fdm_state->get_Altitude() * FEET_TO_METER,
492                                 cur_light_params.sun_rotation,
493                                 globals->get_time_params()->getGst(),
494                                 globals->get_ephem()->getSunRightAscension(),
495                                 globals->get_ephem()->getSunDeclination(),
496                                 50000.0,
497                                 globals->get_ephem()->getMoonRightAscension(),
498                                 globals->get_ephem()->getMoonDeclination(),
499                                 50000.0 );
500         }
501
502         glEnable( GL_DEPTH_TEST );
503         if ( globals->get_options()->get_fog() > 0 ) {
504             glEnable( GL_FOG );
505             glFogi( GL_FOG_MODE, GL_EXP2 );
506             glFogfv( GL_FOG_COLOR, l->adj_fog_color );
507         }
508
509         // set lighting parameters
510         GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
511         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
512         glLightfv( GL_LIGHT0, GL_AMBIENT, black );
513         glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
514         // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
515
516         // texture parameters
517         // glEnable( GL_TEXTURE_2D );
518         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
519         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
520         // set base color (I don't think this is doing anything here)
521         // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
522         //  (GL_FRONT, GL_DIFFUSE, white);
523         // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
524         // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
525
526         sgVec3 sunpos;
527         sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
528         ssgGetLight( 0 ) -> setPosition( sunpos );
529
530         // glMatrixMode( GL_PROJECTION );
531         // glLoadIdentity();
532         float fov = globals->get_options()->get_fov();
533         ssgSetFOV(fov, fov * globals->get_options()->get_win_ratio());
534
535         double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
536             - scenery.cur_elev;
537
538         // FG_LOG( FG_ALL, FG_INFO, "visibility is " 
539         //         << current_weather.get_visibility() );
540             
541         if ( agl > 10.0 ) {
542             ssgSetNearFar( 10.0f, 120000.0f );
543         } else {
544             ssgSetNearFar( 0.5f, 120000.0f );
545         }
546
547         if ( globals->get_options()->get_view_mode() == 
548              FGOptions::FG_VIEW_PILOT )
549         {
550             // disable TuX
551             penguin_sel->select(0);
552         } else if ( globals->get_options()->get_view_mode() == 
553                     FGOptions::FG_VIEW_FOLLOW )
554         {
555             // select view matrix from front of view matrix queue
556             // FGMat4Wrapper tmp = current_view.follow.front();
557             // sgCopyMat4( sgVIEW, tmp.m );
558
559             // enable TuX and set up his position and orientation
560             penguin_sel->select(1);
561
562             sgMat4 sgTRANS;
563             sgMakeTransMat4( sgTRANS, 
564                              globals->get_current_view()->get_view_pos() );
565
566             sgVec3 ownship_up;
567             sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
568
569             sgMat4 sgROT;
570             sgMakeRotMat4( sgROT, -90.0, ownship_up );
571
572             // sgMat4 sgTMP;
573             // sgMat4 sgTUX;
574             // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
575             // sgMultMat4( sgTUX, sgTMP, sgTRANS );
576
577             // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
578             sgMat4 sgTUX;
579             sgCopyMat4( sgTUX, sgROT );
580             sgPostMultMat4( sgTUX, globals->get_current_view()->get_VIEW_ROT() );
581             sgPostMultMat4( sgTUX, sgTRANS );
582         
583             sgCoord tuxpos;
584             sgSetCoord( &tuxpos, sgTUX );
585             penguin_pos->setTransform( &tuxpos );
586         }
587
588         // $$$ begin - added VS Renganthan 17 Oct 2K
589         fgUpdateDCS();
590         // $$$ end - added VS Renganthan 17 Oct 2K
591
592 # ifdef FG_NETWORK_OLK
593         if ( globals->get_options()->get_network_olk() ) {
594             sgCoord fgdpos;
595             other = head->next;             /* put listpointer to start  */
596             while ( other != tail) {        /* display all except myself */
597                 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
598                     other->fgd_sel->select(1);
599                     sgSetCoord( &fgdpos, other->sgFGD_COORD );
600                     other->fgd_pos->setTransform( &fgdpos );
601                 }
602                 other = other->next;
603             }
604
605             // fgd_sel->select(1);
606             // sgCopyMat4( sgTUX, current_view.sgVIEW);
607             // sgCoord fgdpos;
608             // sgSetCoord( &fgdpos, sgFGD_VIEW );
609             // fgd_pos->setTransform( &fgdpos);
610         }
611 # endif
612
613         // ssgSetCamera( current_view.VIEW );
614
615         // position tile nodes and update range selectors
616         global_tile_mgr.prep_ssg_nodes();
617
618         // force the default state so ssg can get back on track if
619         // we've changed things elsewhere (this is now handled
620         // differently)
621         // 
622         // FGMaterialSlot m_slot;
623         // FGMaterialSlot *m_ptr = &m_slot;
624         // if ( material_mgr.find( "Default", m_ptr ) ) {
625         //    m_ptr->get_state()->force();
626         // }
627
628         // draw the sky backdrop
629         thesky->preDraw();
630
631         // draw the ssg scene
632         glEnable( GL_DEPTH_TEST );
633         ssgCullAndDraw( scene );
634
635         // draw the sky cloud layers
636         thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
637
638         // display HUD && Panel
639         glDisable( GL_FOG );
640         glDisable( GL_DEPTH_TEST );
641         // glDisable( GL_CULL_FACE );
642         // glDisable( GL_TEXTURE_2D );
643         hud_and_panel->apply();
644         fgCockpitUpdate();
645
646         // We can do translucent menus, so why not. :-)
647         // glEnable ( GL_BLEND ) ;
648         menus->apply();
649         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
650         puDisplay();
651         // glDisable ( GL_BLEND ) ;
652
653         // glEnable( GL_FOG );
654     }
655
656     glutSwapBuffers();
657 }
658
659
660 // Update internal time dependent calculations (i.e. flight model)
661 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
662     static fdm_state_list fdm_list;
663     fgLIGHT *l = &cur_light_params;
664     int i;
665
666     // update the flight model
667     if ( multi_loop < 0 ) {
668         multi_loop = 1;
669     }
670
671     if ( !globals->get_freeze() && !initial_freeze ) {
672         // run Autopilot system
673         current_autopilot->run();
674
675         // printf("updating flight model x %d\n", multi_loop);
676         /* fgFDMUpdate( globals->get_options()->get_flight_model(), 
677                      fdm_state, 
678                      multi_loop * globals->get_options()->get_speed_up(),
679                      remainder ); */
680         cur_fdm_state->update( multi_loop *
681                                globals->get_options()->get_speed_up() );
682         FGSteam::update( multi_loop * globals->get_options()->get_speed_up() );
683     } else {
684         // fgFDMUpdate( globals->get_options()->get_flight_model(), 
685         //              fdm_state, 0, remainder );
686         cur_fdm_state->update( 0 );
687         FGSteam::update( 0 );
688
689         if ( global_tile_mgr.queue_size() == 0 ) {
690             initial_freeze = false;
691         }
692     }
693
694     fdm_list.push_back( *cur_fdm_state );
695     while ( fdm_list.size() > 15 ) {
696         fdm_list.pop_front();
697     }
698
699     if ( globals->get_options()->get_view_mode() == FGOptions::FG_VIEW_PILOT ) {
700         cur_view_fdm = *cur_fdm_state;
701         // do nothing
702     } else if ( globals->get_options()->get_view_mode()
703                 == FGOptions::FG_VIEW_FOLLOW )
704     {
705         cur_view_fdm = fdm_list.front();
706     }
707
708     // update the view angle
709     for ( i = 0; i < multi_loop; i++ ) {
710         if ( fabs(globals->get_current_view()->get_goal_view_offset() - 
711                   globals->get_current_view()->get_view_offset()) < 0.05 )
712         {
713             globals->get_current_view()->set_view_offset( globals->get_current_view()->get_goal_view_offset() );
714             break;
715         } else {
716             // move current_view.view_offset towards
717             // current_view.goal_view_offset
718             if ( globals->get_current_view()->get_goal_view_offset() > 
719                  globals->get_current_view()->get_view_offset() )
720             {
721                 if ( globals->get_current_view()->get_goal_view_offset() - 
722                      globals->get_current_view()->get_view_offset() < FG_PI )
723                 {
724                     globals->get_current_view()->inc_view_offset( 0.01 );
725                 } else {
726                     globals->get_current_view()->inc_view_offset( -0.01 );
727                 }
728             } else {
729                 if ( globals->get_current_view()->get_view_offset() - 
730                      globals->get_current_view()->get_goal_view_offset() <
731                      FG_PI )
732                 {
733                     globals->get_current_view()->inc_view_offset( -0.01 );
734                 } else {
735                     globals->get_current_view()->inc_view_offset( 0.01 );
736                 }
737             }
738             if ( globals->get_current_view()->get_view_offset() > FG_2PI ) {
739                 globals->get_current_view()->inc_view_offset( -FG_2PI );
740             } else if ( globals->get_current_view()->get_view_offset() < 0 ) {
741                 globals->get_current_view()->inc_view_offset( FG_2PI );
742             }
743         }
744     }
745
746     double tmp = -(l->sun_rotation + FG_PI) 
747         - (cur_fdm_state->get_Psi() -
748            globals->get_current_view()->get_view_offset() );
749     while ( tmp < 0.0 ) {
750         tmp += FG_2PI;
751     }
752     while ( tmp > FG_2PI ) {
753         tmp -= FG_2PI;
754     }
755     /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
756            FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG, 
757            -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
758     l->UpdateAdjFog();
759
760     // Update solar system
761     globals->get_ephem()->update( globals->get_time_params()->getMjd(),
762                                   globals->get_time_params()->getLst(),
763                                   cur_fdm_state->get_Latitude() );
764
765     // Update radio stack model
766     current_radiostack->update( cur_fdm_state->get_Longitude(),
767                                 cur_fdm_state->get_Latitude(),
768                                 cur_fdm_state->get_Altitude() * FEET_TO_METER );
769 }
770
771
772 void fgInitTimeDepCalcs( void ) {
773     // initialize timer
774
775     // #ifdef HAVE_SETITIMER
776     //   fgTimerInit( 1.0 / globals->get_options()->get_model_hz(), 
777     //                fgUpdateTimeDepCalcs );
778     // #endif HAVE_SETITIMER
779 }
780
781
782 static const double alt_adjust_ft = 3.758099;
783 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
784
785
786 // What should we do when we have nothing else to do?  Let's get ready
787 // for the next move and update the display?
788 static void fgMainLoop( void ) {
789     static long remainder = 0;
790     long elapsed;
791 #ifdef FANCY_FRAME_COUNTER
792     int i;
793     double accum;
794 #else
795     static time_t last_time = 0;
796     static int frames = 0;
797 #endif // FANCY_FRAME_COUNTER
798
799     SGTime *t = globals->get_time_params();
800
801     FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
802     FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
803
804 #ifdef FG_NETWORK_OLK
805     if ( globals->get_options()->get_network_olk() ) {
806         if ( net_is_registered == 0 ) {      // We first have to reg. to fgd
807             // printf("FGD: Netupdate\n");
808             fgd_send_com( "A", FGFS_host);   // Send Mat4 data
809             fgd_send_com( "B", FGFS_host);   // Recv Mat4 data
810         }
811     }
812 #endif
813
814 #if defined( ENABLE_PLIB_JOYSTICK )
815     // Read joystick and update control settings
816     if ( globals->get_options()->get_control_mode() == FGOptions::FG_JOYSTICK )
817     {
818         fgJoystickRead();
819     }
820 #elif defined( ENABLE_GLUT_JOYSTICK )
821     // Glut joystick support works by feeding a joystick handler
822     // function to glut.  This is taken care of once in the joystick
823     // init routine and we don't have to worry about it again.
824 #endif
825
826 #ifdef FG_OLD_WEATHER
827     current_weather.Update();
828 #endif
829
830     // Fix elevation.  I'm just sticking this here for now, it should
831     // probably move eventually
832
833     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
834            scenery.cur_elev,
835            cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
836            cur_fdm_state->get_Altitude() * FEET_TO_METER); */
837
838     if ( scenery.cur_elev > -9990 ) {
839         if ( cur_fdm_state->get_Altitude() * FEET_TO_METER < 
840              (scenery.cur_elev + alt_adjust_m - 3.0) ) {
841             // now set aircraft altitude above ground
842             printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n", 
843                    cur_fdm_state->get_Altitude() * FEET_TO_METER,
844                    scenery.cur_elev + alt_adjust_m - 3.0,
845                    scenery.cur_elev + alt_adjust_m );
846             fgFDMForceAltitude( globals->get_options()->get_flight_model(), 
847                                 scenery.cur_elev + alt_adjust_m );
848
849             FG_LOG( FG_ALL, FG_DEBUG, 
850                     "<*> resetting altitude to " 
851                     << cur_fdm_state->get_Altitude() * FEET_TO_METER
852                     << " meters" );
853         }
854         //fgFDMSetGroundElevation( globals->get_options()->get_flight_model(),
855         //                       scenery.cur_elev );  // meters
856     }
857
858     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
859            scenery.cur_elev,
860            cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
861            cur_fdm_state->get_Altitude() * FEET_TO_METER); */
862
863     // update "time"
864     if ( globals->get_warp_delta() != 0 ) {
865         globals->inc_warp( globals->get_warp_delta() );
866     }
867
868     t->update( cur_fdm_state->get_Longitude(),
869                cur_fdm_state->get_Latitude(),
870                globals->get_warp() );
871
872     if ( globals->get_warp_delta() != 0 ) {
873         fgUpdateSkyAndLightingParams();
874     }
875
876     // update magvar model
877     globals->get_mag()->update( cur_fdm_state->get_Longitude(),
878                                 cur_fdm_state->get_Latitude(),
879                                 cur_fdm_state->get_Altitude()* FEET_TO_METER,
880                                 globals->get_time_params()->getJD() );
881
882     // Get elapsed time (in usec) for this past frame
883     elapsed = fgGetTimeInterval();
884     FG_LOG( FG_ALL, FG_DEBUG, 
885             "Elapsed time interval is = " << elapsed 
886             << ", previous remainder is = " << remainder );
887
888     // Calculate frame rate average
889 #ifdef FANCY_FRAME_COUNTER
890     /* old fps calculation */
891     if ( elapsed > 0 ) {
892         double tmp;
893         accum = 0.0;
894         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
895             tmp = general.get_frame(i);
896             accum += tmp;
897             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
898             general.set_frame(i+1,tmp);
899         }
900         tmp = 1000000.0 / (float)elapsed;
901         general.set_frame(0,tmp);
902         // printf("frame[0] = %.2f\n", general.frames[0]);
903         accum += tmp;
904         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
905         // printf("ave = %.2f\n", general.frame_rate);
906     }
907 #else
908     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
909         general.set_frame_rate( frames );
910         FG_LOG( FG_ALL, FG_DEBUG, 
911                 "--> Frame rate is = " << general.get_frame_rate() );
912         frames = 0;
913     }
914     last_time = t->get_cur_time();
915     ++frames;
916 #endif
917
918     // Run flight model
919     if ( ! use_signals ) {
920         // Calculate model iterations needed for next frame
921         elapsed += remainder;
922
923         global_multi_loop = (int)(((double)elapsed * 0.000001) * 
924                            globals->get_options()->get_model_hz());
925         remainder = elapsed - ( (global_multi_loop*1000000) / 
926                                 globals->get_options()->get_model_hz() );
927         FG_LOG( FG_ALL, FG_DEBUG, 
928                 "Model iterations needed = " << global_multi_loop
929                 << ", new remainder = " << remainder );
930         
931         // flight model
932         if ( global_multi_loop > 0 ) {
933             fgUpdateTimeDepCalcs(global_multi_loop, remainder);
934         } else {
935             FG_LOG( FG_ALL, FG_DEBUG, 
936                     "Elapsed time is zero ... we're zinging" );
937         }
938     }
939
940 #if ! defined( macintosh )
941     // Do any I/O channel work that might need to be done
942     fgIOProcess();
943 #endif
944
945     // see if we need to load any new scenery tiles
946     global_tile_mgr.update( cur_fdm_state->get_Longitude() * RAD_TO_DEG,
947                             cur_fdm_state->get_Latitude() * RAD_TO_DEG );
948
949     // Process/manage pending events
950     global_events.Process();
951
952     // Run audio scheduler
953 #ifdef ENABLE_AUDIO_SUPPORT
954     if ( globals->get_options()->get_sound() && !audio_sched->not_working() ) {
955
956         if ( globals->get_options()->get_aircraft() == "c172" ) {
957             // pitch corresponds to rpm
958             // volume corresponds to manifold pressure
959
960             double rpm_factor;
961             if ( cur_fdm_state->get_engine(0) != NULL ) {
962                 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
963             } else {
964                 rpm_factor = 1.0;
965             }
966             // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
967             //      << endl;
968
969             double pitch = 0.3 + rpm_factor * 3.0;
970         
971             // don't run at absurdly slow rates -- not realistic
972             // and sounds bad to boot.  :-)
973             if (pitch < 0.7) { pitch = 0.7; }
974             if (pitch > 5.0) { pitch = 5.0; }
975             // cout << "pitch = " << pitch << endl;
976
977             double mp_factor;
978             if ( cur_fdm_state->get_engine(0) != NULL ) {
979                 mp_factor = 
980                     cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 28;
981             } else {
982                 mp_factor = 1.0;
983             }
984             // cout << "mp = " 
985             //      << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
986             //      << endl;
987
988             double volume = mp_factor;
989
990             if ( volume < 0.3 ) { volume = 0.3; }
991             if ( volume > 2.0 ) { volume = 2.0; }
992             // cout << "volume = " << volume << endl;
993
994             pitch_envelope.setStep  ( 0, 0.01, pitch );
995             volume_envelope.setStep ( 0, 0.01, volume );
996         } else {
997             double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
998             pitch_envelope.setStep  ( 0, 0.01, param );
999             volume_envelope.setStep ( 0, 0.01, param );
1000         }
1001
1002         audio_sched -> update();
1003     }
1004 #endif
1005
1006     // redraw display
1007     fgRenderFrame();
1008
1009     FG_LOG( FG_ALL, FG_DEBUG, "" );
1010 }
1011
1012
1013 // This is the top level master main function that is registered as
1014 // our idle funciton
1015 //
1016
1017 // The first few passes take care of initialization things (a couple
1018 // per pass) and once everything has been initialized fgMainLoop from
1019 // then on.
1020
1021 static void fgIdleFunction ( void ) {
1022     // printf("idle state == %d\n", idle_state);
1023
1024     if ( idle_state == 0 ) {
1025         // Initialize the splash screen right away
1026         if ( globals->get_options()->get_splash_screen() ) {
1027             fgSplashInit();
1028         }
1029         
1030         idle_state++;
1031     } else if ( idle_state == 1 ) {
1032         // Start the intro music
1033 #if !defined(WIN32)
1034         if ( globals->get_options()->get_intro_music() ) {
1035             string lockfile = "/tmp/mpg123.running";
1036             FGPath mp3file( globals->get_options()->get_fg_root() );
1037             mp3file.append( "Sounds/intro.mp3" );
1038
1039             string command = "(touch " + lockfile + "; mpg123 "
1040                 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1041                 + lockfile + ") &";
1042             FG_LOG( FG_GENERAL, FG_INFO, 
1043                     "Starting intro music: " << mp3file.str() );
1044             system ( command.c_str() );
1045         }
1046 #endif
1047
1048         idle_state++;
1049     } else if ( idle_state == 2 ) {
1050         // These are a few miscellaneous things that aren't really
1051         // "subsystems" but still need to be initialized.
1052
1053 #ifdef USE_GLIDE
1054         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1055             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1056         }
1057 #endif
1058
1059         idle_state++;
1060     } else if ( idle_state == 3 ) {
1061         // This is the top level init routine which calls all the
1062         // other subsystem initialization routines.  If you are adding
1063         // a subsystem to flightgear, its initialization call should
1064         // located in this routine.
1065         if( !fgInitSubsystems()) {
1066             FG_LOG( FG_GENERAL, FG_ALERT,
1067                     "Subsystem initializations failed ..." );
1068             exit(-1);
1069         }
1070
1071         idle_state++;
1072     } else if ( idle_state == 4 ) {
1073         // setup OpenGL view parameters
1074         fgInitVisuals();
1075
1076         if ( use_signals ) {
1077             // init timer routines, signals, etc.  Arrange for an alarm
1078             // signal to be generated, etc.
1079             fgInitTimeDepCalcs();
1080         }
1081
1082         idle_state++;
1083     } else if ( idle_state == 5 ) {
1084
1085         idle_state++;
1086     } else if ( idle_state == 6 ) {
1087         // Initialize audio support
1088 #ifdef ENABLE_AUDIO_SUPPORT
1089
1090 #if !defined(WIN32)
1091         if ( globals->get_options()->get_intro_music() ) {
1092             // Let's wait for mpg123 to finish
1093             string lockfile = "/tmp/mpg123.running";
1094             struct stat stat_buf;
1095
1096             FG_LOG( FG_GENERAL, FG_INFO, 
1097                     "Waiting for mpg123 player to finish ..." );
1098             while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1099                 // file exist, wait ...
1100                 sleep(1);
1101                 FG_LOG( FG_GENERAL, FG_INFO, ".");
1102             }
1103             FG_LOG( FG_GENERAL, FG_INFO, "");
1104         }
1105 #endif // WIN32
1106
1107         if ( globals->get_options()->get_sound() ) {
1108             audio_sched = new slScheduler ( 8000 );
1109             audio_mixer = new smMixer;
1110             audio_mixer -> setMasterVolume ( 80 ) ;  /* 80% of max volume. */
1111             audio_sched -> setSafetyMargin ( 1.0 ) ;
1112
1113             FGPath slfile( globals->get_options()->get_fg_root() );
1114             slfile.append( "Sounds/wasp.wav" );
1115
1116             s1 = new slSample ( (char *)slfile.c_str() );
1117             FG_LOG( FG_GENERAL, FG_INFO,
1118                     "Rate = " << s1 -> getRate()
1119                     << "  Bps = " << s1 -> getBps()
1120                     << "  Stereo = " << s1 -> getStereo() );
1121             audio_sched -> loopSample ( s1 );
1122
1123             if ( audio_sched->not_working() ) {
1124                 // skip
1125             } else {
1126                 pitch_envelope.setStep  ( 0, 0.01, 0.6 );
1127                 volume_envelope.setStep ( 0, 0.01, 0.6 );
1128
1129                 audio_sched -> addSampleEnvelope( s1, 0, 0, 
1130                                                   &pitch_envelope,
1131                                                   SL_PITCH_ENVELOPE );
1132                 audio_sched -> addSampleEnvelope( s1, 0, 1, 
1133                                                   &volume_envelope,
1134                                                   SL_VOLUME_ENVELOPE );
1135             }
1136
1137             // strcpy(slfile, path);
1138             // strcat(slfile, "thunder.wav");
1139             // s2 -> loadFile ( slfile );
1140             // s2 -> adjustVolume(0.5);
1141             // audio_sched -> playSample ( s2 );
1142         }
1143 #endif
1144
1145         // sleep(1);
1146         idle_state = 1000;
1147
1148         cout << "Panel visible = " << fgPanelVisible() << endl;
1149         fgReshape( globals->get_options()->get_xsize(),
1150                    globals->get_options()->get_ysize() );
1151     } 
1152
1153     if ( idle_state == 1000 ) {
1154         // We've finished all our initialization steps, from now on we
1155         // run the main loop.
1156
1157         fgMainLoop();
1158     } else {
1159         if ( globals->get_options()->get_splash_screen() == 1 ) {
1160             fgSplashUpdate(0.0);
1161         }
1162     }
1163 }
1164
1165 // options.cxx needs to see this for toggle_panel()
1166 // Handle new window size or exposure
1167 void fgReshape( int width, int height ) {
1168     if ( ! fgPanelVisible() || idle_state != 1000 ) {
1169         globals->get_options()->set_win_ratio( (float)height /
1170                                                (float)width );
1171         glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1172     } else {
1173         int view_h =
1174           int((current_panel->getViewHeight() - current_panel->getYOffset())
1175               * (height / 768.0)) + 1;
1176         globals->get_options()->set_win_ratio( (float)view_h /
1177                                                (float)width );
1178         glViewport(0, (GLint)(height - view_h),
1179                    (GLint)(width), (GLint)(view_h) );
1180     }
1181
1182     globals->get_options()->set_xsize( width );
1183     globals->get_options()->set_ysize( height );
1184
1185     float fov = globals->get_options()->get_fov();
1186     ssgSetFOV(fov, fov * globals->get_options()->get_win_ratio());
1187
1188     fgHUDReshape();
1189
1190     if ( idle_state == 1000 ) {
1191         // yes we've finished all our initializations and are running
1192         // the main loop, so this will now work without seg faulting
1193         // the system.
1194         // globals->get_current_view()->UpdateViewParams();
1195     }
1196 }
1197
1198
1199 // Initialize GLUT and define a main window
1200 int fgGlutInit( int *argc, char **argv ) {
1201
1202 #if !defined( macintosh )
1203     // GLUT will extract all glut specific options so later on we only
1204     // need wory about our own.
1205     glutInit(argc, argv);
1206 #endif
1207
1208     // Define Display Parameters
1209     glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1210
1211     FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1212             globals->get_options()->get_xsize() << "x"
1213             << globals->get_options()->get_ysize() );
1214
1215     // Define initial window size
1216     glutInitWindowSize( globals->get_options()->get_xsize(),
1217                          globals->get_options()->get_ysize() );
1218
1219     // Initialize windows
1220     if ( globals->get_options()->get_game_mode() == 0 ) {
1221         // Open the regular window
1222         glutCreateWindow("FlightGear");
1223 #ifndef GLUT_WRONG_VERSION
1224     } else {
1225         // Open the cool new 'game mode' window
1226         char game_mode_str[256];
1227         sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1228                  globals->get_options()->get_xsize(),
1229                  globals->get_options()->get_ysize(),
1230                  globals->get_options()->get_bpp());
1231
1232         FG_LOG( FG_GENERAL, FG_INFO, 
1233                 "game mode params = " << game_mode_str );
1234         glutGameModeString( game_mode_str );
1235         glutEnterGameMode();
1236 #endif
1237     }
1238
1239     // This seems to be the absolute earliest in the init sequence
1240     // that these calls will return valid info.  Too bad it's after
1241     // we've already created and sized out window. :-(
1242     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1243     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1244     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1245     int tmp;
1246     glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1247     general.set_glMaxTexSize( tmp );
1248     FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1249     FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1250
1251 #if 0
1252     // try to determine if we should adjust the initial default
1253     // display resolution.  The options class defaults (is
1254     // initialized) to 640x480.
1255     string renderer = general.glRenderer;
1256
1257     // currently we only know how to deal with Mesa/Glide/Voodoo cards
1258     if ( renderer.find( "Glide" ) != string::npos ) {
1259         FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1260         if ( renderer.find( "FB/8" ) != string::npos ) {
1261             // probably a voodoo-2
1262             if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1263                 // probably two SLI'd Voodoo-2's
1264                 globals->get_options()->set_xsize( 1024 );
1265                 globals->get_options()->set_ysize( 768 );
1266                 FG_LOG( FG_GENERAL, FG_INFO,
1267                         "It looks like you have two sli'd voodoo-2's." << endl
1268                         << "upgrading your win resolution to 1024 x 768" );
1269                 glutReshapeWindow(1024, 768);
1270             } else {
1271                 // probably a single non-SLI'd Voodoo-2
1272                 globals->get_options()->set_xsize( 800 );
1273                 globals->get_options()->set_ysize( 600 );
1274                 FG_LOG( FG_GENERAL, FG_INFO,
1275                         "It looks like you have a voodoo-2." << endl
1276                         << "upgrading your win resolution to 800 x 600" );
1277                 glutReshapeWindow(800, 600);
1278             }
1279         } else if ( renderer.find( "FB/2" ) != string::npos ) {
1280             // probably a voodoo-1, stick with the default
1281         }
1282     } else {
1283         // we have no special knowledge of this card, stick with the default
1284     }
1285 #endif
1286
1287     return(1);
1288 }
1289
1290
1291 // Initialize GLUT event handlers
1292 int fgGlutInitEvents( void ) {
1293     // call fgReshape() on window resizes
1294     glutReshapeFunc( fgReshape );
1295
1296     // call GLUTkey() on keyboard event
1297     glutKeyboardFunc( GLUTkey );
1298     glutSpecialFunc( GLUTspecialkey );
1299
1300     // call guiMouseFunc() whenever our little rodent is used
1301     glutMouseFunc ( guiMouseFunc );
1302     glutMotionFunc (guiMotionFunc );
1303     glutPassiveMotionFunc (guiMotionFunc );
1304
1305     // call fgMainLoop() whenever there is
1306     // nothing else to do
1307     glutIdleFunc( fgIdleFunction );
1308
1309     // draw the scene
1310     glutDisplayFunc( fgRenderFrame );
1311
1312     return(1);
1313 }
1314
1315
1316 // Main ...
1317 int main( int argc, char **argv ) {
1318
1319 #if defined( macintosh )
1320     freopen ("stdout.txt", "w", stdout );
1321     freopen ("stderr.txt", "w", stderr );
1322     argc = ccommand( &argv );
1323 #endif
1324
1325 #ifdef HAVE_BC5PLUS
1326     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1327 #endif
1328
1329     // set default log levels
1330     fglog().setLogLevels( FG_ALL, FG_INFO );
1331
1332     FG_LOG( FG_GENERAL, FG_INFO, "FlightGear:  Version "
1333             << FLIGHTGEAR_VERSION << endl );
1334
1335     // seed the random number generater
1336     fg_srandom();
1337
1338     // Allocate global data structures.  This needs to happen before
1339     // we parse command line options
1340     globals = new FGGlobals;
1341
1342     SGRoute *route = new SGRoute;
1343     globals->set_route( route );
1344
1345     FGOptions *options = new FGOptions;
1346     globals->set_options( options );
1347
1348     FGViewer *pv = new FGViewer;
1349     globals->set_current_view( pv );
1350     // FGViewer *cv = new FGViewer;
1351     // globals->set_current_view( cv );
1352     
1353     // Scan the config file(s) and command line options to see if
1354     // fg_root was specified (ignore all other options for now)
1355     fgInitFGRoot(argc, argv);
1356
1357     // cout << "1. airport_id = " << globals->get_options()->get_airport_id() << endl;
1358
1359     // Read global preferences from $FG_ROOT/preferences.xml
1360     FGPath props_path(globals->get_options()->get_fg_root());
1361     props_path.append("preferences.xml");
1362     FG_LOG(FG_INPUT, FG_INFO, "Reading global preferences");
1363     if (!readPropertyList(props_path.str(), &current_properties)) {
1364       FG_LOG(FG_INPUT, FG_ALERT, "Failed to read global preferences from "
1365              << props_path.str());
1366     } else {
1367       FG_LOG(FG_INPUT, FG_INFO, "Finished Reading global preferences");
1368     }
1369
1370     // cout << "2. airport_id = " << globals->get_options()->get_airport_id() << endl;
1371
1372     // Initialize the Aircraft directory to "" (UIUC)
1373     aircraft_dir = "";
1374
1375     // Load the configuration parameters
1376     if ( !fgInitConfig(argc, argv) ) {
1377         FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1378         exit(-1);
1379     }
1380
1381     // Initialize the Window/Graphics environment.
1382     if( !fgGlutInit(&argc, argv) ) {
1383         FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1384         exit(-1);
1385     }
1386
1387     // Initialize the various GLUT Event Handlers.
1388     if( !fgGlutInitEvents() ) {
1389         FG_LOG( FG_GENERAL, FG_ALERT, 
1390                 "GLUT event handler initialization failed ..." );
1391         exit(-1);
1392     }
1393  
1394     // Initialize ssg (from plib).  Needs to come before we do any
1395     // other ssg stuff, but after opengl/glut has been initialized.
1396     ssgInit();
1397
1398     // Initialize the user interface (we need to do this before
1399     // passing off control to glut and before fgInitGeneral to get our
1400     // fonts !!!
1401     guiInit();
1402
1403     // set current_options lon/lat if an airport id is specified
1404     // cout << "3. airport_id = " << globals->get_options()->get_airport_id() << endl;
1405     if ( globals->get_options()->get_airport_id().length() ) {
1406         // fgSetPosFromAirportID( globals->get_options()->get_airport_id() );
1407         fgSetPosFromAirportIDandHdg( globals->get_options()->get_airport_id(),
1408                                      globals->get_options()->get_heading() );
1409     }
1410
1411     // Initialize time
1412     FGPath zone( globals->get_options()->get_fg_root() );
1413     zone.append( "Timezone" );
1414     SGTime *t = new SGTime( globals->get_options()->get_lon() * DEG_TO_RAD,
1415                             globals->get_options()->get_lat() * DEG_TO_RAD,
1416                             zone.str() );
1417
1418     // Handle potential user specified time offsets
1419     time_t cur_time = t->get_cur_time();
1420     time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1421     time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1422     time_t aircraftLocalTime = 
1423         sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1424
1425     // Okay, we now have six possible scenarios
1426     switch ( globals->get_options()->get_time_offset_type() ) {
1427     case FGOptions::FG_TIME_SYS_OFFSET:
1428         globals->set_warp( globals->get_options()->get_time_offset() );
1429         break;
1430     case FGOptions::FG_TIME_GMT_OFFSET:
1431         globals->set_warp( globals->get_options()->get_time_offset() - 
1432                            (currGMT - systemLocalTime) );
1433         break;
1434     case FGOptions::FG_TIME_LAT_OFFSET:
1435         globals->set_warp( globals->get_options()->get_time_offset() - 
1436                            (aircraftLocalTime - systemLocalTime) );
1437         break;
1438     case FGOptions::FG_TIME_SYS_ABSOLUTE:
1439         globals->set_warp( globals->get_options()->get_time_offset() -
1440                            cur_time );
1441         //printf("warp = %d\n", warp); 
1442         break;
1443     case FGOptions::FG_TIME_GMT_ABSOLUTE:
1444         globals->set_warp( globals->get_options()->get_time_offset() -
1445                            currGMT );
1446         break;
1447     case FGOptions::FG_TIME_LAT_ABSOLUTE:
1448         globals->set_warp( globals->get_options()->get_time_offset() - 
1449                            (aircraftLocalTime - systemLocalTime) - 
1450                            cur_time ); 
1451         break;
1452     default:
1453         FG_LOG( FG_GENERAL, FG_ALERT, "Unsupported type" );
1454         exit( -1 );
1455     }
1456
1457     FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = " 
1458             << globals->get_warp() );
1459
1460     globals->set_warp_delta( 0 );
1461
1462     t->update( 0.0, 0.0, globals->get_warp() );
1463
1464     globals->set_time_params( t );
1465
1466     // Do some quick general initializations
1467     if( !fgInitGeneral()) {
1468         FG_LOG( FG_GENERAL, FG_ALERT, 
1469                 "General initializations failed ..." );
1470         exit(-1);
1471     }
1472
1473     //
1474     // some ssg test stuff (requires data from the plib source
1475     // distribution) specifically from the ssg tux example
1476     //
1477
1478     FGPath modelpath( globals->get_options()->get_fg_root() );
1479     // modelpath.append( "Models" );
1480     // modelpath.append( "Geometry" );
1481   
1482     FGPath texturepath( globals->get_options()->get_fg_root() );
1483     texturepath.append( "Models" );
1484     texturepath.append( "Textures" );
1485   
1486     ssgModelPath( (char *)modelpath.c_str() );
1487     ssgTexturePath( (char *)texturepath.c_str() );
1488
1489     // Scene graph root
1490     scene = new ssgRoot;
1491     scene->setName( "Scene" );
1492
1493     // Initialize the sky
1494     FGPath ephem_data_path( globals->get_options()->get_fg_root() );
1495     ephem_data_path.append( "Astro" );
1496     SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1497     ephem->update( globals->get_time_params()->getMjd(),
1498                    globals->get_time_params()->getLst(),
1499                    0.0 );
1500     globals->set_ephem( ephem );
1501
1502     FGPath sky_tex_path( globals->get_options()->get_fg_root() );
1503     sky_tex_path.append( "Textures" );
1504     sky_tex_path.append( "Sky" );
1505     thesky = new SGSky;
1506     thesky->texture_path( sky_tex_path.str() );
1507
1508     thesky->build( 550.0, 550.0,
1509                    globals->get_ephem()->getNumPlanets(), 
1510                    globals->get_ephem()->getPlanets(), 60000.0,
1511                    globals->get_ephem()->getNumStars(),
1512                    globals->get_ephem()->getStars(), 60000.0 );
1513
1514     if ( globals->get_options()->get_clouds() == true ) {
1515         thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1516                                  SG_CLOUD_MOSTLY_SUNNY );
1517         thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1518                                  SG_CLOUD_CIRRUS );
1519         // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1520         //                          SG_CLOUD_MOSTLY_SUNNY );
1521         // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1522         // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1523     }
1524
1525     // Initialize MagVar model
1526     SGMagVar *magvar = new SGMagVar();
1527     globals->set_mag( magvar );
1528
1529     // Terrain branch
1530     terrain = new ssgBranch;
1531     terrain->setName( "Terrain" );
1532     scene->addKid( terrain );
1533
1534     // temporary visible aircraft "own ship"
1535     penguin_sel = new ssgSelector;
1536     penguin_pos = new ssgTransform;
1537     string tux_path =
1538       current_properties.getStringValue("/sim/model/path",
1539                                         "Models/Geometry/glider.ac");
1540     ssgEntity *tux_obj = ssgLoad((char *)(tux_path.c_str()));
1541
1542     // align the model properly for FGFS
1543     ssgTransform *tux_align = new ssgTransform;
1544     tux_align->addKid(tux_obj);
1545     sgMat4 tux_matrix;
1546     float h_rot =
1547       current_properties.getFloatValue("/sim/model/h-rotation", 0.0);
1548     float p_rot =
1549       current_properties.getFloatValue("/sim/model/p-rotation", 0.0);
1550     float r_rot =
1551       current_properties.getFloatValue("/sim/model/r-rotation", 0.0);
1552     sgMakeRotMat4(tux_matrix, h_rot, h_rot, r_rot);
1553     tux_align->setTransform(tux_matrix);
1554
1555     penguin_pos->addKid( tux_align );
1556     penguin_sel->addKid( penguin_pos );
1557     ssgFlatten( tux_obj );
1558     ssgStripify( penguin_sel );
1559     penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1560     scene->addKid( penguin_sel );
1561
1562     // $$$ begin - added VS Renganthan 17 Oct 2K
1563     fgLoadDCS();
1564     // $$$ end - added VS Renganthan 17 Oct 2K
1565
1566 #ifdef FG_NETWORK_OLK
1567     // Do the network intialization
1568     if ( globals->get_options()->get_network_olk() ) {
1569         printf("Multipilot mode %s\n", fg_net_init( scene ) );
1570     }
1571 #endif
1572
1573     // build our custom render states
1574     fgBuildRenderStates();
1575
1576     // pass control off to the master GLUT event handler
1577     glutMainLoop();
1578
1579     // we never actually get here ... but to avoid compiler warnings,
1580     // etc.
1581     return 0;
1582 }
1583
1584
1585 // $$$ end - added VS Renganathan, 15 Oct 2K
1586 void fgLoadDCS(void) {
1587
1588     string obj_filename;
1589
1590     FGPath tile_path( globals->get_options()->get_fg_root());
1591     tile_path.append( "Scenery" );
1592     tile_path.append( "Objects.txt" );
1593     fg_gzifstream in( tile_path.str() );
1594     if ( ! in.is_open() ) {
1595         FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1596     }
1597
1598     FGPath modelpath( globals->get_options()->get_fg_root() );
1599     modelpath.append( "Models" );
1600     modelpath.append( "Geometry" );
1601   
1602     FGPath texturepath( globals->get_options()->get_fg_root() );
1603     texturepath.append( "Models" );
1604     texturepath.append( "Textures" );
1605  
1606     ssgModelPath( (char *)modelpath.c_str() );
1607     ssgTexturePath( (char *)texturepath.c_str() );
1608
1609     // while ( ! in.eof() ) {
1610     //     in >> obj_filename >> obj_lat >> obj_lon >> obj_alt;
1611     //     totalDCSobj = totalDCSobj+1;
1612
1613     ship_sel = new ssgSelector;
1614     ship_pos = new ssgTransform;
1615     ssgEntity *ship_obj = ssgLoadOBJ( "saratoga.obj" );
1616     if ( ship_obj != NULL ) {
1617         ship_pos->addKid( ship_obj ); // add object to transform node
1618         ship_sel->addKid( ship_pos ); // add transform node to selector
1619         // ssgFlatten( ship_obj );
1620         // ssgStripify( ship_sel );
1621         ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1622         scene->addKid( ship_sel ); //add selector node to root node
1623     } else {
1624         FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << "saratoga.obj" );
1625     }
1626
1627     //     if (in.eof()) break;
1628
1629     // } // while
1630     return;
1631 }
1632
1633
1634 void fgUpdateDCS (void) {
1635
1636     // double eye_lat,eye_lon,eye_alt;
1637     static double obj_lat=15.377603*DEG_TO_RAD;
1638     static double obj_lon= 73.816436*DEG_TO_RAD;
1639     static double obj_alt=0.15;
1640     // static double obj_head;
1641     double sl_radius,obj_latgc;
1642     // float nresultmat[4][4];
1643     double bz[3];
1644
1645     obj_lat = obj_lat + 0.0000001;
1646
1647     // Instantaneous Geodetic Lat/Lon/Alt of moving object
1648     //    obj_lon = current_aircraft.fdm_state->get_aux5()*DEG_TO_RAD;
1649     //    obj_lat = current_aircraft.fdm_state->get_aux6()*DEG_TO_RAD;
1650     //    obj_alt = current_aircraft.fdm_state->get_aux7();
1651           
1652     // Geodetic to Geocentric angles for rotation
1653     sgGeodToGeoc(obj_lat,obj_alt,&sl_radius,&obj_latgc);
1654
1655     // moving object gbs-posn in cartesian coords
1656     Point3D obj_posn = Point3D( obj_lon,obj_lat,obj_alt);
1657     Point3D obj_pos = sgGeodToCart( obj_posn );
1658
1659     // Translate moving object w.r.t eye
1660     Point3D Objtrans = obj_pos-scenery.center;
1661     bz[0]=Objtrans.x();
1662     bz[1]=Objtrans.y();
1663     bz[2]=Objtrans.z();
1664
1665     // rotate dynamic objects for lat,lon & alt and other motion about its axes
1666     if ( ship_sel != NULL ) {
1667         ship_sel->select(1);
1668         
1669         sgMat4 sgTRANS;
1670         sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1671
1672         sgVec3 ship_fwd,ship_rt,ship_up;
1673         sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1674         sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1675         sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1676
1677         sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1678         sgMakeRotMat4( sgROT_lon, obj_lon*RAD_TO_DEG, ship_up );
1679         sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1680         sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1681         
1682         sgMat4 sgTUX;
1683         sgCopyMat4( sgTUX, sgROT_hdg );
1684         sgPostMultMat4( sgTUX, sgROT_lat );
1685         sgPostMultMat4( sgTUX, sgROT_lon );
1686         sgPostMultMat4( sgTUX, sgTRANS );
1687
1688         sgCoord shippos;
1689         sgSetCoord( &shippos, sgTUX );
1690         ship_pos->setTransform( &shippos );
1691     }
1692 }
1693
1694 // $$$ end - added VS Renganathan, 15 Oct 2K