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"
103 #include "keyboard.hxx"
104 #include "options.hxx"
105 #include "splash.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;
125 static int global_multi_loop;
130 // Global structures for the Audio library
131 #ifdef ENABLE_AUDIO_SUPPORT
132 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
133 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
134 slScheduler *audio_sched;
135 smMixer *audio_mixer;
142 ssgRoot *scene = NULL;
143 ssgBranch *terrain = NULL;
144 ssgSelector *penguin_sel = NULL;
145 ssgTransform *penguin_pos = NULL;
147 // current fdm/position used for view
148 FGInterface cur_view_fdm;
151 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
153 { 1.0f, 0.0f, 0.0f, 0.0f },
154 { 0.0f, 0.0f, -1.0f, 0.0f },
155 { 0.0f, 1.0f, 0.0f, 0.0f },
156 { 0.0f, 0.0f, 0.0f, 1.0f }
159 // The following defines flight gear options. Because glutlib will also
160 // want to parse its own options, those options must not be included here
161 // or they will get parsed by the main program option parser. Hence case
162 // is significant for any option added that might be in conflict with
165 // glutlib parses for:
167 // -direct (invalid in Win32)
171 // -indirect (invalid in Win32)
174 // Note that glutlib depends upon strings while this program's
175 // option parser wants only initial characters followed by numbers
180 // fgInitVisuals() -- Initialize various GL/view parameters
181 void fgInitVisuals( void ) {
184 l = &cur_light_params;
186 #ifndef GLUT_WRONG_VERSION
187 // Go full screen if requested ...
188 if ( current_options.get_fullscreen() ) {
193 // If enabled, normal vectors specified with glNormal are scaled
194 // to unit length after transformation. See glNormal.
195 // xglEnable( GL_NORMALIZE );
197 xglEnable( GL_LIGHTING );
198 xglEnable( GL_LIGHT0 );
199 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
202 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
203 ssgGetLight( 0 ) -> setPosition( sunpos );
205 // xglFogi (GL_FOG_MODE, GL_LINEAR);
206 xglFogi (GL_FOG_MODE, GL_EXP2);
207 if ( (current_options.get_fog() == 1) ||
208 (current_options.get_shading() == 0) ) {
209 // if fastest fog requested, or if flat shading force fastest
210 xglHint ( GL_FOG_HINT, GL_FASTEST );
211 } else if ( current_options.get_fog() == 2 ) {
212 xglHint ( GL_FOG_HINT, GL_NICEST );
214 if ( current_options.get_wireframe() ) {
216 xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
219 // This is the default anyways, but it can't hurt
220 xglFrontFace ( GL_CCW );
223 // xglEnable(GL_POINT_SMOOTH);
224 // xglEnable(GL_LINE_SMOOTH);
225 // xglEnable(GL_POLYGON_SMOOTH);
229 // Update all Visuals (redraws anything graphics related)
230 void fgRenderFrame( void ) {
231 fgLIGHT *l = &cur_light_params;
232 FGTime *t = FGTime::cur_time_params;
233 // FGView *v = ¤t_view;
234 static double last_visibility = -9999;
235 static bool in_puff = false;
236 static double puff_length = 0;
237 static double puff_progression = 0;
238 const double ramp_up = 0.15;
239 const double ramp_down = 0.15;
242 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
243 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
244 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
245 // GLfloat mat_shininess[] = { 10.0 };
246 GLbitfield clear_mask;
248 if ( idle_state != 1000 ) {
249 // still initializing, draw the splash screen
250 if ( current_options.get_splash_screen() == 1 ) {
254 // idle_state is now 1000 meaning we've finished all our
255 // initializations and are running the main loop, so this will
256 // now work without seg faulting the system.
258 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
259 // FG_Altitude * FEET_TO_METER);
261 // this is just a temporary hack, to make me understand Pui
262 // timerText -> setLabel (ctime (&t->cur_time));
265 // update view volume parameters
266 // cout << "before pilot_view update" << endl;
267 pilot_view.UpdateViewParams(*cur_fdm_state);
268 // cout << "after pilot_view update" << endl;
269 current_view.UpdateViewParams(cur_view_fdm);
271 // set the sun position
272 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
274 clear_mask = GL_DEPTH_BUFFER_BIT;
275 if ( current_options.get_wireframe() ) {
276 clear_mask |= GL_COLOR_BUFFER_BIT;
278 if ( current_options.get_panel_status() ) {
279 // we can't clear the screen when the panel is active
280 } else if ( current_options.get_skyblend() ) {
281 if ( current_options.get_textures() ) {
282 // glClearColor(black[0], black[1], black[2], black[3]);
283 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
284 l->adj_fog_color[2], l->adj_fog_color[3]);
285 clear_mask |= GL_COLOR_BUFFER_BIT;
288 glClearColor(l->sky_color[0], l->sky_color[1],
289 l->sky_color[2], l->sky_color[3]);
290 clear_mask |= GL_COLOR_BUFFER_BIT;
292 xglClear( clear_mask );
294 // Tell GL we are switching to model view parameters
296 // I really should create a derived ssg node or use a call
297 // back or something so that I can draw the sky within the
298 // ssgCullandDraw() function, but for now I just mimic what
299 // ssg does to set up the model view matrix
300 xglMatrixMode(GL_MODELVIEW);
302 sgMat4 vm_tmp, view_mat;
303 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
304 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
305 sgPreMultMat4( view_mat, vm_tmp ) ;
306 xglLoadMatrixf( (float *)view_mat );
309 xglDisable( GL_DEPTH_TEST );
310 xglDisable( GL_LIGHTING );
311 xglDisable( GL_CULL_FACE );
313 xglDisable( GL_FOG );
314 /* if ( current_options.get_fog() > 0 ) {
316 xglFogi( GL_FOG_MODE, GL_EXP2 );
317 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
320 xglShadeModel( GL_SMOOTH );
321 if ( current_options.get_skyblend() ) {
325 // xglDisable( GL_FOG );
327 // setup transformation for drawing astronomical objects
329 // Translate to view position
330 Point3D view_pos = current_view.get_view_pos();
331 xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
332 // Rotate based on gst (sidereal time)
333 // note: constant should be 15.041085, Curt thought it was 15
334 angle = t->getGst() * 15.041085;
335 // printf("Rotating astro objects by %.2f degrees\n",angle);
336 xglRotatef( angle, 0.0, 0.0, -1.0 );
338 // draw stars and planets
340 xglDisable( GL_COLOR_MATERIAL ); // just to make sure ...
341 xglEnable( GL_CULL_FACE ); // for moon
342 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
343 //xglEnable(GL_DEPTH_TEST);
344 SolarSystem::theSolarSystem->draw();
345 // reset blending function
346 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
351 if ( current_options.get_shading() ) {
352 xglShadeModel( GL_SMOOTH );
354 xglShadeModel( GL_FLAT );
356 xglEnable( GL_DEPTH_TEST );
357 if ( current_options.get_fog() > 0 ) {
359 xglFogi( GL_FOG_MODE, GL_EXP2 );
360 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
363 // update fog params if visibility has changed
364 double cur_visibility = WeatherDatabase->getWeatherVisibility();
365 double actual_visibility = cur_visibility;
367 if ( current_options.get_clouds() ) {
368 double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
369 current_options.get_clouds_asl() );
370 // cout << "altitude diff = " << diff << endl;
373 // calc chance of entering cloud puff
374 double rnd = fg_random();
375 double chance = rnd * rnd * rnd;
376 if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) {
379 puff_length = fg_random() * 2.0; // up to 2 seconds
380 } while ( puff_length <= 0.0 );
381 puff_progression = 0.0;
385 actual_visibility = cur_visibility * (diff - 25) / 50.0;
388 // modify actual_visibility based on puff envelope
390 if ( puff_progression <= ramp_up ) {
391 double x = FG_PI_2 * puff_progression / ramp_up;
392 double factor = 1.0 - sin( x );
393 actual_visibility = actual_visibility * factor;
394 } else if ( puff_progression >= ramp_up + puff_length ) {
396 (puff_progression - (ramp_up + puff_length)) /
398 double factor = sin( x );
399 actual_visibility = actual_visibility * factor;
401 actual_visibility = 0.0;
404 /* cout << "len = " << puff_length
406 << " factor = " << factor
407 << " actual_visibility = " << actual_visibility
410 puff_progression += ( global_multi_loop *
411 current_options.get_speed_up() ) /
412 (double)current_options.get_model_hz();
414 /* cout << "gml = " << global_multi_loop
415 << " speed up = " << current_options.get_speed_up()
416 << " hz = " << current_options.get_model_hz() << endl;
419 if ( puff_progression > puff_length + ramp_up + ramp_down) {
424 // never let visibility drop below zero
425 if ( actual_visibility < 0 ) {
426 actual_visibility = 0;
431 // cout << "actual visibility = " << actual_visibility << endl;
433 if ( actual_visibility != last_visibility ) {
434 last_visibility = actual_visibility;
436 // cout << "----> updating fog params" << endl;
438 GLfloat fog_exp_density;
439 GLfloat fog_exp2_density;
442 fog_exp_density = -log(0.01 / actual_visibility);
445 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
447 // Set correct opengl fog density
448 xglFogf (GL_FOG_DENSITY, fog_exp2_density);
451 // set lighting parameters
452 xglLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
453 xglLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
454 // xglLightfv(GL_LIGHT0, GL_SPECULAR, white );
456 // texture parameters
457 xglEnable( GL_TEXTURE_2D );
458 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
459 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
460 // set base color (I don't think this is doing anything here)
461 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
462 // (GL_FRONT, GL_DIFFUSE, white);
463 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
464 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
467 if ( current_options.get_textures() ) {
468 // texture parameters
469 xglEnable( GL_TEXTURE_2D );
470 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
471 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
472 // set base color (I don't think this is doing anything here)
473 xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
474 xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
475 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
476 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
478 xglDisable( GL_TEXTURE_2D );
479 xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
480 xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
481 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
482 // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
487 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
488 ssgGetLight( 0 ) -> setPosition( sunpos );
490 // xglMatrixMode( GL_PROJECTION );
491 // xglLoadIdentity();
492 float fov = current_options.get_fov();
493 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
495 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
498 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
499 // << current_weather.get_visibility() );
502 ssgSetNearFar( 10.0f, 100000.0f );
504 ssgSetNearFar( 0.5f, 100000.0f );
507 if ( current_options.get_view_mode() ==
508 fgOPTIONS::FG_VIEW_PILOT )
511 penguin_sel->select(0);
512 } else if ( current_options.get_view_mode() ==
513 fgOPTIONS::FG_VIEW_FOLLOW )
515 // select view matrix from front of view matrix queue
516 // FGMat4Wrapper tmp = current_view.follow.front();
517 // sgCopyMat4( sgVIEW, tmp.m );
519 // enable TuX and set up his position and orientation
520 penguin_sel->select(1);
523 sgMakeTransMat4( sgTRANS,
524 pilot_view.view_pos.x(),
525 pilot_view.view_pos.y(),
526 pilot_view.view_pos.z() );
529 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
532 sgMakeRotMat4( sgROT, -90.0, ownship_up );
536 sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
537 sgMultMat4( sgTUX, sgTMP, sgTRANS );
540 sgSetCoord( &tuxpos, sgTUX );
541 penguin_pos->setTransform( &tuxpos );
544 ssgSetCamera( current_view.VIEW );
546 // position tile nodes and update range selectors
547 global_tile_mgr.prep_ssg_nodes();
549 // force the default state so ssg can get back on track if
550 // we've changed things elsewhere
551 FGMaterialSlot m_slot;
552 FGMaterialSlot *m_ptr = &m_slot;
553 if ( material_mgr.find( "Default", m_ptr ) ) {
554 m_ptr->get_state()->force();
557 // draw the ssg scene
558 ssgCullAndDraw( scene );
560 xglDisable( GL_TEXTURE_2D );
561 xglDisable( GL_FOG );
563 // display HUD && Panel
564 xglDisable( GL_CULL_FACE );
567 // We can do translucent menus, so why not. :-)
568 xglEnable ( GL_BLEND ) ;
569 xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
571 xglDisable ( GL_BLEND ) ;
580 // Update internal time dependent calculations (i.e. flight model)
581 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
582 static fdm_state_list fdm_list;
583 // FGInterface fdm_state;
584 fgLIGHT *l = &cur_light_params;
585 FGTime *t = FGTime::cur_time_params;
586 // FGView *v = ¤t_view;
589 // update the flight model
590 if ( multi_loop < 0 ) {
594 if ( !t->getPause() ) {
595 // run Autopilot system
598 // printf("updating flight model x %d\n", multi_loop);
599 /* fgFDMUpdate( current_options.get_flight_model(),
601 multi_loop * current_options.get_speed_up(),
603 cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
605 // fgFDMUpdate( current_options.get_flight_model(),
606 // fdm_state, 0, remainder );
607 cur_fdm_state->update( 0 );
610 fdm_list.push_back( *cur_fdm_state );
611 while ( fdm_list.size() > 15 ) {
612 fdm_list.pop_front();
615 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
616 cur_view_fdm = *cur_fdm_state;
618 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
619 cur_view_fdm = fdm_list.front();
622 // update the view angle
623 for ( i = 0; i < multi_loop; i++ ) {
624 if ( fabs(current_view.get_goal_view_offset() -
625 current_view.get_view_offset()) < 0.05 )
627 current_view.set_view_offset( current_view.get_goal_view_offset() );
630 // move current_view.view_offset towards current_view.goal_view_offset
631 if ( current_view.get_goal_view_offset() >
632 current_view.get_view_offset() )
634 if ( current_view.get_goal_view_offset() -
635 current_view.get_view_offset() < FG_PI )
637 current_view.inc_view_offset( 0.01 );
639 current_view.inc_view_offset( -0.01 );
642 if ( current_view.get_view_offset() -
643 current_view.get_goal_view_offset() < FG_PI )
645 current_view.inc_view_offset( -0.01 );
647 current_view.inc_view_offset( 0.01 );
650 if ( current_view.get_view_offset() > FG_2PI ) {
651 current_view.inc_view_offset( -FG_2PI );
652 } else if ( current_view.get_view_offset() < 0 ) {
653 current_view.inc_view_offset( FG_2PI );
658 double tmp = -(l->sun_rotation + FG_PI)
659 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
660 while ( tmp < 0.0 ) {
663 while ( tmp > FG_2PI ) {
666 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
667 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
668 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
673 void fgInitTimeDepCalcs( void ) {
676 // #ifdef HAVE_SETITIMER
677 // fgTimerInit( 1.0 / current_options.get_model_hz(),
678 // fgUpdateTimeDepCalcs );
679 // #endif HAVE_SETITIMER
683 static const double alt_adjust_ft = 3.758099;
684 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
687 // What should we do when we have nothing else to do? Let's get ready
688 // for the next move and update the display?
689 static void fgMainLoop( void ) {
691 static long remainder = 0;
693 #ifdef FANCY_FRAME_COUNTER
697 static time_t last_time = 0;
698 static int frames = 0;
699 #endif // FANCY_FRAME_COUNTER
701 t = FGTime::cur_time_params;
703 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
704 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
706 #if defined( ENABLE_PLIB_JOYSTICK )
707 // Read joystick and update control settings
708 if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
711 #elif defined( ENABLE_GLUT_JOYSTICK )
712 // Glut joystick support works by feeding a joystick handler
713 // function to glut. This is taken care of once in the joystick
714 // init routine and we don't have to worry about it again.
717 #ifdef FG_OLD_WEATHER
718 current_weather.Update();
721 // Fix elevation. I'm just sticking this here for now, it should
722 // probably move eventually
724 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
726 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
727 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
729 if ( scenery.cur_elev > -9990 ) {
730 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
731 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
732 // now set aircraft altitude above ground
733 printf("Current Altitude = %.2f < %.2f forcing to %.2f\n",
734 cur_fdm_state->get_Altitude() * FEET_TO_METER,
735 scenery.cur_elev + alt_adjust_m - 3.0,
736 scenery.cur_elev + alt_adjust_m );
737 fgFDMForceAltitude( current_options.get_flight_model(),
738 scenery.cur_elev + alt_adjust_m );
740 FG_LOG( FG_ALL, FG_DEBUG,
741 "<*> resetting altitude to "
742 << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
744 fgFDMSetGroundElevation( current_options.get_flight_model(),
745 scenery.cur_elev ); // meters
748 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
750 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
751 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
754 t->update(*cur_fdm_state);
756 // Get elapsed time (in usec) for this past frame
757 elapsed = fgGetTimeInterval();
758 FG_LOG( FG_ALL, FG_DEBUG,
759 "Elapsed time interval is = " << elapsed
760 << ", previous remainder is = " << remainder );
762 // Calculate frame rate average
763 #ifdef FANCY_FRAME_COUNTER
764 /* old fps calculation */
768 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
769 tmp = general.get_frame(i);
771 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
772 general.set_frame(i+1,tmp);
774 tmp = 1000000.0 / (float)elapsed;
775 general.set_frame(0,tmp);
776 // printf("frame[0] = %.2f\n", general.frames[0]);
778 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
779 // printf("ave = %.2f\n", general.frame_rate);
782 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
783 general.set_frame_rate( frames );
784 FG_LOG( FG_ALL, FG_DEBUG,
785 "--> Frame rate is = " << general.get_frame_rate() );
788 last_time = t->get_cur_time();
793 if ( ! use_signals ) {
794 // Calculate model iterations needed for next frame
795 elapsed += remainder;
797 global_multi_loop = (int)(((double)elapsed * 0.000001) *
798 current_options.get_model_hz());
799 remainder = elapsed - ( (global_multi_loop*1000000) /
800 current_options.get_model_hz() );
801 FG_LOG( FG_ALL, FG_DEBUG,
802 "Model iterations needed = " << global_multi_loop
803 << ", new remainder = " << remainder );
806 if ( global_multi_loop > 0 ) {
807 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
809 FG_LOG( FG_ALL, FG_DEBUG,
810 "Elapsed time is zero ... we're zinging" );
814 #if ! defined( MACOS )
815 // Do any I/O channel work that might need to be done
819 // see if we need to load any new scenery tiles
820 global_tile_mgr.update();
822 // Process/manage pending events
823 global_events.Process();
825 // Run audio scheduler
826 #ifdef ENABLE_AUDIO_SUPPORT
827 if ( current_options.get_sound() && !audio_sched->not_working() ) {
829 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
831 // note: all these factors are relative to the sample. our
832 // sample format should really contain a conversion factor so
833 // that we can get prop speed right for arbitrary samples.
834 // Note that for normal-size props, there is a point at which
835 // the prop tips approach the speed of sound; that is a pretty
836 // strong limit to how fast the prop can go.
838 // multiplication factor is prime pitch control; add some log
839 // component for verisimilitude
841 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
842 //fprintf(stderr, "pitch1: %f ", pitch);
843 if (controls.get_throttle(0) > 0.0 || cur_fdm_state->v_rel_wind > 40.0) {
844 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
845 // only add relative wind and AoA if prop is moving
846 // or we're really flying at idle throttle
847 if (pitch < 5.4) { // this needs tuning
848 // prop tips not breaking sound barrier
849 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
851 // prop tips breaking sound barrier
852 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
854 //fprintf(stderr, "pitch2: %f ", pitch);
855 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
857 // Angle of Attack next... -x^3(e^x) is my best guess Just
858 // need to calculate some reasonable scaling factor and
859 // then clamp it on the positive aoa (neg adj) side
860 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
862 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
863 if (aoa_adj < -0.8) aoa_adj = -0.8;
865 //fprintf(stderr, "pitch3: %f ", pitch);
867 // don't run at absurdly slow rates -- not realistic
868 // and sounds bad to boot. :-)
869 if (pitch < 0.8) pitch = 0.8;
871 //fprintf(stderr, "pitch4: %f\n", pitch);
873 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
874 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
875 // fprintf(stderr, "volume: %f\n", volume);
877 pitch_envelope.setStep ( 0, 0.01, pitch );
878 volume_envelope.setStep ( 0, 0.01, volume );
882 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
883 pitch_envelope.setStep ( 0, 0.01, param );
884 volume_envelope.setStep ( 0, 0.01, param );
886 # endif // experimental throttle patch
888 audio_sched -> update();
895 FG_LOG( FG_ALL, FG_DEBUG, "" );
899 // This is the top level master main function that is registered as
903 // The first few passes take care of initialization things (a couple
904 // per pass) and once everything has been initialized fgMainLoop from
907 static void fgIdleFunction ( void ) {
908 // printf("idle state == %d\n", idle_state);
910 if ( idle_state == 0 ) {
911 // Initialize the splash screen right away
912 if ( current_options.get_splash_screen() ) {
917 } else if ( idle_state == 1 ) {
918 // Start the intro music
920 if ( current_options.get_intro_music() ) {
921 string lockfile = "/tmp/mpg123.running";
922 FGPath mp3file( current_options.get_fg_root() );
923 mp3file.append( "Sounds/intro.mp3" );
925 string command = "(touch " + lockfile + "; mpg123 "
926 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
928 FG_LOG( FG_GENERAL, FG_INFO,
929 "Starting intro music: " << mp3file.str() );
930 system ( command.c_str() );
935 } else if ( idle_state == 2 ) {
936 // These are a few miscellaneous things that aren't really
937 // "subsystems" but still need to be initialized.
940 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
941 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
946 } else if ( idle_state == 3 ) {
947 // This is the top level init routine which calls all the
948 // other subsystem initialization routines. If you are adding
949 // a subsystem to flight gear, its initialization call should
950 // located in this routine.
951 if( !fgInitSubsystems()) {
952 FG_LOG( FG_GENERAL, FG_ALERT,
953 "Subsystem initializations failed ..." );
958 } else if ( idle_state == 4 ) {
959 // setup OpenGL view parameters
963 // init timer routines, signals, etc. Arrange for an alarm
964 // signal to be generated, etc.
965 fgInitTimeDepCalcs();
969 } else if ( idle_state == 5 ) {
972 } else if ( idle_state == 6 ) {
973 // Initialize audio support
974 #ifdef ENABLE_AUDIO_SUPPORT
977 if ( current_options.get_intro_music() ) {
978 // Let's wait for mpg123 to finish
979 string lockfile = "/tmp/mpg123.running";
980 struct stat stat_buf;
982 FG_LOG( FG_GENERAL, FG_INFO,
983 "Waiting for mpg123 player to finish ..." );
984 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
985 // file exist, wait ...
987 FG_LOG( FG_GENERAL, FG_INFO, ".");
989 FG_LOG( FG_GENERAL, FG_INFO, "");
993 if ( current_options.get_sound() ) {
994 audio_sched = new slScheduler ( 8000 );
995 audio_mixer = new smMixer;
996 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
997 audio_sched -> setSafetyMargin ( 1.0 ) ;
999 FGPath slfile( current_options.get_fg_root() );
1000 slfile.append( "Sounds/wasp.wav" );
1002 s1 = new slSample ( (char *)slfile.c_str() );
1003 FG_LOG( FG_GENERAL, FG_INFO,
1004 "Rate = " << s1 -> getRate()
1005 << " Bps = " << s1 -> getBps()
1006 << " Stereo = " << s1 -> getStereo() );
1007 audio_sched -> loopSample ( s1 );
1009 if ( audio_sched->not_working() ) {
1012 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1013 volume_envelope.setStep ( 0, 0.01, 0.6 );
1015 audio_sched -> addSampleEnvelope( s1, 0, 0,
1017 SL_PITCH_ENVELOPE );
1018 audio_sched -> addSampleEnvelope( s1, 0, 1,
1020 SL_VOLUME_ENVELOPE );
1023 // strcpy(slfile, path);
1024 // strcat(slfile, "thunder.wav");
1025 // s2 -> loadFile ( slfile );
1026 // s2 -> adjustVolume(0.5);
1027 // audio_sched -> playSample ( s2 );
1035 if ( idle_state == 1000 ) {
1036 // We've finished all our initialization steps, from now on we
1037 // run the main loop.
1041 if ( current_options.get_splash_screen() == 1 ) {
1042 fgSplashUpdate(0.0);
1047 // options.cxx needs to see this for toggle_panel()
1048 // Handle new window size or exposure
1049 void fgReshape( int width, int height ) {
1050 if ( ! current_options.get_panel_status() ) {
1051 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1052 xglViewport(0, 0 , (GLint)(width), (GLint)(height) );
1054 current_view.set_win_ratio( (GLfloat) width /
1055 ((GLfloat) (height)*0.4232) );
1056 xglViewport(0, (GLint)((height)*0.5768), (GLint)(width),
1057 (GLint)((height)*0.4232) );
1060 current_view.set_winWidth( width );
1061 current_view.set_winHeight( height );
1062 current_view.force_update_fov_math();
1064 // set these fov to be the same as in fgRenderFrame()
1065 float x_fov = current_options.get_fov();
1066 float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1067 ssgSetFOV( x_fov, y_fov );
1069 glViewport ( 0, 0, width, height );
1070 float fov = current_options.get_fov();
1071 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1073 if ( idle_state == 1000 ) {
1074 // yes we've finished all our initializations and are running
1075 // the main loop, so this will now work without seg faulting
1077 solarSystemRebuild();
1078 current_view.UpdateViewParams(cur_view_fdm);
1079 if ( current_options.get_panel_status() ) {
1080 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
1086 // Initialize GLUT and define a main window
1087 int fgGlutInit( int *argc, char **argv ) {
1089 #if !defined( MACOS )
1090 // GLUT will extract all glut specific options so later on we only
1091 // need wory about our own.
1092 xglutInit(argc, argv);
1095 // Define Display Parameters
1096 xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1098 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1099 current_options.get_xsize() << "x" << current_options.get_ysize() );
1101 // Define initial window size
1102 xglutInitWindowSize( current_options.get_xsize(),
1103 current_options.get_ysize() );
1105 // Initialize windows
1106 if ( current_options.get_game_mode() == 0 ) {
1107 // Open the regular window
1108 xglutCreateWindow("Flight Gear");
1109 #ifndef GLUT_WRONG_VERSION
1111 // Open the cool new 'game mode' window
1112 char game_mode_str[256];
1113 sprintf( game_mode_str, "width=%d height=%d bpp=32",
1114 current_options.get_xsize(),
1115 current_options.get_ysize() );
1117 FG_LOG( FG_GENERAL, FG_INFO,
1118 "game mode params = " << game_mode_str );
1119 glutGameModeString( game_mode_str );
1120 glutEnterGameMode();
1124 // This seems to be the absolute earliest in the init sequence
1125 // that these calls will return valid info. Too bad it's after
1126 // we've already created and sized out window. :-(
1127 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1128 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1129 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1131 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1134 // try to determine if we should adjust the initial default
1135 // display resolution. The options class defaults (is
1136 // initialized) to 640x480.
1137 string renderer = general.glRenderer;
1139 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1140 if ( renderer.find( "Glide" ) != string::npos ) {
1141 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1142 if ( renderer.find( "FB/8" ) != string::npos ) {
1143 // probably a voodoo-2
1144 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1145 // probably two SLI'd Voodoo-2's
1146 current_options.set_xsize( 1024 );
1147 current_options.set_ysize( 768 );
1148 FG_LOG( FG_GENERAL, FG_INFO,
1149 "It looks like you have two sli'd voodoo-2's." << endl
1150 << "upgrading your win resolution to 1024 x 768" );
1151 glutReshapeWindow(1024, 768);
1153 // probably a single non-SLI'd Voodoo-2
1154 current_options.set_xsize( 800 );
1155 current_options.set_ysize( 600 );
1156 FG_LOG( FG_GENERAL, FG_INFO,
1157 "It looks like you have a voodoo-2." << endl
1158 << "upgrading your win resolution to 800 x 600" );
1159 glutReshapeWindow(800, 600);
1161 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1162 // probably a voodoo-1, stick with the default
1165 // we have no special knowledge of this card, stick with the default
1173 // Initialize GLUT event handlers
1174 int fgGlutInitEvents( void ) {
1175 // call fgReshape() on window resizes
1176 xglutReshapeFunc( fgReshape );
1178 // call GLUTkey() on keyboard event
1179 xglutKeyboardFunc( GLUTkey );
1180 glutSpecialFunc( GLUTspecialkey );
1182 // call guiMouseFunc() whenever our little rodent is used
1183 glutMouseFunc ( guiMouseFunc );
1184 glutMotionFunc (guiMotionFunc );
1185 glutPassiveMotionFunc (guiMotionFunc );
1187 // call fgMainLoop() whenever there is
1188 // nothing else to do
1189 xglutIdleFunc( fgIdleFunction );
1192 xglutDisplayFunc( fgRenderFrame );
1199 int main( int argc, char **argv ) {
1201 #if defined( MACOS )
1202 argc = ccommand( &argv );
1206 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1209 // set default log levels
1210 fglog().setLogLevels( FG_ALL, FG_INFO );
1212 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1214 // seed the random number generater
1217 // Load the configuration parameters
1218 if ( !fgInitConfig(argc, argv) ) {
1219 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1223 // Initialize the Window/Graphics environment.
1224 if( !fgGlutInit(&argc, argv) ) {
1225 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1229 // Initialize the various GLUT Event Handlers.
1230 if( !fgGlutInitEvents() ) {
1231 FG_LOG( FG_GENERAL, FG_ALERT,
1232 "GLUT event handler initialization failed ..." );
1236 // Initialize ssg (from plib)
1239 // Initialize the user interface (we need to do this before
1240 // passing off control to glut and before fgInitGeneral to get our
1244 // Do some quick general initializations
1245 if( !fgInitGeneral()) {
1246 FG_LOG( FG_GENERAL, FG_ALERT,
1247 "General initializations failed ..." );
1252 // some ssg test stuff (requires data from the plib source
1253 // distribution) specifically from the ssg tux example
1256 FGPath modelpath( current_options.get_fg_root() );
1257 modelpath.append( "Models" );
1258 modelpath.append( "Geometry" );
1260 FGPath texturepath( current_options.get_fg_root() );
1261 texturepath.append( "Models" );
1262 texturepath.append( "Textures" );
1264 ssgModelPath( (char *)modelpath.c_str() );
1265 ssgTexturePath( (char *)texturepath.c_str() );
1267 scene = new ssgRoot;
1268 terrain = new ssgBranch;
1269 terrain->setName( "Terrain" );
1270 penguin_sel = new ssgSelector;
1271 penguin_pos = new ssgTransform;
1273 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1274 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1275 tux_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1276 penguin_pos->addKid( tux_obj );
1277 penguin_sel->addKid( penguin_pos );
1278 ssgFlatten( tux_obj );
1279 ssgStripify( penguin_sel );
1281 #ifdef FG_NETWORK_OLK
1282 // Do the network intialization
1283 printf("Multipilot mode %s\n", fg_net_init() );
1286 scene->addKid( terrain );
1287 scene->addKid( penguin_sel );
1289 // pass control off to the master GLUT event handler
1292 // we never actually get here ... but to avoid compiler warnings,