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