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
41 #include <simgear/xgl/xgl.h>
51 #ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h> /* for stat() */
56 # include <unistd.h> /* for stat() */
59 #include <plib/pu.h> // plib include
60 #include <plib/ssg.h> // plib include
62 #ifdef ENABLE_AUDIO_SUPPORT
63 # include <plib/sl.h> // plib include
64 # include <plib/sm.h> // plib include
67 #include <simgear/constants.h> // for VERSION
68 #include <simgear/debug/logstream.hxx>
69 #include <simgear/math/fg_geodesy.hxx>
70 #include <simgear/math/polar3d.hxx>
71 #include <simgear/math/fg_random.h>
72 #include <simgear/misc/fgpath.hxx>
74 #include <Include/general.hxx>
76 #include <Aircraft/aircraft.hxx>
77 #include <Ephemeris/ephemeris.hxx>
79 #include <Autopilot/autopilot.hxx>
80 #include <Cockpit/cockpit.hxx>
81 #include <Cockpit/steam.hxx>
82 #include <FDM/UIUCModel/uiuc_aircraft.h>
83 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
85 #include <Joystick/joystick.hxx>
87 #include <NetworkOLK/network.h>
89 #include <Objects/materialmgr.hxx>
90 #include <Scenery/scenery.hxx>
91 #include <Scenery/tilemgr.hxx>
92 #include <Sky/sky.hxx>
93 #include <Time/event.hxx>
94 #include <Time/fg_time.hxx>
95 #include <Time/fg_timer.hxx>
96 #include <Time/sunpos.hxx>
98 #ifndef FG_OLD_WEATHER
99 # include <WeatherCM/FGLocalWeatherDatabase.h>
101 # include <Weather/weather.hxx>
104 #include "fg_init.hxx"
106 #include "keyboard.hxx"
107 #include "options.hxx"
108 #include "splash.hxx"
112 // -dw- use custom sioux settings so I can see output window
115 # include <sioux.h> // settings for output window
117 # include <console.h>
121 // This is a record containing a bit of global housekeeping information
124 // Specify our current idle function state. This is used to run all
125 // our initializations out of the glutIdleLoop() so that we can get a
126 // splash screen up and running right away.
127 static int idle_state = 0;
128 static int global_multi_loop;
133 // Global structures for the Audio library
134 #ifdef ENABLE_AUDIO_SUPPORT
135 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
136 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
137 slScheduler *audio_sched;
138 smMixer *audio_mixer;
145 ssgRoot *scene = NULL;
146 ssgBranch *terrain = NULL;
147 ssgSelector *penguin_sel = NULL;
148 ssgTransform *penguin_pos = NULL;
150 #ifdef FG_NETWORK_OLK
151 ssgSelector *fgd_sel = NULL;
152 ssgTransform *fgd_pos = NULL;
156 // current fdm/position used for view
157 FGInterface cur_view_fdm;
164 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
166 { 1.0f, 0.0f, 0.0f, 0.0f },
167 { 0.0f, 0.0f, -1.0f, 0.0f },
168 { 0.0f, 1.0f, 0.0f, 0.0f },
169 { 0.0f, 0.0f, 0.0f, 1.0f }
172 // The following defines flight gear options. Because glutlib will also
173 // want to parse its own options, those options must not be included here
174 // or they will get parsed by the main program option parser. Hence case
175 // is significant for any option added that might be in conflict with
178 // glutlib parses for:
180 // -direct (invalid in Win32)
184 // -indirect (invalid in Win32)
187 // Note that glutlib depends upon strings while this program's
188 // option parser wants only initial characters followed by numbers
193 ssgSimpleState *default_state;
194 ssgSimpleState *hud_and_panel;
195 ssgSimpleState *menus;
197 void fgBuildRenderStates( void ) {
198 default_state = new ssgSimpleState;
199 default_state->disable( GL_TEXTURE_2D );
200 default_state->enable( GL_CULL_FACE );
201 default_state->disable( GL_COLOR_MATERIAL );
202 default_state->disable( GL_BLEND );
203 default_state->disable( GL_ALPHA_TEST );
204 default_state->disable( GL_LIGHTING );
205 default_state->setMaterial( GL_AMBIENT_AND_DIFFUSE, 1.0, 1.0, 1.0, 1.0 );
207 hud_and_panel = new ssgSimpleState;
208 hud_and_panel->disable( GL_CULL_FACE );
209 hud_and_panel->disable( GL_TEXTURE_2D );
210 hud_and_panel->disable( GL_LIGHTING );
212 menus = new ssgSimpleState;
213 menus->disable( GL_CULL_FACE );
214 menus->disable( GL_TEXTURE_2D );
215 menus->enable( GL_BLEND );
219 // fgInitVisuals() -- Initialize various GL/view parameters
220 void fgInitVisuals( void ) {
223 l = &cur_light_params;
225 #ifndef GLUT_WRONG_VERSION
226 // Go full screen if requested ...
227 if ( current_options.get_fullscreen() ) {
232 // If enabled, normal vectors specified with glNormal are scaled
233 // to unit length after transformation. See glNormal.
234 // glEnable( GL_NORMALIZE );
236 glEnable( GL_LIGHTING );
237 glEnable( GL_LIGHT0 );
238 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
241 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
242 ssgGetLight( 0 ) -> setPosition( sunpos );
244 // glFogi (GL_FOG_MODE, GL_LINEAR);
245 glFogi (GL_FOG_MODE, GL_EXP2);
246 if ( (current_options.get_fog() == 1) ||
247 (current_options.get_shading() == 0) ) {
248 // if fastest fog requested, or if flat shading force fastest
249 glHint ( GL_FOG_HINT, GL_FASTEST );
250 } else if ( current_options.get_fog() == 2 ) {
251 glHint ( GL_FOG_HINT, GL_NICEST );
253 if ( current_options.get_wireframe() ) {
255 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
258 // This is the default anyways, but it can't hurt
259 glFrontFace ( GL_CCW );
262 // glEnable(GL_POINT_SMOOTH);
263 // glEnable(GL_LINE_SMOOTH);
264 // glEnable(GL_POLYGON_SMOOTH);
268 // Update all Visuals (redraws anything graphics related)
269 void fgRenderFrame( void ) {
270 fgLIGHT *l = &cur_light_params;
271 FGTime *t = FGTime::cur_time_params;
272 // FGView *v = ¤t_view;
273 static double last_visibility = -9999;
274 static bool in_puff = false;
275 static double puff_length = 0;
276 static double puff_progression = 0;
277 const double ramp_up = 0.15;
278 const double ramp_down = 0.15;
281 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
282 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
283 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
284 // GLfloat mat_shininess[] = { 10.0 };
285 GLbitfield clear_mask;
287 if ( idle_state != 1000 ) {
288 // still initializing, draw the splash screen
289 if ( current_options.get_splash_screen() == 1 ) {
293 // idle_state is now 1000 meaning we've finished all our
294 // initializations and are running the main loop, so this will
295 // now work without seg faulting the system.
297 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
298 // FG_Altitude * FEET_TO_METER);
300 // this is just a temporary hack, to make me understand Pui
301 // timerText -> setLabel (ctime (&t->cur_time));
304 // update view volume parameters
305 // cout << "before pilot_view update" << endl;
306 pilot_view.UpdateViewParams(*cur_fdm_state);
307 // cout << "after pilot_view update" << endl;
308 current_view.UpdateViewParams(cur_view_fdm);
310 // set the sun position
311 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
313 clear_mask = GL_DEPTH_BUFFER_BIT;
314 if ( current_options.get_wireframe() ) {
315 clear_mask |= GL_COLOR_BUFFER_BIT;
317 if ( current_options.get_panel_status() ) {
318 // we can't clear the screen when the panel is active
319 } else if ( current_options.get_skyblend() ) {
320 if ( current_options.get_textures() ) {
321 // glClearColor(black[0], black[1], black[2], black[3]);
322 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
323 l->adj_fog_color[2], l->adj_fog_color[3]);
324 clear_mask |= GL_COLOR_BUFFER_BIT;
327 glClearColor(l->sky_color[0], l->sky_color[1],
328 l->sky_color[2], l->sky_color[3]);
329 clear_mask |= GL_COLOR_BUFFER_BIT;
331 glClear( clear_mask );
333 // Tell GL we are switching to model view parameters
335 // I really should create a derived ssg node or use a call
336 // back or something so that I can draw the sky within the
337 // ssgCullandDraw() function, but for now I just mimic what
338 // ssg does to set up the model view matrix
339 glMatrixMode(GL_MODELVIEW);
341 ssgSetCamera( current_view.VIEW );
344 sgMat4 vm_tmp, view_mat;
345 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
346 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
347 sgPreMultMat4( view_mat, vm_tmp ) ;
348 glLoadMatrixf( (float *)view_mat );
351 // set the opengl state to known default values
352 default_state->force();
355 if ( current_options.get_skyblend() ) {
358 current_view.get_view_pos().x(),
359 current_view.get_view_pos().y(),
360 current_view.get_view_pos().z() );
363 sgSetVec3( zero_elev,
364 current_view.get_cur_zero_elev().x(),
365 current_view.get_cur_zero_elev().y(),
366 current_view.get_cur_zero_elev().z() );
368 /* cout << "thesky->repaint() sky_color = "
369 << cur_light_params.sky_color[0] << " "
370 << cur_light_params.sky_color[1] << " "
371 << cur_light_params.sky_color[2] << " "
372 << cur_light_params.sky_color[3] << endl;
374 << cur_light_params.fog_color[0] << " "
375 << cur_light_params.fog_color[1] << " "
376 << cur_light_params.fog_color[2] << " "
377 << cur_light_params.fog_color[3] << endl;
378 cout << " sun_angle = " << cur_light_params.sun_angle
379 << " moon_angle = " << cur_light_params.moon_angle
381 thesky->repaint( cur_light_params.sky_color,
382 cur_light_params.adj_fog_color,
383 cur_light_params.sun_angle,
384 cur_light_params.moon_angle,
385 ephem->getNumPlanets(), ephem->getPlanets(),
386 ephem->getNumStars(), ephem->getStars() );
388 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
389 << view_pos[1] << " " << view_pos[2] << endl;
390 cout << " zero_elev = " << zero_elev[0] << " "
391 << zero_elev[1] << " " << zero_elev[2]
392 << " lon = " << cur_fdm_state->get_Longitude()
393 << " lat = " << cur_fdm_state->get_Latitude() << endl;
394 cout << " sun_rot = " << cur_light_params.sun_rotation
395 << " gst = " << FGTime::cur_time_params->getGst() << endl;
396 cout << " sun ra = " << ephem->getSunRightAscension()
397 << " sun dec = " << ephem->getSunDeclination()
398 << " moon ra = " << ephem->getMoonRightAscension()
399 << " moon dec = " << ephem->getMoonDeclination() << endl; */
401 thesky->reposition( view_pos, zero_elev,
402 cur_fdm_state->get_Longitude(),
403 cur_fdm_state->get_Latitude(),
404 cur_light_params.sun_rotation,
405 FGTime::cur_time_params->getGst(),
406 ephem->getSunRightAscension(),
407 ephem->getSunDeclination(), 50000.0,
408 ephem->getMoonRightAscension(),
409 ephem->getMoonDeclination(), 50000.0 );
412 glEnable( GL_DEPTH_TEST );
413 if ( current_options.get_fog() > 0 ) {
415 glFogi( GL_FOG_MODE, GL_EXP2 );
416 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
419 // update fog params if visibility has changed
420 #ifndef FG_OLD_WEATHER
421 double cur_visibility = WeatherDatabase->getWeatherVisibility();
423 double cur_visibility = current_weather.get_visibility();
425 double actual_visibility = cur_visibility;
427 if ( current_options.get_clouds() ) {
428 double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
429 current_options.get_clouds_asl() );
430 // cout << "altitude diff = " << diff << endl;
433 // calc chance of entering cloud puff
434 double rnd = fg_random();
435 double chance = rnd * rnd * rnd;
436 if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) {
439 puff_length = fg_random() * 2.0; // up to 2 seconds
440 } while ( puff_length <= 0.0 );
441 puff_progression = 0.0;
445 actual_visibility = cur_visibility * (diff - 25) / 50.0;
448 // modify actual_visibility based on puff envelope
450 if ( puff_progression <= ramp_up ) {
451 double x = FG_PI_2 * puff_progression / ramp_up;
452 double factor = 1.0 - sin( x );
453 actual_visibility = actual_visibility * factor;
454 } else if ( puff_progression >= ramp_up + puff_length ) {
456 (puff_progression - (ramp_up + puff_length)) /
458 double factor = sin( x );
459 actual_visibility = actual_visibility * factor;
461 actual_visibility = 0.0;
464 /* cout << "len = " << puff_length
466 << " factor = " << factor
467 << " actual_visibility = " << actual_visibility
470 puff_progression += ( global_multi_loop *
471 current_options.get_speed_up() ) /
472 (double)current_options.get_model_hz();
474 /* cout << "gml = " << global_multi_loop
475 << " speed up = " << current_options.get_speed_up()
476 << " hz = " << current_options.get_model_hz() << endl;
479 if ( puff_progression > puff_length + ramp_up + ramp_down) {
484 // never let visibility drop below zero
485 if ( actual_visibility < 0 ) {
486 actual_visibility = 0;
491 // cout << "actual visibility = " << actual_visibility << endl;
493 if ( actual_visibility != last_visibility ) {
494 last_visibility = actual_visibility;
496 // cout << "----> updating fog params" << endl;
498 GLfloat fog_exp_density;
499 GLfloat fog_exp2_density;
502 fog_exp_density = -log(0.01 / actual_visibility);
505 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
507 // Set correct opengl fog density
508 glFogf (GL_FOG_DENSITY, fog_exp2_density);
511 // set lighting parameters
512 glLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
513 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
514 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
516 // texture parameters
517 // glEnable( GL_TEXTURE_2D );
518 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
519 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
520 // set base color (I don't think this is doing anything here)
521 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
522 // (GL_FRONT, GL_DIFFUSE, white);
523 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
524 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
527 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
528 ssgGetLight( 0 ) -> setPosition( sunpos );
530 // glMatrixMode( GL_PROJECTION );
532 float fov = current_options.get_fov();
533 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
535 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
538 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
539 // << current_weather.get_visibility() );
542 ssgSetNearFar( 10.0f, 120000.0f );
544 ssgSetNearFar( 0.5f, 120000.0f );
547 if ( current_options.get_view_mode() ==
548 fgOPTIONS::FG_VIEW_PILOT )
551 penguin_sel->select(0);
552 } else if ( current_options.get_view_mode() ==
553 fgOPTIONS::FG_VIEW_FOLLOW )
555 // select view matrix from front of view matrix queue
556 // FGMat4Wrapper tmp = current_view.follow.front();
557 // sgCopyMat4( sgVIEW, tmp.m );
559 // enable TuX and set up his position and orientation
560 penguin_sel->select(1);
563 sgMakeTransMat4( sgTRANS,
564 pilot_view.view_pos.x(),
565 pilot_view.view_pos.y(),
566 pilot_view.view_pos.z() );
569 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
572 sgMakeRotMat4( sgROT, -90.0, ownship_up );
576 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
577 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
579 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
581 sgCopyMat4( sgTUX, sgROT );
582 sgPostMultMat4( sgTUX, pilot_view.VIEW_ROT );
583 sgPostMultMat4( sgTUX, sgTRANS );
586 sgSetCoord( &tuxpos, sgTUX );
587 penguin_pos->setTransform( &tuxpos );
590 # ifdef FG_NETWORK_OLK
591 if ( current_options.get_network_olk() ) {
593 other = head->next; /* put listpointer to start */
594 while ( other != tail) { /* display all except myself */
595 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
596 other->fgd_sel->select(1);
597 sgSetCoord( &fgdpos, other->sgFGD_COORD );
598 other->fgd_pos->setTransform( &fgdpos );
603 // fgd_sel->select(1);
604 // sgCopyMat4( sgTUX, current_view.sgVIEW);
606 // sgSetCoord( &fgdpos, sgFGD_VIEW );
607 // fgd_pos->setTransform( &fgdpos);
611 // ssgSetCamera( current_view.VIEW );
613 // position tile nodes and update range selectors
614 global_tile_mgr.prep_ssg_nodes();
616 // force the default state so ssg can get back on track if
617 // we've changed things elsewhere
618 FGMaterialSlot m_slot;
619 FGMaterialSlot *m_ptr = &m_slot;
620 if ( material_mgr.find( "Default", m_ptr ) ) {
621 m_ptr->get_state()->force();
624 // draw the ssg scene
625 ssgCullAndDraw( scene );
628 // display HUD && Panel
630 glDisable( GL_DEPTH_TEST );
631 // glDisable( GL_CULL_FACE );
632 // glDisable( GL_TEXTURE_2D );
633 hud_and_panel->apply();
636 // We can do translucent menus, so why not. :-)
637 // glEnable ( GL_BLEND ) ;
639 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
641 // glDisable ( GL_BLEND ) ;
643 // glEnable( GL_FOG );
650 // Update internal time dependent calculations (i.e. flight model)
651 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
652 static fdm_state_list fdm_list;
653 // FGInterface fdm_state;
654 fgLIGHT *l = &cur_light_params;
655 FGTime *t = FGTime::cur_time_params;
656 // FGView *v = ¤t_view;
659 // update the flight model
660 if ( multi_loop < 0 ) {
664 if ( !t->getPause() ) {
665 // run Autopilot system
668 // printf("updating flight model x %d\n", multi_loop);
669 /* fgFDMUpdate( current_options.get_flight_model(),
671 multi_loop * current_options.get_speed_up(),
673 cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
674 FGSteam::update( multi_loop * current_options.get_speed_up() );
676 // fgFDMUpdate( current_options.get_flight_model(),
677 // fdm_state, 0, remainder );
678 cur_fdm_state->update( 0 );
679 FGSteam::update( 0 );
682 fdm_list.push_back( *cur_fdm_state );
683 while ( fdm_list.size() > 15 ) {
684 fdm_list.pop_front();
687 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
688 cur_view_fdm = *cur_fdm_state;
690 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
691 cur_view_fdm = fdm_list.front();
694 // update the view angle
695 for ( i = 0; i < multi_loop; i++ ) {
696 if ( fabs(current_view.get_goal_view_offset() -
697 current_view.get_view_offset()) < 0.05 )
699 current_view.set_view_offset( current_view.get_goal_view_offset() );
702 // move current_view.view_offset towards current_view.goal_view_offset
703 if ( current_view.get_goal_view_offset() >
704 current_view.get_view_offset() )
706 if ( current_view.get_goal_view_offset() -
707 current_view.get_view_offset() < FG_PI )
709 current_view.inc_view_offset( 0.01 );
711 current_view.inc_view_offset( -0.01 );
714 if ( current_view.get_view_offset() -
715 current_view.get_goal_view_offset() < FG_PI )
717 current_view.inc_view_offset( -0.01 );
719 current_view.inc_view_offset( 0.01 );
722 if ( current_view.get_view_offset() > FG_2PI ) {
723 current_view.inc_view_offset( -FG_2PI );
724 } else if ( current_view.get_view_offset() < 0 ) {
725 current_view.inc_view_offset( FG_2PI );
730 double tmp = -(l->sun_rotation + FG_PI)
731 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
732 while ( tmp < 0.0 ) {
735 while ( tmp > FG_2PI ) {
738 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
739 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
740 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
743 // Update solar system
744 ephem->update( t, cur_fdm_state->get_Latitude() );
748 void fgInitTimeDepCalcs( void ) {
751 // #ifdef HAVE_SETITIMER
752 // fgTimerInit( 1.0 / current_options.get_model_hz(),
753 // fgUpdateTimeDepCalcs );
754 // #endif HAVE_SETITIMER
758 static const double alt_adjust_ft = 3.758099;
759 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
762 // What should we do when we have nothing else to do? Let's get ready
763 // for the next move and update the display?
764 static void fgMainLoop( void ) {
766 static long remainder = 0;
768 #ifdef FANCY_FRAME_COUNTER
772 static time_t last_time = 0;
773 static int frames = 0;
774 #endif // FANCY_FRAME_COUNTER
776 t = FGTime::cur_time_params;
778 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
779 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
781 #ifdef FG_NETWORK_OLK
782 if ( current_options.get_network_olk() ) {
783 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
784 // printf("FGD: Netupdate\n");
785 fgd_send_com( "A", FGFS_host); // Send Mat4 data
786 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
791 #if defined( ENABLE_PLIB_JOYSTICK )
792 // Read joystick and update control settings
793 if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
796 #elif defined( ENABLE_GLUT_JOYSTICK )
797 // Glut joystick support works by feeding a joystick handler
798 // function to glut. This is taken care of once in the joystick
799 // init routine and we don't have to worry about it again.
802 #ifdef FG_OLD_WEATHER
803 current_weather.Update();
806 // Fix elevation. I'm just sticking this here for now, it should
807 // probably move eventually
809 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
811 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
812 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
814 if ( scenery.cur_elev > -9990 ) {
815 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
816 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
817 // now set aircraft altitude above ground
818 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
819 cur_fdm_state->get_Altitude() * FEET_TO_METER,
820 scenery.cur_elev + alt_adjust_m - 3.0,
821 scenery.cur_elev + alt_adjust_m );
822 fgFDMForceAltitude( current_options.get_flight_model(),
823 scenery.cur_elev + alt_adjust_m );
825 FG_LOG( FG_ALL, FG_DEBUG,
826 "<*> resetting altitude to "
827 << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
829 fgFDMSetGroundElevation( current_options.get_flight_model(),
830 scenery.cur_elev ); // meters
833 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
835 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
836 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
839 t->update( cur_fdm_state->get_Longitude(),
840 cur_fdm_state->get_Latitude(),
841 cur_fdm_state->get_Altitude()* FEET_TO_METER );
843 // Get elapsed time (in usec) for this past frame
844 elapsed = fgGetTimeInterval();
845 FG_LOG( FG_ALL, FG_DEBUG,
846 "Elapsed time interval is = " << elapsed
847 << ", previous remainder is = " << remainder );
849 // Calculate frame rate average
850 #ifdef FANCY_FRAME_COUNTER
851 /* old fps calculation */
855 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
856 tmp = general.get_frame(i);
858 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
859 general.set_frame(i+1,tmp);
861 tmp = 1000000.0 / (float)elapsed;
862 general.set_frame(0,tmp);
863 // printf("frame[0] = %.2f\n", general.frames[0]);
865 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
866 // printf("ave = %.2f\n", general.frame_rate);
869 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
870 general.set_frame_rate( frames );
871 FG_LOG( FG_ALL, FG_DEBUG,
872 "--> Frame rate is = " << general.get_frame_rate() );
875 last_time = t->get_cur_time();
880 if ( ! use_signals ) {
881 // Calculate model iterations needed for next frame
882 elapsed += remainder;
884 global_multi_loop = (int)(((double)elapsed * 0.000001) *
885 current_options.get_model_hz());
886 remainder = elapsed - ( (global_multi_loop*1000000) /
887 current_options.get_model_hz() );
888 FG_LOG( FG_ALL, FG_DEBUG,
889 "Model iterations needed = " << global_multi_loop
890 << ", new remainder = " << remainder );
893 if ( global_multi_loop > 0 ) {
894 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
896 FG_LOG( FG_ALL, FG_DEBUG,
897 "Elapsed time is zero ... we're zinging" );
901 #if ! defined( MACOS )
902 // Do any I/O channel work that might need to be done
906 // see if we need to load any new scenery tiles
907 global_tile_mgr.update();
909 // Process/manage pending events
910 global_events.Process();
912 // Run audio scheduler
913 #ifdef ENABLE_AUDIO_SUPPORT
914 if ( current_options.get_sound() && !audio_sched->not_working() ) {
916 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
918 // note: all these factors are relative to the sample. our
919 // sample format should really contain a conversion factor so
920 // that we can get prop speed right for arbitrary samples.
921 // Note that for normal-size props, there is a point at which
922 // the prop tips approach the speed of sound; that is a pretty
923 // strong limit to how fast the prop can go.
925 // multiplication factor is prime pitch control; add some log
926 // component for verisimilitude
928 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
929 //fprintf(stderr, "pitch1: %f ", pitch);
930 if (controls.get_throttle(0) > 0.0 || cur_fdm_state->v_rel_wind > 40.0) {
931 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
932 // only add relative wind and AoA if prop is moving
933 // or we're really flying at idle throttle
934 if (pitch < 5.4) { // this needs tuning
935 // prop tips not breaking sound barrier
936 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
938 // prop tips breaking sound barrier
939 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
941 //fprintf(stderr, "pitch2: %f ", pitch);
942 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
944 // Angle of Attack next... -x^3(e^x) is my best guess Just
945 // need to calculate some reasonable scaling factor and
946 // then clamp it on the positive aoa (neg adj) side
947 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
949 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
950 if (aoa_adj < -0.8) aoa_adj = -0.8;
952 //fprintf(stderr, "pitch3: %f ", pitch);
954 // don't run at absurdly slow rates -- not realistic
955 // and sounds bad to boot. :-)
956 if (pitch < 0.8) pitch = 0.8;
958 //fprintf(stderr, "pitch4: %f\n", pitch);
960 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
961 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
962 // fprintf(stderr, "volume: %f\n", volume);
964 pitch_envelope.setStep ( 0, 0.01, pitch );
965 volume_envelope.setStep ( 0, 0.01, volume );
969 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
970 pitch_envelope.setStep ( 0, 0.01, param );
971 volume_envelope.setStep ( 0, 0.01, param );
973 # endif // experimental throttle patch
975 audio_sched -> update();
982 FG_LOG( FG_ALL, FG_DEBUG, "" );
986 // This is the top level master main function that is registered as
990 // The first few passes take care of initialization things (a couple
991 // per pass) and once everything has been initialized fgMainLoop from
994 static void fgIdleFunction ( void ) {
995 // printf("idle state == %d\n", idle_state);
997 if ( idle_state == 0 ) {
998 // Initialize the splash screen right away
999 if ( current_options.get_splash_screen() ) {
1004 } else if ( idle_state == 1 ) {
1005 // Start the intro music
1007 if ( current_options.get_intro_music() ) {
1008 string lockfile = "/tmp/mpg123.running";
1009 FGPath mp3file( current_options.get_fg_root() );
1010 mp3file.append( "Sounds/intro.mp3" );
1012 string command = "(touch " + lockfile + "; mpg123 "
1013 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1015 FG_LOG( FG_GENERAL, FG_INFO,
1016 "Starting intro music: " << mp3file.str() );
1017 system ( command.c_str() );
1022 } else if ( idle_state == 2 ) {
1023 // These are a few miscellaneous things that aren't really
1024 // "subsystems" but still need to be initialized.
1027 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1028 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1033 } else if ( idle_state == 3 ) {
1034 // This is the top level init routine which calls all the
1035 // other subsystem initialization routines. If you are adding
1036 // a subsystem to flight gear, its initialization call should
1037 // located in this routine.
1038 if( !fgInitSubsystems()) {
1039 FG_LOG( FG_GENERAL, FG_ALERT,
1040 "Subsystem initializations failed ..." );
1045 } else if ( idle_state == 4 ) {
1046 // setup OpenGL view parameters
1049 if ( use_signals ) {
1050 // init timer routines, signals, etc. Arrange for an alarm
1051 // signal to be generated, etc.
1052 fgInitTimeDepCalcs();
1056 } else if ( idle_state == 5 ) {
1059 } else if ( idle_state == 6 ) {
1060 // Initialize audio support
1061 #ifdef ENABLE_AUDIO_SUPPORT
1064 if ( current_options.get_intro_music() ) {
1065 // Let's wait for mpg123 to finish
1066 string lockfile = "/tmp/mpg123.running";
1067 struct stat stat_buf;
1069 FG_LOG( FG_GENERAL, FG_INFO,
1070 "Waiting for mpg123 player to finish ..." );
1071 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1072 // file exist, wait ...
1074 FG_LOG( FG_GENERAL, FG_INFO, ".");
1076 FG_LOG( FG_GENERAL, FG_INFO, "");
1080 if ( current_options.get_sound() ) {
1081 audio_sched = new slScheduler ( 8000 );
1082 audio_mixer = new smMixer;
1083 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1084 audio_sched -> setSafetyMargin ( 1.0 ) ;
1086 FGPath slfile( current_options.get_fg_root() );
1087 slfile.append( "Sounds/wasp.wav" );
1089 s1 = new slSample ( (char *)slfile.c_str() );
1090 FG_LOG( FG_GENERAL, FG_INFO,
1091 "Rate = " << s1 -> getRate()
1092 << " Bps = " << s1 -> getBps()
1093 << " Stereo = " << s1 -> getStereo() );
1094 audio_sched -> loopSample ( s1 );
1096 if ( audio_sched->not_working() ) {
1099 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1100 volume_envelope.setStep ( 0, 0.01, 0.6 );
1102 audio_sched -> addSampleEnvelope( s1, 0, 0,
1104 SL_PITCH_ENVELOPE );
1105 audio_sched -> addSampleEnvelope( s1, 0, 1,
1107 SL_VOLUME_ENVELOPE );
1110 // strcpy(slfile, path);
1111 // strcat(slfile, "thunder.wav");
1112 // s2 -> loadFile ( slfile );
1113 // s2 -> adjustVolume(0.5);
1114 // audio_sched -> playSample ( s2 );
1122 if ( idle_state == 1000 ) {
1123 // We've finished all our initialization steps, from now on we
1124 // run the main loop.
1128 if ( current_options.get_splash_screen() == 1 ) {
1129 fgSplashUpdate(0.0);
1134 // options.cxx needs to see this for toggle_panel()
1135 // Handle new window size or exposure
1136 void fgReshape( int width, int height ) {
1137 if ( ! current_options.get_panel_status() ) {
1138 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1139 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1141 current_view.set_win_ratio( (GLfloat) width /
1142 ((GLfloat) (height)*0.4232) );
1143 glViewport(0, (GLint)((height)*0.5768), (GLint)(width),
1144 (GLint)((height)*0.4232) );
1147 current_view.set_winWidth( width );
1148 current_view.set_winHeight( height );
1149 current_view.force_update_fov_math();
1151 // set these fov to be the same as in fgRenderFrame()
1152 float x_fov = current_options.get_fov();
1153 float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1154 ssgSetFOV( x_fov, y_fov );
1156 glViewport ( 0, 0, width, height );
1157 float fov = current_options.get_fov();
1158 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1160 if ( idle_state == 1000 ) {
1161 // yes we've finished all our initializations and are running
1162 // the main loop, so this will now work without seg faulting
1164 current_view.UpdateViewParams(cur_view_fdm);
1165 if ( current_options.get_panel_status() ) {
1166 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
1172 // Initialize GLUT and define a main window
1173 int fgGlutInit( int *argc, char **argv ) {
1175 #if !defined( MACOS )
1176 // GLUT will extract all glut specific options so later on we only
1177 // need wory about our own.
1178 glutInit(argc, argv);
1181 // Define Display Parameters
1182 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1184 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1185 current_options.get_xsize() << "x" << current_options.get_ysize() );
1187 // Define initial window size
1188 glutInitWindowSize( current_options.get_xsize(),
1189 current_options.get_ysize() );
1191 // Initialize windows
1192 if ( current_options.get_game_mode() == 0 ) {
1193 // Open the regular window
1194 glutCreateWindow("Flight Gear");
1195 #ifndef GLUT_WRONG_VERSION
1197 // Open the cool new 'game mode' window
1198 char game_mode_str[256];
1199 sprintf( game_mode_str, "width=%d height=%d bpp=32",
1200 current_options.get_xsize(),
1201 current_options.get_ysize() );
1203 FG_LOG( FG_GENERAL, FG_INFO,
1204 "game mode params = " << game_mode_str );
1205 glutGameModeString( game_mode_str );
1206 glutEnterGameMode();
1210 // This seems to be the absolute earliest in the init sequence
1211 // that these calls will return valid info. Too bad it's after
1212 // we've already created and sized out window. :-(
1213 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1214 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1215 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1217 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1220 // try to determine if we should adjust the initial default
1221 // display resolution. The options class defaults (is
1222 // initialized) to 640x480.
1223 string renderer = general.glRenderer;
1225 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1226 if ( renderer.find( "Glide" ) != string::npos ) {
1227 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1228 if ( renderer.find( "FB/8" ) != string::npos ) {
1229 // probably a voodoo-2
1230 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1231 // probably two SLI'd Voodoo-2's
1232 current_options.set_xsize( 1024 );
1233 current_options.set_ysize( 768 );
1234 FG_LOG( FG_GENERAL, FG_INFO,
1235 "It looks like you have two sli'd voodoo-2's." << endl
1236 << "upgrading your win resolution to 1024 x 768" );
1237 glutReshapeWindow(1024, 768);
1239 // probably a single non-SLI'd Voodoo-2
1240 current_options.set_xsize( 800 );
1241 current_options.set_ysize( 600 );
1242 FG_LOG( FG_GENERAL, FG_INFO,
1243 "It looks like you have a voodoo-2." << endl
1244 << "upgrading your win resolution to 800 x 600" );
1245 glutReshapeWindow(800, 600);
1247 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1248 // probably a voodoo-1, stick with the default
1251 // we have no special knowledge of this card, stick with the default
1259 // Initialize GLUT event handlers
1260 int fgGlutInitEvents( void ) {
1261 // call fgReshape() on window resizes
1262 glutReshapeFunc( fgReshape );
1264 // call GLUTkey() on keyboard event
1265 glutKeyboardFunc( GLUTkey );
1266 glutSpecialFunc( GLUTspecialkey );
1268 // call guiMouseFunc() whenever our little rodent is used
1269 glutMouseFunc ( guiMouseFunc );
1270 glutMotionFunc (guiMotionFunc );
1271 glutPassiveMotionFunc (guiMotionFunc );
1273 // call fgMainLoop() whenever there is
1274 // nothing else to do
1275 glutIdleFunc( fgIdleFunction );
1278 glutDisplayFunc( fgRenderFrame );
1285 int main( int argc, char **argv ) {
1287 #if defined( MACOS )
1288 argc = ccommand( &argv );
1292 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1295 // set default log levels
1296 fglog().setLogLevels( FG_ALL, FG_INFO );
1298 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1300 // seed the random number generater
1303 // AIRCRAFT defined in uiuc_aircraft.h
1304 // AIRCRAFTDIR defined in uiuc_aircraftdir.h
1305 aircraft_ = new AIRCRAFT;
1306 aircraftdir_ = new AIRCRAFTDIR;
1307 aircraft_dir = ""; // Initialize the Aircraft directory to "" (UIUC)
1309 // Load the configuration parameters
1310 if ( !fgInitConfig(argc, argv) ) {
1311 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1315 // Initialize the Window/Graphics environment.
1316 if( !fgGlutInit(&argc, argv) ) {
1317 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1321 // Initialize the various GLUT Event Handlers.
1322 if( !fgGlutInitEvents() ) {
1323 FG_LOG( FG_GENERAL, FG_ALERT,
1324 "GLUT event handler initialization failed ..." );
1328 // Initialize ssg (from plib). Needs to come before we do any
1329 // other ssg stuff, but after opengl/glut has been initialized.
1332 // Initialize the user interface (we need to do this before
1333 // passing off control to glut and before fgInitGeneral to get our
1338 FGTime::cur_time_params = new FGTime();
1339 // FGTime::cur_time_params->init( cur_fdm_state->get_Longitude(),
1340 // cur_fdm_state->get_Latitude() );
1341 // FGTime::cur_time_params->update( cur_fdm_state->get_Longitude() );
1342 FGTime::cur_time_params->init( 0.0, 0.0 );
1343 FGTime::cur_time_params->update( 0.0, 0.0, 0.0 );
1345 // Do some quick general initializations
1346 if( !fgInitGeneral()) {
1347 FG_LOG( FG_GENERAL, FG_ALERT,
1348 "General initializations failed ..." );
1353 // some ssg test stuff (requires data from the plib source
1354 // distribution) specifically from the ssg tux example
1357 FGPath modelpath( current_options.get_fg_root() );
1358 modelpath.append( "Models" );
1359 modelpath.append( "Geometry" );
1361 FGPath texturepath( current_options.get_fg_root() );
1362 texturepath.append( "Models" );
1363 texturepath.append( "Textures" );
1365 ssgModelPath( (char *)modelpath.c_str() );
1366 ssgTexturePath( (char *)texturepath.c_str() );
1369 scene = new ssgRoot;
1370 scene->setName( "Scene" );
1372 // Initialize the sky
1373 FGPath ephem_data_path( current_options.get_fg_root() );
1374 ephem_data_path.append( "Astro" );
1375 ephem = new FGEphemeris( ephem_data_path.c_str() );
1376 ephem->update( FGTime::cur_time_params, 0.0 );
1378 FGPath sky_tex_path( current_options.get_fg_root() );
1379 sky_tex_path.append( "Textures" );
1380 sky_tex_path.append( "Sky" );
1382 thesky->texture_path( sky_tex_path.str() );
1384 ssgBranch *sky = thesky->build( 550.0, 550.0,
1385 ephem->getNumPlanets(),
1386 ephem->getPlanets(), 60000.0,
1387 ephem->getNumStars(),
1388 ephem->getStars(), 60000.0 );
1389 scene->addKid( sky );
1392 terrain = new ssgBranch;
1393 terrain->setName( "Terrain" );
1394 scene->addKid( terrain );
1396 // temporary visible aircraft "own ship"
1397 penguin_sel = new ssgSelector;
1398 penguin_pos = new ssgTransform;
1399 // ssgBranch *tux_obj = ssgMakeSphere( 10.0, 10, 10 );
1400 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1401 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1403 penguin_pos->addKid( tux_obj );
1404 penguin_sel->addKid( penguin_pos );
1405 ssgFlatten( tux_obj );
1406 ssgStripify( penguin_sel );
1407 penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1408 scene->addKid( penguin_sel );
1410 #ifdef FG_NETWORK_OLK
1411 // Do the network intialization
1412 if ( current_options.get_network_olk() ) {
1413 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1417 // build our custom render states
1418 fgBuildRenderStates();
1420 // pass control off to the master GLUT event handler
1423 // we never actually get here ... but to avoid compiler warnings,