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