]> git.mxchange.org Git - flightgear.git/blob - Main/GLUTmain.cxx
187ad17c76279ecf6259bdb854d2490c2697f06c
[flightgear.git] / Main / GLUTmain.cxx
1 // GLUTmain.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson for OpenGL, started May 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@me.umn.edu
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 // (Log is kept at end of this file)
23
24 #define MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
25
26 #ifdef HAVE_CONFIG_H
27 #  include <config.h>
28 #endif
29
30 #ifdef HAVE_WINDOWS_H
31 #  include <windows.h>                     
32 #  include <float.h>                    
33 #endif
34
35 #include <GL/glut.h>
36 #include <XGL/xgl.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <string>
40
41 #ifdef HAVE_STDLIB_H
42 #   include <stdlib.h>
43 #endif
44
45 #ifdef HAVE_SYS_STAT_H
46 #  include <sys/stat.h> /* for stat() */
47 #endif
48
49 #ifdef HAVE_UNISTD_H
50 #  include <unistd.h>    /* for stat() */
51 #endif
52
53 #include <Include/fg_constants.h>  // for VERSION
54 #include <Include/general.hxx>
55
56 #include <Aircraft/aircraft.hxx>
57 #include <Astro/sky.hxx>
58 #include <Astro/stars.hxx>
59 #include <Astro/solarsystem.hxx>
60
61 #ifdef ENABLE_AUDIO_SUPPORT
62 #  include <Audio/src/sl.h>
63 #  include <Audio/src/sm.h>
64 #endif
65
66 #include <Autopilot/autopilot.hxx>
67 #include <Cockpit/cockpit.hxx>
68 #include <Debug/logstream.hxx>
69 #include <GUI/gui.h>
70 #include <Joystick/joystick.hxx>
71 #include <Math/fg_geodesy.hxx>
72 #include <Math/mat3.h>
73 #include <Math/polar3d.hxx>
74 #include <PUI/pu.h>
75 #include <Scenery/scenery.hxx>
76 #include <Scenery/tilemgr.hxx>
77 #include <Time/event.hxx>
78 #include <Time/fg_time.hxx>
79 #include <Time/fg_timer.hxx>
80 #include <Time/sunpos.hxx>
81 #include <Weather/weather.hxx>
82
83 #include "GLUTkey.hxx"
84 #include "fg_init.hxx"
85 #include "options.hxx"
86 #include "splash.hxx"
87 #include "views.hxx"
88 #include "fg_serial.hxx"
89
90
91 // This is a record containing a bit of global housekeeping information
92 FGGeneral general;
93
94 // Specify our current idle function state.  This is used to run all
95 // our initializations out of the glutIdleLoop() so that we can get a
96 // splash screen up and running right away.
97 static int idle_state = 0;
98
99 // Another hack
100 int use_signals = 0;
101
102 // Yet another hack, this time for the panel
103 int panel_hist = 0;
104
105 // Global structures for the Audio library
106 #ifdef ENABLE_AUDIO_SUPPORT
107 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
108 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
109 slScheduler *audio_sched;
110 smMixer *audio_mixer;
111 slSample *s1;
112 slSample *s2;
113 #endif
114
115
116 // The following defines flight gear options. Because glutlib will also
117 // want to parse its own options, those options must not be included here
118 // or they will get parsed by the main program option parser. Hence case
119 // is significant for any option added that might be in conflict with
120 // glutlib's parser.
121 //
122 // glutlib parses for:
123 //    -display
124 //    -direct   (invalid in Win32)
125 //    -geometry
126 //    -gldebug
127 //    -iconized
128 //    -indirect (invalid in Win32)
129 //    -synce
130 //
131 // Note that glutlib depends upon strings while this program's
132 // option parser wants only initial characters followed by numbers
133 // or pathnames.
134 //
135
136
137 // fgInitVisuals() -- Initialize various GL/view parameters
138 static void fgInitVisuals( void ) {
139     fgLIGHT *l;
140
141     l = &cur_light_params;
142
143     // Go full screen if requested ...
144     if ( current_options.get_fullscreen() ) {
145         glutFullScreen();
146     }
147
148     // If enabled, normal vectors specified with glNormal are scaled
149     // to unit length after transformation.  See glNormal.
150     // xglEnable( GL_NORMALIZE );
151
152     xglEnable( GL_LIGHTING );
153     xglEnable( GL_LIGHT0 );
154     xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
155
156     // xglFogi (GL_FOG_MODE, GL_LINEAR);
157     xglFogi (GL_FOG_MODE, GL_EXP2);
158     // Fog density is now set when the weather system is initialized
159     // xglFogf (GL_FOG_DENSITY, w->fog_density);
160     if ( (current_options.get_fog() == 1) || 
161          (current_options.get_shading() == 0) ) {
162         // if fastest fog requested, or if flat shading force fastest
163         xglHint ( GL_FOG_HINT, GL_FASTEST );
164     } else if ( current_options.get_fog() == 2 ) {
165         xglHint ( GL_FOG_HINT, GL_NICEST );
166     }
167     if ( current_options.get_wireframe() ) {
168         // draw wire frame
169         xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
170     }
171
172     // This is the default anyways, but it can't hurt
173     xglFrontFace ( GL_CCW );
174
175     // Just testing ...
176     // xglEnable(GL_POINT_SMOOTH);
177     // xglEnable(GL_LINE_SMOOTH);
178     // xglEnable(GL_POLYGON_SMOOTH);      
179 }
180
181
182 #if 0
183 // Draw a basic instrument panel
184 static void fgUpdateInstrViewParams( void ) {
185
186     exit(0);
187
188     fgVIEW *v = &current_view;
189
190     xglViewport(0, 0 , (GLint)(v->winWidth), (GLint)(v->winHeight) / 2);
191   
192     xglMatrixMode(GL_PROJECTION);
193     xglPushMatrix();
194   
195     xglLoadIdentity();
196     gluOrtho2D(0, 640, 0, 480);
197     xglMatrixMode(GL_MODELVIEW);
198     xglPushMatrix();
199     xglLoadIdentity();
200
201     xglColor3f(1.0, 1.0, 1.0);
202     xglIndexi(7);
203   
204     xglDisable(GL_DEPTH_TEST);
205     xglDisable(GL_LIGHTING);
206   
207     xglLineWidth(1);
208     xglColor3f (0.5, 0.5, 0.5);
209
210     xglBegin(GL_QUADS);
211     xglVertex2f(0.0, 0.00);
212     xglVertex2f(0.0, 480.0);
213     xglVertex2f(640.0,480.0);
214     xglVertex2f(640.0, 0.0);
215     xglEnd();
216
217     xglRectf(0.0,0.0, 640, 480);
218     xglEnable(GL_DEPTH_TEST);
219     xglEnable(GL_LIGHTING);
220     xglMatrixMode(GL_PROJECTION);
221     xglPopMatrix();
222     xglMatrixMode(GL_MODELVIEW);
223     xglPopMatrix();
224 }
225 #endif
226
227
228 // Update all Visuals (redraws anything graphics related)
229 static void fgRenderFrame( void ) {
230     fgLIGHT *l = &cur_light_params;
231     fgTIME *t = &cur_time_params;
232     FGView *v = &current_view;
233
234     double angle;
235     static int iteration = 0;
236     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
237     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
238     GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
239     GLbitfield clear_mask;
240
241     if ( idle_state != 1000 ) {
242         // still initializing, draw the splash screen
243         if ( current_options.get_splash_screen() == 1 ) {
244             fgSplashUpdate(0.0);
245         }
246     } else {
247         // idle_state is now 1000 meaning we've finished all our
248         // initializations and are running the main loop, so this will
249         // now work without seg faulting the system.
250
251         // printf("Ground = %.2f  Altitude = %.2f\n", scenery.cur_elev, 
252         //        FG_Altitude * FEET_TO_METER);
253     
254         // this is just a temporary hack, to make me understand Pui
255         // timerText -> setLabel (ctime (&t->cur_time));
256         // end of hack
257
258         // update view volume parameters
259         v->UpdateViewParams();
260
261         // set the sun position
262         xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
263
264         clear_mask = GL_DEPTH_BUFFER_BIT;
265         if ( current_options.get_wireframe() ) {
266             clear_mask |= GL_COLOR_BUFFER_BIT;
267         }
268         if ( current_options.get_panel_status() ) {
269             // we can't clear the screen when the panel is active
270         } else if ( current_options.get_skyblend() ) {
271             if ( current_options.get_textures() ) {
272                 // glClearColor(black[0], black[1], black[2], black[3]);
273                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
274                              l->adj_fog_color[2], l->adj_fog_color[3]);
275                 clear_mask |= GL_COLOR_BUFFER_BIT;              
276             }
277         } else {
278             glClearColor(l->sky_color[0], l->sky_color[1], 
279                          l->sky_color[2], l->sky_color[3]);
280             clear_mask |= GL_COLOR_BUFFER_BIT;
281         }
282         xglClear( clear_mask );
283
284         // Tell GL we are switching to model view parameters
285         xglMatrixMode(GL_MODELVIEW);
286         // xglLoadIdentity();
287
288         // draw sky
289         xglDisable( GL_DEPTH_TEST );
290         xglDisable( GL_LIGHTING );
291         xglDisable( GL_CULL_FACE );
292         xglDisable( GL_FOG );
293         xglShadeModel( GL_SMOOTH );
294         if ( current_options.get_skyblend() ) {
295             fgSkyRender();
296         }
297
298         // setup transformation for drawing astronomical objects
299         xglPushMatrix();
300         // Translate to view position
301         Point3D view_pos = v->get_view_pos();
302         xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
303         // Rotate based on gst (sidereal time)
304         // note: constant should be 15.041085, Curt thought it was 15
305         angle = t->gst * 15.041085;
306         // printf("Rotating astro objects by %.2f degrees\n",angle);
307         xglRotatef( angle, 0.0, 0.0, -1.0 );
308
309         // draw stars and planets
310         fgStarsRender();
311         SolarSystem::theSolarSystem->draw();
312
313         xglPopMatrix();
314
315         // draw scenery
316         if ( current_options.get_shading() ) {
317             xglShadeModel( GL_SMOOTH ); 
318         } else {
319             xglShadeModel( GL_FLAT ); 
320         }
321         xglEnable( GL_DEPTH_TEST );
322         if ( current_options.get_fog() > 0 ) {
323             xglEnable( GL_FOG );
324             xglFogfv (GL_FOG_COLOR, l->adj_fog_color);
325         }
326         // set lighting parameters
327         xglLightfv(GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
328         xglLightfv(GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
329         
330         if ( current_options.get_textures() ) {
331             // texture parameters
332             xglEnable( GL_TEXTURE_2D );
333             xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
334             xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
335             // set base color (I don't think this is doing anything here)
336             xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
337             xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
338         } else {
339             xglDisable( GL_TEXTURE_2D );
340             xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
341             xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
342             // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
343             // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
344         }
345
346         fgTileMgrRender();
347
348         xglDisable( GL_TEXTURE_2D );
349         xglDisable( GL_FOG );
350
351         if ( (iteration == 0) && (current_options.get_panel_status()) ) {   
352             // Did we run this loop before ?? ...and do we need the panel ??
353             fgPanelReInit(0, 0, 1024, 768);
354         }
355
356         // display HUD && Panel
357         fgCockpitUpdate();
358         iteration = 1; // don't ReInit the panel in the future
359
360         // We can do translucent menus, so why not. :-)
361         xglEnable    ( GL_BLEND ) ;
362         xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
363         puDisplay();
364         xglDisable   ( GL_BLEND ) ;
365         xglEnable( GL_FOG );
366     }
367
368     xglutSwapBuffers();
369 }
370
371
372 // Update internal time dependent calculations (i.e. flight model)
373 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
374     FGState *f = current_aircraft.fdm_state;
375     fgLIGHT *l = &cur_light_params;
376     fgTIME *t = &cur_time_params;
377     FGView *v = &current_view;
378     int i;
379
380     // update the flight model
381     if ( multi_loop < 0 ) {
382         multi_loop = DEFAULT_MULTILOOP;
383     }
384
385     if ( !t->pause ) {
386         // run Autopilot system
387         fgAPRun();
388
389         // printf("updating flight model x %d\n", multi_loop);
390         fgFDMUpdate( current_options.get_flight_model(), 
391                              cur_fdm_state, multi_loop, remainder );
392     } else {
393         fgFDMUpdate( current_options.get_flight_model(), 
394                              cur_fdm_state, 0, remainder );
395     }
396
397     // update the view angle
398     for ( i = 0; i < multi_loop; i++ ) {
399         if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
400             v->set_view_offset( v->get_goal_view_offset() );
401             break;
402         } else {
403             // move v->view_offset towards v->goal_view_offset
404             if ( v->get_goal_view_offset() > v->get_view_offset() ) {
405                 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
406                     v->inc_view_offset( 0.01 );
407                 } else {
408                     v->inc_view_offset( -0.01 );
409                 }
410             } else {
411                 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
412                     v->inc_view_offset( -0.01 );
413                 } else {
414                     v->inc_view_offset( 0.01 );
415                 }
416             }
417             if ( v->get_view_offset() > FG_2PI ) {
418                 v->inc_view_offset( -FG_2PI );
419             } else if ( v->get_view_offset() < 0 ) {
420                 v->inc_view_offset( FG_2PI );
421             }
422         }
423     }
424
425     double tmp = -(l->sun_rotation + FG_PI) 
426         - (f->get_Psi() - v->get_view_offset() );
427     while ( tmp < 0.0 ) {
428         tmp += FG_2PI;
429     }
430     while ( tmp > FG_2PI ) {
431         tmp -= FG_2PI;
432     }
433     /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
434            FG_Psi * RAD_TO_DEG, v->view_offset * RAD_TO_DEG, 
435            -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
436     l->UpdateAdjFog();
437 }
438
439
440 void fgInitTimeDepCalcs( void ) {
441     // initialize timer
442
443     // #ifdef HAVE_SETITIMER
444     //   fgTimerInit( 1.0 / DEFAULT_TIMER_HZ, fgUpdateTimeDepCalcs );
445     // #endif HAVE_SETITIMER
446 }
447
448 static const double alt_adjust_ft = 3.758099;
449 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
450
451 // What should we do when we have nothing else to do?  Let's get ready
452 // for the next move and update the display?
453 static void fgMainLoop( void ) {
454     FGState *f;
455     fgTIME *t;
456     static long remainder = 0;
457     long elapsed, multi_loop;
458     // int i;
459     // double accum;
460     static time_t last_time = 0;
461     static int frames = 0;
462
463     f = current_aircraft.fdm_state;
464     t = &cur_time_params;
465
466     FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
467     FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
468
469 #if defined( ENABLE_LINUX_JOYSTICK )
470     // Read joystick and update control settings
471     fgJoystickRead();
472 #elif defined( ENABLE_GLUT_JOYSTICK )
473     // Glut joystick support works by feeding a joystick handler
474     // function to glut.  This is taken care of once in the joystick
475     // init routine and we don't have to worry about it again.
476 #endif
477
478     current_weather.Update();
479
480     // Fix elevation.  I'm just sticking this here for now, it should
481     // probably move eventually
482
483     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
484            scenery.cur_elev,
485            f->get_Runway_altitude() * FEET_TO_METER,
486            f->get_Altitude() * FEET_TO_METER); */
487
488     if ( scenery.cur_elev > -9990 ) {
489         if ( f->get_Altitude() * FEET_TO_METER < 
490              (scenery.cur_elev + alt_adjust_m - 3.0) ) {
491             // now set aircraft altitude above ground
492             printf("Current Altitude = %.2f < %.2f forcing to %.2f\n", 
493                    f->get_Altitude() * FEET_TO_METER,
494                    scenery.cur_elev + alt_adjust_m - 3.0,
495                    scenery.cur_elev + alt_adjust_m );
496             fgFDMForceAltitude( current_options.get_flight_model(), 
497                                 scenery.cur_elev + alt_adjust_m );
498
499             FG_LOG( FG_ALL, FG_DEBUG, 
500                     "<*> resetting altitude to " 
501                     << f->get_Altitude() * FEET_TO_METER << " meters" );
502         }
503         fgFDMSetGroundElevation( current_options.get_flight_model(),
504                                  scenery.cur_elev );  // meters
505     }
506
507     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
508            scenery.cur_elev,
509            f->get_Runway_altitude() * FEET_TO_METER,
510            f->get_Altitude() * FEET_TO_METER); */
511
512     // update "time"
513     fgTimeUpdate(f, t);
514
515     // Get elapsed time (in usec) for this past frame
516     elapsed = fgGetTimeInterval();
517     FG_LOG( FG_ALL, FG_DEBUG, 
518             "Elapsed time interval is = " << elapsed 
519             << ", previous remainder is = " << remainder );
520
521     // Calculate frame rate average
522     if ( (t->cur_time != last_time) && (last_time > 0) ) {
523         general.set_frame_rate( frames );
524         FG_LOG( FG_ALL, FG_DEBUG, 
525                 "--> Frame rate is = " << general.get_frame_rate() );
526         frames = 0;
527     }
528     last_time = t->cur_time;
529     ++frames;
530
531     /* old fps calculation
532     if ( elapsed > 0 ) {
533         accum = 0.0;
534         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
535             accum += g->frames[i];
536             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
537             g->frames[i+1] = g->frames[i];
538         }
539         g->frames[0] = 1000.0 / (float)elapsed;
540         // printf("frame[0] = %.2f\n", g->frames[0]);
541         accum += g->frames[0];
542         g->frame_rate = accum / (float)FG_FRAME_RATE_HISTORY;
543         // printf("ave = %.2f\n", g->frame_rate);
544     }
545     */
546
547     // Run flight model
548     if ( ! use_signals ) {
549         // Calculate model iterations needed for next frame
550         elapsed += remainder;
551
552         multi_loop = (int)(((double)elapsed * 0.000001) * DEFAULT_MODEL_HZ);
553         remainder = elapsed - ((multi_loop*1000000) / DEFAULT_MODEL_HZ);
554         FG_LOG( FG_ALL, FG_DEBUG, 
555                 "Model iterations needed = " << multi_loop
556                 << ", new remainder = " << remainder );
557         
558         // flight model
559         if ( multi_loop > 0 ) {
560             fgUpdateTimeDepCalcs(multi_loop, remainder);
561         } else {
562             FG_LOG( FG_ALL, FG_INFO, "Elapsed time is zero ... we're zinging" );
563         }
564     }
565
566     // Do any serial port work that might need to be done
567     fgSerialProcess();
568
569     // see if we need to load any new scenery tiles
570     fgTileMgrUpdate();
571
572     // Process/manage pending events
573     global_events.Process();
574
575     // Run audio scheduler
576 #ifdef ENABLE_AUDIO_SUPPORT
577     if ( current_options.get_sound() && audio_sched->working() ) {
578
579 #   ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
580
581         // note: all these factors are relative to the sample.  our
582         // sample format should really contain a conversion factor so
583         // that we can get prop speed right for arbitrary samples.
584         // Note that for normal-size props, there is a point at which
585         // the prop tips approach the speed of sound; that is a pretty
586         // strong limit to how fast the prop can go.
587
588         // multiplication factor is prime pitch control; add some log
589         // component for verisimilitude
590
591         double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
592         //fprintf(stderr, "pitch1: %f ", pitch);
593         if (controls.get_throttle(0) > 0.0 || f->v_rel_wind > 40.0) {
594             //fprintf(stderr, "rel_wind: %f ", f->v_rel_wind);
595             // only add relative wind and AoA if prop is moving
596             // or we're really flying at idle throttle
597             if (pitch < 5.4) {  // this needs tuning
598                 // prop tips not breaking sound barrier
599                 pitch += log(f->v_rel_wind + 0.8)/2;
600             } else {
601                 // prop tips breaking sound barrier
602                 pitch += log(f->v_rel_wind + 0.8)/10;
603             }
604             //fprintf(stderr, "pitch2: %f ", pitch);
605             //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
606
607             // Angle of Attack next... -x^3(e^x) is my best guess Just
608             // need to calculate some reasonable scaling factor and
609             // then clamp it on the positive aoa (neg adj) side
610             double aoa = f->get_Gamma_vert_rad() * 2.2;
611             double tmp = 3.0;
612             double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
613             if (aoa_adj < -0.8) aoa_adj = -0.8;
614             pitch += aoa_adj;
615             //fprintf(stderr, "pitch3: %f ", pitch);
616
617             // don't run at absurdly slow rates -- not realistic
618             // and sounds bad to boot.  :-)
619             if (pitch < 0.8) pitch = 0.8;
620         }
621         //fprintf(stderr, "pitch4: %f\n", pitch);
622
623         double volume = controls.get_throttle(0) * 1.15 + 0.3 +
624             log(f->v_rel_wind + 1.0)/14.0;
625         // fprintf(stderr, "volume: %f\n", volume);
626
627         pitch_envelope.setStep  ( 0, 0.01, pitch );
628         volume_envelope.setStep ( 0, 0.01, volume );
629
630 #   else
631
632        double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
633        pitch_envelope.setStep  ( 0, 0.01, param );
634        volume_envelope.setStep ( 0, 0.01, param );
635
636 #   endif // experimental throttle patch
637
638         audio_sched -> update();
639     }
640 #endif
641
642     // redraw display
643     fgRenderFrame();
644
645     FG_LOG( FG_ALL, FG_DEBUG, "" );
646 }
647
648
649 // This is the top level master main function that is registered as
650 // our idle funciton
651 //
652
653 // The first few passes take care of initialization things (a couple
654 // per pass) and once everything has been initialized fgMainLoop from
655 // then on.
656
657 static void fgIdleFunction ( void ) {
658     // printf("idle state == %d\n", idle_state);
659
660     if ( idle_state == 0 ) {
661         // Initialize the splash screen right away
662         if ( current_options.get_splash_screen() ) {
663             fgSplashInit();
664         }
665         
666         idle_state++;
667     } else if ( idle_state == 1 ) {
668         // Start the intro music
669 #if !defined(WIN32)
670         if ( current_options.get_intro_music() ) {
671             string lockfile = "/tmp/mpg123.running";
672             string mp3file = current_options.get_fg_root() +
673                 "/Sounds/intro.mp3";
674             string command = "(touch " + lockfile + "; mpg123 " + mp3file +
675                  "> /dev/null 2>&1; /bin/rm " + lockfile + ") &";
676             FG_LOG( FG_GENERAL, FG_INFO, 
677                     "Starting intro music: " << mp3file );
678             system ( command.c_str() );
679         }
680 #endif
681
682         idle_state++;
683     } else if ( idle_state == 2 ) {
684         // These are a few miscellaneous things that aren't really
685         // "subsystems" but still need to be initialized.
686
687 #ifdef USE_GLIDE
688         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
689             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
690         }
691 #endif
692
693         idle_state++;
694     } else if ( idle_state == 3 ) {
695         // This is the top level init routine which calls all the
696         // other subsystem initialization routines.  If you are adding
697         // a subsystem to flight gear, its initialization call should
698         // located in this routine.
699         if( !fgInitSubsystems()) {
700             FG_LOG( FG_GENERAL, FG_ALERT,
701                     "Subsystem initializations failed ..." );
702             exit(-1);
703         }
704
705         idle_state++;
706     } else if ( idle_state == 4 ) {
707         // setup OpenGL view parameters
708         fgInitVisuals();
709
710         if ( use_signals ) {
711             // init timer routines, signals, etc.  Arrange for an alarm
712             // signal to be generated, etc.
713             fgInitTimeDepCalcs();
714         }
715
716         idle_state++;
717     } else if ( idle_state == 5 ) {
718
719         idle_state++;
720     } else if ( idle_state == 6 ) {
721         // Initialize audio support
722 #ifdef ENABLE_AUDIO_SUPPORT
723
724 #if !defined(WIN32)
725         if ( current_options.get_intro_music() ) {
726             // Let's wait for mpg123 to finish
727             string lockfile = "/tmp/mpg123.running";
728             struct stat stat_buf;
729
730             FG_LOG( FG_GENERAL, FG_INFO, 
731                     "Waiting for mpg123 player to finish ..." );
732             while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
733                 // file exist, wait ...
734                 sleep(1);
735                 FG_LOG( FG_GENERAL, FG_INFO, ".");
736             }
737             FG_LOG( FG_GENERAL, FG_INFO, "");
738         }
739 #endif // WIN32
740
741         audio_sched = new slScheduler ( 8000 );
742         audio_mixer = new smMixer;
743         audio_mixer -> setMasterVolume ( 80 ) ;  /* 80% of max volume. */
744         audio_sched -> setSafetyMargin ( 1.0 ) ;
745         string slfile = current_options.get_fg_root() + "/Sounds/wasp.wav";
746
747         s1 = new slSample ( (char *)slfile.c_str() );
748         FG_LOG( FG_GENERAL, FG_INFO,
749                 "Rate = " << s1 -> getRate()
750                 << "  Bps = " << s1 -> getBps()
751                 << "  Stereo = " << s1 -> getStereo() );
752         audio_sched -> loopSample ( s1 );
753
754         if ( audio_sched->working() ) {
755             pitch_envelope.setStep  ( 0, 0.01, 0.6 );
756             volume_envelope.setStep ( 0, 0.01, 0.6 );
757
758             audio_sched -> addSampleEnvelope( s1, 0, 0, &
759                                               pitch_envelope,
760                                               SL_PITCH_ENVELOPE );
761             audio_sched -> addSampleEnvelope( s1, 0, 1, 
762                                               &volume_envelope,
763                                               SL_VOLUME_ENVELOPE );
764         }
765
766         // strcpy(slfile, path);
767         // strcat(slfile, "thunder.wav");
768         // s2 -> loadFile ( slfile );
769         // s2 -> adjustVolume(0.5);
770         // audio_sched -> playSample ( s2 );
771 #endif
772
773         // sleep(1);
774         idle_state = 1000;
775     } 
776
777     if ( idle_state == 1000 ) {
778         // We've finished all our initialization steps, from now on we
779         // run the main loop.
780
781         fgMainLoop();
782     } else {
783         if ( current_options.get_splash_screen() == 1 ) {
784             fgSplashUpdate(0.0);
785         }
786     }
787 }
788
789
790 // Handle new window size or exposure
791 static void fgReshape( int width, int height ) {
792     // Do this so we can call fgReshape(0,0) ourselves without having
793     // to know what the values of width & height are.
794     if ( (height > 0) && (width > 0) ) {
795         if ( ! current_options.get_panel_status() ) {
796             current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
797         } else {
798             current_view.set_win_ratio( (GLfloat) width / 
799                                         ((GLfloat) (height)*0.4232) );
800         }
801     }
802
803     current_view.set_winWidth( width );
804     current_view.set_winHeight( height );
805     current_view.force_update_fov_math();
806
807     // Inform gl of our view window size (now handled elsewhere)
808     // xglViewport(0, 0, (GLint)width, (GLint)height);
809     if ( idle_state == 1000 ) {
810         // yes we've finished all our initializations and are running
811         // the main loop, so this will now work without seg faulting
812         // the system.
813         current_view.UpdateViewParams();
814         if ( current_options.get_panel_status() ) {
815             fgPanelReInit(0, 0, 1024, 768);
816         }
817     }
818 }
819
820
821 // Initialize GLUT and define a main window
822 int fgGlutInit( int *argc, char **argv ) {
823     // GLUT will extract all glut specific options so later on we only
824     // need wory about our own.
825     xglutInit(argc, argv);
826
827     // Define Display Parameters
828     xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
829
830     FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
831             current_options.get_xsize() << "x" << current_options.get_ysize() );
832
833     // Define initial window size
834     xglutInitWindowSize( current_options.get_xsize(),
835                          current_options.get_ysize() );
836
837     // Initialize windows
838     if ( current_options.get_game_mode() == 0 ) {
839         // Open the regular window
840         xglutCreateWindow("Flight Gear");
841     } else {
842         // Open the cool new 'game mode' window
843         char game_mode_str[256];
844         sprintf( game_mode_str, "width=%d height=%d bpp=16",
845                  current_options.get_xsize(),
846                  current_options.get_ysize() );
847
848         FG_LOG( FG_GENERAL, FG_INFO, 
849                 "game mode params = " << game_mode_str );
850         glutGameModeString( game_mode_str );
851         glutEnterGameMode();
852     }
853
854     // This seems to be the absolute earliest in the init sequence
855     // that these calls will return valid info.  Too bad it's after
856     // we've already created and sized out window. :-(
857     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
858     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
859     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
860
861     FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
862
863 #if 0
864     // try to determine if we should adjust the initial default
865     // display resolution.  The options class defaults (is
866     // initialized) to 640x480.
867     string renderer = general.glRenderer;
868
869     // currently we only know how to deal with Mesa/Glide/Voodoo cards
870     if ( renderer.find( "Glide" ) != string::npos ) {
871         FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
872         if ( renderer.find( "FB/8" ) != string::npos ) {
873             // probably a voodoo-2
874             if ( renderer.find( "TMU/SLI" ) != string::npos ) {
875                 // probably two SLI'd Voodoo-2's
876                 current_options.set_xsize( 1024 );
877                 current_options.set_ysize( 768 );
878                 FG_LOG( FG_GENERAL, FG_INFO,
879                         "It looks like you have two sli'd voodoo-2's." << endl
880                         << "upgrading your win resolution to 1024 x 768" );
881                 glutReshapeWindow(1024, 768);
882             } else {
883                 // probably a single non-SLI'd Voodoo-2
884                 current_options.set_xsize( 800 );
885                 current_options.set_ysize( 600 );
886                 FG_LOG( FG_GENERAL, FG_INFO,
887                         "It looks like you have a voodoo-2." << endl
888                         << "upgrading your win resolution to 800 x 600" );
889                 glutReshapeWindow(800, 600);
890             }
891         } else if ( renderer.find( "FB/2" ) != string::npos ) {
892             // probably a voodoo-1, stick with the default
893         }
894     } else {
895         // we have no special knowledge of this card, stick with the default
896     }
897 #endif
898
899     return(1);
900 }
901
902
903 // Initialize GLUT event handlers
904 int fgGlutInitEvents( void ) {
905     // call fgReshape() on window resizes
906     xglutReshapeFunc( fgReshape );
907
908     // call GLUTkey() on keyboard event
909     xglutKeyboardFunc( GLUTkey );
910     glutSpecialFunc( GLUTspecialkey );
911
912     // call guiMouseFunc() whenever our little rodent is used
913     glutMouseFunc ( guiMouseFunc );
914     glutMotionFunc (guiMotionFunc );
915     glutPassiveMotionFunc (guiMotionFunc );
916
917     // call fgMainLoop() whenever there is
918     // nothing else to do
919     xglutIdleFunc( fgIdleFunction );
920
921     // draw the scene
922     xglutDisplayFunc( fgRenderFrame );
923
924     return(1);
925 }
926
927
928 // Main ...
929 int main( int argc, char **argv ) {
930     FGState *f;
931
932     f = current_aircraft.fdm_state;
933
934 #ifdef HAVE_BC5PLUS
935     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
936 #endif
937
938     // Initialize the [old] debugging output system
939     // fgInitDebug();
940
941     // set default log levels
942     fglog().setLogLevels( FG_ALL, FG_INFO );
943
944     FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear:  Version " << VERSION << endl );
945
946     string root;
947
948     FG_LOG( FG_GENERAL, FG_INFO, "General Initialization" );
949     FG_LOG( FG_GENERAL, FG_INFO, "======= ==============" );
950
951     // Attempt to locate and parse a config file
952     // First check fg_root
953     string config = current_options.get_fg_root() + "/system.fgfsrc";
954     current_options.parse_config_file( config );
955
956     // Next check home directory
957     char* envp = ::getenv( "HOME" );
958     if ( envp != NULL ) {
959         config = envp;
960         config += "/.fgfsrc";
961         current_options.parse_config_file( config );
962     }
963
964     // Parse remaining command line options
965     // These will override anything specified in a config file
966     if ( current_options.parse_command_line(argc, argv) !=
967                                       fgOPTIONS::FG_OPTIONS_OK )
968     {
969         // Something must have gone horribly wrong with the command
970         // line parsing or maybe the user just requested help ... :-)
971         current_options.usage();
972         FG_LOG( FG_GENERAL, FG_ALERT, "\nExiting ...");
973         // cout << endl << "Exiting ..." << endl;
974         exit(-1);
975     }
976     
977     // Initialize the Window/Graphics environment.
978     if( !fgGlutInit(&argc, argv) ) {
979         FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
980         exit(-1);
981     }
982
983     // Initialize the various GLUT Event Handlers.
984     if( !fgGlutInitEvents() ) {
985         FG_LOG( FG_GENERAL, FG_ALERT, 
986                 "GLUT event handler initialization failed ..." );
987         exit(-1);
988     }
989
990     // First do some quick general initializations
991     if( !fgInitGeneral()) {
992         FG_LOG( FG_GENERAL, FG_ALERT, 
993                 "General initializations failed ..." );
994         exit(-1);
995     }
996
997     // Init the user interface (we need to do this before passing off
998     // control to glut
999     guiInit();
1000
1001     // pass control off to the master GLUT event handler
1002     glutMainLoop();
1003
1004     // we never actually get here ... but just in case ... :-)
1005     return(0);
1006 }
1007
1008
1009 // $Log$
1010 // Revision 1.84  1999/02/02 20:13:34  curt
1011 // MSVC++ portability changes by Bernie Bright:
1012 //
1013 // Lib/Serial/serial.[ch]xx: Initial Windows support - incomplete.
1014 // Simulator/Astro/stars.cxx: typo? included <stdio> instead of <cstdio>
1015 // Simulator/Cockpit/hud.cxx: Added Standard headers
1016 // Simulator/Cockpit/panel.cxx: Redefinition of default parameter
1017 // Simulator/Flight/flight.cxx: Replaced cout with FG_LOG.  Deleted <stdio.h>
1018 // Simulator/Main/fg_init.cxx:
1019 // Simulator/Main/GLUTmain.cxx:
1020 // Simulator/Main/options.hxx: Shuffled <fg_serial.hxx> dependency
1021 // Simulator/Objects/material.hxx:
1022 // Simulator/Time/timestamp.hxx: VC++ friend kludge
1023 // Simulator/Scenery/tile.[ch]xx: Fixed using std::X declarations
1024 // Simulator/Main/views.hxx: Added a constant
1025 //
1026 // Revision 1.83  1999/01/27 04:49:17  curt
1027 // Game mode fixes from Norman Vine.
1028 // Initial altitude setting tweaks and fixes (especially for when starting
1029 // below sea level.)
1030 //
1031 // Revision 1.82  1999/01/20 13:42:24  curt
1032 // Tweaked FDM interface.
1033 // Testing check sum support for NMEA serial output.
1034 //
1035 // Revision 1.81  1999/01/19 20:57:03  curt
1036 // MacOS portability changes contributed by "Robert Puyol" <puyol@abvent.fr>
1037 //
1038 // Revision 1.80  1999/01/09 13:37:40  curt
1039 // Convert fgTIMESTAMP to FGTimeStamp which holds usec instead of ms.
1040 //
1041 // Revision 1.79  1999/01/08 03:23:56  curt
1042 // Beginning work on compensating for sim time vs. real world time "jitter".
1043 //
1044 // Revision 1.78  1999/01/07 20:25:08  curt
1045 // Updated struct fgGENERAL to class FGGeneral.
1046 //
1047 // Revision 1.77  1998/12/18 23:40:55  curt
1048 // New frame rate counting mechanism.
1049 //
1050 // Revision 1.76  1998/12/11 20:26:26  curt
1051 // Fixed view frustum culling accuracy bug so we can look out the sides and
1052 // back without tri-stripes dropping out.
1053 //
1054 // Revision 1.75  1998/12/09 18:50:23  curt
1055 // Converted "class fgVIEW" to "class FGView" and updated to make data
1056 // members private and make required accessor functions.
1057 //
1058 // Revision 1.74  1998/12/06 14:52:54  curt
1059 // Fixed a problem with the initial starting altitude.  "v->abs_view_pos" wasn't
1060 // being calculated correctly at the beginning causing the first terrain
1061 // intersection to fail, returning a ground altitude of zero, causing the plane
1062 // to free fall for one frame, until the ground altitude was corrected, but now
1063 // being under the ground we got a big bounce and the plane always ended up
1064 // upside down.
1065 //
1066 // Revision 1.73  1998/12/06 13:51:22  curt
1067 // Turned "struct fgWEATHER" into "class FGWeather".
1068 //
1069 // Revision 1.72  1998/12/05 15:54:18  curt
1070 // Renamed class fgFLIGHT to class FGState as per request by JSB.
1071 //
1072 // Revision 1.71  1998/12/05 14:19:51  curt
1073 // Looking into a problem with cur_view_params.abs_view_pos initialization.
1074 //
1075 // Revision 1.70  1998/12/03 01:17:14  curt
1076 // Converted fgFLIGHT to a class.
1077 //
1078 // Revision 1.69  1998/11/23 20:51:26  curt
1079 // Fiddling with when I can get info from the opengl driver.
1080 //
1081 // Revision 1.68  1998/11/20 01:02:35  curt
1082 // Try to detect Mesa/Glide/Voodoo and chose the appropriate resolution.
1083 //
1084 // Revision 1.67  1998/11/16 13:59:58  curt
1085 // Added pow() macro bug work around.
1086 // Added support for starting FGFS at various resolutions.
1087 // Added some initial serial port support.
1088 // Specify default log levels in main().
1089 //
1090 // Revision 1.66  1998/11/11 00:24:00  curt
1091 // Added Michael Johnson's audio patches for testing.
1092 // Also did a few tweaks to avoid numerical problems when starting at a place
1093 // with no (or bogus) scenery.
1094 //
1095 // Revision 1.65  1998/11/09 23:39:22  curt
1096 // Tweaks for the instrument panel.
1097 //
1098 // Revision 1.64  1998/11/07 19:07:09  curt
1099 // Enable release builds using the --without-logging option to the configure
1100 // script.  Also a couple log message cleanups, plus some C to C++ comment
1101 // conversion.
1102 //
1103 // Revision 1.63  1998/11/06 21:18:08  curt
1104 // Converted to new logstream debugging facility.  This allows release
1105 // builds with no messages at all (and no performance impact) by using
1106 // the -DFG_NDEBUG flag.
1107 //
1108 // Revision 1.62  1998/10/27 02:14:35  curt
1109 // Changes to support GLUT joystick routines as fall back.
1110 //
1111 // Revision 1.61  1998/10/25 14:08:47  curt
1112 // Turned "struct fgCONTROLS" into a class, with inlined accessor functions.
1113 //
1114 // Revision 1.60  1998/10/25 10:57:18  curt
1115 // Changes to use the new joystick library if it is available.
1116 //
1117 // Revision 1.59  1998/10/17 01:34:21  curt
1118 // C++ ifying ...
1119 //
1120 // Revision 1.58  1998/10/16 23:27:52  curt
1121 // C++-ifying.
1122 //
1123 // Revision 1.57  1998/10/16 00:54:00  curt
1124 // Converted to Point3D class.
1125 //
1126 // Revision 1.56  1998/10/02 12:46:47  curt
1127 // Added an "auto throttle"
1128 //
1129 // Revision 1.55  1998/09/29 14:58:18  curt
1130 // Use working() instead of !not_working() for audio.
1131 //
1132 // Revision 1.54  1998/09/29 02:03:38  curt
1133 // Autopilot mods.
1134 //
1135 // Revision 1.53  1998/09/26 13:18:35  curt
1136 // Check if audio "working()" before doing audio manipulations.
1137 //
1138 // Revision 1.52  1998/09/25 16:02:07  curt
1139 // Added support for pitch and volume envelopes and tied them to the
1140 // throttle setting.
1141 //
1142 // Revision 1.51  1998/09/15 04:27:28  curt
1143 // Changes for new Astro code.
1144 //
1145 // Revision 1.50  1998/09/15 02:09:24  curt
1146 // Include/fg_callback.hxx
1147 //   Moved code inline to stop g++ 2.7 from complaining.
1148 //
1149 // Simulator/Time/event.[ch]xx
1150 //   Changed return type of fgEVENT::printStat().  void caused g++ 2.7 to
1151 //   complain bitterly.
1152 //
1153 // Minor bugfix and changes.
1154 //
1155 // Simulator/Main/GLUTmain.cxx
1156 //   Added missing type to idle_state definition - eliminates a warning.
1157 //
1158 // Simulator/Main/fg_init.cxx
1159 //   Changes to airport lookup.
1160 //
1161 // Simulator/Main/options.cxx
1162 //   Uses fg_gzifstream when loading config file.
1163 //
1164 // Revision 1.49  1998/09/09 16:25:39  curt
1165 // Only use GLUT_STENCIL if the instument panel has been requested.
1166 //
1167 // Revision 1.48  1998/08/28 18:15:03  curt
1168 // Added new cockpit code from Friedemann Reinhard
1169 // <mpt218@faupt212.physik.uni-erlangen.de>
1170 //
1171 // Revision 1.47  1998/08/27 17:02:04  curt
1172 // Contributions from Bernie Bright <bbright@c031.aone.net.au>
1173 // - use strings for fg_root and airport_id and added methods to return
1174 //   them as strings,
1175 // - inlined all access methods,
1176 // - made the parsing functions private methods,
1177 // - deleted some unused functions.
1178 // - propogated some of these changes out a bit further.
1179 //
1180 // Revision 1.46  1998/08/22  14:49:56  curt
1181 // Attempting to iron out seg faults and crashes.
1182 // Did some shuffling to fix a initialization order problem between view
1183 // position, scenery elevation.
1184 //
1185 // Revision 1.45  1998/08/20 20:32:31  curt
1186 // Reshuffled some of the code in and around views.[ch]xx
1187 //
1188 // Revision 1.44  1998/08/20 15:10:33  curt
1189 // Added GameGLUT support.
1190 //
1191 // Revision 1.43  1998/08/12 21:01:47  curt
1192 // Master volume from 30% -> 80%
1193 //
1194 // Revision 1.42  1998/07/30 23:48:25  curt
1195 // Output position & orientation when pausing.
1196 // Eliminated libtool use.
1197 // Added options to specify initial position and orientation.
1198 // Changed default fov to 55 degrees.
1199 // Added command line option to start in paused or unpaused state.
1200 //
1201 // Revision 1.41  1998/07/27 18:41:24  curt
1202 // Added a pause command "p"
1203 // Fixed some initialization order problems between pui and glut.
1204 // Added an --enable/disable-sound option.
1205 //
1206 // Revision 1.40  1998/07/24 21:56:59  curt
1207 // Set near clip plane to 0.5 meters when close to the ground.  Also, let the view get a bit closer to the ground before hitting the hard limit.
1208 //
1209 // Revision 1.39  1998/07/24 21:39:08  curt
1210 // Debugging output tweaks.
1211 // Cast glGetString to (char *) to avoid compiler errors.
1212 // Optimizations to fgGluLookAt() by Norman Vine.
1213 //
1214 // Revision 1.38  1998/07/22 21:40:43  curt
1215 // Clear to adjusted fog color (for sunrise/sunset effects)
1216 // Make call to fog sunrise/sunset adjustment method.
1217 // Add a stdc++ library bug work around to fg_init.cxx
1218 //
1219 // Revision 1.37  1998/07/20 12:49:44  curt
1220 // Tweaked color buffer clearing defaults.  We clear the color buffer if we
1221 // are doing textures.  Assumptions:  If we are doing textures we have hardware
1222 // support that can clear the color buffer for "free."  If we are doing software
1223 // rendering with textures, then the extra clear time gets lost in the noise.
1224 //
1225 // Revision 1.36  1998/07/16 17:33:35  curt
1226 // "H" / "h" now control hud brightness as well with off being one of the
1227 //   states.
1228 // Better checking for xmesa/fx 3dfx fullscreen/window support for deciding
1229 //   whether or not to build in the feature.
1230 // Translucent menu support.
1231 // HAVE_AUDIO_SUPPORT -> ENABLE_AUDIO_SUPPORT
1232 // Use fork() / wait() for playing mp3 init music in background under unix.
1233 // Changed default tile diameter to 5.
1234 //
1235 // Revision 1.35  1998/07/13 21:01:36  curt
1236 // Wrote access functions for current fgOPTIONS.
1237 //
1238 // Revision 1.34  1998/07/13 15:32:37  curt
1239 // Clear color buffer if drawing wireframe.
1240 // When specifying and airport, start elevation at -1000 and let the system
1241 // position you at ground level.
1242 //
1243 // Revision 1.33  1998/07/12 03:14:42  curt
1244 // Added ground collision detection.
1245 // Did some serious horsing around to be able to "hug" the ground properly
1246 //   and still be able to take off.
1247 // Set the near clip plane to 1.0 meters when less than 10 meters above the
1248 //   ground.
1249 // Did some serious horsing around getting the initial airplane position to be
1250 //   correct based on rendered terrain elevation.
1251 // Added a little cheat/hack that will prevent the view position from ever
1252 //   dropping below the terrain, even when the flight model doesn't quite
1253 //   put you as high as you'd like.
1254 //
1255 // Revision 1.32  1998/07/08 14:45:07  curt
1256 // polar3d.h renamed to polar3d.hxx
1257 // vector.h renamed to vector.hxx
1258 // updated audio support so it waits to create audio classes (and tie up
1259 //   /dev/dsp) until the mpg123 player is finished.
1260 //
1261 // Revision 1.31  1998/07/06 21:34:17  curt
1262 // Added an enable/disable splash screen option.
1263 // Added an enable/disable intro music option.
1264 // Added an enable/disable instrument panel option.
1265 // Added an enable/disable mouse pointer option.
1266 // Added using namespace std for compilers that support this.
1267 //
1268 // Revision 1.30  1998/07/06 02:42:03  curt
1269 // Added support for switching between fullscreen and window mode for
1270 // Mesa/3dfx/glide.
1271 //
1272 // Added a basic splash screen.  Restructured the main loop and top level
1273 // initialization routines to do this.
1274 //
1275 // Hacked in some support for playing a startup mp3 sound file while rest
1276 // of sim initializes.  Currently only works in Unix using the mpg123 player.
1277 // Waits for the mpg123 player to finish before initializing internal
1278 // sound drivers.
1279 //
1280 // Revision 1.29  1998/07/04 00:52:22  curt
1281 // Add my own version of gluLookAt() (which is nearly identical to the
1282 // Mesa/glu version.)  But, by calculating the Model View matrix our selves
1283 // we can save this matrix without having to read it back in from the video
1284 // card.  This hopefully allows us to save a few cpu cycles when rendering
1285 // out the fragments because we can just use glLoadMatrixd() with the
1286 // precalculated matrix for each tile rather than doing a push(), translate(),
1287 // pop() for every fragment.
1288 //
1289 // Panel status defaults to off for now until it gets a bit more developed.
1290 //
1291 // Extract OpenGL driver info on initialization.
1292 //
1293 // Revision 1.28  1998/06/27 16:54:32  curt
1294 // Replaced "extern displayInstruments" with a entry in fgOPTIONS.
1295 // Don't change the view port when displaying the panel.
1296 //
1297 // Revision 1.27  1998/06/17 21:35:10  curt
1298 // Refined conditional audio support compilation.
1299 // Moved texture parameter setup calls to ../Scenery/materials.cxx
1300 // #include <string.h> before various STL includes.
1301 // Make HUD default state be enabled.
1302 //
1303 // Revision 1.26  1998/06/13 00:40:32  curt
1304 // Tweaked fog command line options.
1305 //
1306 // Revision 1.25  1998/06/12 14:27:26  curt
1307 // Pui -> PUI, Gui -> GUI.
1308 //
1309 // Revision 1.24  1998/06/12 00:57:39  curt
1310 // Added support for Pui/Gui.
1311 // Converted fog to GL_FOG_EXP2.
1312 // Link to static simulator parts.
1313 // Update runfg.bat to try to be a little smarter.
1314 //
1315 // Revision 1.23  1998/06/08 17:57:04  curt
1316 // Minor sound/startup position tweaks.
1317 //
1318 // Revision 1.22  1998/06/05 18:18:40  curt
1319 // A bit of fiddling with audio ...
1320 //
1321 // Revision 1.21  1998/06/03 22:01:06  curt
1322 // Tweaking sound library usage.
1323 //
1324 // Revision 1.20  1998/06/03 00:47:11  curt
1325 // Updated to compile in audio support if OSS available.
1326 // Updated for new version of Steve's audio library.
1327 // STL includes don't use .h
1328 // Small view optimizations.
1329 //
1330 // Revision 1.19  1998/06/01 17:54:40  curt
1331 // Added Linux audio support.
1332 // avoid glClear( COLOR_BUFFER_BIT ) when not using it to set the sky color.
1333 // map stl tweaks.
1334 //
1335 // Revision 1.18  1998/05/29 20:37:19  curt
1336 // Tweaked material properties & lighting a bit in GLUTmain.cxx.
1337 // Read airport list into a "map" STL for dynamic list sizing and fast tree
1338 // based lookups.
1339 //
1340 // Revision 1.17  1998/05/22 21:28:52  curt
1341 // Modifications to use the new fgEVENT_MGR class.
1342 //
1343 // Revision 1.16  1998/05/20 20:51:33  curt
1344 // Tweaked smooth shaded texture lighting properties.
1345 // Converted fgLIGHT to a C++ class.
1346 //
1347 // Revision 1.15  1998/05/16 13:08:34  curt
1348 // C++ - ified views.[ch]xx
1349 // Shuffled some additional view parameters into the fgVIEW class.
1350 // Changed tile-radius to tile-diameter because it is a much better
1351 //   name.
1352 // Added a WORLD_TO_EYE transformation to views.cxx.  This allows us
1353 //  to transform world space to eye space for view frustum culling.
1354 //
1355 // Revision 1.14  1998/05/13 18:29:57  curt
1356 // Added a keyboard binding to dynamically adjust field of view.
1357 // Added a command line option to specify fov.
1358 // Adjusted terrain color.
1359 // Root path info moved to fgOPTIONS.
1360 // Added ability to parse options out of a config file.
1361 //
1362 // Revision 1.13  1998/05/11 18:18:15  curt
1363 // For flat shading use "glHint (GL_FOG_HINT, GL_FASTEST )"
1364 //
1365 // Revision 1.12  1998/05/07 23:14:15  curt
1366 // Added "D" key binding to set autopilot heading.
1367 // Made frame rate calculation average out over last 10 frames.
1368 // Borland C++ floating point exception workaround.
1369 // Added a --tile-radius=n option.
1370 //
1371 // Revision 1.11  1998/05/06 03:16:23  curt
1372 // Added an averaged global frame rate counter.
1373 // Added an option to control tile radius.
1374 //
1375 // Revision 1.10  1998/05/03 00:47:31  curt
1376 // Added an option to enable/disable full-screen mode.
1377 //
1378 // Revision 1.9  1998/04/30 12:34:17  curt
1379 // Added command line rendering options:
1380 //   enable/disable fog/haze
1381 //   specify smooth/flat shading
1382 //   disable sky blending and just use a solid color
1383 //   enable wireframe drawing mode
1384 //
1385 // Revision 1.8  1998/04/28 01:20:21  curt
1386 // Type-ified fgTIME and fgVIEW.
1387 // Added a command line option to disable textures.
1388 //
1389 // Revision 1.7  1998/04/26 05:10:02  curt
1390 // "struct fgLIGHT" -> "fgLIGHT" because fgLIGHT is typedef'd.
1391 //
1392 // Revision 1.6  1998/04/25 22:06:30  curt
1393 // Edited cvs log messages in source files ... bad bad bad!
1394 //
1395 // Revision 1.5  1998/04/25 20:24:01  curt
1396 // Cleaned up initialization sequence to eliminate interdependencies
1397 // between sun position, lighting, and view position.  This creates a
1398 // valid single pass initialization path.
1399 //
1400 // Revision 1.4  1998/04/24 14:19:30  curt
1401 // Fog tweaks.
1402 //
1403 // Revision 1.3  1998/04/24 00:49:18  curt
1404 // Wrapped "#include <config.h>" in "#ifdef HAVE_CONFIG_H"
1405 // Trying out some different option parsing code.
1406 // Some code reorganization.
1407 //
1408 // Revision 1.2  1998/04/22 13:25:41  curt
1409 // C++ - ifing the code.
1410 // Starting a bit of reorganization of lighting code.
1411 //
1412 // Revision 1.1  1998/04/21 17:02:39  curt
1413 // Prepairing for C++ integration.
1414 //
1415 // Revision 1.71  1998/04/18 04:11:26  curt
1416 // Moved fg_debug to it's own library, added zlib support.
1417 //
1418 // Revision 1.70  1998/04/14 02:21:02  curt
1419 // Incorporated autopilot heading hold contributed by:  Jeff Goeke-Smith
1420 // <jgoeke@voyager.net>
1421 //
1422 // Revision 1.69  1998/04/08 23:35:34  curt
1423 // Tweaks to Gnu automake/autoconf system.
1424 //
1425 // Revision 1.68  1998/04/03 22:09:03  curt
1426 // Converting to Gnu autoconf system.
1427 //
1428 // Revision 1.67  1998/03/23 21:24:37  curt
1429 // Source code formating tweaks.
1430 //
1431 // Revision 1.66  1998/03/14 00:31:20  curt
1432 // Beginning initial terrain texturing experiments.
1433 //
1434 // Revision 1.65  1998/03/09 22:45:57  curt
1435 // Minor tweaks for building on sparc platform.
1436 //
1437 // Revision 1.64  1998/02/20 00:16:23  curt
1438 // Thursday's tweaks.
1439 //
1440 // Revision 1.63  1998/02/16 16:17:39  curt
1441 // Minor tweaks.
1442 //
1443 // Revision 1.62  1998/02/16 13:39:42  curt
1444 // Miscellaneous weekend tweaks.  Fixed? a cache problem that caused whole
1445 // tiles to occasionally be missing.
1446 //
1447 // Revision 1.61  1998/02/12 21:59:46  curt
1448 // Incorporated code changes contributed by Charlie Hotchkiss
1449 // <chotchkiss@namg.us.anritsu.com>
1450 //
1451 // Revision 1.60  1998/02/11 02:50:40  curt
1452 // Minor changes.
1453 //
1454 // Revision 1.59  1998/02/09 22:56:54  curt
1455 // Removed "depend" files from cvs control.  Other minor make tweaks.
1456 //
1457 // Revision 1.58  1998/02/09 15:07:49  curt
1458 // Minor tweaks.
1459 //
1460 // Revision 1.57  1998/02/07 15:29:40  curt
1461 // Incorporated HUD changes and struct/typedef changes from Charlie Hotchkiss
1462 // <chotchkiss@namg.us.anritsu.com>
1463 //
1464 // Revision 1.56  1998/02/03 23:20:23  curt
1465 // Lots of little tweaks to fix various consistency problems discovered by
1466 // Solaris' CC.  Fixed a bug in fg_debug.c with how the fgPrintf() wrapper
1467 // passed arguments along to the real printf().  Also incorporated HUD changes
1468 // by Michele America.
1469 //
1470 // Revision 1.55  1998/02/02 20:53:58  curt
1471 // Incorporated Durk's changes.
1472 //
1473 // Revision 1.54  1998/01/31 00:43:10  curt
1474 // Added MetroWorks patches from Carmen Volpe.
1475 //
1476 // Revision 1.53  1998/01/27 18:35:54  curt
1477 // Minor tweaks.
1478 //
1479 // Revision 1.52  1998/01/27 00:47:56  curt
1480 // Incorporated Paul Bleisch's <pbleisch@acm.org> new debug message
1481 // system and commandline/config file processing code.
1482 //
1483 // Revision 1.51  1998/01/26 15:57:05  curt
1484 // Tweaks for dynamic scenery development.
1485 //
1486 // Revision 1.50  1998/01/19 19:27:07  curt
1487 // Merged in make system changes from Bob Kuehne <rpk@sgi.com>
1488 // This should simplify things tremendously.
1489 //
1490 // Revision 1.49  1998/01/19 18:40:31  curt
1491 // Tons of little changes to clean up the code and to remove fatal errors
1492 // when building with the c++ compiler.
1493 //
1494 // Revision 1.48  1998/01/19 18:35:46  curt
1495 // Minor tweaks and fixes for cygwin32.
1496 //
1497 // Revision 1.47  1998/01/13 00:23:08  curt
1498 // Initial changes to support loading and management of scenery tiles.  Note,
1499 // there's still a fair amount of work left to be done.
1500 //
1501 // Revision 1.46  1998/01/08 02:22:06  curt
1502 // Beginning to integrate Tile management subsystem.
1503 //
1504 // Revision 1.45  1998/01/07 03:18:55  curt
1505 // Moved astronomical stuff from .../Src/Scenery to .../Src/Astro/
1506 //
1507 // Revision 1.44  1997/12/30 22:22:31  curt
1508 // Further integration of event manager.
1509 //
1510 // Revision 1.43  1997/12/30 20:47:43  curt
1511 // Integrated new event manager with subsystem initializations.
1512 //
1513 // Revision 1.42  1997/12/30 16:36:47  curt
1514 // Merged in Durk's changes ...
1515 //
1516 // Revision 1.41  1997/12/30 13:06:56  curt
1517 // A couple lighting tweaks ...
1518 //
1519 // Revision 1.40  1997/12/30 01:38:37  curt
1520 // Switched back to per vertex normals and smooth shading for terrain.
1521 //
1522 // Revision 1.39  1997/12/22 23:45:45  curt
1523 // First stab at sunset/sunrise sky glow effects.
1524 //
1525 // Revision 1.38  1997/12/22 04:14:28  curt
1526 // Aligned sky with sun so dusk/dawn effects can be correct relative to the sun.
1527 //
1528 // Revision 1.37  1997/12/19 23:34:03  curt
1529 // Lot's of tweaking with sky rendering and lighting.
1530 //
1531 // Revision 1.36  1997/12/19 16:44:57  curt
1532 // Working on scene rendering order and options.
1533 //
1534 // Revision 1.35  1997/12/18 23:32:32  curt
1535 // First stab at sky dome actually starting to look reasonable. :-)
1536 //
1537 // Revision 1.34  1997/12/17 23:13:34  curt
1538 // Began working on rendering a sky.
1539 //
1540 // Revision 1.33  1997/12/15 23:54:45  curt
1541 // Add xgl wrappers for debugging.
1542 // Generate terrain normals on the fly.
1543 //
1544 // Revision 1.32  1997/12/15 20:59:08  curt
1545 // Misc. tweaks.
1546 //
1547 // Revision 1.31  1997/12/12 21:41:25  curt
1548 // More light/material property tweaking ... still a ways off.
1549 //
1550 // Revision 1.30  1997/12/12 19:52:47  curt
1551 // Working on lightling and material properties.
1552 //
1553 // Revision 1.29  1997/12/11 04:43:54  curt
1554 // Fixed sun vector and lighting problems.  I thing the moon is now lit
1555 // correctly.
1556 //
1557 // Revision 1.28  1997/12/10 22:37:45  curt
1558 // Prepended "fg" on the name of all global structures that didn't have it yet.
1559 // i.e. "struct WEATHER {}" became "struct fgWEATHER {}"
1560 //
1561 // Revision 1.27  1997/12/09 05:11:54  curt
1562 // Working on tweaking lighting.
1563 //
1564 // Revision 1.26  1997/12/09 04:25:29  curt
1565 // Working on adding a global lighting params structure.
1566 //
1567 // Revision 1.25  1997/12/08 22:54:09  curt
1568 // Enabled GL_CULL_FACE.
1569 //
1570 // Revision 1.24  1997/11/25 19:25:32  curt
1571 // Changes to integrate Durk's moon/sun code updates + clean up.
1572 //
1573 // Revision 1.23  1997/11/15 18:16:34  curt
1574 // minor tweaks.
1575 //
1576 // Revision 1.22  1997/10/30 12:38:41  curt
1577 // Working on new scenery subsystem.
1578 //
1579 // Revision 1.21  1997/09/23 00:29:38  curt
1580 // Tweaks to get things to compile with gcc-win32.
1581 //
1582 // Revision 1.20  1997/09/22 14:44:19  curt
1583 // Continuing to try to align stars correctly.
1584 //
1585 // Revision 1.19  1997/09/18 16:20:08  curt
1586 // At dusk/dawn add/remove stars in stages.
1587 //
1588 // Revision 1.18  1997/09/16 22:14:51  curt
1589 // Tweaked time of day lighting equations.  Don't draw stars during the day.
1590 //
1591 // Revision 1.17  1997/09/16 15:50:29  curt
1592 // Working on star alignment and time issues.
1593 //
1594 // Revision 1.16  1997/09/13 02:00:06  curt
1595 // Mostly working on stars and generating sidereal time for accurate star
1596 // placement.
1597 //
1598 // Revision 1.15  1997/09/05 14:17:27  curt
1599 // More tweaking with stars.
1600 //
1601 // Revision 1.14  1997/09/05 01:35:53  curt
1602 // Working on getting stars right.
1603 //
1604 // Revision 1.13  1997/09/04 02:17:34  curt
1605 // Shufflin' stuff.
1606 //
1607 // Revision 1.12  1997/08/27 21:32:24  curt
1608 // Restructured view calculation code.  Added stars.
1609 //
1610 // Revision 1.11  1997/08/27 03:30:16  curt
1611 // Changed naming scheme of basic shared structures.
1612 //
1613 // Revision 1.10  1997/08/25 20:27:22  curt
1614 // Merged in initial HUD and Joystick code.
1615 //
1616 // Revision 1.9  1997/08/22 21:34:39  curt
1617 // Doing a bit of reorganizing and house cleaning.
1618 //
1619 // Revision 1.8  1997/08/19 23:55:03  curt
1620 // Worked on better simulating real lighting.
1621 //
1622 // Revision 1.7  1997/08/16 12:22:38  curt
1623 // Working on improving the lighting/shading.
1624 //
1625 // Revision 1.6  1997/08/13 20:24:56  curt
1626 // Changes due to changing sunpos interface.
1627 //
1628 // Revision 1.5  1997/08/06 21:08:32  curt
1629 // Sun position now really* works (I think) ... I still have sun time warping
1630 // code in place, probably should remove it soon.
1631 //
1632 // Revision 1.4  1997/08/06 15:41:26  curt
1633 // Working on correct sun position.
1634 //
1635 // Revision 1.3  1997/08/06 00:24:22  curt
1636 // Working on correct real time sun lighting.
1637 //
1638 // Revision 1.2  1997/08/04 20:25:15  curt
1639 // Organizational tweaking.
1640 //
1641 // Revision 1.1  1997/08/02 18:45:00  curt
1642 // Renamed GLmain.c GLUTmain.c
1643 //
1644 // Revision 1.43  1997/08/02 16:23:47  curt
1645 // Misc. tweaks.
1646 //
1647 // Revision 1.42  1997/08/01 19:43:33  curt
1648 // Making progress with coordinate system overhaul.
1649 //
1650 // Revision 1.41  1997/07/31 22:52:37  curt
1651 // Working on redoing internal coordinate systems & scenery transformations.
1652 //
1653 // Revision 1.40  1997/07/30 16:12:42  curt
1654 // Moved fg_random routines from Util/ to Math/
1655 //
1656 // Revision 1.39  1997/07/21 14:45:01  curt
1657 // Minor tweaks.
1658 //
1659 // Revision 1.38  1997/07/19 23:04:47  curt
1660 // Added an initial weather section.
1661 //
1662 // Revision 1.37  1997/07/19 22:34:02  curt
1663 // Moved PI definitions to ../constants.h
1664 // Moved random() stuff to ../Utils/ and renamed fg_random()
1665 //
1666 // Revision 1.36  1997/07/18 23:41:25  curt
1667 // Tweaks for building with Cygnus Win32 compiler.
1668 //
1669 // Revision 1.35  1997/07/18 14:28:34  curt
1670 // Hacked in some support for wind/turbulence.
1671 //
1672 // Revision 1.34  1997/07/16 20:04:48  curt
1673 // Minor tweaks to aid Win32 port.
1674 //
1675 // Revision 1.33  1997/07/12 03:50:20  curt
1676 // Added an #include <Windows32/Base.h> to help compiling for Win32
1677 //
1678 // Revision 1.32  1997/07/11 03:23:18  curt
1679 // Solved some scenery display/orientation problems.  Still have a positioning
1680 // (or transformation?) problem.
1681 //
1682 // Revision 1.31  1997/07/11 01:29:58  curt
1683 // More tweaking of terrian floor.
1684 //
1685 // Revision 1.30  1997/07/10 04:26:37  curt
1686 // We now can interpolated ground elevation for any position in the grid.  We
1687 // can use this to enforce a "hard" ground.  We still need to enforce some
1688 // bounds checking so that we don't try to lookup data points outside the
1689 // grid data set.
1690 //
1691 // Revision 1.29  1997/07/09 21:31:12  curt
1692 // Working on making the ground "hard."
1693 //
1694 // Revision 1.28  1997/07/08 18:20:12  curt
1695 // Working on establishing a hard ground.
1696 //
1697 // Revision 1.27  1997/07/07 20:59:49  curt
1698 // Working on scenery transformations to enable us to fly fluidly over the
1699 // poles with no discontinuity/distortion in scenery.
1700 //
1701 // Revision 1.26  1997/07/05 20:43:34  curt
1702 // renamed mat3 directory to Math so we could add other math related routines.
1703 //
1704 // Revision 1.25  1997/06/29 21:19:17  curt
1705 // Working on scenery management system.
1706 //
1707 // Revision 1.24  1997/06/26 22:14:53  curt
1708 // Beginning work on a scenery management system.
1709 //
1710 // Revision 1.23  1997/06/26 19:08:33  curt
1711 // Restructuring make, adding automatic "make dep" support.
1712 //
1713 // Revision 1.22  1997/06/25 15:39:47  curt
1714 // Minor changes to compile with rsxnt/win32.
1715 //
1716 // Revision 1.21  1997/06/22 21:44:41  curt
1717 // Working on intergrating the VRML (subset) parser.
1718 //
1719 // Revision 1.20  1997/06/21 17:12:53  curt
1720 // Capitalized subdirectory names.
1721 //
1722 // Revision 1.19  1997/06/18 04:10:31  curt
1723 // A couple more runway tweaks ...
1724 //
1725 // Revision 1.18  1997/06/18 02:21:24  curt
1726 // Hacked in a runway
1727 //
1728 // Revision 1.17  1997/06/17 16:51:58  curt
1729 // Timer interval stuff now uses gettimeofday() instead of ftime()
1730 //
1731 // Revision 1.16  1997/06/17 04:19:16  curt
1732 // More timer related tweaks with respect to view direction changes.
1733 //
1734 // Revision 1.15  1997/06/17 03:41:10  curt
1735 // Nonsignal based interval timing is now working.
1736 // This would be a good time to look at cleaning up the code structure a bit.
1737 //
1738 // Revision 1.14  1997/06/16 19:32:51  curt
1739 // Starting to add general timer support.
1740 //
1741 // Revision 1.13  1997/06/02 03:40:06  curt
1742 // A tiny bit more view tweaking.
1743 //
1744 // Revision 1.12  1997/06/02 03:01:38  curt
1745 // Working on views (side, front, back, transitions, etc.)
1746 //
1747 // Revision 1.11  1997/05/31 19:16:25  curt
1748 // Elevator trim added.
1749 //
1750 // Revision 1.10  1997/05/31 04:13:52  curt
1751 // WE CAN NOW FLY!!!
1752 //
1753 // Continuing work on the LaRCsim flight model integration.
1754 // Added some MSFS-like keyboard input handling.
1755 //
1756 // Revision 1.9  1997/05/30 19:27:01  curt
1757 // The LaRCsim flight model is starting to look like it is working.
1758 //
1759 // Revision 1.8  1997/05/30 03:54:10  curt
1760 // Made a bit more progress towards integrating the LaRCsim flight model.
1761 //
1762 // Revision 1.7  1997/05/29 22:39:49  curt
1763 // Working on incorporating the LaRCsim flight model.
1764 //
1765 // Revision 1.6  1997/05/29 12:31:39  curt
1766 // Minor tweaks, moving towards general flight model integration.
1767 //
1768 // Revision 1.5  1997/05/29 02:33:23  curt
1769 // Updated to reflect changing interfaces in other "modules."
1770 //
1771 // Revision 1.4  1997/05/27 17:44:31  curt
1772 // Renamed & rearranged variables and routines.   Added some initial simple
1773 // timer/alarm routines so the flight model can be updated on a regular 
1774 // interval.
1775 //
1776 // Revision 1.3  1997/05/23 15:40:25  curt
1777 // Added GNU copyright headers.
1778 // Fog now works!
1779 //
1780 // Revision 1.2  1997/05/23 00:35:12  curt
1781 // Trying to get fog to work ...
1782 //
1783 // Revision 1.1  1997/05/21 15:57:51  curt
1784 // Renamed due to added GLUT support.
1785 //
1786 // Revision 1.3  1997/05/19 18:22:42  curt
1787 // Parameter tweaking ... starting to stub in fog support.
1788 //
1789 // Revision 1.2  1997/05/17 00:17:34  curt
1790 // Trying to stub in support for standard OpenGL.
1791 //
1792 // Revision 1.1  1997/05/16 16:05:52  curt
1793 // Initial revision.
1794 //