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>
73 #include <simgear/sky/sky.hxx>
74 #include <simgear/timing/sg_time.hxx>
75 #include <simgear/timing/lowleveltime.h>
77 #include <Include/general.hxx>
79 #include <Aircraft/aircraft.hxx>
81 #include <Autopilot/newauto.hxx>
82 #include <Cockpit/cockpit.hxx>
83 #include <Cockpit/radiostack.hxx>
84 #include <Cockpit/steam.hxx>
86 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
88 #include <Joystick/joystick.hxx>
90 #include <NetworkOLK/network.h>
92 #include <Scenery/scenery.hxx>
93 #include <Scenery/tilemgr.hxx>
94 #include <Time/event.hxx>
95 #include <Time/fg_timer.hxx>
96 #include <Time/sunpos.hxx>
97 #include <Time/tmp.hxx>
99 #ifndef FG_OLD_WEATHER
100 # include <WeatherCM/FGLocalWeatherDatabase.h>
102 # include <Weather/weather.hxx>
106 #include "fg_init.hxx"
108 #include "globals.hxx"
109 #include "keyboard.hxx"
110 #include "options.hxx"
111 #include "splash.hxx"
115 // -dw- use custom sioux settings so I can see output window
118 # include <sioux.h> // settings for output window
120 # include <console.h>
124 // This is a record containing a bit of global housekeeping information
127 // Specify our current idle function state. This is used to run all
128 // our initializations out of the glutIdleLoop() so that we can get a
129 // splash screen up and running right away.
130 static int idle_state = 0;
131 static int global_multi_loop;
136 // Global structures for the Audio library
137 #ifdef ENABLE_AUDIO_SUPPORT
138 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
139 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
140 slScheduler *audio_sched;
141 smMixer *audio_mixer;
148 ssgRoot *scene = NULL;
149 ssgBranch *terrain = NULL;
150 ssgSelector *penguin_sel = NULL;
151 ssgTransform *penguin_pos = NULL;
153 #ifdef FG_NETWORK_OLK
154 ssgSelector *fgd_sel = NULL;
155 ssgTransform *fgd_pos = NULL;
159 // current fdm/position used for view
160 FGInterface cur_view_fdm;
166 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
168 { 1.0f, 0.0f, 0.0f, 0.0f },
169 { 0.0f, 0.0f, -1.0f, 0.0f },
170 { 0.0f, 1.0f, 0.0f, 0.0f },
171 { 0.0f, 0.0f, 0.0f, 1.0f }
174 // The following defines flight gear options. Because glutlib will also
175 // want to parse its own options, those options must not be included here
176 // or they will get parsed by the main program option parser. Hence case
177 // is significant for any option added that might be in conflict with
180 // glutlib parses for:
182 // -direct (invalid in Win32)
186 // -indirect (invalid in Win32)
189 // Note that glutlib depends upon strings while this program's
190 // option parser wants only initial characters followed by numbers
195 ssgSimpleState *default_state;
196 ssgSimpleState *hud_and_panel;
197 ssgSimpleState *menus;
199 void fgBuildRenderStates( void ) {
200 default_state = new ssgSimpleState;
201 default_state->disable( GL_TEXTURE_2D );
202 default_state->enable( GL_CULL_FACE );
203 default_state->enable( GL_COLOR_MATERIAL );
204 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
205 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
206 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
207 default_state->disable( GL_BLEND );
208 default_state->disable( GL_ALPHA_TEST );
209 default_state->disable( GL_LIGHTING );
211 hud_and_panel = new ssgSimpleState;
212 hud_and_panel->disable( GL_CULL_FACE );
213 hud_and_panel->disable( GL_TEXTURE_2D );
214 hud_and_panel->disable( GL_LIGHTING );
215 hud_and_panel->enable( GL_BLEND );
217 menus = new ssgSimpleState;
218 menus->disable( GL_CULL_FACE );
219 menus->disable( GL_TEXTURE_2D );
220 menus->enable( GL_BLEND );
224 // fgInitVisuals() -- Initialize various GL/view parameters
225 void fgInitVisuals( void ) {
228 l = &cur_light_params;
230 #ifndef GLUT_WRONG_VERSION
231 // Go full screen if requested ...
232 if ( current_options.get_fullscreen() ) {
237 // If enabled, normal vectors specified with glNormal are scaled
238 // to unit length after transformation. See glNormal.
239 // glEnable( GL_NORMALIZE );
241 glEnable( GL_LIGHTING );
242 glEnable( GL_LIGHT0 );
243 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
246 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
247 ssgGetLight( 0 ) -> setPosition( sunpos );
249 // glFogi (GL_FOG_MODE, GL_LINEAR);
250 glFogi (GL_FOG_MODE, GL_EXP2);
251 if ( (current_options.get_fog() == 1) ||
252 (current_options.get_shading() == 0) ) {
253 // if fastest fog requested, or if flat shading force fastest
254 glHint ( GL_FOG_HINT, GL_FASTEST );
255 } else if ( current_options.get_fog() == 2 ) {
256 glHint ( GL_FOG_HINT, GL_NICEST );
258 if ( current_options.get_wireframe() ) {
260 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
263 // This is the default anyways, but it can't hurt
264 glFrontFace ( GL_CCW );
267 // glEnable(GL_POINT_SMOOTH);
268 // glEnable(GL_LINE_SMOOTH);
269 // glEnable(GL_POLYGON_SMOOTH);
273 // Update all Visuals (redraws anything graphics related)
274 void fgRenderFrame( void ) {
278 fgLIGHT *l = &cur_light_params;
279 static double last_visibility = -9999;
282 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
283 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
284 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
285 // GLfloat mat_shininess[] = { 10.0 };
286 GLbitfield clear_mask;
288 if ( idle_state != 1000 ) {
289 // still initializing, draw the splash screen
290 if ( current_options.get_splash_screen() == 1 ) {
294 // idle_state is now 1000 meaning we've finished all our
295 // initializations and are running the main loop, so this will
296 // now work without seg faulting the system.
298 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
299 // FG_Altitude * FEET_TO_METER);
301 // this is just a temporary hack, to make me understand Pui
302 // timerText -> setLabel (ctime (&t->cur_time));
305 // update view volume parameters
306 // cout << "before pilot_view update" << endl;
307 pilot_view.UpdateViewParams(*cur_fdm_state);
308 // cout << "after pilot_view update" << endl;
309 current_view.UpdateViewParams(cur_view_fdm);
311 // set the sun position
312 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
314 clear_mask = GL_DEPTH_BUFFER_BIT;
315 if ( current_options.get_wireframe() ) {
316 clear_mask |= GL_COLOR_BUFFER_BIT;
319 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();
354 // update fog params if visibility has changed
355 #ifndef FG_OLD_WEATHER
356 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
358 thesky->set_visibility( current_weather.get_visibility() );
361 thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
363 ( global_multi_loop *
364 current_options.get_speed_up() ) /
365 (double)current_options.get_model_hz() );
367 double actual_visibility = thesky->get_visibility();
368 // cout << "actual visibility = " << actual_visibility << endl;
370 if ( actual_visibility != last_visibility ) {
371 last_visibility = actual_visibility;
373 // cout << "----> updating fog params" << endl;
375 GLfloat fog_exp_density;
376 GLfloat fog_exp2_density;
379 fog_exp_density = -log(0.01 / actual_visibility);
382 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
384 // Set correct opengl fog density
385 glFogf (GL_FOG_DENSITY, fog_exp2_density);
388 // update the sky dome
389 if ( current_options.get_skyblend() ) {
392 current_view.get_view_pos().x(),
393 current_view.get_view_pos().y(),
394 current_view.get_view_pos().z() );
397 sgSetVec3( zero_elev,
398 current_view.get_cur_zero_elev().x(),
399 current_view.get_cur_zero_elev().y(),
400 current_view.get_cur_zero_elev().z() );
402 /* cout << "thesky->repaint() sky_color = "
403 << cur_light_params.sky_color[0] << " "
404 << cur_light_params.sky_color[1] << " "
405 << cur_light_params.sky_color[2] << " "
406 << cur_light_params.sky_color[3] << endl;
408 << cur_light_params.fog_color[0] << " "
409 << cur_light_params.fog_color[1] << " "
410 << cur_light_params.fog_color[2] << " "
411 << cur_light_params.fog_color[3] << endl;
412 cout << " sun_angle = " << cur_light_params.sun_angle
413 << " moon_angle = " << cur_light_params.moon_angle
415 thesky->repaint( cur_light_params.sky_color,
416 cur_light_params.adj_fog_color,
417 cur_light_params.sun_angle,
418 cur_light_params.moon_angle,
419 globals->get_ephem()->getNumPlanets(),
420 globals->get_ephem()->getPlanets(),
421 globals->get_ephem()->getNumStars(),
422 globals->get_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 = " << SGTime::cur_time_params->getGst() << endl;
432 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
433 << " sun dec = " << globals->get_ephem()->getSunDeclination()
434 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
435 << " moon dec = " << globals->get_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 globals->get_time_params()->getGst(),
444 globals->get_ephem()->getSunRightAscension(),
445 globals->get_ephem()->getSunDeclination(),
447 globals->get_ephem()->getMoonRightAscension(),
448 globals->get_ephem()->getMoonDeclination(),
452 glEnable( GL_DEPTH_TEST );
453 if ( current_options.get_fog() > 0 ) {
455 glFogi( GL_FOG_MODE, GL_EXP2 );
456 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
459 // set lighting parameters
460 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
461 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
462 glLightfv( GL_LIGHT0, GL_AMBIENT, black );
463 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
464 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
466 // texture parameters
467 // glEnable( GL_TEXTURE_2D );
468 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
469 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
470 // set base color (I don't think this is doing anything here)
471 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
472 // (GL_FRONT, GL_DIFFUSE, white);
473 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
474 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
477 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
478 ssgGetLight( 0 ) -> setPosition( sunpos );
480 // glMatrixMode( GL_PROJECTION );
482 float fov = current_options.get_fov();
483 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
485 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
488 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
489 // << current_weather.get_visibility() );
492 ssgSetNearFar( 10.0f, 120000.0f );
494 ssgSetNearFar( 0.5f, 120000.0f );
497 if ( current_options.get_view_mode() ==
498 fgOPTIONS::FG_VIEW_PILOT )
501 penguin_sel->select(0);
502 } else if ( current_options.get_view_mode() ==
503 fgOPTIONS::FG_VIEW_FOLLOW )
505 // select view matrix from front of view matrix queue
506 // FGMat4Wrapper tmp = current_view.follow.front();
507 // sgCopyMat4( sgVIEW, tmp.m );
509 // enable TuX and set up his position and orientation
510 penguin_sel->select(1);
513 sgMakeTransMat4( sgTRANS,
514 pilot_view.view_pos.x(),
515 pilot_view.view_pos.y(),
516 pilot_view.view_pos.z() );
519 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
522 sgMakeRotMat4( sgROT, -90.0, ownship_up );
526 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
527 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
529 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
531 sgCopyMat4( sgTUX, sgROT );
532 sgPostMultMat4( sgTUX, pilot_view.VIEW_ROT );
533 sgPostMultMat4( sgTUX, sgTRANS );
536 sgSetCoord( &tuxpos, sgTUX );
537 penguin_pos->setTransform( &tuxpos );
540 # ifdef FG_NETWORK_OLK
541 if ( current_options.get_network_olk() ) {
543 other = head->next; /* put listpointer to start */
544 while ( other != tail) { /* display all except myself */
545 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
546 other->fgd_sel->select(1);
547 sgSetCoord( &fgdpos, other->sgFGD_COORD );
548 other->fgd_pos->setTransform( &fgdpos );
553 // fgd_sel->select(1);
554 // sgCopyMat4( sgTUX, current_view.sgVIEW);
556 // sgSetCoord( &fgdpos, sgFGD_VIEW );
557 // fgd_pos->setTransform( &fgdpos);
561 // ssgSetCamera( current_view.VIEW );
563 // position tile nodes and update range selectors
564 global_tile_mgr.prep_ssg_nodes();
566 // force the default state so ssg can get back on track if
567 // we've changed things elsewhere (this is now handled
570 // FGMaterialSlot m_slot;
571 // FGMaterialSlot *m_ptr = &m_slot;
572 // if ( material_mgr.find( "Default", m_ptr ) ) {
573 // m_ptr->get_state()->force();
576 // draw the sky backdrop
579 // draw the ssg scene
580 ssgCullAndDraw( scene );
582 // draw the sky cloud layers
583 thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
585 // display HUD && Panel
587 glDisable( GL_DEPTH_TEST );
588 // glDisable( GL_CULL_FACE );
589 // glDisable( GL_TEXTURE_2D );
590 hud_and_panel->apply();
593 // We can do translucent menus, so why not. :-)
594 // glEnable ( GL_BLEND ) ;
596 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
598 // glDisable ( GL_BLEND ) ;
600 // glEnable( GL_FOG );
607 // Update internal time dependent calculations (i.e. flight model)
608 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
609 static fdm_state_list fdm_list;
610 fgLIGHT *l = &cur_light_params;
613 // update the flight model
614 if ( multi_loop < 0 ) {
618 if ( !globals->get_freeze() ) {
619 // run Autopilot system
620 current_autopilot->run();
622 // printf("updating flight model x %d\n", multi_loop);
623 /* fgFDMUpdate( current_options.get_flight_model(),
625 multi_loop * current_options.get_speed_up(),
627 cur_fdm_state->update( multi_loop * current_options.get_speed_up() );
628 FGSteam::update( multi_loop * current_options.get_speed_up() );
630 // fgFDMUpdate( current_options.get_flight_model(),
631 // fdm_state, 0, remainder );
632 cur_fdm_state->update( 0 );
633 FGSteam::update( 0 );
636 fdm_list.push_back( *cur_fdm_state );
637 while ( fdm_list.size() > 15 ) {
638 fdm_list.pop_front();
641 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
642 cur_view_fdm = *cur_fdm_state;
644 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
645 cur_view_fdm = fdm_list.front();
648 // update the view angle
649 for ( i = 0; i < multi_loop; i++ ) {
650 if ( fabs(current_view.get_goal_view_offset() -
651 current_view.get_view_offset()) < 0.05 )
653 current_view.set_view_offset( current_view.get_goal_view_offset() );
656 // move current_view.view_offset towards current_view.goal_view_offset
657 if ( current_view.get_goal_view_offset() >
658 current_view.get_view_offset() )
660 if ( current_view.get_goal_view_offset() -
661 current_view.get_view_offset() < FG_PI )
663 current_view.inc_view_offset( 0.01 );
665 current_view.inc_view_offset( -0.01 );
668 if ( current_view.get_view_offset() -
669 current_view.get_goal_view_offset() < FG_PI )
671 current_view.inc_view_offset( -0.01 );
673 current_view.inc_view_offset( 0.01 );
676 if ( current_view.get_view_offset() > FG_2PI ) {
677 current_view.inc_view_offset( -FG_2PI );
678 } else if ( current_view.get_view_offset() < 0 ) {
679 current_view.inc_view_offset( FG_2PI );
684 double tmp = -(l->sun_rotation + FG_PI)
685 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
686 while ( tmp < 0.0 ) {
689 while ( tmp > FG_2PI ) {
692 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
693 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
694 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
697 // Update solar system
698 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
699 globals->get_time_params()->getLst(),
700 cur_fdm_state->get_Latitude() );
702 // Update radio stack model
703 current_radiostack->update( cur_fdm_state->get_Longitude(),
704 cur_fdm_state->get_Latitude(),
705 cur_fdm_state->get_Altitude() * FEET_TO_METER );
709 void fgInitTimeDepCalcs( void ) {
712 // #ifdef HAVE_SETITIMER
713 // fgTimerInit( 1.0 / current_options.get_model_hz(),
714 // fgUpdateTimeDepCalcs );
715 // #endif HAVE_SETITIMER
719 static const double alt_adjust_ft = 3.758099;
720 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
723 // What should we do when we have nothing else to do? Let's get ready
724 // for the next move and update the display?
725 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 SGTime *t = globals->get_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 if ( globals->get_warp_delta() != 0 ) {
800 globals->inc_warp( globals->get_warp_delta() );
803 t->update( cur_fdm_state->get_Longitude(),
804 cur_fdm_state->get_Latitude(),
805 globals->get_warp() );
807 if ( globals->get_warp_delta() != 0 ) {
808 fgUpdateSkyAndLightingParams();
811 // update magvar model
812 cur_magvar.update( cur_fdm_state->get_Longitude(),
813 cur_fdm_state->get_Latitude(),
814 cur_fdm_state->get_Altitude()* FEET_TO_METER,
815 globals->get_time_params()->getJD() );
817 // Get elapsed time (in usec) for this past frame
818 elapsed = fgGetTimeInterval();
819 FG_LOG( FG_ALL, FG_DEBUG,
820 "Elapsed time interval is = " << elapsed
821 << ", previous remainder is = " << remainder );
823 // Calculate frame rate average
824 #ifdef FANCY_FRAME_COUNTER
825 /* old fps calculation */
829 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
830 tmp = general.get_frame(i);
832 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
833 general.set_frame(i+1,tmp);
835 tmp = 1000000.0 / (float)elapsed;
836 general.set_frame(0,tmp);
837 // printf("frame[0] = %.2f\n", general.frames[0]);
839 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
840 // printf("ave = %.2f\n", general.frame_rate);
843 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
844 general.set_frame_rate( frames );
845 FG_LOG( FG_ALL, FG_DEBUG,
846 "--> Frame rate is = " << general.get_frame_rate() );
849 last_time = t->get_cur_time();
854 if ( ! use_signals ) {
855 // Calculate model iterations needed for next frame
856 elapsed += remainder;
858 global_multi_loop = (int)(((double)elapsed * 0.000001) *
859 current_options.get_model_hz());
860 remainder = elapsed - ( (global_multi_loop*1000000) /
861 current_options.get_model_hz() );
862 FG_LOG( FG_ALL, FG_DEBUG,
863 "Model iterations needed = " << global_multi_loop
864 << ", new remainder = " << remainder );
867 if ( global_multi_loop > 0 ) {
868 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
870 FG_LOG( FG_ALL, FG_DEBUG,
871 "Elapsed time is zero ... we're zinging" );
875 #if ! defined( MACOS )
876 // Do any I/O channel work that might need to be done
880 // see if we need to load any new scenery tiles
881 global_tile_mgr.update( cur_fdm_state->get_Longitude(),
882 cur_fdm_state->get_Latitude() );
884 // Process/manage pending events
885 global_events.Process();
887 // Run audio scheduler
888 #ifdef ENABLE_AUDIO_SUPPORT
889 if ( current_options.get_sound() && !audio_sched->not_working() ) {
891 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
893 // note: all these factors are relative to the sample. our
894 // sample format should really contain a conversion factor so
895 // that we can get prop speed right for arbitrary samples.
896 // Note that for normal-size props, there is a point at which
897 // the prop tips approach the speed of sound; that is a pretty
898 // strong limit to how fast the prop can go.
900 // multiplication factor is prime pitch control; add some log
901 // component for verisimilitude
903 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
904 //fprintf(stderr, "pitch1: %f ", pitch);
905 // if (controls.get_throttle(0) > 0.0 ||
906 // cur_fdm_state->v_rel_wind > 40.0) {
908 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
909 // only add relative wind and AoA if prop is moving
910 // or we're really flying at idle throttle
911 if (pitch < 5.4) { // this needs tuning
912 // prop tips not breaking sound barrier
913 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
915 // prop tips breaking sound barrier
916 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
918 //fprintf(stderr, "pitch2: %f ", pitch);
919 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
921 // Angle of Attack next... -x^3(e^x) is my best guess Just
922 // need to calculate some reasonable scaling factor and
923 // then clamp it on the positive aoa (neg adj) side
924 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
926 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
927 if (aoa_adj < -0.8) aoa_adj = -0.8;
929 //fprintf(stderr, "pitch3: %f ", pitch);
931 // don't run at absurdly slow rates -- not realistic
932 // and sounds bad to boot. :-)
933 if (pitch < 0.8) pitch = 0.8;
935 // fprintf(stderr, "pitch4: %f\n", pitch);
937 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
938 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
939 // fprintf(stderr, "volume: %f\n", volume);
941 pitch_envelope.setStep ( 0, 0.01, pitch );
942 volume_envelope.setStep ( 0, 0.01, volume );
946 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
947 pitch_envelope.setStep ( 0, 0.01, param );
948 volume_envelope.setStep ( 0, 0.01, param );
950 # endif // experimental throttle patch
952 audio_sched -> update();
959 FG_LOG( FG_ALL, FG_DEBUG, "" );
963 // This is the top level master main function that is registered as
967 // The first few passes take care of initialization things (a couple
968 // per pass) and once everything has been initialized fgMainLoop from
971 static void fgIdleFunction ( void ) {
972 // printf("idle state == %d\n", idle_state);
974 if ( idle_state == 0 ) {
975 // Initialize the splash screen right away
976 if ( current_options.get_splash_screen() ) {
981 } else if ( idle_state == 1 ) {
982 // Start the intro music
984 if ( current_options.get_intro_music() ) {
985 string lockfile = "/tmp/mpg123.running";
986 FGPath mp3file( current_options.get_fg_root() );
987 mp3file.append( "Sounds/intro.mp3" );
989 string command = "(touch " + lockfile + "; mpg123 "
990 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
992 FG_LOG( FG_GENERAL, FG_INFO,
993 "Starting intro music: " << mp3file.str() );
994 system ( command.c_str() );
999 } else if ( idle_state == 2 ) {
1000 // These are a few miscellaneous things that aren't really
1001 // "subsystems" but still need to be initialized.
1004 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1005 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1010 } else if ( idle_state == 3 ) {
1011 // This is the top level init routine which calls all the
1012 // other subsystem initialization routines. If you are adding
1013 // a subsystem to flight gear, its initialization call should
1014 // located in this routine.
1015 if( !fgInitSubsystems()) {
1016 FG_LOG( FG_GENERAL, FG_ALERT,
1017 "Subsystem initializations failed ..." );
1022 } else if ( idle_state == 4 ) {
1023 // setup OpenGL view parameters
1026 if ( use_signals ) {
1027 // init timer routines, signals, etc. Arrange for an alarm
1028 // signal to be generated, etc.
1029 fgInitTimeDepCalcs();
1033 } else if ( idle_state == 5 ) {
1036 } else if ( idle_state == 6 ) {
1037 // Initialize audio support
1038 #ifdef ENABLE_AUDIO_SUPPORT
1041 if ( current_options.get_intro_music() ) {
1042 // Let's wait for mpg123 to finish
1043 string lockfile = "/tmp/mpg123.running";
1044 struct stat stat_buf;
1046 FG_LOG( FG_GENERAL, FG_INFO,
1047 "Waiting for mpg123 player to finish ..." );
1048 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1049 // file exist, wait ...
1051 FG_LOG( FG_GENERAL, FG_INFO, ".");
1053 FG_LOG( FG_GENERAL, FG_INFO, "");
1057 if ( current_options.get_sound() ) {
1058 audio_sched = new slScheduler ( 8000 );
1059 audio_mixer = new smMixer;
1060 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1061 audio_sched -> setSafetyMargin ( 1.0 ) ;
1063 FGPath slfile( current_options.get_fg_root() );
1064 slfile.append( "Sounds/wasp.wav" );
1066 s1 = new slSample ( (char *)slfile.c_str() );
1067 FG_LOG( FG_GENERAL, FG_INFO,
1068 "Rate = " << s1 -> getRate()
1069 << " Bps = " << s1 -> getBps()
1070 << " Stereo = " << s1 -> getStereo() );
1071 audio_sched -> loopSample ( s1 );
1073 if ( audio_sched->not_working() ) {
1076 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1077 volume_envelope.setStep ( 0, 0.01, 0.6 );
1079 audio_sched -> addSampleEnvelope( s1, 0, 0,
1081 SL_PITCH_ENVELOPE );
1082 audio_sched -> addSampleEnvelope( s1, 0, 1,
1084 SL_VOLUME_ENVELOPE );
1087 // strcpy(slfile, path);
1088 // strcat(slfile, "thunder.wav");
1089 // s2 -> loadFile ( slfile );
1090 // s2 -> adjustVolume(0.5);
1091 // audio_sched -> playSample ( s2 );
1099 if ( idle_state == 1000 ) {
1100 // We've finished all our initialization steps, from now on we
1101 // run the main loop.
1105 if ( current_options.get_splash_screen() == 1 ) {
1106 fgSplashUpdate(0.0);
1111 // options.cxx needs to see this for toggle_panel()
1112 // Handle new window size or exposure
1113 void fgReshape( int width, int height ) {
1114 if ( ! current_options.get_panel_status() ) {
1115 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1116 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1118 current_view.set_win_ratio( (GLfloat) width /
1119 ((GLfloat) (height)*0.4232) );
1120 glViewport(0, (GLint)((height)*0.5768),
1121 (GLint)(width), (GLint)((height)*0.4232) );
1124 current_view.set_winWidth( width );
1125 current_view.set_winHeight( height );
1126 current_view.force_update_fov_math();
1128 // set these fov to be the same as in fgRenderFrame()
1129 // float x_fov = current_options.get_fov();
1130 // float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1131 // ssgSetFOV( x_fov, y_fov );
1133 // glViewport ( 0, 0, width, height );
1134 float fov = current_options.get_fov();
1135 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1139 if ( idle_state == 1000 ) {
1140 // yes we've finished all our initializations and are running
1141 // the main loop, so this will now work without seg faulting
1143 current_view.UpdateViewParams(cur_view_fdm);
1148 // Initialize GLUT and define a main window
1149 int fgGlutInit( int *argc, char **argv ) {
1151 #if !defined( MACOS )
1152 // GLUT will extract all glut specific options so later on we only
1153 // need wory about our own.
1154 glutInit(argc, argv);
1157 // Define Display Parameters
1158 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1160 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1161 current_options.get_xsize() << "x" << current_options.get_ysize() );
1163 // Define initial window size
1164 glutInitWindowSize( current_options.get_xsize(),
1165 current_options.get_ysize() );
1167 // Initialize windows
1168 if ( current_options.get_game_mode() == 0 ) {
1169 // Open the regular window
1170 glutCreateWindow("Flight Gear");
1171 #ifndef GLUT_WRONG_VERSION
1173 // Open the cool new 'game mode' window
1174 char game_mode_str[256];
1175 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1176 current_options.get_xsize(),
1177 current_options.get_ysize(),
1178 current_options.get_bpp());
1180 FG_LOG( FG_GENERAL, FG_INFO,
1181 "game mode params = " << game_mode_str );
1182 glutGameModeString( game_mode_str );
1183 glutEnterGameMode();
1187 // This seems to be the absolute earliest in the init sequence
1188 // that these calls will return valid info. Too bad it's after
1189 // we've already created and sized out window. :-(
1190 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1191 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1192 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1194 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1197 // try to determine if we should adjust the initial default
1198 // display resolution. The options class defaults (is
1199 // initialized) to 640x480.
1200 string renderer = general.glRenderer;
1202 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1203 if ( renderer.find( "Glide" ) != string::npos ) {
1204 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1205 if ( renderer.find( "FB/8" ) != string::npos ) {
1206 // probably a voodoo-2
1207 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1208 // probably two SLI'd Voodoo-2's
1209 current_options.set_xsize( 1024 );
1210 current_options.set_ysize( 768 );
1211 FG_LOG( FG_GENERAL, FG_INFO,
1212 "It looks like you have two sli'd voodoo-2's." << endl
1213 << "upgrading your win resolution to 1024 x 768" );
1214 glutReshapeWindow(1024, 768);
1216 // probably a single non-SLI'd Voodoo-2
1217 current_options.set_xsize( 800 );
1218 current_options.set_ysize( 600 );
1219 FG_LOG( FG_GENERAL, FG_INFO,
1220 "It looks like you have a voodoo-2." << endl
1221 << "upgrading your win resolution to 800 x 600" );
1222 glutReshapeWindow(800, 600);
1224 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1225 // probably a voodoo-1, stick with the default
1228 // we have no special knowledge of this card, stick with the default
1236 // Initialize GLUT event handlers
1237 int fgGlutInitEvents( void ) {
1238 // call fgReshape() on window resizes
1239 glutReshapeFunc( fgReshape );
1241 // call GLUTkey() on keyboard event
1242 glutKeyboardFunc( GLUTkey );
1243 glutSpecialFunc( GLUTspecialkey );
1245 // call guiMouseFunc() whenever our little rodent is used
1246 glutMouseFunc ( guiMouseFunc );
1247 glutMotionFunc (guiMotionFunc );
1248 glutPassiveMotionFunc (guiMotionFunc );
1250 // call fgMainLoop() whenever there is
1251 // nothing else to do
1252 glutIdleFunc( fgIdleFunction );
1255 glutDisplayFunc( fgRenderFrame );
1262 int main( int argc, char **argv ) {
1264 #if defined( MACOS )
1265 freopen ("stdout.txt", "w", stdout );
1266 freopen ("stderr.txt", "w", stderr );
1267 argc = ccommand( &argv );
1271 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1274 // set default log levels
1275 fglog().setLogLevels( FG_ALL, FG_INFO );
1277 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1279 // seed the random number generater
1282 aircraft_dir = ""; // Initialize the Aircraft directory to "" (UIUC)
1284 // needs to happen before we parse command line options
1285 globals = new FGGlobals;
1287 // Load the configuration parameters
1288 if ( !fgInitConfig(argc, argv) ) {
1289 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1293 // Initialize the Window/Graphics environment.
1294 if( !fgGlutInit(&argc, argv) ) {
1295 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1299 // Initialize the various GLUT Event Handlers.
1300 if( !fgGlutInitEvents() ) {
1301 FG_LOG( FG_GENERAL, FG_ALERT,
1302 "GLUT event handler initialization failed ..." );
1306 // Initialize ssg (from plib). Needs to come before we do any
1307 // other ssg stuff, but after opengl/glut has been initialized.
1310 // Initialize the user interface (we need to do this before
1311 // passing off control to glut and before fgInitGeneral to get our
1316 FGPath zone( current_options.get_fg_root() );
1317 zone.append( "Timezone" );
1318 SGTime *t = new SGTime( 0.0, 0.0, zone.str() );
1320 // Handle potential user specified time offsets
1321 time_t cur_time = t->get_cur_time();
1322 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1323 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1324 time_t aircraftLocalTime =
1325 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1327 // Okay, we now have six possible scenarios
1328 switch ( current_options.get_time_offset_type() ) {
1329 case fgOPTIONS::FG_TIME_SYS_OFFSET:
1330 globals->set_warp( current_options.get_time_offset() );
1332 case fgOPTIONS::FG_TIME_GMT_OFFSET:
1333 globals->set_warp( current_options.get_time_offset() -
1334 (currGMT - systemLocalTime) );
1336 case fgOPTIONS::FG_TIME_LAT_OFFSET:
1337 globals->set_warp( current_options.get_time_offset() -
1338 (aircraftLocalTime - systemLocalTime) );
1340 case fgOPTIONS::FG_TIME_SYS_ABSOLUTE:
1341 globals->set_warp( current_options.get_time_offset() - cur_time );
1342 //printf("warp = %d\n", warp);
1344 case fgOPTIONS::FG_TIME_GMT_ABSOLUTE:
1345 globals->set_warp( current_options.get_time_offset() - currGMT );
1347 case fgOPTIONS::FG_TIME_LAT_ABSOLUTE:
1348 globals->set_warp( current_options.get_time_offset() -
1349 (aircraftLocalTime - systemLocalTime) -
1353 FG_LOG( FG_GENERAL, FG_ALERT, "Unsupported type" );
1357 FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = "
1358 << globals->get_warp() );
1360 globals->set_warp_delta( 0 );
1362 t->update( 0.0, 0.0, globals->get_warp() );
1364 globals->set_time_params( t );
1366 // Do some quick general initializations
1367 if( !fgInitGeneral()) {
1368 FG_LOG( FG_GENERAL, FG_ALERT,
1369 "General initializations failed ..." );
1374 // some ssg test stuff (requires data from the plib source
1375 // distribution) specifically from the ssg tux example
1378 FGPath modelpath( current_options.get_fg_root() );
1379 modelpath.append( "Models" );
1380 modelpath.append( "Geometry" );
1382 FGPath texturepath( current_options.get_fg_root() );
1383 texturepath.append( "Models" );
1384 texturepath.append( "Textures" );
1386 ssgModelPath( (char *)modelpath.c_str() );
1387 ssgTexturePath( (char *)texturepath.c_str() );
1390 scene = new ssgRoot;
1391 scene->setName( "Scene" );
1393 // Initialize the sky
1394 FGPath ephem_data_path( current_options.get_fg_root() );
1395 ephem_data_path.append( "Astro" );
1396 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1397 ephem->update( globals->get_time_params()->getMjd(),
1398 globals->get_time_params()->getLst(),
1400 globals->set_ephem( ephem );
1402 FGPath sky_tex_path( current_options.get_fg_root() );
1403 sky_tex_path.append( "Textures" );
1404 sky_tex_path.append( "Sky" );
1406 thesky->texture_path( sky_tex_path.str() );
1408 thesky->build( 550.0, 550.0,
1409 globals->get_ephem()->getNumPlanets(),
1410 globals->get_ephem()->getPlanets(), 60000.0,
1411 globals->get_ephem()->getNumStars(),
1412 globals->get_ephem()->getStars(), 60000.0 );
1414 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1415 SG_CLOUD_MOSTLY_SUNNY );
1416 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1419 // thesky->add_cloud_layer( 1000.0, 200.0, 50.0, SG_CLOUD_MOSTLY_SUNNY );
1420 // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1421 // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1424 terrain = new ssgBranch;
1425 terrain->setName( "Terrain" );
1426 scene->addKid( terrain );
1428 // temporary visible aircraft "own ship"
1429 penguin_sel = new ssgSelector;
1430 penguin_pos = new ssgTransform;
1431 // ssgBranch *tux_obj = ssgMakeSphere( 10.0, 10, 10 );
1432 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1433 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1435 penguin_pos->addKid( tux_obj );
1436 penguin_sel->addKid( penguin_pos );
1437 ssgFlatten( tux_obj );
1438 ssgStripify( penguin_sel );
1439 penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1440 scene->addKid( penguin_sel );
1442 #ifdef FG_NETWORK_OLK
1443 // Do the network intialization
1444 if ( current_options.get_network_olk() ) {
1445 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1449 // build our custom render states
1450 fgBuildRenderStates();
1452 // pass control off to the master GLUT event handler
1455 // we never actually get here ... but to avoid compiler warnings,