]> git.mxchange.org Git - flightgear.git/blob - src/Main/main.cxx
Borland C++ tweaks.
[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 <XGL/xgl.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <string>
45
46 #ifdef HAVE_STDLIB_H
47 #   include <stdlib.h>
48 #endif
49
50 #ifdef HAVE_SYS_STAT_H
51 #  include <sys/stat.h> /* for stat() */
52 #endif
53
54 #ifdef HAVE_UNISTD_H
55 #  include <unistd.h>    /* for stat() */
56 #endif
57
58 #include <pu.h>                 // plib include
59 #include <ssg.h>                // plib include
60
61 #ifdef ENABLE_AUDIO_SUPPORT
62 #  include <sl.h>               // plib include
63 #  include <sm.h>               // plib include
64 #endif
65
66 #include <Include/fg_constants.h>  // for VERSION
67 #include <Include/general.hxx>
68
69 #include <Debug/logstream.hxx>
70 #include <Aircraft/aircraft.hxx>
71 #include <Astro/sky.hxx>
72 #include <Astro/stars.hxx>
73 #include <Astro/solarsystem.hxx>
74
75 #include <Autopilot/autopilot.hxx>
76 #include <Cockpit/cockpit.hxx>
77 #include <GUI/gui.h>
78 #include <Joystick/joystick.hxx>
79 #include <Math/fg_geodesy.hxx>
80 #include <Math/mat3.h>
81 #include <Math/polar3d.hxx>
82 #include <Math/fg_random.h>
83 #include <Misc/fgpath.hxx>
84 #include <Scenery/scenery.hxx>
85 #include <Scenery/tilemgr.hxx>
86 #include <Time/event.hxx>
87 #include <Time/fg_time.hxx>
88 #include <Time/fg_timer.hxx>
89 #include <Time/sunpos.hxx>
90 #include <Weather/weather.hxx>
91
92 #include "fg_init.hxx"
93 #include "keyboard.hxx"
94 #include "options.hxx"
95 #include "splash.hxx"
96 #include "views.hxx"
97 #include "fg_serial.hxx"
98
99
100 // -dw- use custom sioux settings so I can see output window
101 #ifdef MACOS
102 #  ifndef FG_NDEBUG
103 #    include <sioux.h> // settings for output window
104 #  endif
105 #  include <console.h>
106 #endif
107
108
109 // This is a record containing a bit of global housekeeping information
110 FGGeneral general;
111
112 // Specify our current idle function state.  This is used to run all
113 // our initializations out of the glutIdleLoop() so that we can get a
114 // splash screen up and running right away.
115 static int idle_state = 0;
116
117 // Another hack
118 int use_signals = 0;
119
120 // Global structures for the Audio library
121 #ifdef ENABLE_AUDIO_SUPPORT
122 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
123 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
124 slScheduler *audio_sched;
125 smMixer *audio_mixer;
126 slSample *s1;
127 slSample *s2;
128 #endif
129
130
131 // ssg variables
132 ssgRoot *scene = NULL;
133 ssgTransform *penguin = NULL;
134
135
136 // The following defines flight gear options. Because glutlib will also
137 // want to parse its own options, those options must not be included here
138 // or they will get parsed by the main program option parser. Hence case
139 // is significant for any option added that might be in conflict with
140 // glutlib's parser.
141 //
142 // glutlib parses for:
143 //    -display
144 //    -direct   (invalid in Win32)
145 //    -geometry
146 //    -gldebug
147 //    -iconized
148 //    -indirect (invalid in Win32)
149 //    -synce
150 //
151 // Note that glutlib depends upon strings while this program's
152 // option parser wants only initial characters followed by numbers
153 // or pathnames.
154 //
155
156
157 // fgInitVisuals() -- Initialize various GL/view parameters
158 static void fgInitVisuals( void ) {
159     fgLIGHT *l;
160
161     l = &cur_light_params;
162
163 #ifndef GLUT_WRONG_VERSION
164     // Go full screen if requested ...
165     if ( current_options.get_fullscreen() ) {
166         glutFullScreen();
167     }
168 #endif
169
170     // If enabled, normal vectors specified with glNormal are scaled
171     // to unit length after transformation.  See glNormal.
172     // xglEnable( GL_NORMALIZE );
173
174     xglEnable( GL_LIGHTING );
175     xglEnable( GL_LIGHT0 );
176     xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
177
178     sgVec3 sunpos;
179     sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
180     ssgGetLight( 0 ) -> setPosition( sunpos );
181
182     // xglFogi (GL_FOG_MODE, GL_LINEAR);
183     xglFogi (GL_FOG_MODE, GL_EXP2);
184     // Fog density is now set when the weather system is initialized
185     // xglFogf (GL_FOG_DENSITY, w->fog_density);
186     if ( (current_options.get_fog() == 1) || 
187          (current_options.get_shading() == 0) ) {
188         // if fastest fog requested, or if flat shading force fastest
189         xglHint ( GL_FOG_HINT, GL_FASTEST );
190     } else if ( current_options.get_fog() == 2 ) {
191         xglHint ( GL_FOG_HINT, GL_NICEST );
192     }
193     if ( current_options.get_wireframe() ) {
194         // draw wire frame
195         xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
196     }
197
198     // This is the default anyways, but it can't hurt
199     xglFrontFace ( GL_CCW );
200
201     // Just testing ...
202     // xglEnable(GL_POINT_SMOOTH);
203     // xglEnable(GL_LINE_SMOOTH);
204     // xglEnable(GL_POLYGON_SMOOTH);      
205 }
206
207
208 #if 0
209 // Draw a basic instrument panel
210 static void fgUpdateInstrViewParams( void ) {
211
212     exit(0);
213
214     fgVIEW *v = &current_view;
215
216     xglViewport(0, 0 , (GLint)(v->winWidth), (GLint)(v->winHeight) / 2);
217   
218     xglMatrixMode(GL_PROJECTION);
219     xglPushMatrix();
220   
221     xglLoadIdentity();
222     gluOrtho2D(0, 640, 0, 480);
223     xglMatrixMode(GL_MODELVIEW);
224     xglPushMatrix();
225     xglLoadIdentity();
226
227     xglColor3f(1.0, 1.0, 1.0);
228     xglIndexi(7);
229   
230     xglDisable(GL_DEPTH_TEST);
231     xglDisable(GL_LIGHTING);
232   
233     xglLineWidth(1);
234     xglColor3f (0.5, 0.5, 0.5);
235
236     xglBegin(GL_QUADS);
237     xglVertex2f(0.0, 0.00);
238     xglVertex2f(0.0, 480.0);
239     xglVertex2f(640.0,480.0);
240     xglVertex2f(640.0, 0.0);
241     xglEnd();
242
243     xglRectf(0.0,0.0, 640, 480);
244     xglEnable(GL_DEPTH_TEST);
245     xglEnable(GL_LIGHTING);
246     xglMatrixMode(GL_PROJECTION);
247     xglPopMatrix();
248     xglMatrixMode(GL_MODELVIEW);
249     xglPopMatrix();
250 }
251 #endif
252
253
254 // Update all Visuals (redraws anything graphics related)
255 static void fgRenderFrame( void ) {
256     fgLIGHT *l = &cur_light_params;
257     FGTime *t = FGTime::cur_time_params;
258     FGView *v = &current_view;
259
260     double angle;
261     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
262     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
263     GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
264     // GLfloat mat_shininess[] = { 10.0 };
265     GLbitfield clear_mask;
266
267     if ( idle_state != 1000 ) {
268         // still initializing, draw the splash screen
269         if ( current_options.get_splash_screen() == 1 ) {
270             fgSplashUpdate(0.0);
271         }
272     } else {
273         // idle_state is now 1000 meaning we've finished all our
274         // initializations and are running the main loop, so this will
275         // now work without seg faulting the system.
276
277         // printf("Ground = %.2f  Altitude = %.2f\n", scenery.cur_elev, 
278         //        FG_Altitude * FEET_TO_METER);
279     
280         // this is just a temporary hack, to make me understand Pui
281         // timerText -> setLabel (ctime (&t->cur_time));
282         // end of hack
283
284         // update view volume parameters
285         v->UpdateViewParams();
286
287         // set the sun position
288         xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
289
290         sgVec3 sunpos;
291         sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
292         ssgGetLight( 0 ) -> setPosition( sunpos );
293
294         clear_mask = GL_DEPTH_BUFFER_BIT;
295         if ( current_options.get_wireframe() ) {
296             clear_mask |= GL_COLOR_BUFFER_BIT;
297         }
298         if ( current_options.get_panel_status() ) {
299             // we can't clear the screen when the panel is active
300         } else if ( current_options.get_skyblend() ) {
301             if ( current_options.get_textures() ) {
302                 // glClearColor(black[0], black[1], black[2], black[3]);
303                 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1], 
304                              l->adj_fog_color[2], l->adj_fog_color[3]);
305                 clear_mask |= GL_COLOR_BUFFER_BIT;
306             }
307         } else {
308             glClearColor(l->sky_color[0], l->sky_color[1], 
309                          l->sky_color[2], l->sky_color[3]);
310             clear_mask |= GL_COLOR_BUFFER_BIT;
311         }
312         xglClear( clear_mask );
313
314         // Tell GL we are switching to model view parameters
315         xglMatrixMode(GL_MODELVIEW);
316         // xglLoadIdentity();
317
318         // draw sky
319         xglDisable( GL_DEPTH_TEST );
320         xglDisable( GL_LIGHTING );
321         xglDisable( GL_CULL_FACE );
322         xglDisable( GL_FOG );
323         xglShadeModel( GL_SMOOTH );
324         if ( current_options.get_skyblend() ) {
325             fgSkyRender();
326         }
327
328         // setup transformation for drawing astronomical objects
329         xglPushMatrix();
330         // Translate to view position
331         Point3D view_pos = v->get_view_pos();
332         xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
333         // Rotate based on gst (sidereal time)
334         // note: constant should be 15.041085, Curt thought it was 15
335         angle = t->getGst() * 15.041085;
336         // printf("Rotating astro objects by %.2f degrees\n",angle);
337         xglRotatef( angle, 0.0, 0.0, -1.0 );
338
339         // draw stars and planets
340         fgStarsRender();
341         xglEnable( GL_CULL_FACE ); // for moon
342         //xglEnable(GL_DEPTH_TEST);
343         SolarSystem::theSolarSystem->draw();
344
345         xglPopMatrix();
346
347         // draw scenery
348         if ( current_options.get_shading() ) {
349             xglShadeModel( GL_SMOOTH ); 
350         } else {
351             xglShadeModel( GL_FLAT ); 
352         }
353         xglEnable( GL_DEPTH_TEST );
354         if ( current_options.get_fog() > 0 ) {
355             xglEnable( GL_FOG );
356             xglFogfv (GL_FOG_COLOR, l->adj_fog_color);
357         }
358         // set lighting parameters
359         xglLightfv(GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
360         xglLightfv(GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
361         // xglLightfv(GL_LIGHT0, GL_SPECULAR, white );
362         
363         if ( current_options.get_textures() ) {
364             // texture parameters
365             xglEnable( GL_TEXTURE_2D );
366             xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
367             xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
368             // set base color (I don't think this is doing anything here)
369             xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
370             xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
371             // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
372             // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
373         } else {
374             xglDisable( GL_TEXTURE_2D );
375             xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
376             xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
377             // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
378             // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
379         }
380
381         global_tile_mgr.render();
382
383         xglDisable( GL_TEXTURE_2D );
384         xglDisable( GL_FOG );
385
386         // display HUD && Panel
387         xglDisable( GL_CULL_FACE );
388         fgCockpitUpdate();
389
390         // We can do translucent menus, so why not. :-)
391         xglEnable    ( GL_BLEND ) ;
392         xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
393         puDisplay();
394         xglDisable   ( GL_BLEND ) ;
395         xglEnable( GL_FOG );
396
397         // ssg test
398
399         xglMatrixMode(GL_PROJECTION);
400         xglLoadIdentity();
401         ssgSetFOV(60.0f, 0.0f);
402         ssgSetNearFar(1.0f, 700.0f);
403         sgMat4 sgTRANS;
404
405         sgMakeTransMat4( sgTRANS, 
406                          current_view.view_pos.x() 
407                          + current_view.view_forward[0] * 20,
408                          current_view.view_pos.y() 
409                          + current_view.view_forward[1] * 20,
410                          current_view.view_pos.z() 
411                          + current_view.view_forward[2] * 20 );
412
413         sgMat4 sgTMP;
414         sgMat4 sgTUX;
415         sgMultMat4( sgTMP, current_view.sgUP, sgTRANS );
416         sgMultMat4( sgTUX, current_view.sgLARC_TO_SSG, sgTMP );
417         
418         sgCoord tuxpos;
419         sgSetCoord( &tuxpos, sgTUX );
420         penguin->setTransform( &tuxpos );
421
422         sgMakeTransMat4( sgTRANS, 
423                          current_view.view_pos.x(),
424                          current_view.view_pos.y(),
425                          current_view.view_pos.z() );
426         sgMat4 sgVIEW;
427         sgMultMat4( sgVIEW, current_view.sgVIEW, sgTRANS );
428         ssgSetCamera( sgVIEW );
429         // ssgSetCamera( current_view.sgVIEW );
430         ssgCullAndDraw( scene );
431
432     }
433
434     xglutSwapBuffers();
435 }
436
437
438 // Update internal time dependent calculations (i.e. flight model)
439 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
440     FGInterface *f = current_aircraft.fdm_state;
441     fgLIGHT *l = &cur_light_params;
442     FGTime *t = FGTime::cur_time_params;
443     FGView *v = &current_view;
444     int i;
445
446     // update the flight model
447     if ( multi_loop < 0 ) {
448         multi_loop = DEFAULT_MULTILOOP;
449     }
450
451     if ( !t->getPause() ) {
452         // run Autopilot system
453         fgAPRun();
454
455         // printf("updating flight model x %d\n", multi_loop);
456         fgFDMUpdate( current_options.get_flight_model(), 
457                      cur_fdm_state, multi_loop, remainder );
458     } else {
459         fgFDMUpdate( current_options.get_flight_model(), 
460                      cur_fdm_state, 0, remainder );
461     }
462
463     // update the view angle
464     for ( i = 0; i < multi_loop; i++ ) {
465         if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
466             v->set_view_offset( v->get_goal_view_offset() );
467             break;
468         } else {
469             // move v->view_offset towards v->goal_view_offset
470             if ( v->get_goal_view_offset() > v->get_view_offset() ) {
471                 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
472                     v->inc_view_offset( 0.01 );
473                 } else {
474                     v->inc_view_offset( -0.01 );
475                 }
476             } else {
477                 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
478                     v->inc_view_offset( -0.01 );
479                 } else {
480                     v->inc_view_offset( 0.01 );
481                 }
482             }
483             if ( v->get_view_offset() > FG_2PI ) {
484                 v->inc_view_offset( -FG_2PI );
485             } else if ( v->get_view_offset() < 0 ) {
486                 v->inc_view_offset( FG_2PI );
487             }
488         }
489     }
490
491     double tmp = -(l->sun_rotation + FG_PI) 
492         - (f->get_Psi() - v->get_view_offset() );
493     while ( tmp < 0.0 ) {
494         tmp += FG_2PI;
495     }
496     while ( tmp > FG_2PI ) {
497         tmp -= FG_2PI;
498     }
499     /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
500            FG_Psi * RAD_TO_DEG, v->view_offset * RAD_TO_DEG, 
501            -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
502     l->UpdateAdjFog();
503 }
504
505
506 void fgInitTimeDepCalcs( void ) {
507     // initialize timer
508
509     // #ifdef HAVE_SETITIMER
510     //   fgTimerInit( 1.0 / DEFAULT_TIMER_HZ, fgUpdateTimeDepCalcs );
511     // #endif HAVE_SETITIMER
512 }
513
514 static const double alt_adjust_ft = 3.758099;
515 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
516
517 // What should we do when we have nothing else to do?  Let's get ready
518 // for the next move and update the display?
519 static void fgMainLoop( void ) {
520     FGInterface *f;
521     FGTime *t;
522     static long remainder = 0;
523     long elapsed, multi_loop;
524 #ifdef FANCY_FRAME_COUNTER
525     int i;
526     double accum;
527 #else
528     static time_t last_time = 0;
529     static int frames = 0;
530 #endif // FANCY_FRAME_COUNTER
531
532     f = current_aircraft.fdm_state;
533     t = FGTime::cur_time_params;
534
535     FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
536     FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
537
538 #if defined( ENABLE_PLIB_JOYSTICK )
539     // Read joystick and update control settings
540     fgJoystickRead();
541 #elif defined( ENABLE_GLUT_JOYSTICK )
542     // Glut joystick support works by feeding a joystick handler
543     // function to glut.  This is taken care of once in the joystick
544     // init routine and we don't have to worry about it again.
545 #endif
546
547     current_weather.Update();
548
549     // Fix elevation.  I'm just sticking this here for now, it should
550     // probably move eventually
551
552     /* printf("Before - ground = %.2f  runway = %.2f  alt = %.2f\n",
553            scenery.cur_elev,
554            f->get_Runway_altitude() * FEET_TO_METER,
555            f->get_Altitude() * FEET_TO_METER); */
556
557     if ( scenery.cur_elev > -9990 ) {
558         if ( f->get_Altitude() * FEET_TO_METER < 
559              (scenery.cur_elev + alt_adjust_m - 3.0) ) {
560             // now set aircraft altitude above ground
561             printf("Current Altitude = %.2f < %.2f forcing to %.2f\n", 
562                    f->get_Altitude() * FEET_TO_METER,
563                    scenery.cur_elev + alt_adjust_m - 3.0,
564                    scenery.cur_elev + alt_adjust_m );
565             fgFDMForceAltitude( current_options.get_flight_model(), 
566                                 scenery.cur_elev + alt_adjust_m );
567
568             FG_LOG( FG_ALL, FG_DEBUG, 
569                     "<*> resetting altitude to " 
570                     << f->get_Altitude() * FEET_TO_METER << " meters" );
571         }
572         fgFDMSetGroundElevation( current_options.get_flight_model(),
573                                  scenery.cur_elev );  // meters
574     }
575
576     /* printf("Adjustment - ground = %.2f  runway = %.2f  alt = %.2f\n",
577            scenery.cur_elev,
578            f->get_Runway_altitude() * FEET_TO_METER,
579            f->get_Altitude() * FEET_TO_METER); */
580
581     // update "time"
582     t->update(f);
583
584     // Get elapsed time (in usec) for this past frame
585     elapsed = fgGetTimeInterval();
586     FG_LOG( FG_ALL, FG_DEBUG, 
587             "Elapsed time interval is = " << elapsed 
588             << ", previous remainder is = " << remainder );
589
590     // Calculate frame rate average
591 #ifdef FANCY_FRAME_COUNTER
592     /* old fps calculation */
593     if ( elapsed > 0 ) {
594         double tmp;
595         accum = 0.0;
596         for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
597             tmp = general.get_frame(i);
598             accum += tmp;
599             // printf("frame[%d] = %.2f\n", i, g->frames[i]);
600             general.set_frame(i+1,tmp);
601         }
602         tmp = 1000000.0 / (float)elapsed;
603         general.set_frame(0,tmp);
604         // printf("frame[0] = %.2f\n", general.frames[0]);
605         accum += tmp;
606         general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
607         // printf("ave = %.2f\n", general.frame_rate);
608     }
609 #else
610     if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
611         general.set_frame_rate( frames );
612         FG_LOG( FG_ALL, FG_DEBUG, 
613                 "--> Frame rate is = " << general.get_frame_rate() );
614         frames = 0;
615     }
616     last_time = t->get_cur_time();
617     ++frames;
618 #endif
619
620     // Run flight model
621     if ( ! use_signals ) {
622         // Calculate model iterations needed for next frame
623         elapsed += remainder;
624
625         multi_loop = (int)(((double)elapsed * 0.000001) * DEFAULT_MODEL_HZ);
626         remainder = elapsed - ((multi_loop*1000000) / DEFAULT_MODEL_HZ);
627         FG_LOG( FG_ALL, FG_DEBUG, 
628                 "Model iterations needed = " << multi_loop
629                 << ", new remainder = " << remainder );
630         
631         // flight model
632         if ( multi_loop > 0 ) {
633             fgUpdateTimeDepCalcs(multi_loop, remainder);
634         } else {
635             FG_LOG( FG_ALL, FG_INFO, "Elapsed time is zero ... we're zinging" );
636         }
637     }
638
639 #if ! defined( MACOS )
640     // Do any serial port work that might need to be done
641     fgSerialProcess();
642 #endif
643
644     // see if we need to load any new scenery tiles
645     global_tile_mgr.update();
646
647     // Process/manage pending events
648     global_events.Process();
649
650     // Run audio scheduler
651 #ifdef ENABLE_AUDIO_SUPPORT
652     if ( current_options.get_sound() && !audio_sched->not_working() ) {
653
654 #   ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
655
656         // note: all these factors are relative to the sample.  our
657         // sample format should really contain a conversion factor so
658         // that we can get prop speed right for arbitrary samples.
659         // Note that for normal-size props, there is a point at which
660         // the prop tips approach the speed of sound; that is a pretty
661         // strong limit to how fast the prop can go.
662
663         // multiplication factor is prime pitch control; add some log
664         // component for verisimilitude
665
666         double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
667         //fprintf(stderr, "pitch1: %f ", pitch);
668         if (controls.get_throttle(0) > 0.0 || f->v_rel_wind > 40.0) {
669             //fprintf(stderr, "rel_wind: %f ", f->v_rel_wind);
670             // only add relative wind and AoA if prop is moving
671             // or we're really flying at idle throttle
672             if (pitch < 5.4) {  // this needs tuning
673                 // prop tips not breaking sound barrier
674                 pitch += log(f->v_rel_wind + 0.8)/2;
675             } else {
676                 // prop tips breaking sound barrier
677                 pitch += log(f->v_rel_wind + 0.8)/10;
678             }
679             //fprintf(stderr, "pitch2: %f ", pitch);
680             //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
681
682             // Angle of Attack next... -x^3(e^x) is my best guess Just
683             // need to calculate some reasonable scaling factor and
684             // then clamp it on the positive aoa (neg adj) side
685             double aoa = f->get_Gamma_vert_rad() * 2.2;
686             double tmp = 3.0;
687             double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
688             if (aoa_adj < -0.8) aoa_adj = -0.8;
689             pitch += aoa_adj;
690             //fprintf(stderr, "pitch3: %f ", pitch);
691
692             // don't run at absurdly slow rates -- not realistic
693             // and sounds bad to boot.  :-)
694             if (pitch < 0.8) pitch = 0.8;
695         }
696         //fprintf(stderr, "pitch4: %f\n", pitch);
697
698         double volume = controls.get_throttle(0) * 1.15 + 0.3 +
699             log(f->v_rel_wind + 1.0)/14.0;
700         // fprintf(stderr, "volume: %f\n", volume);
701
702         pitch_envelope.setStep  ( 0, 0.01, pitch );
703         volume_envelope.setStep ( 0, 0.01, volume );
704
705 #   else
706
707        double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
708        pitch_envelope.setStep  ( 0, 0.01, param );
709        volume_envelope.setStep ( 0, 0.01, param );
710
711 #   endif // experimental throttle patch
712
713         audio_sched -> update();
714     }
715 #endif
716
717     // redraw display
718     fgRenderFrame();
719
720     FG_LOG( FG_ALL, FG_DEBUG, "" );
721 }
722
723
724 // This is the top level master main function that is registered as
725 // our idle funciton
726 //
727
728 // The first few passes take care of initialization things (a couple
729 // per pass) and once everything has been initialized fgMainLoop from
730 // then on.
731
732 static void fgIdleFunction ( void ) {
733     // printf("idle state == %d\n", idle_state);
734
735     if ( idle_state == 0 ) {
736         // Initialize the splash screen right away
737         if ( current_options.get_splash_screen() ) {
738             fgSplashInit();
739         }
740         
741         idle_state++;
742     } else if ( idle_state == 1 ) {
743         // Start the intro music
744 #if !defined(WIN32)
745         if ( current_options.get_intro_music() ) {
746             string lockfile = "/tmp/mpg123.running";
747             FGPath mp3file( current_options.get_fg_root() );
748             mp3file.append( "Sounds/intro.mp3" );
749
750             string command = "(touch " + lockfile + "; mpg123 "
751                 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
752                 + lockfile + ") &";
753             FG_LOG( FG_GENERAL, FG_INFO, 
754                     "Starting intro music: " << mp3file.str() );
755             system ( command.c_str() );
756         }
757 #endif
758
759         idle_state++;
760     } else if ( idle_state == 2 ) {
761         // These are a few miscellaneous things that aren't really
762         // "subsystems" but still need to be initialized.
763
764 #ifdef USE_GLIDE
765         if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
766             grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
767         }
768 #endif
769
770         idle_state++;
771     } else if ( idle_state == 3 ) {
772         // This is the top level init routine which calls all the
773         // other subsystem initialization routines.  If you are adding
774         // a subsystem to flight gear, its initialization call should
775         // located in this routine.
776         if( !fgInitSubsystems()) {
777             FG_LOG( FG_GENERAL, FG_ALERT,
778                     "Subsystem initializations failed ..." );
779             exit(-1);
780         }
781
782         idle_state++;
783     } else if ( idle_state == 4 ) {
784         // setup OpenGL view parameters
785         fgInitVisuals();
786
787         if ( use_signals ) {
788             // init timer routines, signals, etc.  Arrange for an alarm
789             // signal to be generated, etc.
790             fgInitTimeDepCalcs();
791         }
792
793         idle_state++;
794     } else if ( idle_state == 5 ) {
795
796         idle_state++;
797     } else if ( idle_state == 6 ) {
798         // Initialize audio support
799 #ifdef ENABLE_AUDIO_SUPPORT
800
801 #if !defined(WIN32)
802         if ( current_options.get_intro_music() ) {
803             // Let's wait for mpg123 to finish
804             string lockfile = "/tmp/mpg123.running";
805             struct stat stat_buf;
806
807             FG_LOG( FG_GENERAL, FG_INFO, 
808                     "Waiting for mpg123 player to finish ..." );
809             while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
810                 // file exist, wait ...
811                 sleep(1);
812                 FG_LOG( FG_GENERAL, FG_INFO, ".");
813             }
814             FG_LOG( FG_GENERAL, FG_INFO, "");
815         }
816 #endif // WIN32
817
818         audio_sched = new slScheduler ( 8000 );
819         audio_mixer = new smMixer;
820         audio_mixer -> setMasterVolume ( 80 ) ;  /* 80% of max volume. */
821         audio_sched -> setSafetyMargin ( 1.0 ) ;
822
823         FGPath slfile( current_options.get_fg_root() );
824         slfile.append( "Sounds/wasp.wav" );
825
826         s1 = new slSample ( (char *)slfile.c_str() );
827         FG_LOG( FG_GENERAL, FG_INFO,
828                 "Rate = " << s1 -> getRate()
829                 << "  Bps = " << s1 -> getBps()
830                 << "  Stereo = " << s1 -> getStereo() );
831         audio_sched -> loopSample ( s1 );
832
833         if ( audio_sched->not_working() ) {
834             // skip
835         } else {
836             pitch_envelope.setStep  ( 0, 0.01, 0.6 );
837             volume_envelope.setStep ( 0, 0.01, 0.6 );
838
839             audio_sched -> addSampleEnvelope( s1, 0, 0, &
840                                               pitch_envelope,
841                                               SL_PITCH_ENVELOPE );
842             audio_sched -> addSampleEnvelope( s1, 0, 1, 
843                                               &volume_envelope,
844                                               SL_VOLUME_ENVELOPE );
845         }
846
847         // strcpy(slfile, path);
848         // strcat(slfile, "thunder.wav");
849         // s2 -> loadFile ( slfile );
850         // s2 -> adjustVolume(0.5);
851         // audio_sched -> playSample ( s2 );
852 #endif
853
854         // sleep(1);
855         idle_state = 1000;
856     } 
857
858     if ( idle_state == 1000 ) {
859         // We've finished all our initialization steps, from now on we
860         // run the main loop.
861
862         fgMainLoop();
863     } else {
864         if ( current_options.get_splash_screen() == 1 ) {
865             fgSplashUpdate(0.0);
866         }
867     }
868 }
869
870 // options.cxx needs to see this for toggle_panel()
871 // Handle new window size or exposure
872 void fgReshape( int width, int height ) {
873     if ( ! current_options.get_panel_status() ) {
874         current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
875         xglViewport(0, 0 , (GLint)(width), (GLint)(height) );
876     } else {
877         current_view.set_win_ratio( (GLfloat) width / 
878                                     ((GLfloat) (height)*0.4232) );
879         xglViewport(0, (GLint)((height)*0.5768), (GLint)(width), 
880                     (GLint)((height)*0.4232) );
881     }
882
883     current_view.set_winWidth( width );
884     current_view.set_winHeight( height );
885     current_view.force_update_fov_math();
886
887     if ( idle_state == 1000 ) {
888         // yes we've finished all our initializations and are running
889         // the main loop, so this will now work without seg faulting
890         // the system.
891         current_view.UpdateViewParams();
892         if ( current_options.get_panel_status() ) {
893             FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
894         }
895     }
896 }
897
898
899 // Initialize GLUT and define a main window
900 int fgGlutInit( int *argc, char **argv ) {
901
902 #if !defined( MACOS )
903     // GLUT will extract all glut specific options so later on we only
904     // need wory about our own.
905     xglutInit(argc, argv);
906 #endif
907
908     // Define Display Parameters
909     xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
910
911     FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
912             current_options.get_xsize() << "x" << current_options.get_ysize() );
913
914     // Define initial window size
915     xglutInitWindowSize( current_options.get_xsize(),
916                          current_options.get_ysize() );
917
918     // Initialize windows
919     if ( current_options.get_game_mode() == 0 ) {
920         // Open the regular window
921         xglutCreateWindow("Flight Gear");
922 #ifndef GLUT_WRONG_VERSION
923     } else {
924         // Open the cool new 'game mode' window
925         char game_mode_str[256];
926         sprintf( game_mode_str, "width=%d height=%d bpp=32",
927                  current_options.get_xsize(),
928                  current_options.get_ysize() );
929
930         FG_LOG( FG_GENERAL, FG_INFO, 
931                 "game mode params = " << game_mode_str );
932         glutGameModeString( game_mode_str );
933         glutEnterGameMode();
934 #endif
935     }
936
937     // This seems to be the absolute earliest in the init sequence
938     // that these calls will return valid info.  Too bad it's after
939     // we've already created and sized out window. :-(
940     general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
941     general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
942     general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
943
944     FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
945
946 #if 0
947     // try to determine if we should adjust the initial default
948     // display resolution.  The options class defaults (is
949     // initialized) to 640x480.
950     string renderer = general.glRenderer;
951
952     // currently we only know how to deal with Mesa/Glide/Voodoo cards
953     if ( renderer.find( "Glide" ) != string::npos ) {
954         FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
955         if ( renderer.find( "FB/8" ) != string::npos ) {
956             // probably a voodoo-2
957             if ( renderer.find( "TMU/SLI" ) != string::npos ) {
958                 // probably two SLI'd Voodoo-2's
959                 current_options.set_xsize( 1024 );
960                 current_options.set_ysize( 768 );
961                 FG_LOG( FG_GENERAL, FG_INFO,
962                         "It looks like you have two sli'd voodoo-2's." << endl
963                         << "upgrading your win resolution to 1024 x 768" );
964                 glutReshapeWindow(1024, 768);
965             } else {
966                 // probably a single non-SLI'd Voodoo-2
967                 current_options.set_xsize( 800 );
968                 current_options.set_ysize( 600 );
969                 FG_LOG( FG_GENERAL, FG_INFO,
970                         "It looks like you have a voodoo-2." << endl
971                         << "upgrading your win resolution to 800 x 600" );
972                 glutReshapeWindow(800, 600);
973             }
974         } else if ( renderer.find( "FB/2" ) != string::npos ) {
975             // probably a voodoo-1, stick with the default
976         }
977     } else {
978         // we have no special knowledge of this card, stick with the default
979     }
980 #endif
981
982     return(1);
983 }
984
985
986 // Initialize GLUT event handlers
987 int fgGlutInitEvents( void ) {
988     // call fgReshape() on window resizes
989     xglutReshapeFunc( fgReshape );
990
991     // call GLUTkey() on keyboard event
992     xglutKeyboardFunc( GLUTkey );
993     glutSpecialFunc( GLUTspecialkey );
994
995     // call guiMouseFunc() whenever our little rodent is used
996     glutMouseFunc ( guiMouseFunc );
997     glutMotionFunc (guiMotionFunc );
998     glutPassiveMotionFunc (guiMotionFunc );
999
1000     // call fgMainLoop() whenever there is
1001     // nothing else to do
1002     xglutIdleFunc( fgIdleFunction );
1003
1004     // draw the scene
1005     xglutDisplayFunc( fgRenderFrame );
1006
1007     return(1);
1008 }
1009
1010
1011 // Main ...
1012 int main( int argc, char **argv ) {
1013
1014 #if defined( MACOS )
1015     argc = ccommand( &argv );
1016 #endif
1017
1018 #ifdef HAVE_BC5PLUS
1019     _control87(MCW_EM, MCW_EM);  /* defined in float.h */
1020 #endif
1021
1022     // set default log levels
1023     fglog().setLogLevels( FG_ALL, FG_INFO );
1024
1025     FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear:  Version " << VERSION << endl );
1026
1027     // seed the random number generater
1028     fg_srandom();
1029
1030     // Load the configuration parameters
1031     if ( !fgInitConfig(argc, argv) ) {
1032         FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1033         exit(-1);
1034     }
1035
1036     // Initialize the Window/Graphics environment.
1037     if( !fgGlutInit(&argc, argv) ) {
1038         FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1039         exit(-1);
1040     }
1041
1042     // Initialize the various GLUT Event Handlers.
1043     if( !fgGlutInitEvents() ) {
1044         FG_LOG( FG_GENERAL, FG_ALERT, 
1045                 "GLUT event handler initialization failed ..." );
1046         exit(-1);
1047     }
1048
1049     // Initialize ssg (from plib)
1050     ssgInit();
1051
1052     // Initialize the user interface (we need to do this before
1053     // passing off control to glut and before fgInitGeneral to get our
1054     // fonts !!!
1055     guiInit();
1056
1057     // Do some quick general initializations
1058     if( !fgInitGeneral()) {
1059         FG_LOG( FG_GENERAL, FG_ALERT, 
1060                 "General initializations failed ..." );
1061         exit(-1);
1062     }
1063
1064     //
1065     // some ssg test stuff (requires data from the plib source
1066     // distribution) specifically from the ssg tux example
1067     //
1068
1069     ssgModelPath( "/stage/pinky01/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1070     ssgTexturePath( "/stage/pinky01/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1071
1072     scene = new ssgRoot;
1073     penguin = new ssgTransform;
1074
1075     ssgEntity *tux_obj = ssgLoadAC( "tuxedo.ac" );
1076     penguin->addKid( tux_obj );
1077     ssgFlatten( tux_obj );
1078     ssgStripify( penguin );
1079
1080     scene->addKid( penguin );
1081
1082     // pass control off to the master GLUT event handler
1083     glutMainLoop();
1084
1085     // we never actually get here ... but to avoid compiler warnings,
1086     // etc.
1087     return 0;
1088 }