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.
28 #include <simgear/compiler.h>
29 #include <simgear/misc/exception.hxx>
31 #ifdef SG_MATH_EXCEPTION_CLASH
51 #ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h> // for stat()
56 # include <unistd.h> // for stat()
60 // # include <GL/glext.h>
66 #include <simgear/constants.h> // for VERSION
67 #include <simgear/debug/logstream.hxx>
68 #include <simgear/math/polar3d.hxx>
69 #include <simgear/math/sg_random.h>
70 #include <simgear/misc/sg_path.hxx>
71 #include <simgear/sky/sky.hxx>
72 #include <simgear/timing/sg_time.hxx>
73 #include <simgear/timing/lowleveltime.h>
75 #include <Include/general.hxx>
77 #include <Aircraft/aircraft.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 <GUI/sgVec3Slider.hxx>
87 // #include <Joystick/joystick.hxx>
89 #include <NetworkOLK/network.h>
91 #include <Objects/matlib.hxx>
92 #include <Scenery/scenery.hxx>
93 #include <Scenery/tilemgr.hxx>
94 #ifdef ENABLE_AUDIO_SUPPORT
95 # include <Sound/soundmgr.hxx>
96 # include <Sound/morse.hxx>
98 #include <Time/event.hxx>
99 #include <Time/fg_timer.hxx>
100 #include <Time/light.hxx>
101 #include <Time/sunpos.hxx>
102 #include <Time/tmp.hxx>
104 #include <Input/input.hxx>
106 // begin - added Venky
107 // $$$ begin - added VS Renganathan
108 #include <simgear/misc/sgstream.hxx>
109 #include <FDM/flight.hxx>
110 #include <FDM/ADA.hxx>
111 void fgLoadDCS (void);
112 void fgUpdateDCS (void);
113 ssgSelector *ship_sel=NULL;
114 // upto 32 instances of a same object can be loaded.
115 ssgTransform *ship_pos[32];
116 double obj_lat[32],obj_lon[32],obj_alt[32];
118 // $$$ end - added VS Renganathan
121 #ifndef FG_OLD_WEATHER
122 # include <WeatherCM/FGLocalWeatherDatabase.h>
124 # include <Weather/weather.hxx>
129 #include "fg_init.hxx"
131 #include "fg_props.hxx"
132 #include "globals.hxx"
133 #include "splash.hxx"
134 #include "viewmgr.hxx"
137 # include <console.h> // -dw- for command line dialog
141 // This is a record containing a bit of global housekeeping information
144 // Specify our current idle function state. This is used to run all
145 // our initializations out of the glutIdleLoop() so that we can get a
146 // splash screen up and running right away.
147 static int idle_state = 0;
148 static long global_multi_loop;
150 // attempt to avoid a large bounce at startup
151 static bool initial_freeze = true;
153 // forward declaration
154 void fgReshape( int width, int height );
156 // Global structures for the Audio library
157 #ifdef ENABLE_AUDIO_SUPPORT
158 static FGSimpleSound *s1;
159 static FGSimpleSound *s2;
164 ssgRoot *scene = NULL;
165 ssgBranch *terrain = NULL;
167 // aircraft model stuff
168 ssgSelector *acmodel_selector = NULL;
169 ssgTransform *acmodel_pos = NULL;
170 ssgSelector *prop_selector = NULL;
171 ssgSelector *flaps_selector = NULL;
172 int acmodel_npropsettings;
173 int acmodel_proprpms[4][2]; // different propeller settings
175 ssgRoot *lighting = NULL;
176 ssgBranch *ground = NULL;
177 ssgBranch *airport = NULL;
179 #ifdef FG_NETWORK_OLK
180 ssgSelector *fgd_sel = NULL;
181 ssgTransform *fgd_pos = NULL;
184 // current fdm/position used for view
185 FGInterface cur_view_fdm;
191 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
193 { 1.0f, 0.0f, 0.0f, 0.0f },
194 { 0.0f, 0.0f, -1.0f, 0.0f },
195 { 0.0f, 1.0f, 0.0f, 0.0f },
196 { 0.0f, 0.0f, 0.0f, 1.0f }
199 // The following defines flightgear options. Because glutlib will also
200 // want to parse its own options, those options must not be included here
201 // or they will get parsed by the main program option parser. Hence case
202 // is significant for any option added that might be in conflict with
205 // glutlib parses for:
207 // -direct (invalid in Win32)
211 // -indirect (invalid in Win32)
214 // Note that glutlib depends upon strings while this program's
215 // option parser wants only initial characters followed by numbers
220 ssgSimpleState *default_state;
221 ssgSimpleState *hud_and_panel;
222 ssgSimpleState *menus;
224 void fgBuildRenderStates( void ) {
225 default_state = new ssgSimpleState;
226 default_state->ref();
227 default_state->disable( GL_TEXTURE_2D );
228 default_state->enable( GL_CULL_FACE );
229 default_state->enable( GL_COLOR_MATERIAL );
230 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
231 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
232 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
233 default_state->disable( GL_BLEND );
234 default_state->disable( GL_ALPHA_TEST );
235 default_state->disable( GL_LIGHTING );
237 hud_and_panel = new ssgSimpleState;
238 hud_and_panel->ref();
239 hud_and_panel->disable( GL_CULL_FACE );
240 hud_and_panel->disable( GL_TEXTURE_2D );
241 hud_and_panel->disable( GL_LIGHTING );
242 hud_and_panel->enable( GL_BLEND );
244 menus = new ssgSimpleState;
246 menus->disable( GL_CULL_FACE );
247 menus->disable( GL_TEXTURE_2D );
248 menus->enable( GL_BLEND );
251 // fgFindNode -- a function that finds a named node in an ssg graph
252 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
253 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
255 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
256 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
257 while (kid != NULL) {
258 ssgEntity *n = fgFindNode(kid, name);
262 kid = ((ssgBranch*)node)->getNextKid();
269 // fgInitVisuals() -- Initialize various GL/view parameters
270 void fgInitVisuals( void ) {
273 l = &cur_light_params;
275 #ifndef GLUT_WRONG_VERSION
276 // Go full screen if requested ...
277 if ( fgGetBool("/sim/startup/fullscreen") ) {
282 // If enabled, normal vectors specified with glNormal are scaled
283 // to unit length after transformation. See glNormal.
284 // glEnable( GL_NORMALIZE );
286 glEnable( GL_LIGHTING );
287 glEnable( GL_LIGHT0 );
288 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
291 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
292 ssgGetLight( 0 ) -> setPosition( sunpos );
294 // glFogi (GL_FOG_MODE, GL_LINEAR);
295 glFogi (GL_FOG_MODE, GL_EXP2);
296 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
297 (!fgGetBool("/sim/rendering/shading"))) {
298 // if fastest fog requested, or if flat shading force fastest
299 glHint ( GL_FOG_HINT, GL_FASTEST );
300 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
301 glHint ( GL_FOG_HINT, GL_NICEST );
303 if ( fgGetBool("/sim/rendering/wireframe") ) {
305 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
308 // This is the default anyways, but it can't hurt
309 glFrontFace ( GL_CCW );
312 // glEnable(GL_POINT_SMOOTH);
313 // glEnable(GL_LINE_SMOOTH);
314 // glEnable(GL_POLYGON_SMOOTH);
318 // For HiRes screen Dumps using Brian Pauls TR Library
319 void trRenderFrame( void ) {
321 if ( fgPanelVisible() ) {
322 GLfloat height = fgGetInt("/sim/startup/ysize");
324 (current_panel->getViewHeight() - current_panel->getYOffset())
325 * (height / 768.0) + 1;
326 glTranslatef( 0.0, view_h, 0.0 );
329 static double m_log01 = -log( 0.01 );
330 static double sqrt_m_log01 = sqrt( m_log01 );
332 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
333 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
335 fgLIGHT *l = &cur_light_params;
337 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
338 l->adj_fog_color[2], l->adj_fog_color[3]);
340 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
342 // set the opengl state to known default values
343 default_state->force();
346 double actual_visibility = thesky->get_visibility();
347 // GLfloat fog_exp_density = m_log01 / actual_visibility;
348 GLfloat fog_exp2_density = sqrt_m_log01 / actual_visibility;
349 GLfloat fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 1.5 );
352 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
353 glFogi ( GL_FOG_MODE, GL_EXP2 );
354 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
356 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
357 // we only update GL_AMBIENT for our lights we will never get
358 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
359 // explicitely to black.
360 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
362 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
364 // texture parameters
365 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
366 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
368 // we need a white diffuse light for the phase of the moon
369 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
372 // draw the ssg scene
373 // return to the desired diffuse color
374 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
375 glEnable( GL_DEPTH_TEST );
376 ssgCullAndDraw( scene );
379 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
380 ssgCullAndDraw( lighting );
382 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
384 // need to do this here as hud_and_panel state is static to
385 // main.cxx and HUD and Panel routines have to be called with
386 // knowledge of the the TR struct < see gui.cxx::HighResDump()
387 hud_and_panel->apply();
391 // Update all Visuals (redraws anything graphics related)
392 void fgRenderFrame( void ) {
393 // Update the default (kludged) properties.
396 fgLIGHT *l = &cur_light_params;
397 static double last_visibility = -9999;
399 static GLfloat fog_exp_density;
400 static GLfloat fog_exp2_density;
401 static GLfloat fog_exp2_punch_through;
404 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
405 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
406 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
407 // GLfloat mat_shininess[] = { 10.0 };
408 GLbitfield clear_mask;
410 if ( idle_state != 1000 ) {
411 // still initializing, draw the splash screen
412 if ( fgGetBool("/sim/startup/splash-screen") ) {
416 // idle_state is now 1000 meaning we've finished all our
417 // initializations and are running the main loop, so this will
418 // now work without seg faulting the system.
420 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
421 // FG_Altitude * SG_FEET_TO_METER);
423 // this is just a temporary hack, to make me understand Pui
424 // timerText -> setLabel (ctime (&t->cur_time));
427 // calculate our current position in cartesian space
428 scenery.center = scenery.next_center;
429 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
430 // scenery.center.y(), scenery.center.z());
432 FGViewerRPH *pilot_view =
433 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
435 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
436 cur_fdm_state->get_Lat_geocentric(),
437 cur_fdm_state->get_Altitude() *
439 pilot_view->set_sea_level_radius( cur_fdm_state->
440 get_Sea_level_radius() *
442 pilot_view->set_rph( cur_fdm_state->get_Phi(),
443 cur_fdm_state->get_Theta(),
444 cur_fdm_state->get_Psi() );
446 FGViewerLookAt *chase_view =
447 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
449 sgVec3 po; // chase view pilot_offset
450 sgVec3 wup; // chase view world up
451 sgSetVec3( po, 0.0, 0.0, 100.0 );
452 sgCopyVec3( wup, pilot_view->get_world_up() );
453 sgMat4 CXFM; // chase view + pilot offset xform
455 chase_view->get_view_offset() * SGD_RADIANS_TO_DEGREES -
456 cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES,
458 sgVec3 npo; // new pilot offset after rotation
459 sgVec3 *pPO = PilotOffsetGet();
460 sgXformVec3( po, *pPO, pilot_view->get_UP() );
461 sgXformVec3( npo, po, CXFM );
463 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
464 cur_fdm_state->get_Lat_geocentric(),
465 cur_fdm_state->get_Altitude() *
467 chase_view->set_sea_level_radius( cur_fdm_state->
468 get_Sea_level_radius() *
470 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
471 chase_view->set_view_forward( pilot_view->get_view_pos() );
472 chase_view->set_view_up( wup );
476 sgCopyMat4( rph, pilot_view->get_VIEW() );
477 cout << "RPH Matrix = " << endl;
479 for ( i = 0; i < 4; i++ ) {
480 for ( j = 0; j < 4; j++ ) {
481 printf("%10.4f ", rph[i][j]);
487 sgCopyMat4( la, chase_view->get_VIEW() );
488 cout << "LookAt Matrix = " << endl;
489 for ( i = 0; i < 4; i++ ) {
490 for ( j = 0; j < 4; j++ ) {
491 printf("%10.4f ", la[i][j]);
498 fgReshape( fgGetInt("/sim/startup/xsize"),
499 fgGetInt("/sim/startup/ysize") );
504 if ( ! fgPanelVisible() ) {
506 (GLint)(fgGetInt("/sim/startup/xsize")),
507 (GLint)(fgGetInt("/sim/startup/ysize")) );
510 int( (current_panel->getViewHeight() -
511 current_panel->getYOffset())
512 * (fgGetInt("/sim/startup/ysize") / 768.0) );
514 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
515 (GLint)(fgGetInt("/sim/startup/xsize")),
520 // set the sun position
521 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
523 clear_mask = GL_DEPTH_BUFFER_BIT;
524 if ( fgGetBool("/sim/rendering/wireframe") ) {
525 clear_mask |= GL_COLOR_BUFFER_BIT;
528 if ( fgGetBool("/sim/rendering/skyblend") ) {
529 if ( fgGetBool("/sim/rendering/textures") ) {
530 // glClearColor(black[0], black[1], black[2], black[3]);
531 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
532 l->adj_fog_color[2], l->adj_fog_color[3]);
533 clear_mask |= GL_COLOR_BUFFER_BIT;
536 glClearColor(l->sky_color[0], l->sky_color[1],
537 l->sky_color[2], l->sky_color[3]);
538 clear_mask |= GL_COLOR_BUFFER_BIT;
540 glClear( clear_mask );
542 // Tell GL we are switching to model view parameters
544 // I really should create a derived ssg node or use a call
545 // back or something so that I can draw the sky within the
546 // ssgCullAndDraw() function, but for now I just mimic what
547 // ssg does to set up the model view matrix
548 glMatrixMode(GL_MODELVIEW);
550 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
552 // set the opengl state to known default values
553 default_state->force();
555 // update fog params if visibility has changed
556 #ifndef FG_OLD_WEATHER
557 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
559 thesky->set_visibility( current_weather.get_visibility() );
562 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
563 ( global_multi_loop *
564 fgGetInt("/sim/speed-up") ) /
565 (double)fgGetInt("/sim/model-hz") );
567 double actual_visibility = thesky->get_visibility();
568 // cout << "actual visibility = " << actual_visibility << endl;
570 if ( actual_visibility != last_visibility ) {
571 last_visibility = actual_visibility;
573 // cout << "----> updating fog params" << endl;
576 fog_exp_density = -log(0.01) / actual_visibility;
579 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
580 fog_exp2_punch_through = sqrt( -log(0.01) ) /
581 ( actual_visibility * 1.5 );
584 // Set correct opengl fog density
585 glFogf (GL_FOG_DENSITY, fog_exp2_density);
587 // update the sky dome
588 if ( fgGetBool("/sim/rendering/skyblend") ) {
589 /* cout << "thesky->repaint() sky_color = "
590 << cur_light_params.sky_color[0] << " "
591 << cur_light_params.sky_color[1] << " "
592 << cur_light_params.sky_color[2] << " "
593 << cur_light_params.sky_color[3] << endl;
595 << cur_light_params.fog_color[0] << " "
596 << cur_light_params.fog_color[1] << " "
597 << cur_light_params.fog_color[2] << " "
598 << cur_light_params.fog_color[3] << endl;
599 cout << " sun_angle = " << cur_light_params.sun_angle
600 << " moon_angle = " << cur_light_params.moon_angle
602 thesky->repaint( cur_light_params.sky_color,
603 cur_light_params.adj_fog_color,
604 cur_light_params.sun_angle,
605 cur_light_params.moon_angle,
606 globals->get_ephem()->getNumPlanets(),
607 globals->get_ephem()->getPlanets(),
608 globals->get_ephem()->getNumStars(),
609 globals->get_ephem()->getStars() );
611 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
612 << view_pos[1] << " " << view_pos[2] << endl;
613 cout << " zero_elev = " << zero_elev[0] << " "
614 << zero_elev[1] << " " << zero_elev[2]
615 << " lon = " << cur_fdm_state->get_Longitude()
616 << " lat = " << cur_fdm_state->get_Latitude() << endl;
617 cout << " sun_rot = " << cur_light_params.sun_rotation
618 << " gst = " << SGTime::cur_time_params->getGst() << endl;
619 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
620 << " sun dec = " << globals->get_ephem()->getSunDeclination()
621 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
622 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
624 thesky->reposition( globals->get_current_view()->get_view_pos(),
625 globals->get_current_view()->get_zero_elev(),
626 globals->get_current_view()->get_world_up(),
627 cur_fdm_state->get_Longitude(),
628 cur_fdm_state->get_Latitude(),
629 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
630 cur_light_params.sun_rotation,
631 globals->get_time_params()->getGst(),
632 globals->get_ephem()->getSunRightAscension(),
633 globals->get_ephem()->getSunDeclination(),
635 globals->get_ephem()->getMoonRightAscension(),
636 globals->get_ephem()->getMoonDeclination(),
640 glEnable( GL_DEPTH_TEST );
641 if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
643 glFogi( GL_FOG_MODE, GL_EXP2 );
644 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
647 // set sun/lighting parameters
648 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
650 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
651 // we only update GL_AMBIENT for our lights we will never get
652 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
653 // explicitely to black.
654 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
655 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
656 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
658 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
659 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
660 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
662 // texture parameters
663 // glEnable( GL_TEXTURE_2D );
664 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
665 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
667 // glMatrixMode( GL_PROJECTION );
669 float fov = globals->get_current_view()->get_fov();
670 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
672 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
675 // SG_LOG( SG_ALL, SG_INFO, "visibility is "
676 // << current_weather.get_visibility() );
679 ssgSetNearFar( 10.0f, 120000.0f );
681 ssgSetNearFar( 0.5f, 120000.0f );
684 if ( globals->get_viewmgr()->get_current() == 0 ) {
685 // disable aircraft model
686 acmodel_selector->select(0);
688 // enable aircraft model and set up its position and orientation
689 acmodel_selector->select(1);
691 FGViewerRPH *pilot_view =
692 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
695 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
698 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
701 sgMakeRotMat4( sgROT, -90.0, ownship_up );
705 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
706 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
708 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
710 sgCopyMat4( sgTUX, sgROT );
711 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
712 sgPostMultMat4( sgTUX, sgTRANS );
715 sgSetCoord( &tuxpos, sgTUX );
716 acmodel_pos->setTransform( &tuxpos );
718 // set up moving parts
719 if (flaps_selector != NULL) {
720 flaps_selector->select( (globals->get_controls()->get_flaps() > 0.5f) ? 1 : 2 );
723 if (prop_selector != NULL) {
724 int propsel_mask = 0;
725 double rpm = fgGetDouble("/engines/engine[0]/rpm");
726 for (int i = 0; i < acmodel_npropsettings; i++) {
727 if (rpm >= acmodel_proprpms[i][0] &&
728 rpm <= acmodel_proprpms[i][1]) {
729 propsel_mask |= 1 << i;
732 prop_selector->select(propsel_mask);
736 // $$$ begin - added VS Renganthan 17 Oct 2K
738 // $$$ end - added VS Renganthan 17 Oct 2K
740 # ifdef FG_NETWORK_OLK
741 if ( fgGetBool("/sim/networking/network-olk") ) {
743 other = head->next; /* put listpointer to start */
744 while ( other != tail) { /* display all except myself */
745 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
746 other->fgd_sel->select(1);
747 sgSetCoord( &fgdpos, other->sgFGD_COORD );
748 other->fgd_pos->setTransform( &fgdpos );
753 // fgd_sel->select(1);
754 // sgCopyMat4( sgTUX, current_view.sgVIEW);
756 // sgSetCoord( &fgdpos, sgFGD_VIEW );
757 // fgd_pos->setTransform( &fgdpos);
761 // position tile nodes and update range selectors
762 global_tile_mgr.prep_ssg_nodes();
764 if ( fgGetBool("/sim/rendering/skyblend") ) {
765 // draw the sky backdrop
767 // we need a white diffuse light for the phase of the moon
768 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
772 // return to the desired diffuse color
773 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
776 // draw the ssg scene
777 glEnable( GL_DEPTH_TEST );
778 ssgCullAndDraw( scene );
780 // change state for lighting here
783 // Set punch through fog density
784 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
786 ssgCullAndDraw( lighting );
788 if ( fgGetBool("/sim/rendering/skyblend") ) {
789 // draw the sky cloud layers
790 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
793 // display HUD && Panel
795 glDisable( GL_DEPTH_TEST );
796 // glDisable( GL_CULL_FACE );
797 // glDisable( GL_TEXTURE_2D );
799 // update the input subsystem
800 current_input.update();
802 // update the controls subsystem
803 globals->get_controls()->update();
805 hud_and_panel->apply();
808 // update the panel subsystem
809 if (current_panel != 0)
810 current_panel->update();
812 // We can do translucent menus, so why not. :-)
814 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
816 // glDisable ( GL_BLEND ) ;
818 // glEnable( GL_FOG );
825 // Update internal time dependent calculations (i.e. flight model)
826 void fgUpdateTimeDepCalcs() {
827 static bool inited = false;
829 fgLIGHT *l = &cur_light_params;
834 if ( !globals->get_freeze() && !initial_freeze ) {
835 // conceptually, this could be done for each fdm instance ...
838 cur_fdm_state->stamp();
844 long elapsed = current - cur_fdm_state->get_time_stamp();
845 cur_fdm_state->set_time_stamp( current );
846 elapsed += cur_fdm_state->get_remainder();
847 // cout << "elapsed = " << elapsed << endl;
848 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
849 multi_loop = (long)(((double)elapsed * 0.000001) /
850 cur_fdm_state->get_delta_t() );
851 cur_fdm_state->set_multi_loop( multi_loop );
852 long remainder = elapsed - (long)( (multi_loop*1000000) *
853 cur_fdm_state->get_delta_t() );
854 cur_fdm_state->set_remainder( remainder );
855 // cout << "remainder = " << remainder << endl;
857 // chop max interations to something reasonable if the sim was
858 // delayed for an excesive amount of time
859 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
860 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
861 cur_fdm_state->set_remainder( 0 );
864 // cout << "multi_loop = " << multi_loop << endl;
865 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
866 // run Autopilot system
867 current_autopilot->run();
870 cur_fdm_state->update( 1 );
872 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
874 cur_fdm_state->update( 0 );
875 FGSteam::update( 0 );
877 //if ( global_tile_mgr.queue_size() == 0 ) {
878 initial_freeze = false;
882 if ( fgGetString("/sim/view-mode") == "pilot" ) {
883 cur_view_fdm = *cur_fdm_state;
887 // update the view angle
888 FGViewer *v = globals->get_current_view();
889 for ( i = 0; i < multi_loop; i++ ) {
890 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
891 v->set_view_offset( v->get_goal_view_offset() );
894 // move current_view.view_offset towards
895 // current_view.goal_view_offset
896 if ( v->get_goal_view_offset() > v->get_view_offset() )
898 if ( v->get_goal_view_offset() - v->get_view_offset() < SGD_PI ){
899 v->inc_view_offset( 0.01 );
901 v->inc_view_offset( -0.01 );
904 if ( v->get_view_offset() - v->get_goal_view_offset() < SGD_PI ){
905 v->inc_view_offset( -0.01 );
907 v->inc_view_offset( 0.01 );
910 if ( v->get_view_offset() > SGD_2PI ) {
911 v->inc_view_offset( -SGD_2PI );
912 } else if ( v->get_view_offset() < 0 ) {
913 v->inc_view_offset( SGD_2PI );
918 double tmp = -(l->sun_rotation + SGD_PI)
919 - (cur_fdm_state->get_Psi() -
920 globals->get_current_view()->get_view_offset() );
921 while ( tmp < 0.0 ) {
924 while ( tmp > SGD_2PI ) {
927 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
928 FG_Psi * SGD_RADIANS_TO_DEGREES, current_view.view_offset * SGD_RADIANS_TO_DEGREES,
929 -(l->sun_rotation+SGD_PI) * SGD_RADIANS_TO_DEGREES, tmp * SGD_RADIANS_TO_DEGREES); */
932 // Update solar system
933 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
934 globals->get_time_params()->getLst(),
935 cur_fdm_state->get_Latitude() );
937 // Update radio stack model
938 current_radiostack->update();
942 void fgInitTimeDepCalcs( void ) {
945 // #ifdef HAVE_SETITIMER
946 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
947 // fgUpdateTimeDepCalcs );
948 // #endif HAVE_SETITIMER
952 static const double alt_adjust_ft = 3.758099;
953 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
956 // What should we do when we have nothing else to do? Let's get ready
957 // for the next move and update the display?
958 static void fgMainLoop( void ) {
959 static long remainder = 0;
961 #ifdef FANCY_FRAME_COUNTER
965 static time_t last_time = 0;
966 static int frames = 0;
967 #endif // FANCY_FRAME_COUNTER
969 SGTime *t = globals->get_time_params();
971 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
972 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
974 #ifdef FG_NETWORK_OLK
975 if ( fgGetBool("/sim/networking/network-olk") ) {
976 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
977 // printf("FGD: Netupdate\n");
978 fgd_send_com( "A", FGFS_host); // Send Mat4 data
979 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
984 #if defined( ENABLE_PLIB_JOYSTICK )
985 // Read joystick and update control settings
986 // if ( fgGetString("/sim/control-mode") == "joystick" )
990 #elif defined( ENABLE_GLUT_JOYSTICK )
991 // Glut joystick support works by feeding a joystick handler
992 // function to glut. This is taken care of once in the joystick
993 // init routine and we don't have to worry about it again.
996 #ifdef FG_OLD_WEATHER
997 current_weather.Update();
1000 // Fix elevation. I'm just sticking this here for now, it should
1001 // probably move eventually
1003 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1005 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1006 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1008 if ( scenery.cur_elev > -9990 ) {
1009 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
1010 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
1011 // now set aircraft altitude above ground
1012 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
1013 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1014 scenery.cur_elev + alt_adjust_m - 3.0,
1015 scenery.cur_elev + alt_adjust_m );
1016 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
1017 scenery.cur_elev + alt_adjust_m );
1019 SG_LOG( SG_ALL, SG_DEBUG,
1020 "<*> resetting altitude to "
1021 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1026 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1028 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1029 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1031 // cout << "Warp = " << globals->get_warp() << endl;
1034 if ( globals->get_warp_delta() != 0 ) {
1035 globals->inc_warp( globals->get_warp_delta() );
1038 t->update( cur_fdm_state->get_Longitude(),
1039 cur_fdm_state->get_Latitude(),
1040 globals->get_warp() );
1042 if ( globals->get_warp_delta() != 0 ) {
1043 fgUpdateSkyAndLightingParams();
1046 // update magvar model
1047 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
1048 cur_fdm_state->get_Latitude(),
1049 cur_fdm_state->get_Altitude()* SG_FEET_TO_METER,
1050 globals->get_time_params()->getJD() );
1052 // Get elapsed time (in usec) for this past frame
1053 elapsed = fgGetTimeInterval();
1054 SG_LOG( SG_ALL, SG_DEBUG,
1055 "Elapsed time interval is = " << elapsed
1056 << ", previous remainder is = " << remainder );
1058 // Calculate frame rate average
1059 #ifdef FANCY_FRAME_COUNTER
1060 /* old fps calculation */
1061 if ( elapsed > 0 ) {
1064 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1065 tmp = general.get_frame(i);
1067 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1068 general.set_frame(i+1,tmp);
1070 tmp = 1000000.0 / (float)elapsed;
1071 general.set_frame(0,tmp);
1072 // printf("frame[0] = %.2f\n", general.frames[0]);
1074 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1075 // printf("ave = %.2f\n", general.frame_rate);
1078 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1079 general.set_frame_rate( frames );
1080 SG_LOG( SG_ALL, SG_DEBUG,
1081 "--> Frame rate is = " << general.get_frame_rate() );
1084 last_time = t->get_cur_time();
1090 // Calculate model iterations needed for next frame
1091 elapsed += remainder;
1093 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1094 fgGetInt("/sim/model-hz"));
1095 remainder = elapsed - ( (global_multi_loop*1000000) /
1096 fgGetInt("/sim/model-hz") );
1097 SG_LOG( SG_ALL, SG_DEBUG,
1098 "Model iterations needed = " << global_multi_loop
1099 << ", new remainder = " << remainder );
1101 // chop max interations to something reasonable if the sim was
1102 // delayed for an excesive amount of time
1103 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1104 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1109 if ( global_multi_loop > 0 ) {
1110 fgUpdateTimeDepCalcs();
1112 SG_LOG( SG_ALL, SG_DEBUG,
1113 "Elapsed time is zero ... we're zinging" );
1116 #if ! defined( macintosh )
1117 // Do any I/O channel work that might need to be done
1121 // see if we need to load any new scenery tiles
1122 global_tile_mgr.update( cur_fdm_state->get_Longitude()
1123 * SGD_RADIANS_TO_DEGREES,
1124 cur_fdm_state->get_Latitude()
1125 * SGD_RADIANS_TO_DEGREES );
1127 // see if we need to load any deferred-load textures
1128 material_lib.load_next_deferred();
1130 // Process/manage pending events
1131 global_events.Process();
1133 // Run audio scheduler
1134 #ifdef ENABLE_AUDIO_SUPPORT
1135 if ( fgGetBool("/sim/sound") && globals->get_soundmgr()->is_working() ) {
1136 if ( fgGetString("/sim/aircraft") == "c172" ) {
1137 // pitch corresponds to rpm
1138 // volume corresponds to manifold pressure
1140 // cout << "AUDIO working = "
1141 // << globals->get_soundmgr()->is_working() << endl;
1144 if ( cur_fdm_state->get_engine(0) != NULL ) {
1145 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1149 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1152 double pitch = 0.3 + rpm_factor * 3.0;
1154 // don't run at absurdly slow rates -- not realistic
1155 // and sounds bad to boot. :-)
1156 if (pitch < 0.7) { pitch = 0.7; }
1157 if (pitch > 5.0) { pitch = 5.0; }
1160 if ( cur_fdm_state->get_engine(0) != NULL ) {
1162 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1167 << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1170 double volume = 0.15 + mp_factor / 2.0;
1172 if ( volume < 0.15 ) { volume = 0.15; }
1173 if ( volume > 0.5 ) { volume = 0.5; }
1174 // cout << "volume = " << volume << endl;
1176 s1->set_pitch( pitch );
1177 s1->set_volume( volume );
1180 = globals->get_controls()->get_throttle( 0 ) * 2.0 + 1.0;
1181 s1->set_pitch( param );
1182 s1->set_volume( param );
1185 globals->get_soundmgr()->update();
1192 SG_LOG( SG_ALL, SG_DEBUG, "" );
1196 // This is the top level master main function that is registered as
1197 // our idle funciton
1200 // The first few passes take care of initialization things (a couple
1201 // per pass) and once everything has been initialized fgMainLoop from
1204 static void fgIdleFunction ( void ) {
1205 // printf("idle state == %d\n", idle_state);
1207 if ( idle_state == 0 ) {
1208 // Initialize the splash screen right away
1209 if ( fgGetBool("/sim/startup/splash-screen") ) {
1214 } else if ( idle_state == 1 ) {
1215 // Initialize audio support
1216 #ifdef ENABLE_AUDIO_SUPPORT
1218 // Start the intro music
1220 if ( fgGetBool("/sim/startup/intro-music") ) {
1221 SGPath mp3file( globals->get_fg_root() );
1222 mp3file.append( "Sounds/intro.mp3" );
1224 SG_LOG( SG_GENERAL, SG_INFO,
1225 "Starting intro music: " << mp3file.str() );
1227 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1228 system ( command.c_str() );
1232 FGSoundMgr *soundmgr = new FGSoundMgr;
1233 globals->set_soundmgr( soundmgr );
1235 if ( fgGetBool("/sim/sound") ) {
1236 globals->get_soundmgr()->init();
1238 s1 = new FGSimpleSound( fgGetString("/sim/sounds/engine",
1239 "Sounds/wasp.wav") );
1240 globals->get_soundmgr()->add( s1, "engine loop" );
1241 globals->get_soundmgr()->play_looped( "engine loop" );
1242 SG_LOG( SG_GENERAL, SG_INFO,
1243 "Rate = " << s1->get_sample()->getRate()
1244 << " Bps = " << s1->get_sample()->getBps()
1245 << " Stereo = " << s1->get_sample()->getStereo() );
1247 // s2 = new FGSimpleSound( "Sounds/corflaps.wav" );
1248 // s2->set_volume( 0.3 );
1249 // globals->get_soundmgr()->add( s2, "flaps" );
1254 } else if ( idle_state == 2 ) {
1255 // These are a few miscellaneous things that aren't really
1256 // "subsystems" but still need to be initialized.
1259 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1260 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1265 } else if ( idle_state == 3 ) {
1266 // This is the top level init routine which calls all the
1267 // other subsystem initialization routines. If you are adding
1268 // a subsystem to flightgear, its initialization call should
1269 // located in this routine.
1270 if( !fgInitSubsystems()) {
1271 SG_LOG( SG_GENERAL, SG_ALERT,
1272 "Subsystem initializations failed ..." );
1277 } else if ( idle_state == 4 ) {
1278 // setup OpenGL view parameters
1282 } else if ( idle_state == 5 ) {
1285 } else if ( idle_state == 6 ) {
1289 cout << "Panel visible = " << fgPanelVisible() << endl;
1290 fgReshape( fgGetInt("/sim/startup/xsize"),
1291 fgGetInt("/sim/startup/ysize") );
1294 if ( idle_state == 1000 ) {
1295 // We've finished all our initialization steps, from now on we
1296 // run the main loop.
1300 if ( fgGetBool("/sim/startup/splash-screen") ) {
1301 fgSplashUpdate(0.0);
1306 // options.cxx needs to see this for toggle_panel()
1307 // Handle new window size or exposure
1308 void fgReshape( int width, int height ) {
1310 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1311 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1312 globals->get_viewmgr()->get_view(i)->
1313 set_win_ratio( (float)height / (float)width );
1316 int((current_panel->getViewHeight() -
1317 current_panel->getYOffset())
1318 * (height / 768.0)) + 1;
1319 globals->get_viewmgr()->get_view(i)->
1320 set_win_ratio( (float)view_h / (float)width );
1324 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1325 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1328 int((current_panel->getViewHeight() - current_panel->getYOffset())
1329 * (height / 768.0)) + 1;
1330 glViewport(0, (GLint)(height - view_h),
1331 (GLint)(width), (GLint)(view_h) );
1334 fgSetInt("/sim/startup/xsize", width);
1335 fgSetInt("/sim/startup/ysize", height);
1337 float fov = globals->get_current_view()->get_fov();
1338 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1344 // Initialize GLUT and define a main window
1345 int fgGlutInit( int *argc, char **argv ) {
1347 #if !defined( macintosh )
1348 // GLUT will extract all glut specific options so later on we only
1349 // need wory about our own.
1350 glutInit(argc, argv);
1353 // Define Display Parameters
1354 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1356 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1357 fgGetInt("/sim/startup/xsize") << "x"
1358 << fgGetInt("/sim/startup/ysize") );
1360 // Define initial window size
1361 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1362 fgGetInt("/sim/startup/ysize") );
1364 // Initialize windows
1365 if ( !fgGetBool("/sim/startup/game-mode")) {
1366 // Open the regular window
1367 glutCreateWindow("FlightGear");
1368 #ifndef GLUT_WRONG_VERSION
1370 // Open the cool new 'game mode' window
1371 char game_mode_str[256];
1372 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1373 fgGetInt("/sim/startup/xsize"),
1374 fgGetInt("/sim/startup/ysize"),
1375 fgGetInt("/sim/rendering/bits-per-pixel"));
1377 SG_LOG( SG_GENERAL, SG_INFO,
1378 "game mode params = " << game_mode_str );
1379 glutGameModeString( game_mode_str );
1380 glutEnterGameMode();
1384 // This seems to be the absolute earliest in the init sequence
1385 // that these calls will return valid info. Too bad it's after
1386 // we've already created and sized out window. :-(
1387 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1388 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1389 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1390 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1393 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1394 general.set_glMaxTexSize( tmp );
1395 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1397 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1398 general.set_glDepthBits( tmp );
1399 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1405 // Initialize GLUT event handlers
1406 int fgGlutInitEvents( void ) {
1407 // call fgReshape() on window resizes
1408 glutReshapeFunc( fgReshape );
1410 // call GLUTkey() on keyboard event
1411 glutKeyboardFunc(GLUTkey);
1412 glutKeyboardUpFunc(GLUTkeyup);
1413 glutSpecialFunc(GLUTspecialkey);
1414 glutSpecialUpFunc(GLUTspecialkeyup);
1416 // call guiMouseFunc() whenever our little rodent is used
1417 glutMouseFunc ( guiMouseFunc );
1418 glutMotionFunc (guiMotionFunc );
1419 glutPassiveMotionFunc (guiMotionFunc );
1421 // call fgMainLoop() whenever there is
1422 // nothing else to do
1423 glutIdleFunc( fgIdleFunction );
1426 glutDisplayFunc( fgRenderFrame );
1433 int mainLoop( int argc, char **argv ) {
1435 #if defined( macintosh )
1436 freopen ("stdout.txt", "w", stdout );
1437 freopen ("stderr.txt", "w", stderr );
1438 argc = ccommand( &argv );
1442 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1445 // set default log levels
1446 sglog().setLogLevels( SG_ALL, SG_INFO );
1449 #ifdef FLIGHTGEAR_VERSION
1450 version = FLIGHTGEAR_VERSION;
1452 version = "unknown version";
1454 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1455 << version << endl );
1457 // Allocate global data structures. This needs to happen before
1458 // we parse command line options
1460 globals = new FGGlobals;
1462 // seed the random number generater
1465 SGRoute *route = new SGRoute;
1466 globals->set_route( route );
1468 FGControls *controls = new FGControls;
1469 globals->set_controls( controls );
1471 FGViewMgr *viewmgr = new FGViewMgr;
1472 globals->set_viewmgr( viewmgr );
1474 FGViewerRPH *pv = new FGViewerRPH;
1475 globals->get_viewmgr()->add_view( pv );
1477 FGViewerLookAt *chase = new FGViewerLookAt;
1478 globals->get_viewmgr()->add_view( chase );
1480 string_list *col = new string_list;
1481 globals->set_channel_options_list( col );
1483 // set current view to 0 (first) which is our main pilot view
1484 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1486 // Scan the config file(s) and command line options to see if
1487 // fg_root was specified (ignore all other options for now)
1488 fgInitFGRoot(argc, argv);
1490 // Check for the correct base package version
1491 string base_version = fgBasePackageVersion();
1492 if ( !(base_version == "0.7.9") ) {
1493 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1494 << "Found version " << base_version );
1495 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1499 // Initialize the Aircraft directory to "" (UIUC)
1502 // Load the configuration parameters
1503 if ( !fgInitConfig(argc, argv) ) {
1504 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1508 // Initialize the Window/Graphics environment.
1509 if( !fgGlutInit(&argc, argv) ) {
1510 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1514 // Initialize the various GLUT Event Handlers.
1515 if( !fgGlutInitEvents() ) {
1516 SG_LOG( SG_GENERAL, SG_ALERT,
1517 "GLUT event handler initialization failed ..." );
1521 // Initialize ssg (from plib). Needs to come before we do any
1522 // other ssg stuff, but after opengl/glut has been initialized.
1525 // Initialize the user interface (we need to do this before
1526 // passing off control to glut and before fgInitGeneral to get our
1530 #ifdef GL_EXT_texture_lod_bias
1531 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1535 #ifdef GL_EXT_texture_filter_anisotropic
1536 float max_anisotropy;
1537 glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy );
1538 glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1540 cout << "Max anisotropy = " << max_anisotropy << endl;
1544 // set current_options lon/lat if an airport id is specified
1545 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1546 if ( fgGetString("/sim/startup/airport-id").length() ) {
1547 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1548 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1549 fgGetDouble("/orientation/heading-deg") );
1553 SGPath zone( globals->get_fg_root() );
1554 zone.append( "Timezone" );
1555 SGTime *t = new SGTime( fgGetDouble("/position/longitude-deg") * SGD_DEGREES_TO_RADIANS,
1556 fgGetDouble("/position/latitude-deg") * SGD_DEGREES_TO_RADIANS,
1559 // Handle potential user specified time offsets
1560 time_t cur_time = t->get_cur_time();
1561 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1562 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1563 time_t aircraftLocalTime =
1564 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1566 // Okay, we now have six possible scenarios
1567 int offset = fgGetInt("/sim/startup/time-offset");
1568 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1569 if (offset_type == "system-offset") {
1570 globals->set_warp( offset );
1571 } else if (offset_type == "gmt-offset") {
1572 globals->set_warp( offset - (currGMT - systemLocalTime) );
1573 } else if (offset_type == "latitude-offset") {
1574 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1575 } else if (offset_type == "system") {
1576 globals->set_warp( offset - cur_time );
1577 } else if (offset_type == "gmt") {
1578 globals->set_warp( offset - currGMT );
1579 } else if (offset_type == "latitude") {
1580 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1583 SG_LOG( SG_GENERAL, SG_ALERT,
1584 "Unsupported offset type " << offset_type );
1588 SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = "
1589 << globals->get_warp() );
1591 globals->set_warp_delta( 0 );
1593 t->update( 0.0, 0.0, globals->get_warp() );
1595 globals->set_time_params( t );
1597 // Do some quick general initializations
1598 if( !fgInitGeneral()) {
1599 SG_LOG( SG_GENERAL, SG_ALERT,
1600 "General initializations failed ..." );
1604 SGPath modelpath( globals->get_fg_root() );
1605 ssgModelPath( (char *)modelpath.c_str() );
1608 scene = new ssgRoot;
1609 scene->setName( "Scene" );
1611 lighting = new ssgRoot;
1612 lighting->setName( "Lighting" );
1614 // Initialize the sky
1615 SGPath ephem_data_path( globals->get_fg_root() );
1616 ephem_data_path.append( "Astro" );
1617 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1618 ephem->update( globals->get_time_params()->getMjd(),
1619 globals->get_time_params()->getLst(),
1621 globals->set_ephem( ephem );
1625 SGPath sky_tex_path( globals->get_fg_root() );
1626 sky_tex_path.append( "Textures" );
1627 sky_tex_path.append( "Sky" );
1628 thesky->texture_path( sky_tex_path.str() );
1630 thesky->build( 550.0, 550.0,
1631 globals->get_ephem()->getNumPlanets(),
1632 globals->get_ephem()->getPlanets(), 60000.0,
1633 globals->get_ephem()->getNumStars(),
1634 globals->get_ephem()->getStars(), 60000.0 );
1636 if ( fgGetBool("/environment/clouds/status") ) {
1637 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1638 // SG_CLOUD_OVERCAST );
1639 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1640 SG_CLOUD_MOSTLY_CLOUDY );
1641 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1642 // SG_CLOUD_MOSTLY_SUNNY );
1643 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1647 // Initialize MagVar model
1648 SGMagVar *magvar = new SGMagVar();
1649 globals->set_mag( magvar );
1652 terrain = new ssgBranch;
1653 terrain->setName( "Terrain" );
1654 scene->addKid( terrain );
1657 ground = new ssgBranch;
1658 ground->setName( "Ground Lighting" );
1659 lighting->addKid( ground );
1661 airport = new ssgBranch;
1662 airport->setName( "Airport Lighting" );
1663 lighting->addKid( airport );
1665 // temporary visible aircraft "own ship"
1666 acmodel_selector = new ssgSelector;
1667 acmodel_pos = new ssgTransform;
1669 // Get the model location, and load textures from the same
1670 // directory. Use an absolute path for the model to avoid
1671 // incompatibilities in different versions of PLIB.
1672 string acmodel_path =
1673 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1674 SGPath full_model = globals->get_fg_root();
1675 full_model.append(acmodel_path);
1677 #if !defined( PLIB_1_2_X )
1678 // this should be redundant ... but it breaks for relative paths
1679 // ssgModelPath( (char *)full_model.dir().c_str() );
1682 ssgTexturePath( (char *)full_model.dir().c_str() );
1683 ssgEntity *acmodel_obj = ssgLoad( (char *)full_model.c_str() );
1684 if( !acmodel_obj ) {
1685 // fall back to default
1686 acmodel_obj = ssgLoad( (char *)"Models/Geometry/glider.ac" );
1687 if( !acmodel_obj ) {
1688 SG_LOG( SG_GENERAL, SG_ALERT, "FAILED to LOAD an AC model! ..." );
1693 // find moving parts (if this is an MDL model)
1694 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1695 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1697 acmodel_npropsettings = 0;
1698 if (prop_selector != NULL) {
1699 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1700 kid = prop_selector->getNextKid()) {
1701 int prop_low, prop_high;
1702 if ( sscanf(kid->getName(), "PROP_%d_%d",
1703 &prop_low, &prop_high) == 2 ) {
1704 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1705 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1706 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1707 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1708 acmodel_npropsettings++;
1710 SG_LOG( SG_GENERAL, SG_INFO, "PROPELLER SETTING " << prop_low <<
1716 // align the model properly for FGFS
1717 ssgTransform *acmodel_align = new ssgTransform;
1718 acmodel_align->addKid(acmodel_obj);
1722 float h_rot = fgGetFloat("/sim/model/heading-offset-deg", 0.0);
1723 float p_rot = fgGetFloat("/sim/model/roll-offset-deg", 0.0);
1724 float r_rot = fgGetFloat("/sim/model/pitch-offset-deg", 0.0);
1725 float x_off = fgGetFloat("/sim/model/x-offset-m", 0.0);
1726 float y_off = fgGetFloat("/sim/model/y-offset-m", 0.0);
1727 float z_off = fgGetFloat("/sim/model/z-offset-m", 0.0);
1728 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1729 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1730 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1731 acmodel_align->setTransform(res_matrix);
1733 acmodel_pos->addKid( acmodel_align );
1734 acmodel_selector->addKid( acmodel_pos );
1735 //ssgFlatten( acmodel_obj );
1736 //ssgStripify( acmodel_selector );
1737 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1738 scene->addKid( acmodel_selector );
1740 // $$$ begin - added VS Renganthan 17 Oct 2K
1742 // $$$ end - added VS Renganthan 17 Oct 2K
1744 #ifdef FG_NETWORK_OLK
1745 // Do the network intialization
1746 if ( fgGetBool("/sim/networking/network-olk") ) {
1747 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1751 // build our custom render states
1752 fgBuildRenderStates();
1754 // pass control off to the master GLUT event handler
1757 // we never actually get here ... but to avoid compiler warnings,
1763 // $$$ end - added VS Renganathan, 15 Oct 2K
1764 // - added Venky , 12 Nov 2K
1766 // Main entry point; catch any exceptions that have made it this far.
1767 int main ( int argc, char **argv ) {
1768 // FIXME: add other, more specific
1771 mainLoop(argc, argv);
1772 } catch (sg_throwable &t) {
1773 SG_LOG(SG_GENERAL, SG_ALERT,
1774 "Fatal error: " << t.getFormattedMessage()
1775 << "\n (received from " << t.getOrigin() << ')');
1781 void fgLoadDCS(void) {
1783 ssgEntity *ship_obj = NULL;
1786 char obj_filename[25];
1788 for ( int k = 0; k < 32; k++ ) {
1792 SGPath tile_path( globals->get_fg_root());
1793 tile_path.append( "Scenery" );
1794 tile_path.append( "Objects.txt" );
1795 sg_gzifstream in( tile_path.str() );
1796 if ( ! in.is_open() ) {
1797 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1800 SGPath modelpath( globals->get_fg_root() );
1801 modelpath.append( "Models" );
1802 modelpath.append( "Geometry" );
1804 SGPath texturepath( globals->get_fg_root() );
1805 texturepath.append( "Models" );
1806 texturepath.append( "Textures" );
1808 ssgModelPath( (char *)modelpath.c_str() );
1809 ssgTexturePath( (char *)texturepath.c_str() );
1811 ship_sel = new ssgSelector;
1814 while ( ! in.eof() ) {
1816 if ( in.get( c ) && c == '#' ) {
1820 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1821 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1822 int chj=getchar();*/
1824 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1825 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1827 ship_pos[objc] = new ssgTransform;
1829 // type "repeat" in objects.txt to load one more
1830 // instance of the last object.
1832 if ( strcmp(obj_filename,"repeat") != 0) {
1833 ship_obj = ssgLoadOBJ( obj_filename );
1836 if ( ship_obj != NULL ) {
1837 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1838 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1840 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1846 if (in.eof()) break;
1850 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1852 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1853 scene->addKid( ship_sel ); //add selector node to root node
1860 void fgUpdateDCS (void) {
1862 // double eye_lat,eye_lon,eye_alt;
1863 // static double obj_head;
1864 double sl_radius,obj_latgc;
1865 // float nresultmat[4][4];
1866 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1869 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1870 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1872 // Deck should be the first object in objects.txt in case of fdm=ada
1874 if (fgGetString("/sim/flight-model") == "ada") {
1875 obj_lon[0] = fdm->get_aux5()*SGD_DEGREES_TO_RADIANS;
1876 obj_lat[0] = fdm->get_aux6()*SGD_DEGREES_TO_RADIANS;
1877 obj_alt[0] = fdm->get_aux7();
1880 for ( int m = 0; m < objc; m++ ) {
1881 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1884 //Geodetic to Geocentric angles for rotation
1885 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1887 //moving object gbs-posn in cartesian coords
1888 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1889 Point3D obj_pos = sgGeodToCart( obj_posn );
1891 // Translate moving object w.r.t eye
1892 Point3D Objtrans = obj_pos-scenery.center;
1897 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1900 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1902 sgVec3 ship_fwd,ship_rt,ship_up;
1903 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1904 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1905 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1907 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1908 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1909 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1910 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1913 sgCopyMat4( sgTUX, sgROT_hdg );
1914 sgPostMultMat4( sgTUX, sgROT_lat );
1915 sgPostMultMat4( sgTUX, sgROT_lon );
1916 sgPostMultMat4( sgTUX, sgTRANS );
1919 sgSetCoord(&shippos, sgTUX );
1920 ship_pos[m]->setTransform( &shippos );
1922 if ( ship_sel != NULL ) {
1923 ship_sel->select(0xFFFFFFFF);
1927 // $$$ end - added VS Renganathan, 15 Oct 2K
1928 // added Venky , 12 Nov 2K