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