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/newauto.hxx>
80 #include <Cockpit/cockpit.hxx>
81 #include <Cockpit/radiostack.hxx>
82 #include <Cockpit/steam.hxx>
84 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
86 #include <Joystick/joystick.hxx>
88 #include <NetworkOLK/network.h>
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>
105 #include "fg_init.hxx"
107 #include "keyboard.hxx"
108 #include "options.hxx"
109 #include "splash.hxx"
113 // -dw- use custom sioux settings so I can see output window
116 # include <sioux.h> // settings for output window
118 # include <console.h>
122 // This is a record containing a bit of global housekeeping information
125 // Specify our current idle function state. This is used to run all
126 // our initializations out of the glutIdleLoop() so that we can get a
127 // splash screen up and running right away.
128 static int idle_state = 0;
129 static int global_multi_loop;
134 // Global structures for the Audio library
135 #ifdef ENABLE_AUDIO_SUPPORT
136 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
137 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
138 slScheduler *audio_sched;
139 smMixer *audio_mixer;
146 ssgRoot *scene = NULL;
147 ssgBranch *terrain = NULL;
148 ssgSelector *penguin_sel = NULL;
149 ssgTransform *penguin_pos = NULL;
151 #ifdef FG_NETWORK_OLK
152 ssgSelector *fgd_sel = NULL;
153 ssgTransform *fgd_pos = NULL;
157 // current fdm/position used for view
158 FGInterface cur_view_fdm;
165 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
167 { 1.0f, 0.0f, 0.0f, 0.0f },
168 { 0.0f, 0.0f, -1.0f, 0.0f },
169 { 0.0f, 1.0f, 0.0f, 0.0f },
170 { 0.0f, 0.0f, 0.0f, 1.0f }
173 // The following defines flight gear options. Because glutlib will also
174 // want to parse its own options, those options must not be included here
175 // or they will get parsed by the main program option parser. Hence case
176 // is significant for any option added that might be in conflict with
179 // glutlib parses for:
181 // -direct (invalid in Win32)
185 // -indirect (invalid in Win32)
188 // Note that glutlib depends upon strings while this program's
189 // option parser wants only initial characters followed by numbers
194 ssgSimpleState *default_state;
195 ssgSimpleState *hud_and_panel;
196 ssgSimpleState *menus;
198 void fgBuildRenderStates( void ) {
199 default_state = new ssgSimpleState;
200 default_state->disable( GL_TEXTURE_2D );
201 default_state->enable( GL_CULL_FACE );
202 default_state->enable( GL_COLOR_MATERIAL );
203 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
204 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
205 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
206 default_state->disable( GL_BLEND );
207 default_state->disable( GL_ALPHA_TEST );
208 default_state->disable( GL_LIGHTING );
210 hud_and_panel = new ssgSimpleState;
211 hud_and_panel->disable( GL_CULL_FACE );
212 hud_and_panel->disable( GL_TEXTURE_2D );
213 hud_and_panel->disable( GL_LIGHTING );
214 hud_and_panel->enable( GL_BLEND );
216 menus = new ssgSimpleState;
217 menus->disable( GL_CULL_FACE );
218 menus->disable( GL_TEXTURE_2D );
219 menus->enable( GL_BLEND );
223 // fgInitVisuals() -- Initialize various GL/view parameters
224 void fgInitVisuals( void ) {
227 l = &cur_light_params;
229 #ifndef GLUT_WRONG_VERSION
230 // Go full screen if requested ...
231 if ( current_options.get_fullscreen() ) {
236 // If enabled, normal vectors specified with glNormal are scaled
237 // to unit length after transformation. See glNormal.
238 // glEnable( GL_NORMALIZE );
240 glEnable( GL_LIGHTING );
241 glEnable( GL_LIGHT0 );
242 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
245 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
246 ssgGetLight( 0 ) -> setPosition( sunpos );
248 // glFogi (GL_FOG_MODE, GL_LINEAR);
249 glFogi (GL_FOG_MODE, GL_EXP2);
250 if ( (current_options.get_fog() == 1) ||
251 (current_options.get_shading() == 0) ) {
252 // if fastest fog requested, or if flat shading force fastest
253 glHint ( GL_FOG_HINT, GL_FASTEST );
254 } else if ( current_options.get_fog() == 2 ) {
255 glHint ( GL_FOG_HINT, GL_NICEST );
257 if ( current_options.get_wireframe() ) {
259 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
262 // This is the default anyways, but it can't hurt
263 glFrontFace ( GL_CCW );
266 // glEnable(GL_POINT_SMOOTH);
267 // glEnable(GL_LINE_SMOOTH);
268 // glEnable(GL_POLYGON_SMOOTH);
272 // Update all Visuals (redraws anything graphics related)
273 void fgRenderFrame( void ) {
277 fgLIGHT *l = &cur_light_params;
278 FGTime *t = FGTime::cur_time_params;
279 // FGView *v = ¤t_view;
280 static double last_visibility = -9999;
283 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
284 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
285 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
286 // GLfloat mat_shininess[] = { 10.0 };
287 GLbitfield clear_mask;
289 if ( idle_state != 1000 ) {
290 // still initializing, draw the splash screen
291 if ( current_options.get_splash_screen() == 1 ) {
295 // idle_state is now 1000 meaning we've finished all our
296 // initializations and are running the main loop, so this will
297 // now work without seg faulting the system.
299 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
300 // FG_Altitude * FEET_TO_METER);
302 // this is just a temporary hack, to make me understand Pui
303 // timerText -> setLabel (ctime (&t->cur_time));
306 // update view volume parameters
307 // cout << "before pilot_view update" << endl;
308 pilot_view.UpdateViewParams(*cur_fdm_state);
309 // cout << "after pilot_view update" << endl;
310 current_view.UpdateViewParams(cur_view_fdm);
312 // set the sun position
313 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
315 clear_mask = GL_DEPTH_BUFFER_BIT;
316 if ( current_options.get_wireframe() ) {
317 clear_mask |= GL_COLOR_BUFFER_BIT;
319 if ( current_options.get_panel_status() ) {
320 // we can't clear the screen when the panel is active
321 } else if ( current_options.get_skyblend() ) {
322 if ( current_options.get_textures() ) {
323 // glClearColor(black[0], black[1], black[2], black[3]);
324 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
325 l->adj_fog_color[2], l->adj_fog_color[3]);
326 clear_mask |= GL_COLOR_BUFFER_BIT;
329 glClearColor(l->sky_color[0], l->sky_color[1],
330 l->sky_color[2], l->sky_color[3]);
331 clear_mask |= GL_COLOR_BUFFER_BIT;
333 glClear( clear_mask );
335 // Tell GL we are switching to model view parameters
337 // I really should create a derived ssg node or use a call
338 // back or something so that I can draw the sky within the
339 // ssgCullAndDraw() function, but for now I just mimic what
340 // ssg does to set up the model view matrix
341 glMatrixMode(GL_MODELVIEW);
343 ssgSetCamera( current_view.VIEW );
346 sgMat4 vm_tmp, view_mat;
347 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
348 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
349 sgPreMultMat4( view_mat, vm_tmp ) ;
350 glLoadMatrixf( (float *)view_mat );
353 // set the opengl state to known default values
354 default_state->force();
356 // update fog params if visibility has changed
357 #ifndef FG_OLD_WEATHER
358 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
360 thesky->set_visibility( current_weather.get_visibility() );
363 thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
365 ( global_multi_loop *
366 current_options.get_speed_up() ) /
367 (double)current_options.get_model_hz() );
369 double actual_visibility = thesky->get_visibility();
370 // cout << "actual visibility = " << actual_visibility << endl;
372 if ( actual_visibility != last_visibility ) {
373 last_visibility = actual_visibility;
375 // cout << "----> updating fog params" << endl;
377 GLfloat fog_exp_density;
378 GLfloat fog_exp2_density;
381 fog_exp_density = -log(0.01 / actual_visibility);
384 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
386 // Set correct opengl fog density
387 glFogf (GL_FOG_DENSITY, fog_exp2_density);
390 // update the sky dome
391 if ( current_options.get_skyblend() ) {
394 current_view.get_view_pos().x(),
395 current_view.get_view_pos().y(),
396 current_view.get_view_pos().z() );
399 sgSetVec3( zero_elev,
400 current_view.get_cur_zero_elev().x(),
401 current_view.get_cur_zero_elev().y(),
402 current_view.get_cur_zero_elev().z() );
404 /* cout << "thesky->repaint() sky_color = "
405 << cur_light_params.sky_color[0] << " "
406 << cur_light_params.sky_color[1] << " "
407 << cur_light_params.sky_color[2] << " "
408 << cur_light_params.sky_color[3] << endl;
410 << cur_light_params.fog_color[0] << " "
411 << cur_light_params.fog_color[1] << " "
412 << cur_light_params.fog_color[2] << " "
413 << cur_light_params.fog_color[3] << endl;
414 cout << " sun_angle = " << cur_light_params.sun_angle
415 << " moon_angle = " << cur_light_params.moon_angle
417 thesky->repaint( cur_light_params.sky_color,
418 cur_light_params.adj_fog_color,
419 cur_light_params.sun_angle,
420 cur_light_params.moon_angle,
421 ephem->getNumPlanets(), ephem->getPlanets(),
422 ephem->getNumStars(), ephem->getStars() );
424 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
425 << view_pos[1] << " " << view_pos[2] << endl;
426 cout << " zero_elev = " << zero_elev[0] << " "
427 << zero_elev[1] << " " << zero_elev[2]
428 << " lon = " << cur_fdm_state->get_Longitude()
429 << " lat = " << cur_fdm_state->get_Latitude() << endl;
430 cout << " sun_rot = " << cur_light_params.sun_rotation
431 << " gst = " << FGTime::cur_time_params->getGst() << endl;
432 cout << " sun ra = " << ephem->getSunRightAscension()
433 << " sun dec = " << ephem->getSunDeclination()
434 << " moon ra = " << ephem->getMoonRightAscension()
435 << " moon dec = " << ephem->getMoonDeclination() << endl; */
437 thesky->reposition( view_pos, zero_elev,
438 current_view.get_local_up(),
439 cur_fdm_state->get_Longitude(),
440 cur_fdm_state->get_Latitude(),
441 cur_fdm_state->get_Altitude() * FEET_TO_METER,
442 cur_light_params.sun_rotation,
443 FGTime::cur_time_params->getGst(),
444 ephem->getSunRightAscension(),
445 ephem->getSunDeclination(), 50000.0,
446 ephem->getMoonRightAscension(),
447 ephem->getMoonDeclination(), 50000.0 );
450 glEnable( GL_DEPTH_TEST );
451 if ( current_options.get_fog() > 0 ) {
453 glFogi( GL_FOG_MODE, GL_EXP2 );
454 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
457 // set lighting parameters
458 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
459 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
460 glLightfv( GL_LIGHT0, GL_AMBIENT, black );
461 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
462 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
464 // texture parameters
465 // glEnable( GL_TEXTURE_2D );
466 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
467 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
468 // set base color (I don't think this is doing anything here)
469 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
470 // (GL_FRONT, GL_DIFFUSE, white);
471 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
472 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
475 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
476 ssgGetLight( 0 ) -> setPosition( sunpos );
478 // glMatrixMode( GL_PROJECTION );
480 float fov = current_options.get_fov();
481 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
483 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
486 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
487 // << current_weather.get_visibility() );
490 ssgSetNearFar( 10.0f, 120000.0f );
492 ssgSetNearFar( 0.5f, 120000.0f );
495 if ( current_options.get_view_mode() ==
496 fgOPTIONS::FG_VIEW_PILOT )
499 penguin_sel->select(0);
500 } else if ( current_options.get_view_mode() ==
501 fgOPTIONS::FG_VIEW_FOLLOW )
503 // select view matrix from front of view matrix queue
504 // FGMat4Wrapper tmp = current_view.follow.front();
505 // sgCopyMat4( sgVIEW, tmp.m );
507 // enable TuX and set up his position and orientation
508 penguin_sel->select(1);
511 sgMakeTransMat4( sgTRANS,
512 pilot_view.view_pos.x(),
513 pilot_view.view_pos.y(),
514 pilot_view.view_pos.z() );
517 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
520 sgMakeRotMat4( sgROT, -90.0, ownship_up );
524 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
525 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
527 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
529 sgCopyMat4( sgTUX, sgROT );
530 sgPostMultMat4( sgTUX, pilot_view.VIEW_ROT );
531 sgPostMultMat4( sgTUX, sgTRANS );
534 sgSetCoord( &tuxpos, sgTUX );
535 penguin_pos->setTransform( &tuxpos );
538 # ifdef FG_NETWORK_OLK
539 if ( current_options.get_network_olk() ) {
541 other = head->next; /* put listpointer to start */
542 while ( other != tail) { /* display all except myself */
543 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
544 other->fgd_sel->select(1);
545 sgSetCoord( &fgdpos, other->sgFGD_COORD );
546 other->fgd_pos->setTransform( &fgdpos );
551 // fgd_sel->select(1);
552 // sgCopyMat4( sgTUX, current_view.sgVIEW);
554 // sgSetCoord( &fgdpos, sgFGD_VIEW );
555 // fgd_pos->setTransform( &fgdpos);
559 // ssgSetCamera( current_view.VIEW );
561 // position tile nodes and update range selectors
562 global_tile_mgr.prep_ssg_nodes();
564 // force the default state so ssg can get back on track if
565 // we've changed things elsewhere (this is now handled
568 // FGMaterialSlot m_slot;
569 // FGMaterialSlot *m_ptr = &m_slot;
570 // if ( material_mgr.find( "Default", m_ptr ) ) {
571 // m_ptr->get_state()->force();
574 // draw the sky backdrop
577 // draw the ssg scene
578 ssgCullAndDraw( scene );
580 // draw the sky cloud layers
581 thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
583 // display HUD && Panel
585 glDisable( GL_DEPTH_TEST );
586 // glDisable( GL_CULL_FACE );
587 // glDisable( GL_TEXTURE_2D );
588 hud_and_panel->apply();
591 // We can do translucent menus, so why not. :-)
592 // glEnable ( GL_BLEND ) ;
594 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
596 // glDisable ( GL_BLEND ) ;
598 // glEnable( GL_FOG );
605 // Update internal time dependent calculations (i.e. flight model)
606 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
607 static fdm_state_list fdm_list;
608 // FGInterface fdm_state;
609 fgLIGHT *l = &cur_light_params;
610 FGTime *t = FGTime::cur_time_params;
611 // FGView *v = ¤t_view;
614 // update the flight model
615 if ( multi_loop < 0 ) {
619 if ( !t->getPause() ) {
620 // run Autopilot system
621 current_autopilot->run();
623 // printf("updating flight model x %d\n", multi_loop);
624 /* fgFDMUpdate( current_options.get_flight_model(),
626 multi_loop * current_options.get_speed_up(),
628 cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
629 FGSteam::update( multi_loop * current_options.get_speed_up() );
631 // fgFDMUpdate( current_options.get_flight_model(),
632 // fdm_state, 0, remainder );
633 cur_fdm_state->update( 0 );
634 FGSteam::update( 0 );
637 fdm_list.push_back( *cur_fdm_state );
638 while ( fdm_list.size() > 15 ) {
639 fdm_list.pop_front();
642 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
643 cur_view_fdm = *cur_fdm_state;
645 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
646 cur_view_fdm = fdm_list.front();
649 // update the view angle
650 for ( i = 0; i < multi_loop; i++ ) {
651 if ( fabs(current_view.get_goal_view_offset() -
652 current_view.get_view_offset()) < 0.05 )
654 current_view.set_view_offset( current_view.get_goal_view_offset() );
657 // move current_view.view_offset towards current_view.goal_view_offset
658 if ( current_view.get_goal_view_offset() >
659 current_view.get_view_offset() )
661 if ( current_view.get_goal_view_offset() -
662 current_view.get_view_offset() < FG_PI )
664 current_view.inc_view_offset( 0.01 );
666 current_view.inc_view_offset( -0.01 );
669 if ( current_view.get_view_offset() -
670 current_view.get_goal_view_offset() < FG_PI )
672 current_view.inc_view_offset( -0.01 );
674 current_view.inc_view_offset( 0.01 );
677 if ( current_view.get_view_offset() > FG_2PI ) {
678 current_view.inc_view_offset( -FG_2PI );
679 } else if ( current_view.get_view_offset() < 0 ) {
680 current_view.inc_view_offset( FG_2PI );
685 double tmp = -(l->sun_rotation + FG_PI)
686 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
687 while ( tmp < 0.0 ) {
690 while ( tmp > FG_2PI ) {
693 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
694 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
695 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
698 // Update solar system
699 ephem->update( t, cur_fdm_state->get_Latitude() );
701 // Update radio stack model
702 current_radiostack->update( cur_fdm_state->get_Longitude(),
703 cur_fdm_state->get_Latitude(),
704 cur_fdm_state->get_Altitude() * FEET_TO_METER );
708 void fgInitTimeDepCalcs( void ) {
711 // #ifdef HAVE_SETITIMER
712 // fgTimerInit( 1.0 / current_options.get_model_hz(),
713 // fgUpdateTimeDepCalcs );
714 // #endif HAVE_SETITIMER
718 static const double alt_adjust_ft = 3.758099;
719 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
722 // What should we do when we have nothing else to do? Let's get ready
723 // for the next move and update the display?
724 static void fgMainLoop( void ) {
726 static long remainder = 0;
728 #ifdef FANCY_FRAME_COUNTER
732 static time_t last_time = 0;
733 static int frames = 0;
734 #endif // FANCY_FRAME_COUNTER
736 t = FGTime::cur_time_params;
738 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
739 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
741 #ifdef FG_NETWORK_OLK
742 if ( current_options.get_network_olk() ) {
743 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
744 // printf("FGD: Netupdate\n");
745 fgd_send_com( "A", FGFS_host); // Send Mat4 data
746 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
751 #if defined( ENABLE_PLIB_JOYSTICK )
752 // Read joystick and update control settings
753 if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
756 #elif defined( ENABLE_GLUT_JOYSTICK )
757 // Glut joystick support works by feeding a joystick handler
758 // function to glut. This is taken care of once in the joystick
759 // init routine and we don't have to worry about it again.
762 #ifdef FG_OLD_WEATHER
763 current_weather.Update();
766 // Fix elevation. I'm just sticking this here for now, it should
767 // probably move eventually
769 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
771 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
772 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
774 if ( scenery.cur_elev > -9990 ) {
775 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
776 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
777 // now set aircraft altitude above ground
778 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
779 cur_fdm_state->get_Altitude() * FEET_TO_METER,
780 scenery.cur_elev + alt_adjust_m - 3.0,
781 scenery.cur_elev + alt_adjust_m );
782 fgFDMForceAltitude( current_options.get_flight_model(),
783 scenery.cur_elev + alt_adjust_m );
785 FG_LOG( FG_ALL, FG_DEBUG,
786 "<*> resetting altitude to "
787 << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
789 fgFDMSetGroundElevation( current_options.get_flight_model(),
790 scenery.cur_elev ); // meters
793 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
795 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
796 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
799 t->update( cur_fdm_state->get_Longitude(),
800 cur_fdm_state->get_Latitude(),
801 cur_fdm_state->get_Altitude()* FEET_TO_METER );
803 // Get elapsed time (in usec) for this past frame
804 elapsed = fgGetTimeInterval();
805 FG_LOG( FG_ALL, FG_DEBUG,
806 "Elapsed time interval is = " << elapsed
807 << ", previous remainder is = " << remainder );
809 // Calculate frame rate average
810 #ifdef FANCY_FRAME_COUNTER
811 /* old fps calculation */
815 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
816 tmp = general.get_frame(i);
818 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
819 general.set_frame(i+1,tmp);
821 tmp = 1000000.0 / (float)elapsed;
822 general.set_frame(0,tmp);
823 // printf("frame[0] = %.2f\n", general.frames[0]);
825 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
826 // printf("ave = %.2f\n", general.frame_rate);
829 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
830 general.set_frame_rate( frames );
831 FG_LOG( FG_ALL, FG_DEBUG,
832 "--> Frame rate is = " << general.get_frame_rate() );
835 last_time = t->get_cur_time();
840 if ( ! use_signals ) {
841 // Calculate model iterations needed for next frame
842 elapsed += remainder;
844 global_multi_loop = (int)(((double)elapsed * 0.000001) *
845 current_options.get_model_hz());
846 remainder = elapsed - ( (global_multi_loop*1000000) /
847 current_options.get_model_hz() );
848 FG_LOG( FG_ALL, FG_DEBUG,
849 "Model iterations needed = " << global_multi_loop
850 << ", new remainder = " << remainder );
853 if ( global_multi_loop > 0 ) {
854 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
856 FG_LOG( FG_ALL, FG_DEBUG,
857 "Elapsed time is zero ... we're zinging" );
861 #if ! defined( MACOS )
862 // Do any I/O channel work that might need to be done
866 // see if we need to load any new scenery tiles
867 global_tile_mgr.update( cur_fdm_state->get_Longitude(),
868 cur_fdm_state->get_Latitude() );
870 // Process/manage pending events
871 global_events.Process();
873 // Run audio scheduler
874 #ifdef ENABLE_AUDIO_SUPPORT
875 if ( current_options.get_sound() && !audio_sched->not_working() ) {
877 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
879 // note: all these factors are relative to the sample. our
880 // sample format should really contain a conversion factor so
881 // that we can get prop speed right for arbitrary samples.
882 // Note that for normal-size props, there is a point at which
883 // the prop tips approach the speed of sound; that is a pretty
884 // strong limit to how fast the prop can go.
886 // multiplication factor is prime pitch control; add some log
887 // component for verisimilitude
889 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
890 //fprintf(stderr, "pitch1: %f ", pitch);
891 // if (controls.get_throttle(0) > 0.0 ||
892 // cur_fdm_state->v_rel_wind > 40.0) {
894 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
895 // only add relative wind and AoA if prop is moving
896 // or we're really flying at idle throttle
897 if (pitch < 5.4) { // this needs tuning
898 // prop tips not breaking sound barrier
899 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
901 // prop tips breaking sound barrier
902 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
904 //fprintf(stderr, "pitch2: %f ", pitch);
905 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
907 // Angle of Attack next... -x^3(e^x) is my best guess Just
908 // need to calculate some reasonable scaling factor and
909 // then clamp it on the positive aoa (neg adj) side
910 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
912 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
913 if (aoa_adj < -0.8) aoa_adj = -0.8;
915 //fprintf(stderr, "pitch3: %f ", pitch);
917 // don't run at absurdly slow rates -- not realistic
918 // and sounds bad to boot. :-)
919 if (pitch < 0.8) pitch = 0.8;
921 // fprintf(stderr, "pitch4: %f\n", pitch);
923 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
924 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
925 // fprintf(stderr, "volume: %f\n", volume);
927 pitch_envelope.setStep ( 0, 0.01, pitch );
928 volume_envelope.setStep ( 0, 0.01, volume );
932 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
933 pitch_envelope.setStep ( 0, 0.01, param );
934 volume_envelope.setStep ( 0, 0.01, param );
936 # endif // experimental throttle patch
938 audio_sched -> update();
945 FG_LOG( FG_ALL, FG_DEBUG, "" );
949 // This is the top level master main function that is registered as
953 // The first few passes take care of initialization things (a couple
954 // per pass) and once everything has been initialized fgMainLoop from
957 static void fgIdleFunction ( void ) {
958 // printf("idle state == %d\n", idle_state);
960 if ( idle_state == 0 ) {
961 // Initialize the splash screen right away
962 if ( current_options.get_splash_screen() ) {
967 } else if ( idle_state == 1 ) {
968 // Start the intro music
970 if ( current_options.get_intro_music() ) {
971 string lockfile = "/tmp/mpg123.running";
972 FGPath mp3file( current_options.get_fg_root() );
973 mp3file.append( "Sounds/intro.mp3" );
975 string command = "(touch " + lockfile + "; mpg123 "
976 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
978 FG_LOG( FG_GENERAL, FG_INFO,
979 "Starting intro music: " << mp3file.str() );
980 system ( command.c_str() );
985 } else if ( idle_state == 2 ) {
986 // These are a few miscellaneous things that aren't really
987 // "subsystems" but still need to be initialized.
990 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
991 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
996 } else if ( idle_state == 3 ) {
997 // This is the top level init routine which calls all the
998 // other subsystem initialization routines. If you are adding
999 // a subsystem to flight gear, its initialization call should
1000 // located in this routine.
1001 if( !fgInitSubsystems()) {
1002 FG_LOG( FG_GENERAL, FG_ALERT,
1003 "Subsystem initializations failed ..." );
1008 } else if ( idle_state == 4 ) {
1009 // setup OpenGL view parameters
1012 if ( use_signals ) {
1013 // init timer routines, signals, etc. Arrange for an alarm
1014 // signal to be generated, etc.
1015 fgInitTimeDepCalcs();
1019 } else if ( idle_state == 5 ) {
1022 } else if ( idle_state == 6 ) {
1023 // Initialize audio support
1024 #ifdef ENABLE_AUDIO_SUPPORT
1027 if ( current_options.get_intro_music() ) {
1028 // Let's wait for mpg123 to finish
1029 string lockfile = "/tmp/mpg123.running";
1030 struct stat stat_buf;
1032 FG_LOG( FG_GENERAL, FG_INFO,
1033 "Waiting for mpg123 player to finish ..." );
1034 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1035 // file exist, wait ...
1037 FG_LOG( FG_GENERAL, FG_INFO, ".");
1039 FG_LOG( FG_GENERAL, FG_INFO, "");
1043 if ( current_options.get_sound() ) {
1044 audio_sched = new slScheduler ( 8000 );
1045 audio_mixer = new smMixer;
1046 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1047 audio_sched -> setSafetyMargin ( 1.0 ) ;
1049 FGPath slfile( current_options.get_fg_root() );
1050 slfile.append( "Sounds/wasp.wav" );
1052 s1 = new slSample ( (char *)slfile.c_str() );
1053 FG_LOG( FG_GENERAL, FG_INFO,
1054 "Rate = " << s1 -> getRate()
1055 << " Bps = " << s1 -> getBps()
1056 << " Stereo = " << s1 -> getStereo() );
1057 audio_sched -> loopSample ( s1 );
1059 if ( audio_sched->not_working() ) {
1062 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1063 volume_envelope.setStep ( 0, 0.01, 0.6 );
1065 audio_sched -> addSampleEnvelope( s1, 0, 0,
1067 SL_PITCH_ENVELOPE );
1068 audio_sched -> addSampleEnvelope( s1, 0, 1,
1070 SL_VOLUME_ENVELOPE );
1073 // strcpy(slfile, path);
1074 // strcat(slfile, "thunder.wav");
1075 // s2 -> loadFile ( slfile );
1076 // s2 -> adjustVolume(0.5);
1077 // audio_sched -> playSample ( s2 );
1085 if ( idle_state == 1000 ) {
1086 // We've finished all our initialization steps, from now on we
1087 // run the main loop.
1091 if ( current_options.get_splash_screen() == 1 ) {
1092 fgSplashUpdate(0.0);
1097 // options.cxx needs to see this for toggle_panel()
1098 // Handle new window size or exposure
1099 void fgReshape( int width, int height ) {
1100 if ( ! current_options.get_panel_status() ) {
1101 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1102 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1104 current_view.set_win_ratio( (GLfloat) width /
1105 ((GLfloat) (height)*0.4232) );
1106 glViewport(0, (GLint)((height)*0.5768),
1107 (GLint)(width), (GLint)((height)*0.4232) );
1110 current_view.set_winWidth( width );
1111 current_view.set_winHeight( height );
1112 current_view.force_update_fov_math();
1114 // set these fov to be the same as in fgRenderFrame()
1115 // float x_fov = current_options.get_fov();
1116 // float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1117 // ssgSetFOV( x_fov, y_fov );
1119 // glViewport ( 0, 0, width, height );
1120 float fov = current_options.get_fov();
1121 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1125 if ( idle_state == 1000 ) {
1126 // yes we've finished all our initializations and are running
1127 // the main loop, so this will now work without seg faulting
1129 current_view.UpdateViewParams(cur_view_fdm);
1134 // Initialize GLUT and define a main window
1135 int fgGlutInit( int *argc, char **argv ) {
1137 #if !defined( MACOS )
1138 // GLUT will extract all glut specific options so later on we only
1139 // need wory about our own.
1140 glutInit(argc, argv);
1143 // Define Display Parameters
1144 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1146 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1147 current_options.get_xsize() << "x" << current_options.get_ysize() );
1149 // Define initial window size
1150 glutInitWindowSize( current_options.get_xsize(),
1151 current_options.get_ysize() );
1153 // Initialize windows
1154 if ( current_options.get_game_mode() == 0 ) {
1155 // Open the regular window
1156 glutCreateWindow("Flight Gear");
1157 #ifndef GLUT_WRONG_VERSION
1159 // Open the cool new 'game mode' window
1160 char game_mode_str[256];
1161 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1162 current_options.get_xsize(),
1163 current_options.get_ysize(),
1164 current_options.get_bpp());
1166 FG_LOG( FG_GENERAL, FG_INFO,
1167 "game mode params = " << game_mode_str );
1168 glutGameModeString( game_mode_str );
1169 glutEnterGameMode();
1173 // This seems to be the absolute earliest in the init sequence
1174 // that these calls will return valid info. Too bad it's after
1175 // we've already created and sized out window. :-(
1176 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1177 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1178 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1180 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1183 // try to determine if we should adjust the initial default
1184 // display resolution. The options class defaults (is
1185 // initialized) to 640x480.
1186 string renderer = general.glRenderer;
1188 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1189 if ( renderer.find( "Glide" ) != string::npos ) {
1190 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1191 if ( renderer.find( "FB/8" ) != string::npos ) {
1192 // probably a voodoo-2
1193 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1194 // probably two SLI'd Voodoo-2's
1195 current_options.set_xsize( 1024 );
1196 current_options.set_ysize( 768 );
1197 FG_LOG( FG_GENERAL, FG_INFO,
1198 "It looks like you have two sli'd voodoo-2's." << endl
1199 << "upgrading your win resolution to 1024 x 768" );
1200 glutReshapeWindow(1024, 768);
1202 // probably a single non-SLI'd Voodoo-2
1203 current_options.set_xsize( 800 );
1204 current_options.set_ysize( 600 );
1205 FG_LOG( FG_GENERAL, FG_INFO,
1206 "It looks like you have a voodoo-2." << endl
1207 << "upgrading your win resolution to 800 x 600" );
1208 glutReshapeWindow(800, 600);
1210 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1211 // probably a voodoo-1, stick with the default
1214 // we have no special knowledge of this card, stick with the default
1222 // Initialize GLUT event handlers
1223 int fgGlutInitEvents( void ) {
1224 // call fgReshape() on window resizes
1225 glutReshapeFunc( fgReshape );
1227 // call GLUTkey() on keyboard event
1228 glutKeyboardFunc( GLUTkey );
1229 glutSpecialFunc( GLUTspecialkey );
1231 // call guiMouseFunc() whenever our little rodent is used
1232 glutMouseFunc ( guiMouseFunc );
1233 glutMotionFunc (guiMotionFunc );
1234 glutPassiveMotionFunc (guiMotionFunc );
1236 // call fgMainLoop() whenever there is
1237 // nothing else to do
1238 glutIdleFunc( fgIdleFunction );
1241 glutDisplayFunc( fgRenderFrame );
1248 int main( int argc, char **argv ) {
1250 #if defined( MACOS )
1251 freopen ("stdout.txt", "w", stdout );
1252 freopen ("stderr.txt", "w", stderr );
1253 argc = ccommand( &argv );
1257 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1260 // set default log levels
1261 fglog().setLogLevels( FG_ALL, FG_INFO );
1263 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1265 // seed the random number generater
1268 aircraft_dir = ""; // Initialize the Aircraft directory to "" (UIUC)
1270 // Load the configuration parameters
1271 if ( !fgInitConfig(argc, argv) ) {
1272 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1276 // Initialize the Window/Graphics environment.
1277 if( !fgGlutInit(&argc, argv) ) {
1278 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1282 // Initialize the various GLUT Event Handlers.
1283 if( !fgGlutInitEvents() ) {
1284 FG_LOG( FG_GENERAL, FG_ALERT,
1285 "GLUT event handler initialization failed ..." );
1289 // Initialize ssg (from plib). Needs to come before we do any
1290 // other ssg stuff, but after opengl/glut has been initialized.
1293 // Initialize the user interface (we need to do this before
1294 // passing off control to glut and before fgInitGeneral to get our
1299 FGTime::cur_time_params = new FGTime();
1300 // FGTime::cur_time_params->init( cur_fdm_state->get_Longitude(),
1301 // cur_fdm_state->get_Latitude() );
1302 // FGTime::cur_time_params->update( cur_fdm_state->get_Longitude() );
1303 FGTime::cur_time_params->init( 0.0, 0.0 );
1304 FGTime::cur_time_params->update( 0.0, 0.0, 0.0 );
1306 // Do some quick general initializations
1307 if( !fgInitGeneral()) {
1308 FG_LOG( FG_GENERAL, FG_ALERT,
1309 "General initializations failed ..." );
1314 // some ssg test stuff (requires data from the plib source
1315 // distribution) specifically from the ssg tux example
1318 FGPath modelpath( current_options.get_fg_root() );
1319 modelpath.append( "Models" );
1320 modelpath.append( "Geometry" );
1322 FGPath texturepath( current_options.get_fg_root() );
1323 texturepath.append( "Models" );
1324 texturepath.append( "Textures" );
1326 ssgModelPath( (char *)modelpath.c_str() );
1327 ssgTexturePath( (char *)texturepath.c_str() );
1330 scene = new ssgRoot;
1331 scene->setName( "Scene" );
1333 // Initialize the sky
1334 FGPath ephem_data_path( current_options.get_fg_root() );
1335 ephem_data_path.append( "Astro" );
1336 ephem = new FGEphemeris( ephem_data_path.c_str() );
1337 ephem->update( FGTime::cur_time_params, 0.0 );
1339 FGPath sky_tex_path( current_options.get_fg_root() );
1340 sky_tex_path.append( "Textures" );
1341 sky_tex_path.append( "Sky" );
1343 thesky->texture_path( sky_tex_path.str() );
1345 thesky->build( 550.0, 550.0,
1346 ephem->getNumPlanets(),
1347 ephem->getPlanets(), 60000.0,
1348 ephem->getNumStars(),
1349 ephem->getStars(), 60000.0 );
1350 thesky->add_cloud_layer( 213.0, 50.0, 50.0, SG_CLOUD_MOSTLY_SUNNY );
1351 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, SG_CLOUD_MOSTLY_SUNNY );
1352 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1355 terrain = new ssgBranch;
1356 terrain->setName( "Terrain" );
1357 scene->addKid( terrain );
1359 // temporary visible aircraft "own ship"
1360 penguin_sel = new ssgSelector;
1361 penguin_pos = new ssgTransform;
1362 // ssgBranch *tux_obj = ssgMakeSphere( 10.0, 10, 10 );
1363 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1364 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1366 penguin_pos->addKid( tux_obj );
1367 penguin_sel->addKid( penguin_pos );
1368 ssgFlatten( tux_obj );
1369 ssgStripify( penguin_sel );
1370 penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1371 scene->addKid( penguin_sel );
1373 #ifdef FG_NETWORK_OLK
1374 // Do the network intialization
1375 if ( current_options.get_network_olk() ) {
1376 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1380 // build our custom render states
1381 fgBuildRenderStates();
1383 // pass control off to the master GLUT event handler
1386 // we never actually get here ... but to avoid compiler warnings,