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