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