1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson for OpenGL, started May 1997.
5 // Copyright (C) 1997 - 1999 Curtis L. Olson - curt@flightgear.org
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 #define MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
31 #ifdef FG_MATH_EXCEPTION_CLASH
41 #include <simgear/xgl/xgl.h>
51 #ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h> /* for stat() */
56 # include <unistd.h> /* for stat() */
59 #include <plib/pu.h> // plib include
60 #include <plib/ssg.h> // plib include
62 #ifdef ENABLE_AUDIO_SUPPORT
63 # include <plib/sl.h> // plib include
64 # include <plib/sm.h> // plib include
67 #include <simgear/constants.h> // for VERSION
68 #include <simgear/debug/logstream.hxx>
69 #include <simgear/math/fg_geodesy.hxx>
70 #include <simgear/math/polar3d.hxx>
71 #include <simgear/math/fg_random.h>
72 #include <simgear/misc/fgpath.hxx>
74 #include <Include/general.hxx>
76 #include <Aircraft/aircraft.hxx>
77 #include <Ephemeris/ephemeris.hxx>
79 #include <Autopilot/autopilot.hxx>
80 #include <Cockpit/cockpit.hxx>
81 #include <Cockpit/steam.hxx>
83 #include <Joystick/joystick.hxx>
85 #include <NetworkOLK/network.h>
87 #include <Objects/materialmgr.hxx>
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/tilemgr.hxx>
90 #include <Sky/sky.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 #ifdef FG_NETWORK_OLK
149 ssgSelector *fgd_sel = NULL;
150 ssgTransform *fgd_pos = NULL;
154 // current fdm/position used for view
155 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 ssgSimpleState *default_state;
192 ssgSimpleState *hud_and_panel;
193 ssgSimpleState *menus;
195 void fgBuildRenderStates( void ) {
196 default_state = new ssgSimpleState;
197 default_state->disable( GL_TEXTURE_2D );
198 default_state->enable( GL_CULL_FACE );
199 default_state->disable( GL_COLOR_MATERIAL );
200 default_state->disable( GL_BLEND );
201 default_state->disable( GL_ALPHA_TEST );
202 default_state->disable( GL_LIGHTING );
203 default_state->setMaterial( GL_AMBIENT_AND_DIFFUSE, 1.0, 1.0, 1.0, 1.0 );
205 hud_and_panel = new ssgSimpleState;
206 hud_and_panel->disable( GL_CULL_FACE );
207 hud_and_panel->disable( GL_TEXTURE_2D );
208 hud_and_panel->disable( GL_LIGHTING );
210 menus = new ssgSimpleState;
211 menus->disable( GL_CULL_FACE );
212 menus->disable( GL_TEXTURE_2D );
213 menus->enable( GL_BLEND );
217 // fgInitVisuals() -- Initialize various GL/view parameters
218 void fgInitVisuals( void ) {
221 l = &cur_light_params;
223 #ifndef GLUT_WRONG_VERSION
224 // Go full screen if requested ...
225 if ( current_options.get_fullscreen() ) {
230 // If enabled, normal vectors specified with glNormal are scaled
231 // to unit length after transformation. See glNormal.
232 // glEnable( GL_NORMALIZE );
234 glEnable( GL_LIGHTING );
235 glEnable( GL_LIGHT0 );
236 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
239 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
240 ssgGetLight( 0 ) -> setPosition( sunpos );
242 // glFogi (GL_FOG_MODE, GL_LINEAR);
243 glFogi (GL_FOG_MODE, GL_EXP2);
244 if ( (current_options.get_fog() == 1) ||
245 (current_options.get_shading() == 0) ) {
246 // if fastest fog requested, or if flat shading force fastest
247 glHint ( GL_FOG_HINT, GL_FASTEST );
248 } else if ( current_options.get_fog() == 2 ) {
249 glHint ( GL_FOG_HINT, GL_NICEST );
251 if ( current_options.get_wireframe() ) {
253 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
256 // This is the default anyways, but it can't hurt
257 glFrontFace ( GL_CCW );
260 // glEnable(GL_POINT_SMOOTH);
261 // glEnable(GL_LINE_SMOOTH);
262 // glEnable(GL_POLYGON_SMOOTH);
266 // Update all Visuals (redraws anything graphics related)
267 void fgRenderFrame( void ) {
268 fgLIGHT *l = &cur_light_params;
269 FGTime *t = FGTime::cur_time_params;
270 // FGView *v = ¤t_view;
271 static double last_visibility = -9999;
272 static bool in_puff = false;
273 static double puff_length = 0;
274 static double puff_progression = 0;
275 const double ramp_up = 0.15;
276 const double ramp_down = 0.15;
279 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
280 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
281 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
282 // GLfloat mat_shininess[] = { 10.0 };
283 GLbitfield clear_mask;
285 if ( idle_state != 1000 ) {
286 // still initializing, draw the splash screen
287 if ( current_options.get_splash_screen() == 1 ) {
291 // idle_state is now 1000 meaning we've finished all our
292 // initializations and are running the main loop, so this will
293 // now work without seg faulting the system.
295 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
296 // FG_Altitude * FEET_TO_METER);
298 // this is just a temporary hack, to make me understand Pui
299 // timerText -> setLabel (ctime (&t->cur_time));
302 // update view volume parameters
303 // cout << "before pilot_view update" << endl;
304 pilot_view.UpdateViewParams(*cur_fdm_state);
305 // cout << "after pilot_view update" << endl;
306 current_view.UpdateViewParams(cur_view_fdm);
308 // set the sun position
309 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
311 clear_mask = GL_DEPTH_BUFFER_BIT;
312 if ( current_options.get_wireframe() ) {
313 clear_mask |= GL_COLOR_BUFFER_BIT;
315 if ( current_options.get_panel_status() ) {
316 // we can't clear the screen when the panel is active
317 } else if ( current_options.get_skyblend() ) {
318 if ( current_options.get_textures() ) {
319 // glClearColor(black[0], black[1], black[2], black[3]);
320 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
321 l->adj_fog_color[2], l->adj_fog_color[3]);
322 clear_mask |= GL_COLOR_BUFFER_BIT;
325 glClearColor(l->sky_color[0], l->sky_color[1],
326 l->sky_color[2], l->sky_color[3]);
327 clear_mask |= GL_COLOR_BUFFER_BIT;
329 glClear( clear_mask );
331 // Tell GL we are switching to model view parameters
333 // I really should create a derived ssg node or use a call
334 // back or something so that I can draw the sky within the
335 // ssgCullandDraw() function, but for now I just mimic what
336 // ssg does to set up the model view matrix
337 glMatrixMode(GL_MODELVIEW);
339 ssgSetCamera( current_view.VIEW );
342 sgMat4 vm_tmp, view_mat;
343 sgTransposeNegateMat4 ( vm_tmp, current_view.VIEW ) ;
344 sgCopyMat4( view_mat, copy_of_ssgOpenGLAxisSwapMatrix ) ;
345 sgPreMultMat4( view_mat, vm_tmp ) ;
346 glLoadMatrixf( (float *)view_mat );
349 // set the opengl state to known default values
350 default_state->force();
353 if ( current_options.get_skyblend() ) {
356 current_view.get_view_pos().x(),
357 current_view.get_view_pos().y(),
358 current_view.get_view_pos().z() );
361 sgSetVec3( zero_elev,
362 current_view.get_cur_zero_elev().x(),
363 current_view.get_cur_zero_elev().y(),
364 current_view.get_cur_zero_elev().z() );
366 /* cout << "thesky->repaint() sky_color = "
367 << cur_light_params.sky_color[0] << " "
368 << cur_light_params.sky_color[1] << " "
369 << cur_light_params.sky_color[2] << " "
370 << cur_light_params.sky_color[3] << endl;
372 << cur_light_params.fog_color[0] << " "
373 << cur_light_params.fog_color[1] << " "
374 << cur_light_params.fog_color[2] << " "
375 << cur_light_params.fog_color[3] << endl;
376 cout << " sun_angle = " << cur_light_params.sun_angle
377 << " moon_angle = " << cur_light_params.moon_angle
379 thesky->repaint( cur_light_params.sky_color,
380 cur_light_params.adj_fog_color,
381 cur_light_params.sun_angle,
382 cur_light_params.moon_angle,
383 ephem->getNumPlanets(), ephem->getPlanets(),
384 ephem->getNumStars(), ephem->getStars() );
386 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
387 << view_pos[1] << " " << view_pos[2] << endl;
388 cout << " zero_elev = " << zero_elev[0] << " "
389 << zero_elev[1] << " " << zero_elev[2]
390 << " lon = " << cur_fdm_state->get_Longitude()
391 << " lat = " << cur_fdm_state->get_Latitude() << endl;
392 cout << " sun_rot = " << cur_light_params.sun_rotation
393 << " gst = " << FGTime::cur_time_params->getGst() << endl;
394 cout << " sun ra = " << ephem->getSunRightAscension()
395 << " sun dec = " << ephem->getSunDeclination()
396 << " moon ra = " << ephem->getMoonRightAscension()
397 << " moon dec = " << ephem->getMoonDeclination() << endl; */
399 thesky->reposition( view_pos, zero_elev,
400 cur_fdm_state->get_Longitude(),
401 cur_fdm_state->get_Latitude(),
402 cur_light_params.sun_rotation,
403 FGTime::cur_time_params->getGst(),
404 ephem->getSunRightAscension(),
405 ephem->getSunDeclination(), 50000.0,
406 ephem->getMoonRightAscension(),
407 ephem->getMoonDeclination(), 50000.0 );
410 glEnable( GL_DEPTH_TEST );
411 if ( current_options.get_fog() > 0 ) {
413 glFogi( GL_FOG_MODE, GL_EXP2 );
414 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
417 // update fog params if visibility has changed
418 #ifndef FG_OLD_WEATHER
419 double cur_visibility = WeatherDatabase->getWeatherVisibility();
421 double cur_visibility = current_weather.get_visibility();
423 double actual_visibility = cur_visibility;
425 if ( current_options.get_clouds() ) {
426 double diff = fabs( cur_fdm_state->get_Altitude() * FEET_TO_METER -
427 current_options.get_clouds_asl() );
428 // cout << "altitude diff = " << diff << endl;
431 // calc chance of entering cloud puff
432 double rnd = fg_random();
433 double chance = rnd * rnd * rnd;
434 if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) {
437 puff_length = fg_random() * 2.0; // up to 2 seconds
438 } while ( puff_length <= 0.0 );
439 puff_progression = 0.0;
443 actual_visibility = cur_visibility * (diff - 25) / 50.0;
446 // modify actual_visibility based on puff envelope
448 if ( puff_progression <= ramp_up ) {
449 double x = FG_PI_2 * puff_progression / ramp_up;
450 double factor = 1.0 - sin( x );
451 actual_visibility = actual_visibility * factor;
452 } else if ( puff_progression >= ramp_up + puff_length ) {
454 (puff_progression - (ramp_up + puff_length)) /
456 double factor = sin( x );
457 actual_visibility = actual_visibility * factor;
459 actual_visibility = 0.0;
462 /* cout << "len = " << puff_length
464 << " factor = " << factor
465 << " actual_visibility = " << actual_visibility
468 puff_progression += ( global_multi_loop *
469 current_options.get_speed_up() ) /
470 (double)current_options.get_model_hz();
472 /* cout << "gml = " << global_multi_loop
473 << " speed up = " << current_options.get_speed_up()
474 << " hz = " << current_options.get_model_hz() << endl;
477 if ( puff_progression > puff_length + ramp_up + ramp_down) {
482 // never let visibility drop below zero
483 if ( actual_visibility < 0 ) {
484 actual_visibility = 0;
489 // cout << "actual visibility = " << actual_visibility << endl;
491 if ( actual_visibility != last_visibility ) {
492 last_visibility = actual_visibility;
494 // cout << "----> updating fog params" << endl;
496 GLfloat fog_exp_density;
497 GLfloat fog_exp2_density;
500 fog_exp_density = -log(0.01 / actual_visibility);
503 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
505 // Set correct opengl fog density
506 glFogf (GL_FOG_DENSITY, fog_exp2_density);
509 // set lighting parameters
510 glLightfv( GL_LIGHT0, GL_AMBIENT, l->scene_ambient );
511 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
512 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
514 // texture parameters
515 // glEnable( GL_TEXTURE_2D );
516 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
517 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
518 // set base color (I don't think this is doing anything here)
519 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
520 // (GL_FRONT, GL_DIFFUSE, white);
521 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
522 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
525 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
526 ssgGetLight( 0 ) -> setPosition( sunpos );
528 // glMatrixMode( GL_PROJECTION );
530 float fov = current_options.get_fov();
531 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
533 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
536 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
537 // << current_weather.get_visibility() );
540 ssgSetNearFar( 10.0f, 120000.0f );
542 ssgSetNearFar( 0.5f, 120000.0f );
545 if ( current_options.get_view_mode() ==
546 fgOPTIONS::FG_VIEW_PILOT )
549 penguin_sel->select(0);
550 } else if ( current_options.get_view_mode() ==
551 fgOPTIONS::FG_VIEW_FOLLOW )
553 // select view matrix from front of view matrix queue
554 // FGMat4Wrapper tmp = current_view.follow.front();
555 // sgCopyMat4( sgVIEW, tmp.m );
557 // enable TuX and set up his position and orientation
558 penguin_sel->select(1);
561 sgMakeTransMat4( sgTRANS,
562 pilot_view.view_pos.x(),
563 pilot_view.view_pos.y(),
564 pilot_view.view_pos.z() );
567 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
570 sgMakeRotMat4( sgROT, -90.0, ownship_up );
574 sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
575 sgMultMat4( sgTUX, sgTMP, sgTRANS );
578 sgSetCoord( &tuxpos, sgTUX );
579 penguin_pos->setTransform( &tuxpos );
582 # ifdef FG_NETWORK_OLK
583 if ( current_options.get_network_olk() ) {
585 other = head->next; /* put listpointer to start */
586 while ( other != tail) { /* display all except myself */
587 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
588 other->fgd_sel->select(1);
589 sgSetCoord( &fgdpos, other->sgFGD_COORD );
590 other->fgd_pos->setTransform( &fgdpos );
595 // fgd_sel->select(1);
596 // sgCopyMat4( sgTUX, current_view.sgVIEW);
598 // sgSetCoord( &fgdpos, sgFGD_VIEW );
599 // fgd_pos->setTransform( &fgdpos);
603 // ssgSetCamera( current_view.VIEW );
605 // position tile nodes and update range selectors
606 global_tile_mgr.prep_ssg_nodes();
608 // force the default state so ssg can get back on track if
609 // we've changed things elsewhere
610 FGMaterialSlot m_slot;
611 FGMaterialSlot *m_ptr = &m_slot;
612 if ( material_mgr.find( "Default", m_ptr ) ) {
613 m_ptr->get_state()->force();
616 // draw the ssg scene
617 ssgCullAndDraw( scene );
620 // display HUD && Panel
622 glDisable( GL_DEPTH_TEST );
623 // glDisable( GL_CULL_FACE );
624 // glDisable( GL_TEXTURE_2D );
625 hud_and_panel->apply();
628 // We can do translucent menus, so why not. :-)
629 // glEnable ( GL_BLEND ) ;
631 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
633 // glDisable ( GL_BLEND ) ;
635 // glEnable( GL_FOG );
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() );
666 FGSteam::update( multi_loop * current_options.get_speed_up() );
668 // fgFDMUpdate( current_options.get_flight_model(),
669 // fdm_state, 0, remainder );
670 cur_fdm_state->update( 0 );
671 FGSteam::update( 0 );
674 fdm_list.push_back( *cur_fdm_state );
675 while ( fdm_list.size() > 15 ) {
676 fdm_list.pop_front();
679 if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_PILOT ) {
680 cur_view_fdm = *cur_fdm_state;
682 } else if ( current_options.get_view_mode() == fgOPTIONS::FG_VIEW_FOLLOW ) {
683 cur_view_fdm = fdm_list.front();
686 // update the view angle
687 for ( i = 0; i < multi_loop; i++ ) {
688 if ( fabs(current_view.get_goal_view_offset() -
689 current_view.get_view_offset()) < 0.05 )
691 current_view.set_view_offset( current_view.get_goal_view_offset() );
694 // move current_view.view_offset towards current_view.goal_view_offset
695 if ( current_view.get_goal_view_offset() >
696 current_view.get_view_offset() )
698 if ( current_view.get_goal_view_offset() -
699 current_view.get_view_offset() < FG_PI )
701 current_view.inc_view_offset( 0.01 );
703 current_view.inc_view_offset( -0.01 );
706 if ( current_view.get_view_offset() -
707 current_view.get_goal_view_offset() < FG_PI )
709 current_view.inc_view_offset( -0.01 );
711 current_view.inc_view_offset( 0.01 );
714 if ( current_view.get_view_offset() > FG_2PI ) {
715 current_view.inc_view_offset( -FG_2PI );
716 } else if ( current_view.get_view_offset() < 0 ) {
717 current_view.inc_view_offset( FG_2PI );
722 double tmp = -(l->sun_rotation + FG_PI)
723 - (cur_fdm_state->get_Psi() - current_view.get_view_offset() );
724 while ( tmp < 0.0 ) {
727 while ( tmp > FG_2PI ) {
730 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
731 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
732 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
735 // Update solar system
736 ephem->update( t, cur_fdm_state->get_Latitude() );
740 void fgInitTimeDepCalcs( void ) {
743 // #ifdef HAVE_SETITIMER
744 // fgTimerInit( 1.0 / current_options.get_model_hz(),
745 // fgUpdateTimeDepCalcs );
746 // #endif HAVE_SETITIMER
750 static const double alt_adjust_ft = 3.758099;
751 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
754 // What should we do when we have nothing else to do? Let's get ready
755 // for the next move and update the display?
756 static void fgMainLoop( void ) {
758 static long remainder = 0;
760 #ifdef FANCY_FRAME_COUNTER
764 static time_t last_time = 0;
765 static int frames = 0;
766 #endif // FANCY_FRAME_COUNTER
768 t = FGTime::cur_time_params;
770 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
771 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
773 #ifdef FG_NETWORK_OLK
774 if ( current_options.get_network_olk() ) {
775 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
776 // printf("FGD: Netupdate\n");
777 fgd_send_com( "A", FGFS_host); // Send Mat4 data
778 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
783 #if defined( ENABLE_PLIB_JOYSTICK )
784 // Read joystick and update control settings
785 if ( current_options.get_control_mode() == fgOPTIONS::FG_JOYSTICK ) {
788 #elif defined( ENABLE_GLUT_JOYSTICK )
789 // Glut joystick support works by feeding a joystick handler
790 // function to glut. This is taken care of once in the joystick
791 // init routine and we don't have to worry about it again.
794 #ifdef FG_OLD_WEATHER
795 current_weather.Update();
798 // Fix elevation. I'm just sticking this here for now, it should
799 // probably move eventually
801 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
803 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
804 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
806 if ( scenery.cur_elev > -9990 ) {
807 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
808 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
809 // now set aircraft altitude above ground
810 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
811 cur_fdm_state->get_Altitude() * FEET_TO_METER,
812 scenery.cur_elev + alt_adjust_m - 3.0,
813 scenery.cur_elev + alt_adjust_m );
814 fgFDMForceAltitude( current_options.get_flight_model(),
815 scenery.cur_elev + alt_adjust_m );
817 FG_LOG( FG_ALL, FG_DEBUG,
818 "<*> resetting altitude to "
819 << cur_fdm_state->get_Altitude() * FEET_TO_METER << " meters" );
821 fgFDMSetGroundElevation( current_options.get_flight_model(),
822 scenery.cur_elev ); // meters
825 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
827 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
828 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
831 t->update( cur_fdm_state->get_Longitude() );
833 // Get elapsed time (in usec) for this past frame
834 elapsed = fgGetTimeInterval();
835 FG_LOG( FG_ALL, FG_DEBUG,
836 "Elapsed time interval is = " << elapsed
837 << ", previous remainder is = " << remainder );
839 // Calculate frame rate average
840 #ifdef FANCY_FRAME_COUNTER
841 /* old fps calculation */
845 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
846 tmp = general.get_frame(i);
848 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
849 general.set_frame(i+1,tmp);
851 tmp = 1000000.0 / (float)elapsed;
852 general.set_frame(0,tmp);
853 // printf("frame[0] = %.2f\n", general.frames[0]);
855 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
856 // printf("ave = %.2f\n", general.frame_rate);
859 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
860 general.set_frame_rate( frames );
861 FG_LOG( FG_ALL, FG_DEBUG,
862 "--> Frame rate is = " << general.get_frame_rate() );
865 last_time = t->get_cur_time();
870 if ( ! use_signals ) {
871 // Calculate model iterations needed for next frame
872 elapsed += remainder;
874 global_multi_loop = (int)(((double)elapsed * 0.000001) *
875 current_options.get_model_hz());
876 remainder = elapsed - ( (global_multi_loop*1000000) /
877 current_options.get_model_hz() );
878 FG_LOG( FG_ALL, FG_DEBUG,
879 "Model iterations needed = " << global_multi_loop
880 << ", new remainder = " << remainder );
883 if ( global_multi_loop > 0 ) {
884 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
886 FG_LOG( FG_ALL, FG_DEBUG,
887 "Elapsed time is zero ... we're zinging" );
891 #if ! defined( MACOS )
892 // Do any I/O channel work that might need to be done
896 // see if we need to load any new scenery tiles
897 global_tile_mgr.update();
899 // Process/manage pending events
900 global_events.Process();
902 // Run audio scheduler
903 #ifdef ENABLE_AUDIO_SUPPORT
904 if ( current_options.get_sound() && !audio_sched->not_working() ) {
906 # ifdef MICHAEL_JOHNSON_EXPERIMENTAL_ENGINE_AUDIO
908 // note: all these factors are relative to the sample. our
909 // sample format should really contain a conversion factor so
910 // that we can get prop speed right for arbitrary samples.
911 // Note that for normal-size props, there is a point at which
912 // the prop tips approach the speed of sound; that is a pretty
913 // strong limit to how fast the prop can go.
915 // multiplication factor is prime pitch control; add some log
916 // component for verisimilitude
918 double pitch = log((controls.get_throttle(0) * 14.0) + 1.0);
919 //fprintf(stderr, "pitch1: %f ", pitch);
920 if (controls.get_throttle(0) > 0.0 || cur_fdm_state->v_rel_wind > 40.0) {
921 //fprintf(stderr, "rel_wind: %f ", cur_fdm_state->v_rel_wind);
922 // only add relative wind and AoA if prop is moving
923 // or we're really flying at idle throttle
924 if (pitch < 5.4) { // this needs tuning
925 // prop tips not breaking sound barrier
926 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/2;
928 // prop tips breaking sound barrier
929 pitch += log(cur_fdm_state->v_rel_wind + 0.8)/10;
931 //fprintf(stderr, "pitch2: %f ", pitch);
932 //fprintf(stderr, "AoA: %f ", FG_Gamma_vert_rad);
934 // Angle of Attack next... -x^3(e^x) is my best guess Just
935 // need to calculate some reasonable scaling factor and
936 // then clamp it on the positive aoa (neg adj) side
937 double aoa = cur_fdm_state->get_Gamma_vert_rad() * 2.2;
939 double aoa_adj = pow(-aoa, tmp) * pow(M_E, aoa);
940 if (aoa_adj < -0.8) aoa_adj = -0.8;
942 //fprintf(stderr, "pitch3: %f ", pitch);
944 // don't run at absurdly slow rates -- not realistic
945 // and sounds bad to boot. :-)
946 if (pitch < 0.8) pitch = 0.8;
948 //fprintf(stderr, "pitch4: %f\n", pitch);
950 double volume = controls.get_throttle(0) * 1.15 + 0.3 +
951 log(cur_fdm_state->v_rel_wind + 1.0)/14.0;
952 // fprintf(stderr, "volume: %f\n", volume);
954 pitch_envelope.setStep ( 0, 0.01, pitch );
955 volume_envelope.setStep ( 0, 0.01, volume );
959 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
960 pitch_envelope.setStep ( 0, 0.01, param );
961 volume_envelope.setStep ( 0, 0.01, param );
963 # endif // experimental throttle patch
965 audio_sched -> update();
972 FG_LOG( FG_ALL, FG_DEBUG, "" );
976 // This is the top level master main function that is registered as
980 // The first few passes take care of initialization things (a couple
981 // per pass) and once everything has been initialized fgMainLoop from
984 static void fgIdleFunction ( void ) {
985 // printf("idle state == %d\n", idle_state);
987 if ( idle_state == 0 ) {
988 // Initialize the splash screen right away
989 if ( current_options.get_splash_screen() ) {
994 } else if ( idle_state == 1 ) {
995 // Start the intro music
997 if ( current_options.get_intro_music() ) {
998 string lockfile = "/tmp/mpg123.running";
999 FGPath mp3file( current_options.get_fg_root() );
1000 mp3file.append( "Sounds/intro.mp3" );
1002 string command = "(touch " + lockfile + "; mpg123 "
1003 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1005 FG_LOG( FG_GENERAL, FG_INFO,
1006 "Starting intro music: " << mp3file.str() );
1007 system ( command.c_str() );
1012 } else if ( idle_state == 2 ) {
1013 // These are a few miscellaneous things that aren't really
1014 // "subsystems" but still need to be initialized.
1017 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1018 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1023 } else if ( idle_state == 3 ) {
1024 // This is the top level init routine which calls all the
1025 // other subsystem initialization routines. If you are adding
1026 // a subsystem to flight gear, its initialization call should
1027 // located in this routine.
1028 if( !fgInitSubsystems()) {
1029 FG_LOG( FG_GENERAL, FG_ALERT,
1030 "Subsystem initializations failed ..." );
1035 } else if ( idle_state == 4 ) {
1036 // setup OpenGL view parameters
1039 if ( use_signals ) {
1040 // init timer routines, signals, etc. Arrange for an alarm
1041 // signal to be generated, etc.
1042 fgInitTimeDepCalcs();
1046 } else if ( idle_state == 5 ) {
1049 } else if ( idle_state == 6 ) {
1050 // Initialize audio support
1051 #ifdef ENABLE_AUDIO_SUPPORT
1054 if ( current_options.get_intro_music() ) {
1055 // Let's wait for mpg123 to finish
1056 string lockfile = "/tmp/mpg123.running";
1057 struct stat stat_buf;
1059 FG_LOG( FG_GENERAL, FG_INFO,
1060 "Waiting for mpg123 player to finish ..." );
1061 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1062 // file exist, wait ...
1064 FG_LOG( FG_GENERAL, FG_INFO, ".");
1066 FG_LOG( FG_GENERAL, FG_INFO, "");
1070 if ( current_options.get_sound() ) {
1071 audio_sched = new slScheduler ( 8000 );
1072 audio_mixer = new smMixer;
1073 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1074 audio_sched -> setSafetyMargin ( 1.0 ) ;
1076 FGPath slfile( current_options.get_fg_root() );
1077 slfile.append( "Sounds/wasp.wav" );
1079 s1 = new slSample ( (char *)slfile.c_str() );
1080 FG_LOG( FG_GENERAL, FG_INFO,
1081 "Rate = " << s1 -> getRate()
1082 << " Bps = " << s1 -> getBps()
1083 << " Stereo = " << s1 -> getStereo() );
1084 audio_sched -> loopSample ( s1 );
1086 if ( audio_sched->not_working() ) {
1089 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1090 volume_envelope.setStep ( 0, 0.01, 0.6 );
1092 audio_sched -> addSampleEnvelope( s1, 0, 0,
1094 SL_PITCH_ENVELOPE );
1095 audio_sched -> addSampleEnvelope( s1, 0, 1,
1097 SL_VOLUME_ENVELOPE );
1100 // strcpy(slfile, path);
1101 // strcat(slfile, "thunder.wav");
1102 // s2 -> loadFile ( slfile );
1103 // s2 -> adjustVolume(0.5);
1104 // audio_sched -> playSample ( s2 );
1112 if ( idle_state == 1000 ) {
1113 // We've finished all our initialization steps, from now on we
1114 // run the main loop.
1118 if ( current_options.get_splash_screen() == 1 ) {
1119 fgSplashUpdate(0.0);
1124 // options.cxx needs to see this for toggle_panel()
1125 // Handle new window size or exposure
1126 void fgReshape( int width, int height ) {
1127 if ( ! current_options.get_panel_status() ) {
1128 current_view.set_win_ratio( (GLfloat) width / (GLfloat) height );
1129 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1131 current_view.set_win_ratio( (GLfloat) width /
1132 ((GLfloat) (height)*0.4232) );
1133 glViewport(0, (GLint)((height)*0.5768), (GLint)(width),
1134 (GLint)((height)*0.4232) );
1137 current_view.set_winWidth( width );
1138 current_view.set_winHeight( height );
1139 current_view.force_update_fov_math();
1141 // set these fov to be the same as in fgRenderFrame()
1142 float x_fov = current_options.get_fov();
1143 float y_fov = x_fov * 1.0 / current_view.get_win_ratio();
1144 ssgSetFOV( x_fov, y_fov );
1146 glViewport ( 0, 0, width, height );
1147 float fov = current_options.get_fov();
1148 ssgSetFOV(fov * current_view.get_win_ratio(), fov);
1150 if ( idle_state == 1000 ) {
1151 // yes we've finished all our initializations and are running
1152 // the main loop, so this will now work without seg faulting
1154 current_view.UpdateViewParams(cur_view_fdm);
1155 if ( current_options.get_panel_status() ) {
1156 FGPanel::OurPanel->ReInit(0, 0, 1024, 768);
1162 // Initialize GLUT and define a main window
1163 int fgGlutInit( int *argc, char **argv ) {
1165 #if !defined( MACOS )
1166 // GLUT will extract all glut specific options so later on we only
1167 // need wory about our own.
1168 glutInit(argc, argv);
1171 // Define Display Parameters
1172 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1174 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1175 current_options.get_xsize() << "x" << current_options.get_ysize() );
1177 // Define initial window size
1178 glutInitWindowSize( current_options.get_xsize(),
1179 current_options.get_ysize() );
1181 // Initialize windows
1182 if ( current_options.get_game_mode() == 0 ) {
1183 // Open the regular window
1184 glutCreateWindow("Flight Gear");
1185 #ifndef GLUT_WRONG_VERSION
1187 // Open the cool new 'game mode' window
1188 char game_mode_str[256];
1189 sprintf( game_mode_str, "width=%d height=%d bpp=32",
1190 current_options.get_xsize(),
1191 current_options.get_ysize() );
1193 FG_LOG( FG_GENERAL, FG_INFO,
1194 "game mode params = " << game_mode_str );
1195 glutGameModeString( game_mode_str );
1196 glutEnterGameMode();
1200 // This seems to be the absolute earliest in the init sequence
1201 // that these calls will return valid info. Too bad it's after
1202 // we've already created and sized out window. :-(
1203 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1204 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1205 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1207 FG_LOG ( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1210 // try to determine if we should adjust the initial default
1211 // display resolution. The options class defaults (is
1212 // initialized) to 640x480.
1213 string renderer = general.glRenderer;
1215 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1216 if ( renderer.find( "Glide" ) != string::npos ) {
1217 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1218 if ( renderer.find( "FB/8" ) != string::npos ) {
1219 // probably a voodoo-2
1220 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1221 // probably two SLI'd Voodoo-2's
1222 current_options.set_xsize( 1024 );
1223 current_options.set_ysize( 768 );
1224 FG_LOG( FG_GENERAL, FG_INFO,
1225 "It looks like you have two sli'd voodoo-2's." << endl
1226 << "upgrading your win resolution to 1024 x 768" );
1227 glutReshapeWindow(1024, 768);
1229 // probably a single non-SLI'd Voodoo-2
1230 current_options.set_xsize( 800 );
1231 current_options.set_ysize( 600 );
1232 FG_LOG( FG_GENERAL, FG_INFO,
1233 "It looks like you have a voodoo-2." << endl
1234 << "upgrading your win resolution to 800 x 600" );
1235 glutReshapeWindow(800, 600);
1237 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1238 // probably a voodoo-1, stick with the default
1241 // we have no special knowledge of this card, stick with the default
1249 // Initialize GLUT event handlers
1250 int fgGlutInitEvents( void ) {
1251 // call fgReshape() on window resizes
1252 glutReshapeFunc( fgReshape );
1254 // call GLUTkey() on keyboard event
1255 glutKeyboardFunc( GLUTkey );
1256 glutSpecialFunc( GLUTspecialkey );
1258 // call guiMouseFunc() whenever our little rodent is used
1259 glutMouseFunc ( guiMouseFunc );
1260 glutMotionFunc (guiMotionFunc );
1261 glutPassiveMotionFunc (guiMotionFunc );
1263 // call fgMainLoop() whenever there is
1264 // nothing else to do
1265 glutIdleFunc( fgIdleFunction );
1268 glutDisplayFunc( fgRenderFrame );
1275 int main( int argc, char **argv ) {
1277 #if defined( MACOS )
1278 argc = ccommand( &argv );
1282 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1285 // Initialize ssg (from plib). Needs to come before we do any
1286 // other ssg related stuff
1289 // set default log levels
1290 fglog().setLogLevels( FG_ALL, FG_INFO );
1292 FG_LOG( FG_GENERAL, FG_INFO, "Flight Gear: Version " << VERSION << endl );
1294 // seed the random number generater
1297 // Load the configuration parameters
1298 if ( !fgInitConfig(argc, argv) ) {
1299 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1303 // Initialize the Window/Graphics environment.
1304 if( !fgGlutInit(&argc, argv) ) {
1305 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1309 // Initialize the various GLUT Event Handlers.
1310 if( !fgGlutInitEvents() ) {
1311 FG_LOG( FG_GENERAL, FG_ALERT,
1312 "GLUT event handler initialization failed ..." );
1316 // Initialize the user interface (we need to do this before
1317 // passing off control to glut and before fgInitGeneral to get our
1322 FGTime::cur_time_params = new FGTime();
1323 // FGTime::cur_time_params->init( cur_fdm_state->get_Longitude(),
1324 // cur_fdm_state->get_Latitude() );
1325 // FGTime::cur_time_params->update( cur_fdm_state->get_Longitude() );
1326 FGTime::cur_time_params->init( 0.0, 0.0 );
1327 FGTime::cur_time_params->update( 0.0 );
1329 // Do some quick general initializations
1330 if( !fgInitGeneral()) {
1331 FG_LOG( FG_GENERAL, FG_ALERT,
1332 "General initializations failed ..." );
1337 // some ssg test stuff (requires data from the plib source
1338 // distribution) specifically from the ssg tux example
1341 FGPath modelpath( current_options.get_fg_root() );
1342 modelpath.append( "Models" );
1343 modelpath.append( "Geometry" );
1345 FGPath texturepath( current_options.get_fg_root() );
1346 texturepath.append( "Models" );
1347 texturepath.append( "Textures" );
1349 ssgModelPath( (char *)modelpath.c_str() );
1350 ssgTexturePath( (char *)texturepath.c_str() );
1353 scene = new ssgRoot;
1354 scene->setName( "Scene" );
1356 // Initialize the sky
1357 FGPath ephem_data_path( current_options.get_fg_root() );
1358 ephem_data_path.append( "Astro" );
1359 ephem = new FGEphemeris( ephem_data_path.c_str() );
1360 ephem->update( FGTime::cur_time_params, 0.0 );
1362 FGPath sky_tex_path( current_options.get_fg_root() );
1363 sky_tex_path.append( "Textures" );
1364 sky_tex_path.append( "Sky" );
1366 thesky->texture_path( sky_tex_path.str() );
1368 ssgBranch *sky = thesky->build( 550.0, 550.0,
1369 ephem->getNumPlanets(),
1370 ephem->getPlanets(), 60000.0,
1371 ephem->getNumStars(),
1372 ephem->getStars(), 60000.0 );
1373 scene->addKid( sky );
1376 terrain = new ssgBranch;
1377 terrain->setName( "Terrain" );
1378 scene->addKid( terrain );
1380 // temporary visible aircraft "own ship"
1381 penguin_sel = new ssgSelector;
1382 penguin_pos = new ssgTransform;
1383 // ssgBranch *tux_obj = ssgMakeSphere( 10.0, 10, 10 );
1384 ssgEntity *tux_obj = ssgLoadAC( "glider.ac" );
1385 // ssgEntity *tux_obj = ssgLoadAC( "Tower1x.ac" );
1387 penguin_pos->addKid( tux_obj );
1388 penguin_sel->addKid( penguin_pos );
1389 ssgFlatten( tux_obj );
1390 ssgStripify( penguin_sel );
1391 penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1392 scene->addKid( penguin_sel );
1394 #ifdef FG_NETWORK_OLK
1395 // Do the network intialization
1396 if ( current_options.get_network_olk() ) {
1397 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1401 // build our custom render states
1402 fgBuildRenderStates();
1404 // pass control off to the master GLUT event handler
1407 // we never actually get here ... but to avoid compiler warnings,