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