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 <Astro/skydome.hxx>
78 #include <Astro/stars.hxx>
79 #include <Astro/solarsystem.hxx>
81 #include <Autopilot/autopilot.hxx>
82 #include <Cockpit/cockpit.hxx>
84 #include <Joystick/joystick.hxx>
86 #include <NetworkOLK/network.h>
88 #include <Objects/materialmgr.hxx>
89 #include <Scenery/scenery.hxx>
90 #include <Scenery/tilemgr.hxx>
91 #include <Time/event.hxx>
92 #include <Time/fg_time.hxx>
93 #include <Time/fg_timer.hxx>
94 #include <Time/sunpos.hxx>
96 #ifndef FG_OLD_WEATHER
97 # include <WeatherCM/FGLocalWeatherDatabase.h>
99 # include <Weather/weather.hxx>
102 #include "fg_init.hxx"
104 #include "keyboard.hxx"
105 #include "options.hxx"
106 #include "splash.hxx"
110 // -dw- use custom sioux settings so I can see output window
113 # include <sioux.h> // settings for output window
115 # include <console.h>
119 // This is a record containing a bit of global housekeeping information
122 // Specify our current idle function state. This is used to run all
123 // our initializations out of the glutIdleLoop() so that we can get a
124 // splash screen up and running right away.
125 static int idle_state = 0;
126 static int global_multi_loop;
131 // Global structures for the Audio library
132 #ifdef ENABLE_AUDIO_SUPPORT
133 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
134 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
135 slScheduler *audio_sched;
136 smMixer *audio_mixer;
143 ssgRoot *scene = NULL;
144 ssgBranch *terrain = NULL;
145 ssgSelector *penguin_sel = NULL;
146 ssgTransform *penguin_pos = NULL;
148 // the sky needs to be drawn in a specific order, thus we use several
149 // "roots" so we can explicitely control this.
152 #ifdef FG_NETWORK_OLK
153 ssgSelector *fgd_sel = NULL;
154 ssgTransform *fgd_pos = NULL;
158 // current fdm/position used for view
159 FGInterface cur_view_fdm;
162 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
164 { 1.0f, 0.0f, 0.0f, 0.0f },
165 { 0.0f, 0.0f, -1.0f, 0.0f },
166 { 0.0f, 1.0f, 0.0f, 0.0f },
167 { 0.0f, 0.0f, 0.0f, 1.0f }
170 // The following defines flight gear options. Because glutlib will also
171 // want to parse its own options, those options must not be included here
172 // or they will get parsed by the main program option parser. Hence case
173 // is significant for any option added that might be in conflict with
176 // glutlib parses for:
178 // -direct (invalid in Win32)
182 // -indirect (invalid in Win32)
185 // Note that glutlib depends upon strings while this program's
186 // option parser wants only initial characters followed by numbers
191 // fgInitVisuals() -- Initialize various GL/view parameters
192 void fgInitVisuals( void ) {
195 l = &cur_light_params;
197 #ifndef GLUT_WRONG_VERSION
198 // Go full screen if requested ...
199 if ( current_options.get_fullscreen() ) {
204 // If enabled, normal vectors specified with glNormal are scaled
205 // to unit length after transformation. See glNormal.
206 // xglEnable( GL_NORMALIZE );
208 xglEnable( GL_LIGHTING );
209 xglEnable( GL_LIGHT0 );
210 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
213 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
214 ssgGetLight( 0 ) -> setPosition( sunpos );
216 // xglFogi (GL_FOG_MODE, GL_LINEAR);
217 xglFogi (GL_FOG_MODE, GL_EXP2);
218 if ( (current_options.get_fog() == 1) ||
219 (current_options.get_shading() == 0) ) {
220 // if fastest fog requested, or if flat shading force fastest
221 xglHint ( GL_FOG_HINT, GL_FASTEST );
222 } else if ( current_options.get_fog() == 2 ) {
223 xglHint ( GL_FOG_HINT, GL_NICEST );
225 if ( current_options.get_wireframe() ) {
227 xglPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
230 // This is the default anyways, but it can't hurt
231 xglFrontFace ( GL_CCW );
234 // xglEnable(GL_POINT_SMOOTH);
235 // xglEnable(GL_LINE_SMOOTH);
236 // xglEnable(GL_POLYGON_SMOOTH);
240 // Update all Visuals (redraws anything graphics related)
241 void fgRenderFrame( void ) {
242 fgLIGHT *l = &cur_light_params;
243 FGTime *t = FGTime::cur_time_params;
244 // FGView *v = ¤t_view;
245 static double last_visibility = -9999;
246 static bool in_puff = false;
247 static double puff_length = 0;
248 static double puff_progression = 0;
249 const double ramp_up = 0.15;
250 const double ramp_down = 0.15;
253 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
254 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
255 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
256 // GLfloat mat_shininess[] = { 10.0 };
257 GLbitfield clear_mask;
259 if ( idle_state != 1000 ) {
260 // still initializing, draw the splash screen
261 if ( current_options.get_splash_screen() == 1 ) {
265 // idle_state is now 1000 meaning we've finished all our
266 // initializations and are running the main loop, so this will
267 // now work without seg faulting the system.
269 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
270 // FG_Altitude * FEET_TO_METER);
272 // this is just a temporary hack, to make me understand Pui
273 // timerText -> setLabel (ctime (&t->cur_time));
276 // update view volume parameters
277 // cout << "before pilot_view update" << endl;
278 pilot_view.UpdateViewParams(*cur_fdm_state);
279 // cout << "after pilot_view update" << endl;
280 current_view.UpdateViewParams(cur_view_fdm);
282 // set the sun position
283 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
285 clear_mask = GL_DEPTH_BUFFER_BIT;
286 if ( current_options.get_wireframe() ) {
287 clear_mask |= GL_COLOR_BUFFER_BIT;
289 if ( current_options.get_panel_status() ) {
290 // we can't clear the screen when the panel is active
291 } else if ( current_options.get_skyblend() ) {
292 if ( current_options.get_textures() ) {
293 // glClearColor(black[0], black[1], black[2], black[3]);
294 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
295 l->adj_fog_color[2], l->adj_fog_color[3]);
296 clear_mask |= GL_COLOR_BUFFER_BIT;
299 glClearColor(l->sky_color[0], l->sky_color[1],
300 l->sky_color[2], l->sky_color[3]);
301 clear_mask |= GL_COLOR_BUFFER_BIT;
303 xglClear( clear_mask );
305 // Tell GL we are switching to model view parameters
307 // I really should create a derived ssg node or use a call
308 // back or something so that I can draw the sky within the
309 // ssgCullandDraw() function, but for now I just mimic what
310 // ssg does to set up the model view matrix
311 xglMatrixMode(GL_MODELVIEW);
315 sgMat4 vm_tmp, view_mat;
316 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
317 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
318 sgPreMultMat4( view_mat, vm_tmp ) ;
319 xglLoadMatrixf( (float *)view_mat );
323 xglDisable( GL_DEPTH_TEST );
324 // xglDisable( GL_LIGHTING );
325 xglDisable( GL_CULL_FACE );
326 xglDisable( GL_FOG );
327 xglDisable( GL_TEXTURE_2D );
328 /* if ( current_options.get_fog() > 0 ) {
330 xglFogi( GL_FOG_MODE, GL_EXP2 );
331 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
334 xglShadeModel( GL_SMOOTH );
336 // if ( current_options.get_skyblend() ) {
340 sgSetVec3( zero_elev,
341 current_view.get_cur_zero_elev().x(),
342 current_view.get_cur_zero_elev().y(),
343 current_view.get_cur_zero_elev().z() );
345 current_sky.repaint( cur_light_params.sky_color,
346 cur_light_params.fog_color,
347 cur_light_params.sun_angle );
349 current_sky.reposition( zero_elev,
350 cur_fdm_state->get_Longitude(),
351 cur_fdm_state->get_Latitude(),
352 cur_light_params.sun_rotation );
355 ssgSetCamera( current_view.VIEW );
356 ssgCullAndDraw( sky );
359 // xglDisable( GL_FOG );
363 // setup transformation for drawing astronomical objects
365 // Translate to view position
366 Point3D view_pos = current_view.get_view_pos();
367 xglTranslatef( view_pos.x(), view_pos.y(), view_pos.z() );
368 // Rotate based on gst (sidereal time)
369 // note: constant should be 15.041085, Curt thought it was 15
370 angle = t->getGst() * 15.041085;
371 // printf("Rotating astro objects by %.2f degrees\n",angle);
372 xglRotatef( angle, 0.0, 0.0, -1.0 );
374 // draw stars and planets
376 xglDisable( GL_COLOR_MATERIAL ); // just to make sure ...
377 xglEnable( GL_CULL_FACE ); // for moon
378 xglLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
379 //xglEnable(GL_DEPTH_TEST);
380 SolarSystem::theSolarSystem->draw();
381 // reset blending function
382 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
388 if ( current_options.get_shading() ) {
389 xglShadeModel( GL_SMOOTH );
391 xglShadeModel( GL_FLAT );
393 xglEnable( GL_DEPTH_TEST );
394 if ( current_options.get_fog() > 0 ) {
396 xglFogi( GL_FOG_MODE, GL_EXP2 );
397 xglFogfv( GL_FOG_COLOR, l->adj_fog_color );
400 // update fog params if visibility has changed
401 #ifndef FG_OLD_WEATHER
402 double cur_visibility = WeatherDatabase->getWeatherVisibility();
404 double cur_visibility = current_weather.get_visibility();
406 double actual_visibility = cur_visibility;
408 if ( current_options.get_clouds() ) {
409 double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
410 current_options.get_clouds_asl() );
411 // cout << "altitude diff = " << diff << endl;
414 // calc chance of entering cloud puff
415 double rnd = fg_random();
416 double chance = rnd * rnd * rnd;
417 if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) {
420 puff_length = fg_random() * 2.0; // up to 2 seconds
421 } while ( puff_length <= 0.0 );
422 puff_progression = 0.0;
426 actual_visibility = cur_visibility * (diff - 25) / 50.0;
429 // modify actual_visibility based on puff envelope
431 if ( puff_progression <= ramp_up ) {
432 double x = FG_PI_2 * puff_progression / ramp_up;
433 double factor = 1.0 - sin( x );
434 actual_visibility = actual_visibility * factor;
435 } else if ( puff_progression >= ramp_up + puff_length ) {
437 (puff_progression - (ramp_up + puff_length)) /
439 double factor = sin( x );
440 actual_visibility = actual_visibility * factor;
442 actual_visibility = 0.0;
445 /* cout << "len = " << puff_length
447 << " factor = " << factor
448 << " actual_visibility = " << actual_visibility
451 puff_progression += ( global_multi_loop *
452 current_options.get_speed_up() ) /
453 (double)current_options.get_model_hz();
455 /* cout << "gml = " << global_multi_loop
456 << " speed up = " << current_options.get_speed_up()
457 << " hz = " << current_options.get_model_hz() << endl;
460 if ( puff_progression > puff_length + ramp_up + ramp_down) {
465 // never let visibility drop below zero
466 if ( actual_visibility < 0 ) {
467 actual_visibility = 0;
472 // cout << "actual visibility = " << actual_visibility << endl;
474 if ( actual_visibility != last_visibility ) {
475 last_visibility = actual_visibility;
477 // cout << "----> updating fog params" << endl;
479 GLfloat fog_exp_density;
480 GLfloat fog_exp2_density;
483 fog_exp_density = -log(0.01 / actual_visibility);
486 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
488 // Set correct opengl fog density
489 xglFogf (GL_FOG_DENSITY, fog_exp2_density);
492 // set lighting parameters
493 xglLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
494 xglLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
495 // xglLightfv(GL_LIGHT0, GL_SPECULAR, white );
497 // texture parameters
498 xglEnable( GL_TEXTURE_2D );
499 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
500 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
501 // set base color (I don't think this is doing anything here)
502 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
503 // (GL_FRONT, GL_DIFFUSE, white);
504 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
505 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
508 if ( current_options.get_textures() ) {
509 // texture parameters
510 xglEnable( GL_TEXTURE_2D );
511 xglTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
512 xglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
513 // set base color (I don't think this is doing anything here)
514 xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
515 xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
516 // xglMaterialfv (GL_FRONT, GL_SPECULAR, white);
517 // xglMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
519 xglDisable( GL_TEXTURE_2D );
520 xglMaterialfv (GL_FRONT, GL_AMBIENT, terrain_color);
521 xglMaterialfv (GL_FRONT, GL_DIFFUSE, terrain_color);
522 // xglMaterialfv (GL_FRONT, GL_AMBIENT, white);
523 // xglMaterialfv (GL_FRONT, GL_DIFFUSE, white);
528 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
529 ssgGetLight( 0 ) -> setPosition( sunpos );
531 // xglMatrixMode( GL_PROJECTION );
532 // xglLoadIdentity();
533 float fov = current_options.get_fov();
534 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
536 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
539 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
540 // << current_weather.get_visibility() );
543 ssgSetNearFar( 10.0f, 120000.0f );
545 ssgSetNearFar( 0.5f, 120000.0f );
548 if ( current_options.get_view_mode() ==
549 fgOPTIONS::FG_VIEW_PILOT )
552 penguin_sel->select(0);
553 } else if ( current_options.get_view_mode() ==
554 fgOPTIONS::FG_VIEW_FOLLOW )
556 // select view matrix from front of view matrix queue
557 // FGMat4Wrapper tmp = current_view.follow.front();
558 // sgCopyMat4( sgVIEW, tmp.m );
560 // enable TuX and set up his position and orientation
561 penguin_sel->select(1);
564 sgMakeTransMat4( sgTRANS,
565 pilot_view.view_pos.x(),
566 pilot_view.view_pos.y(),
567 pilot_view.view_pos.z() );
570 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
573 sgMakeRotMat4( sgROT, -90.0, ownship_up );
577 sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
578 sgMultMat4( sgTUX, sgTMP, sgTRANS );
581 sgSetCoord( &tuxpos, sgTUX );
582 penguin_pos->setTransform( &tuxpos );
585 # ifdef FG_NETWORK_OLK
586 if ( current_options.get_network_olk() ) {
588 other = head->next; /* put listpointer to start */
589 while ( other != tail) { /* display all except myself */
590 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
591 other->fgd_sel->select(1);
592 sgSetCoord( &fgdpos, other->sgFGD_COORD );
593 other->fgd_pos->setTransform( &fgdpos );
598 // fgd_sel->select(1);
599 // sgCopyMat4( sgTUX, current_view.sgVIEW);
601 // sgSetCoord( &fgdpos, sgFGD_VIEW );
602 // fgd_pos->setTransform( &fgdpos);
606 ssgSetCamera( current_view.VIEW );
608 // position tile nodes and update range selectors
609 global_tile_mgr.prep_ssg_nodes();
611 // force the default state so ssg can get back on track if
612 // we've changed things elsewhere
613 FGMaterialSlot m_slot;
614 FGMaterialSlot *m_ptr = &m_slot;
615 if ( material_mgr.find( "Default", m_ptr ) ) {
616 m_ptr->get_state()->force();
619 // draw the ssg scene
620 ssgCullAndDraw( scene );
622 xglDisable( GL_TEXTURE_2D );
623 xglDisable( GL_FOG );
625 // display HUD && Panel
626 xglDisable( GL_CULL_FACE );
629 // We can do translucent menus, so why not. :-)
630 xglEnable ( GL_BLEND ) ;
631 xglBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
633 xglDisable ( GL_BLEND ) ;
642 // Update internal time dependent calculations (i.e. flight model)
643 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
644 static fdm_state_list fdm_list;
645 // FGInterface fdm_state;
646 fgLIGHT *l = &cur_light_params;
647 FGTime *t = FGTime::cur_time_params;
648 // FGView *v = ¤t_view;
651 // update the flight model
652 if ( multi_loop < 0 ) {
656 if ( !t->getPause() ) {
657 // run Autopilot system
660 // printf("updating flight model x %d\n", multi_loop);
661 /* fgFDMUpdate( current_options.get_flight_model(),
663 multi_loop * current_options.get_speed_up(),
665 cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
667 // fgFDMUpdate( current_options.get_flight_model(),
668 // fdm_state, 0, remainder );
669 cur_fdm_state->update( 0 );
672 fdm_list.push_back( *cur_fdm_state );
673 while ( fdm_list.size() > 15 ) {
674 fdm_list.pop_front();
677 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
678 cur_view_fdm = *cur_fdm_state;
680 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
681 cur_view_fdm = fdm_list.front();
684 // update the view angle
685 for ( i = 0; i < multi_loop; i++ ) {
686 if ( fabs(current_view.get_goal_view_offset() -
687 current_view.get_view_offset()) < 0.05 )
689 current_view.set_view_offset( current_view.get_goal_view_offset() );
692 // move current_view.view_offset towards current_view.goal_view_offset
693 if ( current_view.get_goal_view_offset() >
694 current_view.get_view_offset() )
696 if ( current_view.get_goal_view_offset() -
697 current_view.get_view_offset() < FG_PI )
699 current_view.inc_view_offset( 0.01 );
701 current_view.inc_view_offset( -0.01 );
704 if ( current_view.get_view_offset() -
705 current_view.get_goal_view_offset() < FG_PI )
707 current_view.inc_view_offset( -0.01 );
709 current_view.inc_view_offset( 0.01 );
712 if ( current_view.get_view_offset() > FG_2PI ) {
713 current_view.inc_view_offset( -FG_2PI );
714 } else if ( current_view.get_view_offset() < 0 ) {
715 current_view.inc_view_offset( FG_2PI );
720 double tmp = -(l->sun_rotation + FG_PI)
721 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
722 while ( tmp < 0.0 ) {
725 while ( tmp > FG_2PI ) {
728 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
729 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
730 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
735 void fgInitTimeDepCalcs( void ) {
738 // #ifdef HAVE_SETITIMER
739 // fgTimerInit( 1.0 / current_options.get_model_hz(),
740 // fgUpdateTimeDepCalcs );
741 // #endif HAVE_SETITIMER
745 static const double alt_adjust_ft = 3.758099;
746 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
749 // What should we do when we have nothing else to do? Let's get ready
750 // for the next move and update the display?
751 static void fgMainLoop( void ) {
753 static long remainder = 0;
755 #ifdef FANCY_FRAME_COUNTER
759 static time_t last_time = 0;
760 static int frames = 0;
761 #endif // FANCY_FRAME_COUNTER
763 t = FGTime::cur_time_params;
765 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
766 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
768 #ifdef FG_NETWORK_OLK
769 if ( current_options.get_network_olk() ) {
770 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
771 // printf("FGD: Netupdate\n");
772 fgd_send_com( "A", FGFS_host); // Send Mat4 data
773 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
778 #if defined( ENABLE_PLIB_JOYSTICK )
779 // Read joystick and update control settings
780 if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
783 #elif defined( ENABLE_GLUT_JOYSTICK )
784 // Glut joystick support works by feeding a joystick handler
785 // function to glut. This is taken care of once in the joystick
786 // init routine and we don't have to worry about it again.
789 #ifdef FG_OLD_WEATHER
790 current_weather.Update();
793 // Fix elevation. I'm just sticking this here for now, it should
794 // probably move eventually
796 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
798 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
799 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
801 if ( scenery.cur_elev > -9990 ) {
802 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
803 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
804 // now set aircraft altitude above ground
805 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
806 cur_fdm_state->get_Altitude() * FEET_TO_METER,
807 scenery.cur_elev + alt_adjust_m - 3.0,
808 scenery.cur_elev + alt_adjust_m );
809 fgFDMForceAltitude( current_options.get_flight_model(),
810 scenery.cur_elev + alt_adjust_m );
812 FG_LOG( FG_ALL, FG_DEBUG,
813 "<*> resetting altitude to "
814 << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
816 fgFDMSetGroundElevation( current_options.get_flight_model(),
817 scenery.cur_elev ); // meters
820 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
822 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
823 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
826 t->update(*cur_fdm_state);
828 // Get elapsed time (in usec) for this past frame
829 elapsed = fgGetTimeInterval();
830 FG_LOG( FG_ALL, FG_DEBUG,
831 "Elapsed time interval is = " << elapsed
832 << ", previous remainder is = " << remainder );
834 // Calculate frame rate average
835 #ifdef FANCY_FRAME_COUNTER
836 /* old fps calculation */
840 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
841 tmp = general.get_frame(i);
843 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
844 general.set_frame(i+1,tmp);
846 tmp = 1000000.0 / (float)elapsed;
847 general.set_frame(0,tmp);
848 // printf("frame[0] = %.2f\n", general.frames[0]);
850 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
851 // printf("ave = %.2f\n", general.frame_rate);
854 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
855 general.set_frame_rate( frames );
856 FG_LOG( FG_ALL, FG_DEBUG,
857 "--> Frame rate is = " << general.get_frame_rate() );
860 last_time = t->get_cur_time();
865 if ( ! use_signals ) {
866 // Calculate model iterations needed for next frame
867 elapsed += remainder;
869 global_multi_loop = (int)(((double)elapsed * 0.000001) *
870 current_options.get_model_hz());
871 remainder = elapsed - ( (global_multi_loop*1000000) /
872 current_options.get_model_hz() );
873 FG_LOG( FG_ALL, FG_DEBUG,
874 "Model iterations needed = " << global_multi_loop
875 << ", new remainder = " << remainder );
878 if ( global_multi_loop > 0 ) {
879 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
881 FG_LOG( FG_ALL, FG_DEBUG,
882 "Elapsed time is zero ... we're zinging" );
886 #if ! defined( MACOS )
887 // Do any I/O channel work that might need to be done
891 // see if we need to load any new scenery tiles
892 global_tile_mgr.update();
894 // Process/manage pending events
895 global_events.Process();
897 // Run audio scheduler
898 #ifdef ENABLE_AUDIO_SUPPORT
899 if ( current_options.get_sound() && !audio_sched->not_working() ) {
901 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
903 // note: all these factors are relative to the sample. our
904 // sample format should really contain a conversion factor so
905 // that we can get prop speed right for arbitrary samples.
906 // Note that for normal-size props, there is a point at which
907 // the prop tips approach the speed of sound; that is a pretty
908 // strong limit to how fast the prop can go.
910 // multiplication factor is prime pitch control; add some log
911 // component for verisimilitude
913 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
914 //fprintf(stderr, "pitch1: %f ", pitch);
915 if (controls.get_throttle(0) > 0.0 || cur_fdm_state->v_rel_wind > 40.0) {
916 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
917 // only add relative wind and AoA if prop is moving
918 // or we're really flying at idle throttle
919 if (pitch < 5.4) { // this needs tuning
920 // prop tips not breaking sound barrier
921 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
923 // prop tips breaking sound barrier
924 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
926 //fprintf(stderr, "pitch2: %f ", pitch);
927 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
929 // Angle of Attack next... -x^3(e^x) is my best guess Just
930 // need to calculate some reasonable scaling factor and
931 // then clamp it on the positive aoa (neg adj) side
932 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
934 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
935 if (aoa_adj < -0.8) aoa_adj = -0.8;
937 //fprintf(stderr, "pitch3: %f ", pitch);
939 // don't run at absurdly slow rates -- not realistic
940 // and sounds bad to boot. :-)
941 if (pitch < 0.8) pitch = 0.8;
943 //fprintf(stderr, "pitch4: %f\n", pitch);
945 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
946 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
947 // fprintf(stderr, "volume: %f\n", volume);
949 pitch_envelope.setStep ( 0, 0.01, pitch );
950 volume_envelope.setStep ( 0, 0.01, volume );
954 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
955 pitch_envelope.setStep ( 0, 0.01, param );
956 volume_envelope.setStep ( 0, 0.01, param );
958 # endif // experimental throttle patch
960 audio_sched -> update();
967 FG_LOG( FG_ALL, FG_DEBUG, "" );
971 // This is the top level master main function that is registered as
975 // The first few passes take care of initialization things (a couple
976 // per pass) and once everything has been initialized fgMainLoop from
979 static void fgIdleFunction ( void ) {
980 // printf("idle state == %d\n", idle_state);
982 if ( idle_state == 0 ) {
983 // Initialize the splash screen right away
984 if ( current_options.get_splash_screen() ) {
989 } else if ( idle_state == 1 ) {
990 // Start the intro music
992 if ( current_options.get_intro_music() ) {
993 string lockfile = "/tmp/mpg123.running";
994 FGPath mp3file( current_options.get_fg_root() );
995 mp3file.append( "Sounds/intro.mp3" );
997 string command = "(touch " + lockfile + "; mpg123 "
998 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1000 FG_LOG( FG_GENERAL, FG_INFO,
1001 "Starting intro music: " << mp3file.str() );
1002 system ( command.c_str() );
1007 } else if ( idle_state == 2 ) {
1008 // These are a few miscellaneous things that aren't really
1009 // "subsystems" but still need to be initialized.
1012 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1013 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1018 } else if ( idle_state == 3 ) {
1019 // This is the top level init routine which calls all the
1020 // other subsystem initialization routines. If you are adding
1021 // a subsystem to flight gear, its initialization call should
1022 // located in this routine.
1023 if( !fgInitSubsystems()) {
1024 FG_LOG( FG_GENERAL, FG_ALERT,
1025 "Subsystem initializations failed ..." );
1030 } else if ( idle_state == 4 ) {
1031 // setup OpenGL view parameters
1034 if ( use_signals ) {
1035 // init timer routines, signals, etc. Arrange for an alarm
1036 // signal to be generated, etc.
1037 fgInitTimeDepCalcs();
1041 } else if ( idle_state == 5 ) {
1044 } else if ( idle_state == 6 ) {
1045 // Initialize audio support
1046 #ifdef ENABLE_AUDIO_SUPPORT
1049 if ( current_options.get_intro_music() ) {
1050 // Let's wait for mpg123 to finish
1051 string lockfile = "/tmp/mpg123.running";
1052 struct stat stat_buf;
1054 FG_LOG( FG_GENERAL, FG_INFO,
1055 "Waiting for mpg123 player to finish ..." );
1056 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1057 // file exist, wait ...
1059 FG_LOG( FG_GENERAL, FG_INFO, ".");
1061 FG_LOG( FG_GENERAL, FG_INFO, "");
1065 if ( current_options.get_sound() ) {
1066 audio_sched = new slScheduler ( 8000 );
1067 audio_mixer = new smMixer;
1068 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1069 audio_sched -> setSafetyMargin ( 1.0 ) ;
1071 FGPath slfile( current_options.get_fg_root() );
1072 slfile.append( "Sounds/wasp.wav" );
1074 s1 = new slSample ( (char *)slfile.c_str() );
1075 FG_LOG( FG_GENERAL, FG_INFO,
1076 "Rate = " << s1 -> getRate()
1077 << " Bps = " << s1 -> getBps()
1078 << " Stereo = " << s1 -> getStereo() );
1079 audio_sched -> loopSample ( s1 );
1081 if ( audio_sched->not_working() ) {
1084 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1085 volume_envelope.setStep ( 0, 0.01, 0.6 );
1087 audio_sched -> addSampleEnvelope( s1, 0, 0,
1089 SL_PITCH_ENVELOPE );
1090 audio_sched -> addSampleEnvelope( s1, 0, 1,
1092 SL_VOLUME_ENVELOPE );
1095 // strcpy(slfile, path);
1096 // strcat(slfile, "thunder.wav");
1097 // s2 -> loadFile ( slfile );
1098 // s2 -> adjustVolume(0.5);
1099 // audio_sched -> playSample ( s2 );
1107 if ( idle_state == 1000 ) {
1108 // We've finished all our initialization steps, from now on we
1109 // run the main loop.
1113 if ( current_options.get_splash_screen() == 1 ) {
1114 fgSplashUpdate(0.0);
1119 // options.cxx needs to see this for toggle_panel()
1120 // Handle new window size or exposure
1121 void fgReshape( int width, int height ) {
1122 if ( ! current_options.get_panel_status() ) {
1123 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1124 xglViewport(0, 0 , (GLint)(width), (GLint)(height) );
1126 current_view.set_win_ratio( (GLfloat) width /
1127 ((GLfloat) (height)*0.4232) );
1128 xglViewport(0, (GLint)((height)*0.5768), (GLint)(width),
1129 (GLint)((height)*0.4232) );
1132 current_view.set_winWidth( width );
1133 current_view.set_winHeight( height );
1134 current_view.force_update_fov_math();
1136 // set these fov to be the same as in fgRenderFrame()
1137 float x_fov = current_options.get_fov();
1138 float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1139 ssgSetFOV( x_fov, y_fov );
1141 glViewport ( 0, 0, width, height );
1142 float fov = current_options.get_fov();
1143 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1145 if ( idle_state == 1000 ) {
1146 // yes we've finished all our initializations and are running
1147 // the main loop, so this will now work without seg faulting
1149 solarSystemRebuild();
1150 current_view.UpdateViewParams(cur_view_fdm);
1151 if ( current_options.get_panel_status() ) {
1152 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
1158 // Initialize GLUT and define a main window
1159 int fgGlutInit( int *argc, char **argv ) {
1161 #if !defined( MACOS )
1162 // GLUT will extract all glut specific options so later on we only
1163 // need wory about our own.
1164 xglutInit(argc, argv);
1167 // Define Display Parameters
1168 xglutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1170 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1171 current_options.get_xsize() << "x" << current_options.get_ysize() );
1173 // Define initial window size
1174 xglutInitWindowSize( current_options.get_xsize(),
1175 current_options.get_ysize() );
1177 // Initialize windows
1178 if ( current_options.get_game_mode() == 0 ) {
1179 // Open the regular window
1180 xglutCreateWindow("Flight Gear");
1181 #ifndef GLUT_WRONG_VERSION
1183 // Open the cool new 'game mode' window
1184 char game_mode_str[256];
1185 sprintf( game_mode_str, "width=%d height=%d bpp=32",
1186 current_options.get_xsize(),
1187 current_options.get_ysize() );
1189 FG_LOG( FG_GENERAL, FG_INFO,
1190 "game mode params = " << game_mode_str );
1191 glutGameModeString( game_mode_str );
1192 glutEnterGameMode();
1196 // This seems to be the absolute earliest in the init sequence
1197 // that these calls will return valid info. Too bad it's after
1198 // we've already created and sized out window. :-(
1199 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1200 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1201 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1203 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1206 // try to determine if we should adjust the initial default
1207 // display resolution. The options class defaults (is
1208 // initialized) to 640x480.
1209 string renderer = general.glRenderer;
1211 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1212 if ( renderer.find( "Glide" ) != string::npos ) {
1213 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1214 if ( renderer.find( "FB/8" ) != string::npos ) {
1215 // probably a voodoo-2
1216 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1217 // probably two SLI'd Voodoo-2's
1218 current_options.set_xsize( 1024 );
1219 current_options.set_ysize( 768 );
1220 FG_LOG( FG_GENERAL, FG_INFO,
1221 "It looks like you have two sli'd voodoo-2's." << endl
1222 << "upgrading your win resolution to 1024 x 768" );
1223 glutReshapeWindow(1024, 768);
1225 // probably a single non-SLI'd Voodoo-2
1226 current_options.set_xsize( 800 );
1227 current_options.set_ysize( 600 );
1228 FG_LOG( FG_GENERAL, FG_INFO,
1229 "It looks like you have a voodoo-2." << endl
1230 << "upgrading your win resolution to 800 x 600" );
1231 glutReshapeWindow(800, 600);
1233 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1234 // probably a voodoo-1, stick with the default
1237 // we have no special knowledge of this card, stick with the default
1245 // Initialize GLUT event handlers
1246 int fgGlutInitEvents( void ) {
1247 // call fgReshape() on window resizes
1248 xglutReshapeFunc( fgReshape );
1250 // call GLUTkey() on keyboard event
1251 xglutKeyboardFunc( GLUTkey );
1252 glutSpecialFunc( GLUTspecialkey );
1254 // call guiMouseFunc() whenever our little rodent is used
1255 glutMouseFunc ( guiMouseFunc );
1256 glutMotionFunc (guiMotionFunc );
1257 glutPassiveMotionFunc (guiMotionFunc );
1259 // call fgMainLoop() whenever there is
1260 // nothing else to do
1261 xglutIdleFunc( fgIdleFunction );
1264 xglutDisplayFunc( fgRenderFrame );
1271 int main( int argc, char **argv ) {
1273 #if defined( MACOS )
1274 argc = ccommand( &argv );
1278 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1281 // set default log levels
1282 fglog().setLogLevels( FG_ALL, FG_INFO );
1284 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1286 // seed the random number generater
1289 // Load the configuration parameters
1290 if ( !fgInitConfig(argc, argv) ) {
1291 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1295 // Initialize the Window/Graphics environment.
1296 if( !fgGlutInit(&argc, argv) ) {
1297 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1301 // Initialize the various GLUT Event Handlers.
1302 if( !fgGlutInitEvents() ) {
1303 FG_LOG( FG_GENERAL, FG_ALERT,
1304 "GLUT event handler initialization failed ..." );
1308 // Initialize ssg (from plib)
1311 // Initialize the user interface (we need to do this before
1312 // passing off control to glut and before fgInitGeneral to get our
1316 // Do some quick general initializations
1317 if( !fgInitGeneral()) {
1318 FG_LOG( FG_GENERAL, FG_ALERT,
1319 "General initializations failed ..." );
1324 // some ssg test stuff (requires data from the plib source
1325 // distribution) specifically from the ssg tux example
1328 FGPath modelpath( current_options.get_fg_root() );
1329 modelpath.append( "Models" );
1330 modelpath.append( "Geometry" );
1332 FGPath texturepath( current_options.get_fg_root() );
1333 texturepath.append( "Models" );
1334 texturepath.append( "Textures" );
1336 ssgModelPath( (char *)modelpath.c_str() );
1337 ssgTexturePath( (char *)texturepath.c_str() );
1340 scene = new ssgRoot;
1341 scene->setName( "Scene" );
1344 terrain = new ssgBranch;
1345 terrain->setName( "Terrain" );
1346 scene->addKid( terrain );
1350 sky->setName( "Sky" );
1351 current_sky.initialize( sky );
1353 // temporary visible aircraft "own ship"
1354 penguin_sel = new ssgSelector;
1355 penguin_pos = new ssgTransform;
1356 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1357 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1358 penguin_pos->addKid( tux_obj );
1359 penguin_sel->addKid( penguin_pos );
1360 ssgFlatten( tux_obj );
1361 ssgStripify( penguin_sel );
1362 penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1363 scene->addKid( penguin_sel );
1365 #ifdef FG_NETWORK_OLK
1366 // Do the network intialization
1367 if ( current_options.get_network_olk() ) {
1368 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1372 // pass control off to the master GLUT event handler
1375 // we never actually get here ... but to avoid compiler warnings,