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>
85 #include <Network/network.h>
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 #include <Weather/weather.hxx>
96 #include "fg_init.hxx"
97 #include "keyboard.hxx"
98 #include "options.hxx"
101 #include "fg_serial.hxx"
104 // -dw- use custom sioux settings so I can see output window
107 # include <sioux.h> // settings for output window
109 # include <console.h>
113 // This is a record containing a bit of global housekeeping information
116 // Specify our current idle function state. This is used to run all
117 // our initializations out of the glutIdleLoop() so that we can get a
118 // splash screen up and running right away.
119 static int idle_state = 0;
124 // Global structures for the Audio library
125 #ifdef ENABLE_AUDIO_SUPPORT
126 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
127 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
128 slScheduler *audio_sched;
129 smMixer *audio_mixer;
136 ssgRoot *scene = NULL;
137 ssgBranch *terrain = NULL;
138 ssgSelector *penguin_sel = NULL;
139 ssgTransform *penguin_pos = NULL;
142 // The following defines flight gear options. Because glutlib will also
143 // want to parse its own options, those options must not be included here
144 // or they will get parsed by the main program option parser. Hence case
145 // is significant for any option added that might be in conflict with
148 // glutlib parses for:
150 // -direct (invalid in Win32)
154 // -indirect (invalid in Win32)
157 // Note that glutlib depends upon strings while this program's
158 // option parser wants only initial characters followed by numbers
163 // fgInitVisuals() -- Initialize various GL/view parameters
164 static void fgInitVisuals( void ) {
167 l = &cur_light_params;
169 #ifndef GLUT_WRONG_VERSION
170 // Go full screen if requested ...
171 if ( current_options.get_fullscreen() ) {
176 // If enabled, normal vectors specified with glNormal are scaled
177 // to unit length after transformation. See glNormal.
178 // xglEnable( GL_NORMALIZE );
180 xglEnable( GL_LIGHTING );
181 xglEnable( GL_LIGHT0 );
182 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
185 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
186 ssgGetLight( 0 ) -> setPosition( sunpos );
188 // xglFogi (GL_FOG_MODE, GL_LINEAR);
189 xglFogi (GL_FOG_MODE, GL_EXP2);
190 if ( (current_options.get_fog() == 1) ||
191 (current_options.get_shading() == 0) ) {
192 // if fastest fog requested, or if flat shading force fastest
193 xglHint ( GL_FOG_HINT, GL_FASTEST );
194 } else if ( current_options.get_fog() == 2 ) {
195 xglHint ( GL_FOG_HINT, GL_NICEST );
197 if ( current_options.get_wireframe() ) {
199 xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
202 // This is the default anyways, but it can't hurt
203 xglFrontFace ( GL_CCW );
206 // xglEnable(GL_POINT_SMOOTH);
207 // xglEnable(GL_LINE_SMOOTH);
208 // xglEnable(GL_POLYGON_SMOOTH);
213 // Draw a basic instrument panel
214 static void fgUpdateInstrViewParams( void ) {
218 fgVIEW *v = ¤t_view;
220 xglViewport(0, 0 , (GLint)(v->winWidth), (GLint)(v->winHeight) / 2);
222 xglMatrixMode(GL_PROJECTION);
226 gluOrtho2D(0, 640, 0, 480);
227 xglMatrixMode(GL_MODELVIEW);
231 xglColor3f(1.0, 1.0, 1.0);
234 xglDisable(GL_DEPTH_TEST);
235 xglDisable(GL_LIGHTING);
238 xglColor3f (0.5, 0.5, 0.5);
241 xglVertex2f(0.0, 0.00);
242 xglVertex2f(0.0, 480.0);
243 xglVertex2f(640.0,480.0);
244 xglVertex2f(640.0, 0.0);
247 xglRectf(0.0,0.0, 640, 480);
248 xglEnable(GL_DEPTH_TEST);
249 xglEnable(GL_LIGHTING);
250 xglMatrixMode(GL_PROJECTION);
252 xglMatrixMode(GL_MODELVIEW);
258 // Update all Visuals (redraws anything graphics related)
259 static void fgRenderFrame( void ) {
260 fgLIGHT *l = &cur_light_params;
261 FGTime *t = FGTime::cur_time_params;
262 FGView *v = ¤t_view;
265 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
266 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
267 GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
268 // GLfloat mat_shininess[] = { 10.0 };
269 GLbitfield clear_mask;
271 if ( idle_state != 1000 ) {
272 // still initializing, draw the splash screen
273 if ( current_options.get_splash_screen() == 1 ) {
277 // idle_state is now 1000 meaning we've finished all our
278 // initializations and are running the main loop, so this will
279 // now work without seg faulting the system.
281 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
282 // FG_Altitude * FEET_TO_METER);
284 // this is just a temporary hack, to make me understand Pui
285 // timerText -> setLabel (ctime (&t->cur_time));
288 // update view volume parameters
289 v->UpdateViewParams();
291 // set the sun position
292 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
295 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
296 ssgGetLight( 0 ) -> setPosition( sunpos );
298 clear_mask = GL_DEPTH_BUFFER_BIT;
299 if ( current_options.get_wireframe() ) {
300 clear_mask |= GL_COLOR_BUFFER_BIT;
302 if ( current_options.get_panel_status() ) {
303 // we can't clear the screen when the panel is active
304 } else if ( current_options.get_skyblend() ) {
305 if ( current_options.get_textures() ) {
306 // glClearColor(black[0], black[1], black[2], black[3]);
307 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
308 l->adj_fog_color[2], l->adj_fog_color[3]);
309 clear_mask |= GL_COLOR_BUFFER_BIT;
312 glClearColor(l->sky_color[0], l->sky_color[1],
313 l->sky_color[2], l->sky_color[3]);
314 clear_mask |= GL_COLOR_BUFFER_BIT;
316 xglClear( clear_mask );
318 // Tell GL we are switching to model view parameters
319 xglMatrixMode(GL_MODELVIEW);
320 // xglLoadIdentity();
323 xglDisable( GL_DEPTH_TEST );
324 xglDisable( GL_LIGHTING );
325 xglDisable( GL_CULL_FACE );
326 xglDisable( GL_FOG );
327 xglShadeModel( GL_SMOOTH );
328 if ( current_options.get_skyblend() ) {
332 // setup transformation for drawing astronomical objects
334 // Translate to view position
335 Point3D view_pos = v->get_view_pos();
336 xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
337 // Rotate based on gst (sidereal time)
338 // note: constant should be 15.041085, Curt thought it was 15
339 angle = t->getGst() * 15.041085;
340 // printf("Rotating astro objects by %.2f degrees\n",angle);
341 xglRotatef( angle, 0.0, 0.0, -1.0 );
343 // draw stars and planets
345 xglEnable( GL_CULL_FACE ); // for moon
346 //xglEnable(GL_DEPTH_TEST);
347 SolarSystem::theSolarSystem->draw();
352 if ( current_options.get_shading() ) {
353 xglShadeModel( GL_SMOOTH );
355 xglShadeModel( GL_FLAT );
357 xglEnable( GL_DEPTH_TEST );
358 if ( current_options.get_fog() > 0 ) {
360 xglFogi( GL_FOG_MODE, GL_EXP2 );
361 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
363 // set lighting parameters
364 xglLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
365 xglLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
366 // xglLightfv(GL_LIGHT0, GL_SPECULAR, white );
368 if ( current_options.get_textures() ) {
369 // texture parameters
370 xglEnable( GL_TEXTURE_2D );
371 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
372 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
373 // set base color (I don't think this is doing anything here)
374 xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
375 xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
376 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
377 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
379 xglDisable( GL_TEXTURE_2D );
380 xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
381 xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
382 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
383 // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
386 // global_tile_mgr.render();
390 xglMatrixMode( GL_PROJECTION );
392 ssgSetFOV( current_options.get_fov(), 0.0f );
394 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
397 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
398 // << current_weather.get_visibility() );
401 // ssgSetNearFar( 10.0f, current_weather.get_visibility() );
402 ssgSetNearFar( 10.0f, 100000.0f );
404 // ssgSetNearFar( 0.5f, current_weather.get_visibility() );
405 ssgSetNearFar( 0.5f, 100000.0f );
410 if ( current_view.view_mode == FGView::FG_VIEW_FIRST_PERSON ) {
411 // select current view matrix
412 sgCopyMat4( sgVIEW, current_view.sgVIEW );
415 penguin_sel->select(0);
416 } else if ( current_view.view_mode == FGView::FG_VIEW_FOLLOW ) {
417 // select view matrix from front of view matrix queue
418 FGMat4Wrapper tmp = current_view.follow.front();
419 sgCopyMat4( sgVIEW, tmp.m );
420 while ( current_view.follow.size() > 10 ) {
421 current_view.follow.pop_front();
424 // enable TuX and set up his position and orientation
425 penguin_sel->select(1);
428 sgMakeTransMat4( sgTRANS,
429 current_view.view_pos.x(),
430 current_view.view_pos.y(),
431 current_view.view_pos.z() );
435 // sgMultMat4( sgTMP, current_view.sgUP, sgTRANS );
436 // sgMultMat4( sgTUX, current_view.sgLARC_TO_SSG, sgTMP );
437 sgMultMat4( sgTUX, current_view.sgVIEW_ROT, sgTRANS );
440 sgSetCoord( &tuxpos, sgTUX );
441 penguin_pos->setTransform( &tuxpos );
444 ssgSetCamera( sgVIEW );
446 // position tile nodes and update range selectors
447 global_tile_mgr.prep_ssg_nodes();
449 // force the default state so ssg can get back on track if
450 // we've changed things elsewhere
451 FGMaterialSlot m_slot;
452 FGMaterialSlot *m_ptr = &m_slot;
453 if ( material_mgr.find( "Default", m_ptr ) );
454 m_ptr->get_state()->force();
456 // draw the ssg scene
457 ssgCullAndDraw( scene );
459 xglDisable( GL_TEXTURE_2D );
460 xglDisable( GL_FOG );
462 // display HUD && Panel
463 xglDisable( GL_CULL_FACE );
466 // We can do translucent menus, so why not. :-)
467 xglEnable ( GL_BLEND ) ;
468 xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
470 xglDisable ( GL_BLEND ) ;
479 // Update internal time dependent calculations (i.e. flight model)
480 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
481 FGInterface *f = current_aircraft.fdm_state;
482 fgLIGHT *l = &cur_light_params;
483 FGTime *t = FGTime::cur_time_params;
484 FGView *v = ¤t_view;
487 // update the flight model
488 if ( multi_loop < 0 ) {
489 multi_loop = DEFAULT_MULTILOOP;
492 if ( !t->getPause() ) {
493 // run Autopilot system
496 // printf("updating flight model x %d\n", multi_loop);
497 fgFDMUpdate( current_options.get_flight_model(),
498 cur_fdm_state, multi_loop, remainder );
500 fgFDMUpdate( current_options.get_flight_model(),
501 cur_fdm_state, 0, remainder );
504 // update the view angle
505 for ( i = 0; i < multi_loop; i++ ) {
506 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
507 v->set_view_offset( v->get_goal_view_offset() );
510 // move v->view_offset towards v->goal_view_offset
511 if ( v->get_goal_view_offset() > v->get_view_offset() ) {
512 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
513 v->inc_view_offset( 0.01 );
515 v->inc_view_offset( -0.01 );
518 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
519 v->inc_view_offset( -0.01 );
521 v->inc_view_offset( 0.01 );
524 if ( v->get_view_offset() > FG_2PI ) {
525 v->inc_view_offset( -FG_2PI );
526 } else if ( v->get_view_offset() < 0 ) {
527 v->inc_view_offset( FG_2PI );
532 double tmp = -(l->sun_rotation + FG_PI)
533 - (f->get_Psi() - v->get_view_offset() );
534 while ( tmp < 0.0 ) {
537 while ( tmp > FG_2PI ) {
540 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
541 FG_Psi * RAD_TO_DEG, v->view_offset * RAD_TO_DEG,
542 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
547 void fgInitTimeDepCalcs( void ) {
550 // #ifdef HAVE_SETITIMER
551 // fgTimerInit( 1.0 / DEFAULT_TIMER_HZ, fgUpdateTimeDepCalcs );
552 // #endif HAVE_SETITIMER
555 static const double alt_adjust_ft = 3.758099;
556 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
558 // What should we do when we have nothing else to do? Let's get ready
559 // for the next move and update the display?
560 static void fgMainLoop( void ) {
563 static long remainder = 0;
564 long elapsed, multi_loop;
565 #ifdef FANCY_FRAME_COUNTER
569 static time_t last_time = 0;
570 static int frames = 0;
571 #endif // FANCY_FRAME_COUNTER
573 f = current_aircraft.fdm_state;
574 t = FGTime::cur_time_params;
576 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
577 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
579 #if defined( ENABLE_PLIB_JOYSTICK )
580 // Read joystick and update control settings
582 #elif defined( ENABLE_GLUT_JOYSTICK )
583 // Glut joystick support works by feeding a joystick handler
584 // function to glut. This is taken care of once in the joystick
585 // init routine and we don't have to worry about it again.
588 current_weather.Update();
590 // Fix elevation. I'm just sticking this here for now, it should
591 // probably move eventually
593 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
595 f->get_Runway_altitude() * FEET_TO_METER,
596 f->get_Altitude() * FEET_TO_METER); */
598 if ( scenery.cur_elev > -9990 ) {
599 if ( f->get_Altitude() * FEET_TO_METER <
600 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
601 // now set aircraft altitude above ground
602 printf("Current Altitude = %.2f < %.2f forcing to %.2f\n",
603 f->get_Altitude() * FEET_TO_METER,
604 scenery.cur_elev + alt_adjust_m - 3.0,
605 scenery.cur_elev + alt_adjust_m );
606 fgFDMForceAltitude( current_options.get_flight_model(),
607 scenery.cur_elev + alt_adjust_m );
609 FG_LOG( FG_ALL, FG_DEBUG,
610 "<*> resetting altitude to "
611 << f->get_Altitude() * FEET_TO_METER << " meters" );
613 fgFDMSetGroundElevation( current_options.get_flight_model(),
614 scenery.cur_elev ); // meters
617 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
619 f->get_Runway_altitude() * FEET_TO_METER,
620 f->get_Altitude() * FEET_TO_METER); */
625 // Get elapsed time (in usec) for this past frame
626 elapsed = fgGetTimeInterval();
627 FG_LOG( FG_ALL, FG_DEBUG,
628 "Elapsed time interval is = " << elapsed
629 << ", previous remainder is = " << remainder );
631 // Calculate frame rate average
632 #ifdef FANCY_FRAME_COUNTER
633 /* old fps calculation */
637 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
638 tmp = general.get_frame(i);
640 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
641 general.set_frame(i+1,tmp);
643 tmp = 1000000.0 / (float)elapsed;
644 general.set_frame(0,tmp);
645 // printf("frame[0] = %.2f\n", general.frames[0]);
647 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
648 // printf("ave = %.2f\n", general.frame_rate);
651 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
652 general.set_frame_rate( frames );
653 FG_LOG( FG_ALL, FG_DEBUG,
654 "--> Frame rate is = " << general.get_frame_rate() );
657 last_time = t->get_cur_time();
662 if ( ! use_signals ) {
663 // Calculate model iterations needed for next frame
664 elapsed += remainder;
666 multi_loop = (int)(((double)elapsed * 0.000001) * DEFAULT_MODEL_HZ);
667 remainder = elapsed - ((multi_loop*1000000) / DEFAULT_MODEL_HZ);
668 FG_LOG( FG_ALL, FG_DEBUG,
669 "Model iterations needed = " << multi_loop
670 << ", new remainder = " << remainder );
673 if ( multi_loop > 0 ) {
674 fgUpdateTimeDepCalcs(multi_loop, remainder);
676 FG_LOG( FG_ALL, FG_INFO, "Elapsed time is zero ... we're zinging" );
680 #if ! defined( MACOS )
681 // Do any serial port work that might need to be done
685 // see if we need to load any new scenery tiles
686 global_tile_mgr.update();
688 // Process/manage pending events
689 global_events.Process();
691 // Run audio scheduler
692 #ifdef ENABLE_AUDIO_SUPPORT
693 if ( current_options.get_sound() && !audio_sched->not_working() ) {
695 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
697 // note: all these factors are relative to the sample. our
698 // sample format should really contain a conversion factor so
699 // that we can get prop speed right for arbitrary samples.
700 // Note that for normal-size props, there is a point at which
701 // the prop tips approach the speed of sound; that is a pretty
702 // strong limit to how fast the prop can go.
704 // multiplication factor is prime pitch control; add some log
705 // component for verisimilitude
707 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
708 //fprintf(stderr, "pitch1: %f ", pitch);
709 if (controls.get_throttle(0) > 0.0 || f->v_rel_wind > 40.0) {
710 //fprintf(stderr, "rel_wind: %f ", f->v_rel_wind);
711 // only add relative wind and AoA if prop is moving
712 // or we're really flying at idle throttle
713 if (pitch < 5.4) { // this needs tuning
714 // prop tips not breaking sound barrier
715 pitch += log(f->v_rel_wind + 0.8)/2;
717 // prop tips breaking sound barrier
718 pitch += log(f->v_rel_wind + 0.8)/10;
720 //fprintf(stderr, "pitch2: %f ", pitch);
721 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
723 // Angle of Attack next... -x^3(e^x) is my best guess Just
724 // need to calculate some reasonable scaling factor and
725 // then clamp it on the positive aoa (neg adj) side
726 double aoa = f->get_Gamma_vert_rad() * 2.2;
728 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
729 if (aoa_adj < -0.8) aoa_adj = -0.8;
731 //fprintf(stderr, "pitch3: %f ", pitch);
733 // don't run at absurdly slow rates -- not realistic
734 // and sounds bad to boot. :-)
735 if (pitch < 0.8) pitch = 0.8;
737 //fprintf(stderr, "pitch4: %f\n", pitch);
739 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
740 log(f->v_rel_wind + 1.0)/14.0;
741 // fprintf(stderr, "volume: %f\n", volume);
743 pitch_envelope.setStep ( 0, 0.01, pitch );
744 volume_envelope.setStep ( 0, 0.01, volume );
748 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
749 pitch_envelope.setStep ( 0, 0.01, param );
750 volume_envelope.setStep ( 0, 0.01, param );
752 # endif // experimental throttle patch
754 audio_sched -> update();
761 FG_LOG( FG_ALL, FG_DEBUG, "" );
765 // This is the top level master main function that is registered as
769 // The first few passes take care of initialization things (a couple
770 // per pass) and once everything has been initialized fgMainLoop from
773 static void fgIdleFunction ( void ) {
774 // printf("idle state == %d\n", idle_state);
776 if ( idle_state == 0 ) {
777 // Initialize the splash screen right away
778 if ( current_options.get_splash_screen() ) {
783 } else if ( idle_state == 1 ) {
784 // Start the intro music
786 if ( current_options.get_intro_music() ) {
787 string lockfile = "/tmp/mpg123.running";
788 FGPath mp3file( current_options.get_fg_root() );
789 mp3file.append( "Sounds/intro.mp3" );
791 string command = "(touch " + lockfile + "; mpg123 "
792 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
794 FG_LOG( FG_GENERAL, FG_INFO,
795 "Starting intro music: " << mp3file.str() );
796 system ( command.c_str() );
801 } else if ( idle_state == 2 ) {
802 // These are a few miscellaneous things that aren't really
803 // "subsystems" but still need to be initialized.
806 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
807 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
812 } else if ( idle_state == 3 ) {
813 // This is the top level init routine which calls all the
814 // other subsystem initialization routines. If you are adding
815 // a subsystem to flight gear, its initialization call should
816 // located in this routine.
817 if( !fgInitSubsystems()) {
818 FG_LOG( FG_GENERAL, FG_ALERT,
819 "Subsystem initializations failed ..." );
824 } else if ( idle_state == 4 ) {
825 // setup OpenGL view parameters
829 // init timer routines, signals, etc. Arrange for an alarm
830 // signal to be generated, etc.
831 fgInitTimeDepCalcs();
835 } else if ( idle_state == 5 ) {
838 } else if ( idle_state == 6 ) {
839 // Initialize audio support
840 #ifdef ENABLE_AUDIO_SUPPORT
843 if ( current_options.get_intro_music() ) {
844 // Let's wait for mpg123 to finish
845 string lockfile = "/tmp/mpg123.running";
846 struct stat stat_buf;
848 FG_LOG( FG_GENERAL, FG_INFO,
849 "Waiting for mpg123 player to finish ..." );
850 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
851 // file exist, wait ...
853 FG_LOG( FG_GENERAL, FG_INFO, ".");
855 FG_LOG( FG_GENERAL, FG_INFO, "");
859 audio_sched = new slScheduler ( 8000 );
860 audio_mixer = new smMixer;
861 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
862 audio_sched -> setSafetyMargin ( 1.0 ) ;
864 FGPath slfile( current_options.get_fg_root() );
865 slfile.append( "Sounds/wasp.wav" );
867 s1 = new slSample ( (char *)slfile.c_str() );
868 FG_LOG( FG_GENERAL, FG_INFO,
869 "Rate = " << s1 -> getRate()
870 << " Bps = " << s1 -> getBps()
871 << " Stereo = " << s1 -> getStereo() );
872 audio_sched -> loopSample ( s1 );
874 if ( audio_sched->not_working() ) {
877 pitch_envelope.setStep ( 0, 0.01, 0.6 );
878 volume_envelope.setStep ( 0, 0.01, 0.6 );
880 audio_sched -> addSampleEnvelope( s1, 0, 0, &
883 audio_sched -> addSampleEnvelope( s1, 0, 1,
885 SL_VOLUME_ENVELOPE );
888 // strcpy(slfile, path);
889 // strcat(slfile, "thunder.wav");
890 // s2 -> loadFile ( slfile );
891 // s2 -> adjustVolume(0.5);
892 // audio_sched -> playSample ( s2 );
899 if ( idle_state == 1000 ) {
900 // We've finished all our initialization steps, from now on we
901 // run the main loop.
905 if ( current_options.get_splash_screen() == 1 ) {
911 // options.cxx needs to see this for toggle_panel()
912 // Handle new window size or exposure
913 void fgReshape( int width, int height ) {
914 if ( ! current_options.get_panel_status() ) {
915 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
916 xglViewport(0, 0 , (GLint)(width), (GLint)(height) );
918 current_view.set_win_ratio( (GLfloat) width /
919 ((GLfloat) (height)*0.4232) );
920 xglViewport(0, (GLint)((height)*0.5768), (GLint)(width),
921 (GLint)((height)*0.4232) );
924 current_view.set_winWidth( width );
925 current_view.set_winHeight( height );
926 current_view.force_update_fov_math();
928 if ( idle_state == 1000 ) {
929 // yes we've finished all our initializations and are running
930 // the main loop, so this will now work without seg faulting
932 current_view.UpdateViewParams();
933 if ( current_options.get_panel_status() ) {
934 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
940 // Initialize GLUT and define a main window
941 int fgGlutInit( int *argc, char **argv ) {
943 #if !defined( MACOS )
944 // GLUT will extract all glut specific options so later on we only
945 // need wory about our own.
946 xglutInit(argc, argv);
949 // Define Display Parameters
950 xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
952 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
953 current_options.get_xsize() << "x" << current_options.get_ysize() );
955 // Define initial window size
956 xglutInitWindowSize( current_options.get_xsize(),
957 current_options.get_ysize() );
959 // Initialize windows
960 if ( current_options.get_game_mode() == 0 ) {
961 // Open the regular window
962 xglutCreateWindow("Flight Gear");
963 #ifndef GLUT_WRONG_VERSION
965 // Open the cool new 'game mode' window
966 char game_mode_str[256];
967 sprintf( game_mode_str, "width=%d height=%d bpp=32",
968 current_options.get_xsize(),
969 current_options.get_ysize() );
971 FG_LOG( FG_GENERAL, FG_INFO,
972 "game mode params = " << game_mode_str );
973 glutGameModeString( game_mode_str );
978 // This seems to be the absolute earliest in the init sequence
979 // that these calls will return valid info. Too bad it's after
980 // we've already created and sized out window. :-(
981 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
982 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
983 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
985 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
988 // try to determine if we should adjust the initial default
989 // display resolution. The options class defaults (is
990 // initialized) to 640x480.
991 string renderer = general.glRenderer;
993 // currently we only know how to deal with Mesa/Glide/Voodoo cards
994 if ( renderer.find( "Glide" ) != string::npos ) {
995 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
996 if ( renderer.find( "FB/8" ) != string::npos ) {
997 // probably a voodoo-2
998 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
999 // probably two SLI'd Voodoo-2's
1000 current_options.set_xsize( 1024 );
1001 current_options.set_ysize( 768 );
1002 FG_LOG( FG_GENERAL, FG_INFO,
1003 "It looks like you have two sli'd voodoo-2's." << endl
1004 << "upgrading your win resolution to 1024 x 768" );
1005 glutReshapeWindow(1024, 768);
1007 // probably a single non-SLI'd Voodoo-2
1008 current_options.set_xsize( 800 );
1009 current_options.set_ysize( 600 );
1010 FG_LOG( FG_GENERAL, FG_INFO,
1011 "It looks like you have a voodoo-2." << endl
1012 << "upgrading your win resolution to 800 x 600" );
1013 glutReshapeWindow(800, 600);
1015 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1016 // probably a voodoo-1, stick with the default
1019 // we have no special knowledge of this card, stick with the default
1027 // Initialize GLUT event handlers
1028 int fgGlutInitEvents( void ) {
1029 // call fgReshape() on window resizes
1030 xglutReshapeFunc( fgReshape );
1032 // call GLUTkey() on keyboard event
1033 xglutKeyboardFunc( GLUTkey );
1034 glutSpecialFunc( GLUTspecialkey );
1036 // call guiMouseFunc() whenever our little rodent is used
1037 glutMouseFunc ( guiMouseFunc );
1038 glutMotionFunc (guiMotionFunc );
1039 glutPassiveMotionFunc (guiMotionFunc );
1041 // call fgMainLoop() whenever there is
1042 // nothing else to do
1043 xglutIdleFunc( fgIdleFunction );
1046 xglutDisplayFunc( fgRenderFrame );
1053 int main( int argc, char **argv ) {
1055 #if defined( MACOS )
1056 argc = ccommand( &argv );
1060 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1063 // set default log levels
1064 fglog().setLogLevels( FG_ALL, FG_INFO );
1066 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1068 // seed the random number generater
1071 // Load the configuration parameters
1072 if ( !fgInitConfig(argc, argv) ) {
1073 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1077 // Initialize the Window/Graphics environment.
1078 if( !fgGlutInit(&argc, argv) ) {
1079 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1083 // Initialize the various GLUT Event Handlers.
1084 if( !fgGlutInitEvents() ) {
1085 FG_LOG( FG_GENERAL, FG_ALERT,
1086 "GLUT event handler initialization failed ..." );
1090 // Initialize ssg (from plib)
1093 // Initialize the user interface (we need to do this before
1094 // passing off control to glut and before fgInitGeneral to get our
1098 // Do some quick general initializations
1099 if( !fgInitGeneral()) {
1100 FG_LOG( FG_GENERAL, FG_ALERT,
1101 "General initializations failed ..." );
1106 // some ssg test stuff (requires data from the plib source
1107 // distribution) specifically from the ssg tux example
1110 // ssgModelPath( "/stage/pinky01/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1111 // ssgTexturePath( "/stage/pinky01/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1112 ssgModelPath( "/h/curt/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1113 ssgTexturePath( "/h/curt/src/Libs/plib-1.0.12/examples/ssg/tux/data/" );
1115 scene = new ssgRoot;
1116 terrain = new ssgBranch;
1117 terrain->setName( "Terrain" );
1118 penguin_sel = new ssgSelector;
1119 penguin_pos = new ssgTransform;
1121 ssgEntity *tux_obj = ssgLoadAC( "tuxedo.ac" );
1122 penguin_pos->addKid( tux_obj );
1123 penguin_sel->addKid( penguin_pos );
1124 ssgFlatten( tux_obj );
1125 ssgStripify( penguin_sel );
1127 #ifdef FG_NETWORK_OLK
1128 // Do the network intialization
1129 printf("Multipilot mode %s\n", fg_net_init() );
1132 scene->addKid( terrain );
1133 scene->addKid( penguin_sel );
1135 // pass control off to the master GLUT event handler
1138 // we never actually get here ... but to avoid compiler warnings,