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