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>
95 #ifndef FG_OLD_WEATHER
96 # include <WeatherCM/FGLocalWeatherDatabase.h>
98 # include <Weather/weather.hxx>
101 #include "fg_init.hxx"
102 #include "keyboard.hxx"
103 #include "options.hxx"
104 #include "splash.hxx"
106 #include "fg_serial.hxx"
109 // -dw- use custom sioux settings so I can see output window
112 # include <sioux.h> // settings for output window
114 # include <console.h>
118 // This is a record containing a bit of global housekeeping information
121 // Specify our current idle function state. This is used to run all
122 // our initializations out of the glutIdleLoop() so that we can get a
123 // splash screen up and running right away.
124 static int idle_state = 0;
129 // Global structures for the Audio library
130 #ifdef ENABLE_AUDIO_SUPPORT
131 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
132 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
133 slScheduler *audio_sched;
134 smMixer *audio_mixer;
141 ssgRoot *scene = NULL;
142 ssgBranch *terrain = NULL;
143 ssgSelector *penguin_sel = NULL;
144 ssgTransform *penguin_pos = NULL;
146 // current fdm/position used for view
147 FGInterface cur_view_fdm;
150 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
152 { 1.0f, 0.0f, 0.0f, 0.0f },
153 { 0.0f, 0.0f, -1.0f, 0.0f },
154 { 0.0f, 1.0f, 0.0f, 0.0f },
155 { 0.0f, 0.0f, 0.0f, 1.0f }
158 // The following defines flight gear options. Because glutlib will also
159 // want to parse its own options, those options must not be included here
160 // or they will get parsed by the main program option parser. Hence case
161 // is significant for any option added that might be in conflict with
164 // glutlib parses for:
166 // -direct (invalid in Win32)
170 // -indirect (invalid in Win32)
173 // Note that glutlib depends upon strings while this program's
174 // option parser wants only initial characters followed by numbers
179 // fgInitVisuals() -- Initialize various GL/view parameters
180 void fgInitVisuals( void ) {
183 l = &cur_light_params;
185 #ifndef GLUT_WRONG_VERSION
186 // Go full screen if requested ...
187 if ( current_options.get_fullscreen() ) {
192 // If enabled, normal vectors specified with glNormal are scaled
193 // to unit length after transformation. See glNormal.
194 // xglEnable( GL_NORMALIZE );
196 xglEnable( GL_LIGHTING );
197 xglEnable( GL_LIGHT0 );
198 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
201 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
202 ssgGetLight( 0 ) -> setPosition( sunpos );
204 // xglFogi (GL_FOG_MODE, GL_LINEAR);
205 xglFogi (GL_FOG_MODE, GL_EXP2);
206 if ( (current_options.get_fog() == 1) ||
207 (current_options.get_shading() == 0) ) {
208 // if fastest fog requested, or if flat shading force fastest
209 xglHint ( GL_FOG_HINT, GL_FASTEST );
210 } else if ( current_options.get_fog() == 2 ) {
211 xglHint ( GL_FOG_HINT, GL_NICEST );
213 if ( current_options.get_wireframe() ) {
215 xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
218 // This is the default anyways, but it can't hurt
219 xglFrontFace ( GL_CCW );
222 // xglEnable(GL_POINT_SMOOTH);
223 // xglEnable(GL_LINE_SMOOTH);
224 // xglEnable(GL_POLYGON_SMOOTH);
228 // Update all Visuals (redraws anything graphics related)
229 void fgRenderFrame( void ) {
230 fgLIGHT *l = &cur_light_params;
231 FGTime *t = FGTime::cur_time_params;
232 // FGView *v = ¤t_view;
233 static double last_visibility = -9999;
236 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
237 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
238 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
239 // GLfloat mat_shininess[] = { 10.0 };
240 GLbitfield clear_mask;
242 if ( idle_state != 1000 ) {
243 // still initializing, draw the splash screen
244 if ( current_options.get_splash_screen() == 1 ) {
248 // idle_state is now 1000 meaning we've finished all our
249 // initializations and are running the main loop, so this will
250 // now work without seg faulting the system.
252 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
253 // FG_Altitude * FEET_TO_METER);
255 // this is just a temporary hack, to make me understand Pui
256 // timerText -> setLabel (ctime (&t->cur_time));
259 // update view volume parameters
260 // cout << "before pilot_view update" << endl;
261 pilot_view.UpdateViewParams(*cur_fdm_state);
262 // cout << "after pilot_view update" << endl;
263 current_view.UpdateViewParams(cur_view_fdm);
265 // set the sun position
266 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
268 clear_mask = GL_DEPTH_BUFFER_BIT;
269 if ( current_options.get_wireframe() ) {
270 clear_mask |= GL_COLOR_BUFFER_BIT;
272 if ( current_options.get_panel_status() ) {
273 // we can't clear the screen when the panel is active
274 } else if ( current_options.get_skyblend() ) {
275 if ( current_options.get_textures() ) {
276 // glClearColor(black[0], black[1], black[2], black[3]);
277 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
278 l->adj_fog_color[2], l->adj_fog_color[3]);
279 clear_mask |= GL_COLOR_BUFFER_BIT;
282 glClearColor(l->sky_color[0], l->sky_color[1],
283 l->sky_color[2], l->sky_color[3]);
284 clear_mask |= GL_COLOR_BUFFER_BIT;
286 xglClear( clear_mask );
288 // Tell GL we are switching to model view parameters
290 // I really should create a derived ssg node or use a call
291 // back or something so that I can draw the sky within the
292 // ssgCullandDraw() function, but for now I just mimic what
293 // ssg does to set up the model view matrix
294 xglMatrixMode(GL_MODELVIEW);
296 sgMat4 vm_tmp, view_mat;
297 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
298 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
299 sgPreMultMat4( view_mat, vm_tmp ) ;
300 xglLoadMatrixf( (float *)view_mat );
303 xglDisable( GL_DEPTH_TEST );
304 xglDisable( GL_LIGHTING );
305 xglDisable( GL_CULL_FACE );
306 xglDisable( GL_FOG );
307 xglShadeModel( GL_SMOOTH );
308 if ( current_options.get_skyblend() ) {
312 // setup transformation for drawing astronomical objects
314 // Translate to view position
315 Point3D view_pos = current_view.get_view_pos();
316 xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
317 // Rotate based on gst (sidereal time)
318 // note: constant should be 15.041085, Curt thought it was 15
319 angle = t->getGst() * 15.041085;
320 // printf("Rotating astro objects by %.2f degrees\n",angle);
321 xglRotatef( angle, 0.0, 0.0, -1.0 );
323 // draw stars and planets
325 xglDisable( GL_COLOR_MATERIAL ); // just to make sure ...
326 xglEnable( GL_CULL_FACE ); // for moon
327 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
328 //xglEnable(GL_DEPTH_TEST);
329 SolarSystem::theSolarSystem->draw();
330 // reset blending function
331 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
336 if ( current_options.get_shading() ) {
337 xglShadeModel( GL_SMOOTH );
339 xglShadeModel( GL_FLAT );
341 xglEnable( GL_DEPTH_TEST );
342 if ( current_options.get_fog() > 0 ) {
344 xglFogi( GL_FOG_MODE, GL_EXP2 );
345 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
348 // update fog params if visibility has changed
349 double cur_visibility = WeatherDatabase->getWeatherVisibility();
350 double actual_visibility = cur_visibility;
352 if ( current_options.get_clouds() ) {
353 double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
354 current_options.get_clouds_asl() );
355 // cout << "altitude diff = " << diff << endl;
357 actual_visibility = cur_visibility * (diff - 25) / 100.0;
358 if ( actual_visibility < 0 ) {
359 actual_visibility = 0;
364 // cout << "actual visibility = " << actual_visibility << endl;
366 if ( actual_visibility != last_visibility ) {
367 last_visibility = actual_visibility;
369 // cout << "----> updating fog params" << endl;
371 GLfloat fog_exp_density;
372 GLfloat fog_exp2_density;
375 fog_exp_density = -log(0.01 / actual_visibility);
378 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
380 // Set correct opengl fog density
381 xglFogf (GL_FOG_DENSITY, fog_exp2_density);
384 // set lighting parameters
385 xglLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
386 xglLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
387 // xglLightfv(GL_LIGHT0, GL_SPECULAR, white );
389 // texture parameters
390 xglEnable( GL_TEXTURE_2D );
391 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
392 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
393 // set base color (I don't think this is doing anything here)
394 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
395 // (GL_FRONT, GL_DIFFUSE, white);
396 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
397 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
400 if ( current_options.get_textures() ) {
401 // texture parameters
402 xglEnable( GL_TEXTURE_2D );
403 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
404 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
405 // set base color (I don't think this is doing anything here)
406 xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
407 xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
408 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
409 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
411 xglDisable( GL_TEXTURE_2D );
412 xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
413 xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
414 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
415 // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
420 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
421 ssgGetLight( 0 ) -> setPosition( sunpos );
423 // xglMatrixMode( GL_PROJECTION );
424 // xglLoadIdentity();
425 float fov = current_options.get_fov();
426 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
428 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
431 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
432 // << current_weather.get_visibility() );
435 ssgSetNearFar( 10.0f, 100000.0f );
437 ssgSetNearFar( 0.5f, 100000.0f );
440 if ( current_options.get_view_mode() ==
441 fgOPTIONS::FG_VIEW_PILOT )
444 penguin_sel->select(0);
445 } else if ( current_options.get_view_mode() ==
446 fgOPTIONS::FG_VIEW_FOLLOW )
448 // select view matrix from front of view matrix queue
449 // FGMat4Wrapper tmp = current_view.follow.front();
450 // sgCopyMat4( sgVIEW, tmp.m );
452 // enable TuX and set up his position and orientation
453 penguin_sel->select(1);
456 sgMakeTransMat4( sgTRANS,
457 pilot_view.view_pos.x(),
458 pilot_view.view_pos.y(),
459 pilot_view.view_pos.z() );
462 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
465 sgMakeRotMat4( sgROT, -90.0, ownship_up );
469 sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
470 sgMultMat4( sgTUX, sgTMP, sgTRANS );
473 sgSetCoord( &tuxpos, sgTUX );
474 penguin_pos->setTransform( &tuxpos );
477 ssgSetCamera( current_view.VIEW );
479 // position tile nodes and update range selectors
480 global_tile_mgr.prep_ssg_nodes();
482 // force the default state so ssg can get back on track if
483 // we've changed things elsewhere
484 FGMaterialSlot m_slot;
485 FGMaterialSlot *m_ptr = &m_slot;
486 if ( material_mgr.find( "Default", m_ptr ) ) {
487 m_ptr->get_state()->force();
490 // draw the ssg scene
491 ssgCullAndDraw( scene );
493 xglDisable( GL_TEXTURE_2D );
494 xglDisable( GL_FOG );
496 // display HUD && Panel
497 xglDisable( GL_CULL_FACE );
500 // We can do translucent menus, so why not. :-)
501 xglEnable ( GL_BLEND ) ;
502 xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
504 xglDisable ( GL_BLEND ) ;
513 // Update internal time dependent calculations (i.e. flight model)
514 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
515 static fdm_state_list fdm_list;
516 // FGInterface fdm_state;
517 fgLIGHT *l = &cur_light_params;
518 FGTime *t = FGTime::cur_time_params;
519 // FGView *v = ¤t_view;
522 // update the flight model
523 if ( multi_loop < 0 ) {
527 if ( !t->getPause() ) {
528 // run Autopilot system
531 // printf("updating flight model x %d\n", multi_loop);
532 /* fgFDMUpdate( current_options.get_flight_model(),
534 multi_loop * current_options.get_speed_up(),
536 cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
538 // fgFDMUpdate( current_options.get_flight_model(),
539 // fdm_state, 0, remainder );
540 cur_fdm_state->update( 0 );
543 fdm_list.push_back( *cur_fdm_state );
544 while ( fdm_list.size() > 15 ) {
545 fdm_list.pop_front();
548 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
549 cur_view_fdm = *cur_fdm_state;
551 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
552 cur_view_fdm = fdm_list.front();
555 // update the view angle
556 for ( i = 0; i < multi_loop; i++ ) {
557 if ( fabs(current_view.get_goal_view_offset() -
558 current_view.get_view_offset()) < 0.05 )
560 current_view.set_view_offset( current_view.get_goal_view_offset() );
563 // move current_view.view_offset towards current_view.goal_view_offset
564 if ( current_view.get_goal_view_offset() >
565 current_view.get_view_offset() )
567 if ( current_view.get_goal_view_offset() -
568 current_view.get_view_offset() < FG_PI )
570 current_view.inc_view_offset( 0.01 );
572 current_view.inc_view_offset( -0.01 );
575 if ( current_view.get_view_offset() -
576 current_view.get_goal_view_offset() < FG_PI )
578 current_view.inc_view_offset( -0.01 );
580 current_view.inc_view_offset( 0.01 );
583 if ( current_view.get_view_offset() > FG_2PI ) {
584 current_view.inc_view_offset( -FG_2PI );
585 } else if ( current_view.get_view_offset() < 0 ) {
586 current_view.inc_view_offset( FG_2PI );
591 double tmp = -(l->sun_rotation + FG_PI)
592 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
593 while ( tmp < 0.0 ) {
596 while ( tmp > FG_2PI ) {
599 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
600 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
601 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
606 void fgInitTimeDepCalcs( void ) {
609 // #ifdef HAVE_SETITIMER
610 // fgTimerInit( 1.0 / current_options.get_model_hz(),
611 // fgUpdateTimeDepCalcs );
612 // #endif HAVE_SETITIMER
616 static const double alt_adjust_ft = 3.758099;
617 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
620 // What should we do when we have nothing else to do? Let's get ready
621 // for the next move and update the display?
622 static void fgMainLoop( void ) {
624 static long remainder = 0;
625 long elapsed, multi_loop;
626 #ifdef FANCY_FRAME_COUNTER
630 static time_t last_time = 0;
631 static int frames = 0;
632 #endif // FANCY_FRAME_COUNTER
634 t = FGTime::cur_time_params;
636 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
637 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
639 #if defined( ENABLE_PLIB_JOYSTICK )
640 // Read joystick and update control settings
641 if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
644 #elif defined( ENABLE_GLUT_JOYSTICK )
645 // Glut joystick support works by feeding a joystick handler
646 // function to glut. This is taken care of once in the joystick
647 // init routine and we don't have to worry about it again.
650 #ifdef FG_OLD_WEATHER
651 current_weather.Update();
654 // Fix elevation. I'm just sticking this here for now, it should
655 // probably move eventually
657 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
659 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
660 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
662 if ( scenery.cur_elev > -9990 ) {
663 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
664 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
665 // now set aircraft altitude above ground
666 printf("Current Altitude = %.2f < %.2f forcing to %.2f\n",
667 cur_fdm_state->get_Altitude() * FEET_TO_METER,
668 scenery.cur_elev + alt_adjust_m - 3.0,
669 scenery.cur_elev + alt_adjust_m );
670 fgFDMForceAltitude( current_options.get_flight_model(),
671 scenery.cur_elev + alt_adjust_m );
673 FG_LOG( FG_ALL, FG_DEBUG,
674 "<*> resetting altitude to "
675 << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
677 fgFDMSetGroundElevation( current_options.get_flight_model(),
678 scenery.cur_elev ); // meters
681 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
683 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
684 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
687 t->update(*cur_fdm_state);
689 // Get elapsed time (in usec) for this past frame
690 elapsed = fgGetTimeInterval();
691 FG_LOG( FG_ALL, FG_DEBUG,
692 "Elapsed time interval is = " << elapsed
693 << ", previous remainder is = " << remainder );
695 // Calculate frame rate average
696 #ifdef FANCY_FRAME_COUNTER
697 /* old fps calculation */
701 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
702 tmp = general.get_frame(i);
704 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
705 general.set_frame(i+1,tmp);
707 tmp = 1000000.0 / (float)elapsed;
708 general.set_frame(0,tmp);
709 // printf("frame[0] = %.2f\n", general.frames[0]);
711 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
712 // printf("ave = %.2f\n", general.frame_rate);
715 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
716 general.set_frame_rate( frames );
717 FG_LOG( FG_ALL, FG_DEBUG,
718 "--> Frame rate is = " << general.get_frame_rate() );
721 last_time = t->get_cur_time();
726 if ( ! use_signals ) {
727 // Calculate model iterations needed for next frame
728 elapsed += remainder;
730 multi_loop = (int)(((double)elapsed * 0.000001) *
731 current_options.get_model_hz());
732 remainder = elapsed - ( (multi_loop*1000000) /
733 current_options.get_model_hz() );
734 FG_LOG( FG_ALL, FG_DEBUG,
735 "Model iterations needed = " << multi_loop
736 << ", new remainder = " << remainder );
739 if ( multi_loop > 0 ) {
740 fgUpdateTimeDepCalcs(multi_loop, remainder);
742 FG_LOG( FG_ALL, FG_DEBUG,
743 "Elapsed time is zero ... we're zinging" );
747 #if ! defined( MACOS )
748 // Do any serial port work that might need to be done
752 // see if we need to load any new scenery tiles
753 global_tile_mgr.update();
755 // Process/manage pending events
756 global_events.Process();
758 // Run audio scheduler
759 #ifdef ENABLE_AUDIO_SUPPORT
760 if ( current_options.get_sound() && !audio_sched->not_working() ) {
762 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
764 // note: all these factors are relative to the sample. our
765 // sample format should really contain a conversion factor so
766 // that we can get prop speed right for arbitrary samples.
767 // Note that for normal-size props, there is a point at which
768 // the prop tips approach the speed of sound; that is a pretty
769 // strong limit to how fast the prop can go.
771 // multiplication factor is prime pitch control; add some log
772 // component for verisimilitude
774 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
775 //fprintf(stderr, "pitch1: %f ", pitch);
776 if (controls.get_throttle(0) > 0.0 || cur_fdm_state->v_rel_wind > 40.0) {
777 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
778 // only add relative wind and AoA if prop is moving
779 // or we're really flying at idle throttle
780 if (pitch < 5.4) { // this needs tuning
781 // prop tips not breaking sound barrier
782 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
784 // prop tips breaking sound barrier
785 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
787 //fprintf(stderr, "pitch2: %f ", pitch);
788 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
790 // Angle of Attack next... -x^3(e^x) is my best guess Just
791 // need to calculate some reasonable scaling factor and
792 // then clamp it on the positive aoa (neg adj) side
793 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
795 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
796 if (aoa_adj < -0.8) aoa_adj = -0.8;
798 //fprintf(stderr, "pitch3: %f ", pitch);
800 // don't run at absurdly slow rates -- not realistic
801 // and sounds bad to boot. :-)
802 if (pitch < 0.8) pitch = 0.8;
804 //fprintf(stderr, "pitch4: %f\n", pitch);
806 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
807 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
808 // fprintf(stderr, "volume: %f\n", volume);
810 pitch_envelope.setStep ( 0, 0.01, pitch );
811 volume_envelope.setStep ( 0, 0.01, volume );
815 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
816 pitch_envelope.setStep ( 0, 0.01, param );
817 volume_envelope.setStep ( 0, 0.01, param );
819 # endif // experimental throttle patch
821 audio_sched -> update();
828 FG_LOG( FG_ALL, FG_DEBUG, "" );
832 // This is the top level master main function that is registered as
836 // The first few passes take care of initialization things (a couple
837 // per pass) and once everything has been initialized fgMainLoop from
840 static void fgIdleFunction ( void ) {
841 // printf("idle state == %d\n", idle_state);
843 if ( idle_state == 0 ) {
844 // Initialize the splash screen right away
845 if ( current_options.get_splash_screen() ) {
850 } else if ( idle_state == 1 ) {
851 // Start the intro music
853 if ( current_options.get_intro_music() ) {
854 string lockfile = "/tmp/mpg123.running";
855 FGPath mp3file( current_options.get_fg_root() );
856 mp3file.append( "Sounds/intro.mp3" );
858 string command = "(touch " + lockfile + "; mpg123 "
859 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
861 FG_LOG( FG_GENERAL, FG_INFO,
862 "Starting intro music: " << mp3file.str() );
863 system ( command.c_str() );
868 } else if ( idle_state == 2 ) {
869 // These are a few miscellaneous things that aren't really
870 // "subsystems" but still need to be initialized.
873 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
874 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
879 } else if ( idle_state == 3 ) {
880 // This is the top level init routine which calls all the
881 // other subsystem initialization routines. If you are adding
882 // a subsystem to flight gear, its initialization call should
883 // located in this routine.
884 if( !fgInitSubsystems()) {
885 FG_LOG( FG_GENERAL, FG_ALERT,
886 "Subsystem initializations failed ..." );
891 } else if ( idle_state == 4 ) {
892 // setup OpenGL view parameters
896 // init timer routines, signals, etc. Arrange for an alarm
897 // signal to be generated, etc.
898 fgInitTimeDepCalcs();
902 } else if ( idle_state == 5 ) {
905 } else if ( idle_state == 6 ) {
906 // Initialize audio support
907 #ifdef ENABLE_AUDIO_SUPPORT
910 if ( current_options.get_intro_music() ) {
911 // Let's wait for mpg123 to finish
912 string lockfile = "/tmp/mpg123.running";
913 struct stat stat_buf;
915 FG_LOG( FG_GENERAL, FG_INFO,
916 "Waiting for mpg123 player to finish ..." );
917 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
918 // file exist, wait ...
920 FG_LOG( FG_GENERAL, FG_INFO, ".");
922 FG_LOG( FG_GENERAL, FG_INFO, "");
926 audio_sched = new slScheduler ( 8000 );
927 audio_mixer = new smMixer;
928 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
929 audio_sched -> setSafetyMargin ( 1.0 ) ;
931 FGPath slfile( current_options.get_fg_root() );
932 slfile.append( "Sounds/wasp.wav" );
934 s1 = new slSample ( (char *)slfile.c_str() );
935 FG_LOG( FG_GENERAL, FG_INFO,
936 "Rate = " << s1 -> getRate()
937 << " Bps = " << s1 -> getBps()
938 << " Stereo = " << s1 -> getStereo() );
939 audio_sched -> loopSample ( s1 );
941 if ( audio_sched->not_working() ) {
944 pitch_envelope.setStep ( 0, 0.01, 0.6 );
945 volume_envelope.setStep ( 0, 0.01, 0.6 );
947 audio_sched -> addSampleEnvelope( s1, 0, 0,
950 audio_sched -> addSampleEnvelope( s1, 0, 1,
952 SL_VOLUME_ENVELOPE );
955 // strcpy(slfile, path);
956 // strcat(slfile, "thunder.wav");
957 // s2 -> loadFile ( slfile );
958 // s2 -> adjustVolume(0.5);
959 // audio_sched -> playSample ( s2 );
966 if ( idle_state == 1000 ) {
967 // We've finished all our initialization steps, from now on we
968 // run the main loop.
972 if ( current_options.get_splash_screen() == 1 ) {
978 // options.cxx needs to see this for toggle_panel()
979 // Handle new window size or exposure
980 void fgReshape( int width, int height ) {
981 if ( ! current_options.get_panel_status() ) {
982 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
983 xglViewport(0, 0 , (GLint)(width), (GLint)(height) );
985 current_view.set_win_ratio( (GLfloat) width /
986 ((GLfloat) (height)*0.4232) );
987 xglViewport(0, (GLint)((height)*0.5768), (GLint)(width),
988 (GLint)((height)*0.4232) );
991 current_view.set_winWidth( width );
992 current_view.set_winHeight( height );
993 current_view.force_update_fov_math();
995 // set these fov to be the same as in fgRenderFrame()
996 float x_fov = current_options.get_fov();
997 float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
998 ssgSetFOV( x_fov, y_fov );
1000 glViewport ( 0, 0, width, height );
1001 float fov = current_options.get_fov();
1002 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1004 if ( idle_state == 1000 ) {
1005 // yes we've finished all our initializations and are running
1006 // the main loop, so this will now work without seg faulting
1008 solarSystemRebuild();
1009 current_view.UpdateViewParams(cur_view_fdm);
1010 if ( current_options.get_panel_status() ) {
1011 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
1017 // Initialize GLUT and define a main window
1018 int fgGlutInit( int *argc, char **argv ) {
1020 #if !defined( MACOS )
1021 // GLUT will extract all glut specific options so later on we only
1022 // need wory about our own.
1023 xglutInit(argc, argv);
1026 // Define Display Parameters
1027 xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1029 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1030 current_options.get_xsize() << "x" << current_options.get_ysize() );
1032 // Define initial window size
1033 xglutInitWindowSize( current_options.get_xsize(),
1034 current_options.get_ysize() );
1036 // Initialize windows
1037 if ( current_options.get_game_mode() == 0 ) {
1038 // Open the regular window
1039 xglutCreateWindow("Flight Gear");
1040 #ifndef GLUT_WRONG_VERSION
1042 // Open the cool new 'game mode' window
1043 char game_mode_str[256];
1044 sprintf( game_mode_str, "width=%d height=%d bpp=32",
1045 current_options.get_xsize(),
1046 current_options.get_ysize() );
1048 FG_LOG( FG_GENERAL, FG_INFO,
1049 "game mode params = " << game_mode_str );
1050 glutGameModeString( game_mode_str );
1051 glutEnterGameMode();
1055 // This seems to be the absolute earliest in the init sequence
1056 // that these calls will return valid info. Too bad it's after
1057 // we've already created and sized out window. :-(
1058 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1059 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1060 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1062 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1065 // try to determine if we should adjust the initial default
1066 // display resolution. The options class defaults (is
1067 // initialized) to 640x480.
1068 string renderer = general.glRenderer;
1070 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1071 if ( renderer.find( "Glide" ) != string::npos ) {
1072 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1073 if ( renderer.find( "FB/8" ) != string::npos ) {
1074 // probably a voodoo-2
1075 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1076 // probably two SLI'd Voodoo-2's
1077 current_options.set_xsize( 1024 );
1078 current_options.set_ysize( 768 );
1079 FG_LOG( FG_GENERAL, FG_INFO,
1080 "It looks like you have two sli'd voodoo-2's." << endl
1081 << "upgrading your win resolution to 1024 x 768" );
1082 glutReshapeWindow(1024, 768);
1084 // probably a single non-SLI'd Voodoo-2
1085 current_options.set_xsize( 800 );
1086 current_options.set_ysize( 600 );
1087 FG_LOG( FG_GENERAL, FG_INFO,
1088 "It looks like you have a voodoo-2." << endl
1089 << "upgrading your win resolution to 800 x 600" );
1090 glutReshapeWindow(800, 600);
1092 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1093 // probably a voodoo-1, stick with the default
1096 // we have no special knowledge of this card, stick with the default
1104 // Initialize GLUT event handlers
1105 int fgGlutInitEvents( void ) {
1106 // call fgReshape() on window resizes
1107 xglutReshapeFunc( fgReshape );
1109 // call GLUTkey() on keyboard event
1110 xglutKeyboardFunc( GLUTkey );
1111 glutSpecialFunc( GLUTspecialkey );
1113 // call guiMouseFunc() whenever our little rodent is used
1114 glutMouseFunc ( guiMouseFunc );
1115 glutMotionFunc (guiMotionFunc );
1116 glutPassiveMotionFunc (guiMotionFunc );
1118 // call fgMainLoop() whenever there is
1119 // nothing else to do
1120 xglutIdleFunc( fgIdleFunction );
1123 xglutDisplayFunc( fgRenderFrame );
1130 int main( int argc, char **argv ) {
1132 #if defined( MACOS )
1133 argc = ccommand( &argv );
1137 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1140 // set default log levels
1141 fglog().setLogLevels( FG_ALL, FG_INFO );
1143 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1145 // seed the random number generater
1148 // Load the configuration parameters
1149 if ( !fgInitConfig(argc, argv) ) {
1150 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1154 // Initialize the Window/Graphics environment.
1155 if( !fgGlutInit(&argc, argv) ) {
1156 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1160 // Initialize the various GLUT Event Handlers.
1161 if( !fgGlutInitEvents() ) {
1162 FG_LOG( FG_GENERAL, FG_ALERT,
1163 "GLUT event handler initialization failed ..." );
1167 // Initialize ssg (from plib)
1170 // Initialize the user interface (we need to do this before
1171 // passing off control to glut and before fgInitGeneral to get our
1175 // Do some quick general initializations
1176 if( !fgInitGeneral()) {
1177 FG_LOG( FG_GENERAL, FG_ALERT,
1178 "General initializations failed ..." );
1183 // some ssg test stuff (requires data from the plib source
1184 // distribution) specifically from the ssg tux example
1187 FGPath modelpath( current_options.get_fg_root() );
1188 modelpath.append( "Models" );
1189 modelpath.append( "Geometry" );
1191 FGPath texturepath( current_options.get_fg_root() );
1192 texturepath.append( "Models" );
1193 texturepath.append( "Textures" );
1195 ssgModelPath( (char *)modelpath.c_str() );
1196 ssgTexturePath( (char *)texturepath.c_str() );
1198 scene = new ssgRoot;
1199 terrain = new ssgBranch;
1200 terrain->setName( "Terrain" );
1201 penguin_sel = new ssgSelector;
1202 penguin_pos = new ssgTransform;
1204 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1205 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1206 penguin_pos->addKid( tux_obj );
1207 penguin_sel->addKid( penguin_pos );
1208 ssgFlatten( tux_obj );
1209 ssgStripify( penguin_sel );
1211 #ifdef FG_NETWORK_OLK
1212 // Do the network intialization
1213 printf("Multipilot mode %s\n", fg_net_init() );
1216 scene->addKid( terrain );
1217 scene->addKid( penguin_sel );
1219 // pass control off to the master GLUT event handler
1222 // we never actually get here ... but to avoid compiler warnings,