1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson for OpenGL, started May 1997.
5 // Copyright (C) 1997 - 1999 Curtis L. Olson - curt@flightgear.org
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.
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.
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.
24 #define MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
31 #ifdef FG_MATH_EXCEPTION_CLASH
50 #ifdef HAVE_SYS_STAT_H
51 # include <sys/stat.h> /* for stat() */
55 # include <unistd.h> /* for stat() */
58 #include <pu.h> // plib include
59 #include <ssg.h> // plib include
61 #ifdef ENABLE_AUDIO_SUPPORT
62 # include <sl.h> // plib include
63 # include <sm.h> // plib include
66 #include <Include/fg_constants.h> // for VERSION
67 #include <Include/general.hxx>
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>
75 #include <Autopilot/autopilot.hxx>
76 #include <Cockpit/cockpit.hxx>
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>
93 #include "fg_init.hxx"
94 #include "keyboard.hxx"
95 #include "options.hxx"
98 #include "fg_serial.hxx"
101 // -dw- use custom sioux settings so I can see output window
104 # include <sioux.h> // settings for output window
106 # include <console.h>
110 // This is a record containing a bit of global housekeeping information
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;
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;
133 ssgRoot *scene = NULL;
134 ssgBranch *terrain = NULL;
135 ssgSelector *penguin_sel = NULL;
136 ssgTransform *penguin_pos = NULL;
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
145 // glutlib parses for:
147 // -direct (invalid in Win32)
151 // -indirect (invalid in Win32)
154 // Note that glutlib depends upon strings while this program's
155 // option parser wants only initial characters followed by numbers
160 // fgInitVisuals() -- Initialize various GL/view parameters
161 static void fgInitVisuals( void ) {
164 l = &cur_light_params;
166 #ifndef GLUT_WRONG_VERSION
167 // Go full screen if requested ...
168 if ( current_options.get_fullscreen() ) {
173 // If enabled, normal vectors specified with glNormal are scaled
174 // to unit length after transformation. See glNormal.
175 // xglEnable( GL_NORMALIZE );
177 xglEnable( GL_LIGHTING );
178 xglEnable( GL_LIGHT0 );
179 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
182 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
183 ssgGetLight( 0 ) -> setPosition( sunpos );
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 );
194 if ( current_options.get_wireframe() ) {
196 xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
199 // This is the default anyways, but it can't hurt
200 xglFrontFace ( GL_CCW );
203 // xglEnable(GL_POINT_SMOOTH);
204 // xglEnable(GL_LINE_SMOOTH);
205 // xglEnable(GL_POLYGON_SMOOTH);
210 // Draw a basic instrument panel
211 static void fgUpdateInstrViewParams( void ) {
215 fgVIEW *v = ¤t_view;
217 xglViewport(0, 0 , (GLint)(v->winWidth), (GLint)(v->winHeight) / 2);
219 xglMatrixMode(GL_PROJECTION);
223 gluOrtho2D(0, 640, 0, 480);
224 xglMatrixMode(GL_MODELVIEW);
228 xglColor3f(1.0, 1.0, 1.0);
231 xglDisable(GL_DEPTH_TEST);
232 xglDisable(GL_LIGHTING);
235 xglColor3f (0.5, 0.5, 0.5);
238 xglVertex2f(0.0, 0.00);
239 xglVertex2f(0.0, 480.0);
240 xglVertex2f(640.0,480.0);
241 xglVertex2f(640.0, 0.0);
244 xglRectf(0.0,0.0, 640, 480);
245 xglEnable(GL_DEPTH_TEST);
246 xglEnable(GL_LIGHTING);
247 xglMatrixMode(GL_PROJECTION);
249 xglMatrixMode(GL_MODELVIEW);
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 = ¤t_view;
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;
268 if ( idle_state != 1000 ) {
269 // still initializing, draw the splash screen
270 if ( current_options.get_splash_screen() == 1 ) {
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.
278 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
279 // FG_Altitude * FEET_TO_METER);
281 // this is just a temporary hack, to make me understand Pui
282 // timerText -> setLabel (ctime (&t->cur_time));
285 // update view volume parameters
286 v->UpdateViewParams();
288 // set the sun position
289 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
292 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
293 ssgGetLight( 0 ) -> setPosition( sunpos );
295 clear_mask = GL_DEPTH_BUFFER_BIT;
296 if ( current_options.get_wireframe() ) {
297 clear_mask |= GL_COLOR_BUFFER_BIT;
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;
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;
313 xglClear( clear_mask );
315 // Tell GL we are switching to model view parameters
316 xglMatrixMode(GL_MODELVIEW);
317 // xglLoadIdentity();
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() ) {
329 // setup transformation for drawing astronomical objects
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 );
340 // draw stars and planets
342 xglEnable( GL_CULL_FACE ); // for moon
343 //xglEnable(GL_DEPTH_TEST);
344 SolarSystem::theSolarSystem->draw();
349 if ( current_options.get_shading() ) {
350 xglShadeModel( GL_SMOOTH );
352 xglShadeModel( GL_FLAT );
354 xglEnable( GL_DEPTH_TEST );
355 if ( current_options.get_fog() > 0 ) {
357 xglFogi( GL_FOG_MODE, GL_EXP2 );
358 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
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 );
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);
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);
383 // global_tile_mgr.render();
387 xglMatrixMode( GL_PROJECTION );
389 ssgSetFOV( current_options.get_fov(), 0.0f );
391 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
394 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
395 // << current_weather.get_visibility() );
398 // ssgSetNearFar( 10.0f, current_weather.get_visibility() );
399 ssgSetNearFar( 10.0f, 100000.0f );
401 // ssgSetNearFar( 0.5f, current_weather.get_visibility() );
402 ssgSetNearFar( 0.5f, 100000.0f );
407 if ( current_view.view_mode == FGView::FG_VIEW_FIRST_PERSON ) {
408 // select current view matrix
409 sgCopyMat4( sgVIEW, current_view.sgVIEW );
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();
421 // enable TuX and set up his position and orientation
422 penguin_sel->select(1);
425 sgMakeTransMat4( sgTRANS,
426 current_view.view_pos.x(),
427 current_view.view_pos.y(),
428 current_view.view_pos.z() );
432 // sgMultMat4( sgTMP, current_view.sgUP, sgTRANS );
433 // sgMultMat4( sgTUX, current_view.sgLARC_TO_SSG, sgTMP );
434 sgMultMat4( sgTUX, current_view.sgVIEW_ROT, sgTRANS );
437 sgSetCoord( &tuxpos, sgTUX );
438 penguin_pos->setTransform( &tuxpos );
441 ssgSetCamera( sgVIEW );
443 // position tile nodes and update range selectors
444 global_tile_mgr.prep_ssg_nodes();
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();
453 // draw the ssg scene
454 ssgCullAndDraw( scene );
456 xglDisable( GL_TEXTURE_2D );
457 xglDisable( GL_FOG );
459 // display HUD && Panel
460 xglDisable( GL_CULL_FACE );
463 // We can do translucent menus, so why not. :-)
464 xglEnable ( GL_BLEND ) ;
465 xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
467 xglDisable ( GL_BLEND ) ;
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 = ¤t_view;
484 // update the flight model
485 if ( multi_loop < 0 ) {
486 multi_loop = DEFAULT_MULTILOOP;
489 if ( !t->getPause() ) {
490 // run Autopilot system
493 // printf("updating flight model x %d\n", multi_loop);
494 fgFDMUpdate( current_options.get_flight_model(),
495 cur_fdm_state, multi_loop, remainder );
497 fgFDMUpdate( current_options.get_flight_model(),
498 cur_fdm_state, 0, remainder );
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() );
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 );
512 v->inc_view_offset( -0.01 );
515 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
516 v->inc_view_offset( -0.01 );
518 v->inc_view_offset( 0.01 );
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 );
529 double tmp = -(l->sun_rotation + FG_PI)
530 - (f->get_Psi() - v->get_view_offset() );
531 while ( tmp < 0.0 ) {
534 while ( tmp > FG_2PI ) {
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); */
544 void fgInitTimeDepCalcs( void ) {
547 // #ifdef HAVE_SETITIMER
548 // fgTimerInit( 1.0 / DEFAULT_TIMER_HZ, fgUpdateTimeDepCalcs );
549 // #endif HAVE_SETITIMER
552 static const double alt_adjust_ft = 3.758099;
553 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
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 ) {
560 static long remainder = 0;
561 long elapsed, multi_loop;
562 #ifdef FANCY_FRAME_COUNTER
566 static time_t last_time = 0;
567 static int frames = 0;
568 #endif // FANCY_FRAME_COUNTER
570 f = current_aircraft.fdm_state;
571 t = FGTime::cur_time_params;
573 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
574 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
576 #if defined( ENABLE_PLIB_JOYSTICK )
577 // Read joystick and update control settings
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.
585 current_weather.Update();
587 // Fix elevation. I'm just sticking this here for now, it should
588 // probably move eventually
590 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
592 f->get_Runway_altitude() * FEET_TO_METER,
593 f->get_Altitude() * FEET_TO_METER); */
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 );
606 FG_LOG( FG_ALL, FG_DEBUG,
607 "<*> resetting altitude to "
608 << f->get_Altitude() * FEET_TO_METER << " meters" );
610 fgFDMSetGroundElevation( current_options.get_flight_model(),
611 scenery.cur_elev ); // meters
614 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
616 f->get_Runway_altitude() * FEET_TO_METER,
617 f->get_Altitude() * FEET_TO_METER); */
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 );
628 // Calculate frame rate average
629 #ifdef FANCY_FRAME_COUNTER
630 /* old fps calculation */
634 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
635 tmp = general.get_frame(i);
637 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
638 general.set_frame(i+1,tmp);
640 tmp = 1000000.0 / (float)elapsed;
641 general.set_frame(0,tmp);
642 // printf("frame[0] = %.2f\n", general.frames[0]);
644 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
645 // printf("ave = %.2f\n", general.frame_rate);
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() );
654 last_time = t->get_cur_time();
659 if ( ! use_signals ) {
660 // Calculate model iterations needed for next frame
661 elapsed += remainder;
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 );
670 if ( multi_loop > 0 ) {
671 fgUpdateTimeDepCalcs(multi_loop, remainder);
673 FG_LOG( FG_ALL, FG_INFO, "Elapsed time is zero ... we're zinging" );
677 #if ! defined( MACOS )
678 // Do any serial port work that might need to be done
682 // see if we need to load any new scenery tiles
683 global_tile_mgr.update();
685 // Process/manage pending events
686 global_events.Process();
688 // Run audio scheduler
689 #ifdef ENABLE_AUDIO_SUPPORT
690 if ( current_options.get_sound() && !audio_sched->not_working() ) {
692 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
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.
701 // multiplication factor is prime pitch control; add some log
702 // component for verisimilitude
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;
714 // prop tips breaking sound barrier
715 pitch += log(f->v_rel_wind + 0.8)/10;
717 //fprintf(stderr, "pitch2: %f ", pitch);
718 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
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;
725 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
726 if (aoa_adj < -0.8) aoa_adj = -0.8;
728 //fprintf(stderr, "pitch3: %f ", pitch);
730 // don't run at absurdly slow rates -- not realistic
731 // and sounds bad to boot. :-)
732 if (pitch < 0.8) pitch = 0.8;
734 //fprintf(stderr, "pitch4: %f\n", pitch);
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);
740 pitch_envelope.setStep ( 0, 0.01, pitch );
741 volume_envelope.setStep ( 0, 0.01, volume );
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 );
749 # endif // experimental throttle patch
751 audio_sched -> update();
758 FG_LOG( FG_ALL, FG_DEBUG, "" );
762 // This is the top level master main function that is registered as
766 // The first few passes take care of initialization things (a couple
767 // per pass) and once everything has been initialized fgMainLoop from
770 static void fgIdleFunction ( void ) {
771 // printf("idle state == %d\n", idle_state);
773 if ( idle_state == 0 ) {
774 // Initialize the splash screen right away
775 if ( current_options.get_splash_screen() ) {
780 } else if ( idle_state == 1 ) {
781 // Start the intro music
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" );
788 string command = "(touch " + lockfile + "; mpg123 "
789 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
791 FG_LOG( FG_GENERAL, FG_INFO,
792 "Starting intro music: " << mp3file.str() );
793 system ( command.c_str() );
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.
803 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
804 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
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 ..." );
821 } else if ( idle_state == 4 ) {
822 // setup OpenGL view parameters
826 // init timer routines, signals, etc. Arrange for an alarm
827 // signal to be generated, etc.
828 fgInitTimeDepCalcs();
832 } else if ( idle_state == 5 ) {
835 } else if ( idle_state == 6 ) {
836 // Initialize audio support
837 #ifdef ENABLE_AUDIO_SUPPORT
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;
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 ...
850 FG_LOG( FG_GENERAL, FG_INFO, ".");
852 FG_LOG( FG_GENERAL, FG_INFO, "");
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 ) ;
861 FGPath slfile( current_options.get_fg_root() );
862 slfile.append( "Sounds/wasp.wav" );
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 );
871 if ( audio_sched->not_working() ) {
874 pitch_envelope.setStep ( 0, 0.01, 0.6 );
875 volume_envelope.setStep ( 0, 0.01, 0.6 );
877 audio_sched -> addSampleEnvelope( s1, 0, 0, &
880 audio_sched -> addSampleEnvelope( s1, 0, 1,
882 SL_VOLUME_ENVELOPE );
885 // strcpy(slfile, path);
886 // strcat(slfile, "thunder.wav");
887 // s2 -> loadFile ( slfile );
888 // s2 -> adjustVolume(0.5);
889 // audio_sched -> playSample ( s2 );
896 if ( idle_state == 1000 ) {
897 // We've finished all our initialization steps, from now on we
898 // run the main loop.
902 if ( current_options.get_splash_screen() == 1 ) {
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) );
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) );
921 current_view.set_winWidth( width );
922 current_view.set_winHeight( height );
923 current_view.force_update_fov_math();
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
929 current_view.UpdateViewParams();
930 if ( current_options.get_panel_status() ) {
931 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
937 // Initialize GLUT and define a main window
938 int fgGlutInit( int *argc, char **argv ) {
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);
946 // Define Display Parameters
947 xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
949 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
950 current_options.get_xsize() << "x" << current_options.get_ysize() );
952 // Define initial window size
953 xglutInitWindowSize( current_options.get_xsize(),
954 current_options.get_ysize() );
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
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() );
968 FG_LOG( FG_GENERAL, FG_INFO,
969 "game mode params = " << game_mode_str );
970 glutGameModeString( game_mode_str );
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 ) );
982 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
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;
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);
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);
1012 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1013 // probably a voodoo-1, stick with the default
1016 // we have no special knowledge of this card, stick with the default
1024 // Initialize GLUT event handlers
1025 int fgGlutInitEvents( void ) {
1026 // call fgReshape() on window resizes
1027 xglutReshapeFunc( fgReshape );
1029 // call GLUTkey() on keyboard event
1030 xglutKeyboardFunc( GLUTkey );
1031 glutSpecialFunc( GLUTspecialkey );
1033 // call guiMouseFunc() whenever our little rodent is used
1034 glutMouseFunc ( guiMouseFunc );
1035 glutMotionFunc (guiMotionFunc );
1036 glutPassiveMotionFunc (guiMotionFunc );
1038 // call fgMainLoop() whenever there is
1039 // nothing else to do
1040 xglutIdleFunc( fgIdleFunction );
1043 xglutDisplayFunc( fgRenderFrame );
1050 int main( int argc, char **argv ) {
1052 #if defined( MACOS )
1053 argc = ccommand( &argv );
1057 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1060 // set default log levels
1061 fglog().setLogLevels( FG_ALL, FG_INFO );
1063 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1065 // seed the random number generater
1068 // Load the configuration parameters
1069 if ( !fgInitConfig(argc, argv) ) {
1070 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1074 // Initialize the Window/Graphics environment.
1075 if( !fgGlutInit(&argc, argv) ) {
1076 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1080 // Initialize the various GLUT Event Handlers.
1081 if( !fgGlutInitEvents() ) {
1082 FG_LOG( FG_GENERAL, FG_ALERT,
1083 "GLUT event handler initialization failed ..." );
1087 // Initialize ssg (from plib)
1090 // Initialize the user interface (we need to do this before
1091 // passing off control to glut and before fgInitGeneral to get our
1095 // Do some quick general initializations
1096 if( !fgInitGeneral()) {
1097 FG_LOG( FG_GENERAL, FG_ALERT,
1098 "General initializations failed ..." );
1103 // some ssg test stuff (requires data from the plib source
1104 // distribution) specifically from the ssg tux example
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/" );
1112 scene = new ssgRoot;
1113 terrain = new ssgBranch;
1114 terrain->setName( "Terrain" );
1115 penguin_sel = new ssgSelector;
1116 penguin_pos = new ssgTransform;
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 );
1124 scene->addKid( terrain );
1125 scene->addKid( penguin_sel );
1127 // pass control off to the master GLUT event handler
1130 // we never actually get here ... but to avoid compiler warnings,