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 #ifdef SG_MATH_EXCEPTION_CLASH
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h> // for stat()
53 # include <unistd.h> // for stat()
57 // # include <GL/glext.h>
63 #include <simgear/constants.h> // for VERSION
64 #include <simgear/debug/logstream.hxx>
65 #include <simgear/math/polar3d.hxx>
66 #include <simgear/math/sg_random.h>
67 #include <simgear/misc/sg_path.hxx>
68 #include <simgear/sky/sky.hxx>
69 #include <simgear/timing/sg_time.hxx>
70 #include <simgear/timing/lowleveltime.h>
72 #include <Include/general.hxx>
74 #include <Aircraft/aircraft.hxx>
76 #include <Autopilot/newauto.hxx>
77 #include <Cockpit/cockpit.hxx>
78 #include <Cockpit/radiostack.hxx>
79 #include <Cockpit/steam.hxx>
81 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
83 #include <GUI/sgVec3Slider.hxx>
84 // #include <Joystick/joystick.hxx>
86 #include <NetworkOLK/network.h>
88 #include <Objects/matlib.hxx>
89 #include <Scenery/scenery.hxx>
90 #include <Scenery/tilemgr.hxx>
91 #ifdef ENABLE_AUDIO_SUPPORT
92 # include <Sound/soundmgr.hxx>
93 # include <Sound/morse.hxx>
95 #include <Time/event.hxx>
96 #include <Time/fg_timer.hxx>
97 #include <Time/light.hxx>
98 #include <Time/sunpos.hxx>
99 #include <Time/tmp.hxx>
101 #include <Input/input.hxx>
103 // begin - added Venky
104 // $$$ begin - added VS Renganathan
105 #include <simgear/misc/sgstream.hxx>
106 #include <FDM/flight.hxx>
107 #include <FDM/ADA.hxx>
108 void fgLoadDCS (void);
109 void fgUpdateDCS (void);
110 ssgSelector *ship_sel=NULL;
111 // upto 32 instances of a same object can be loaded.
112 ssgTransform *ship_pos[32];
113 double obj_lat[32],obj_lon[32],obj_alt[32];
115 // $$$ end - added VS Renganathan
118 #ifndef FG_OLD_WEATHER
119 # include <WeatherCM/FGLocalWeatherDatabase.h>
121 # include <Weather/weather.hxx>
126 #include "fg_init.hxx"
128 #include "fg_props.hxx"
129 #include "globals.hxx"
130 #include "splash.hxx"
133 # include <console.h> // -dw- for command line dialog
137 // This is a record containing a bit of global housekeeping information
140 // Specify our current idle function state. This is used to run all
141 // our initializations out of the glutIdleLoop() so that we can get a
142 // splash screen up and running right away.
143 static int idle_state = 0;
144 static long global_multi_loop;
146 // attempt to avoid a large bounce at startup
147 static bool initial_freeze = true;
149 // forward declaration
150 void fgReshape( int width, int height );
152 // Global structures for the Audio library
153 #ifdef ENABLE_AUDIO_SUPPORT
154 static FGSimpleSound *s1;
155 static FGSimpleSound *s2;
160 ssgRoot *scene = NULL;
161 ssgBranch *terrain = NULL;
163 // aircraft model stuff
164 ssgSelector *acmodel_selector = NULL;
165 ssgTransform *acmodel_pos = NULL;
166 ssgSelector *prop_selector = NULL;
167 ssgSelector *flaps_selector = NULL;
168 int acmodel_npropsettings;
169 int acmodel_proprpms[4][2]; // different propeller settings
171 ssgRoot *lighting = NULL;
172 ssgBranch *ground = NULL;
173 ssgBranch *airport = NULL;
175 #ifdef FG_NETWORK_OLK
176 ssgSelector *fgd_sel = NULL;
177 ssgTransform *fgd_pos = NULL;
180 // current fdm/position used for view
181 FGInterface cur_view_fdm;
187 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
189 { 1.0f, 0.0f, 0.0f, 0.0f },
190 { 0.0f, 0.0f, -1.0f, 0.0f },
191 { 0.0f, 1.0f, 0.0f, 0.0f },
192 { 0.0f, 0.0f, 0.0f, 1.0f }
195 // The following defines flightgear options. Because glutlib will also
196 // want to parse its own options, those options must not be included here
197 // or they will get parsed by the main program option parser. Hence case
198 // is significant for any option added that might be in conflict with
201 // glutlib parses for:
203 // -direct (invalid in Win32)
207 // -indirect (invalid in Win32)
210 // Note that glutlib depends upon strings while this program's
211 // option parser wants only initial characters followed by numbers
216 ssgSimpleState *default_state;
217 ssgSimpleState *hud_and_panel;
218 ssgSimpleState *menus;
220 void fgBuildRenderStates( void ) {
221 default_state = new ssgSimpleState;
222 default_state->ref();
223 default_state->disable( GL_TEXTURE_2D );
224 default_state->enable( GL_CULL_FACE );
225 default_state->enable( GL_COLOR_MATERIAL );
226 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
227 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
228 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
229 default_state->disable( GL_BLEND );
230 default_state->disable( GL_ALPHA_TEST );
231 default_state->disable( GL_LIGHTING );
233 hud_and_panel = new ssgSimpleState;
234 hud_and_panel->ref();
235 hud_and_panel->disable( GL_CULL_FACE );
236 hud_and_panel->disable( GL_TEXTURE_2D );
237 hud_and_panel->disable( GL_LIGHTING );
238 hud_and_panel->enable( GL_BLEND );
240 menus = new ssgSimpleState;
242 menus->disable( GL_CULL_FACE );
243 menus->disable( GL_TEXTURE_2D );
244 menus->enable( GL_BLEND );
247 // fgFindNode -- a function that finds a named node in an ssg graph
248 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
249 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
251 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
252 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
253 while (kid != NULL) {
254 ssgEntity *n = fgFindNode(kid, name);
258 kid = ((ssgBranch*)node)->getNextKid();
265 // fgInitVisuals() -- Initialize various GL/view parameters
266 void fgInitVisuals( void ) {
269 l = &cur_light_params;
271 #ifndef GLUT_WRONG_VERSION
272 // Go full screen if requested ...
273 if ( fgGetBool("/sim/startup/fullscreen") ) {
278 // If enabled, normal vectors specified with glNormal are scaled
279 // to unit length after transformation. See glNormal.
280 // glEnable( GL_NORMALIZE );
282 glEnable( GL_LIGHTING );
283 glEnable( GL_LIGHT0 );
284 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
287 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
288 ssgGetLight( 0 ) -> setPosition( sunpos );
290 // glFogi (GL_FOG_MODE, GL_LINEAR);
291 glFogi (GL_FOG_MODE, GL_EXP2);
292 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
293 (!fgGetBool("/sim/rendering/shading"))) {
294 // if fastest fog requested, or if flat shading force fastest
295 glHint ( GL_FOG_HINT, GL_FASTEST );
296 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
297 glHint ( GL_FOG_HINT, GL_NICEST );
299 if ( fgGetBool("/sim/rendering/wireframe") ) {
301 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
304 // This is the default anyways, but it can't hurt
305 glFrontFace ( GL_CCW );
308 // glEnable(GL_POINT_SMOOTH);
309 // glEnable(GL_LINE_SMOOTH);
310 // glEnable(GL_POLYGON_SMOOTH);
314 // For HiRes screen Dumps using Brian Pauls TR Library
315 void trRenderFrame( void ) {
317 if ( fgPanelVisible() ) {
318 GLfloat height = fgGetInt("/sim/startup/ysize");
320 (current_panel->getViewHeight() - current_panel->getYOffset())
321 * (height / 768.0) + 1;
322 glTranslatef( 0.0, view_h, 0.0 );
325 static double m_log01 = -log( 0.01 );
326 static double sqrt_m_log01 = sqrt( m_log01 );
328 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
329 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
331 fgLIGHT *l = &cur_light_params;
333 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
334 l->adj_fog_color[2], l->adj_fog_color[3]);
336 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
338 // set the opengl state to known default values
339 default_state->force();
342 double actual_visibility = thesky->get_visibility();
343 // GLfloat fog_exp_density = m_log01 / actual_visibility;
344 GLfloat fog_exp2_density = sqrt_m_log01 / actual_visibility;
345 GLfloat fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 1.5 );
348 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
349 glFogi ( GL_FOG_MODE, GL_EXP2 );
350 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
352 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
353 // we only update GL_AMBIENT for our lights we will never get
354 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
355 // explicitely to black.
356 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
358 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
360 // texture parameters
361 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
362 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
364 // we need a white diffuse light for the phase of the moon
365 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
368 // draw the ssg scene
369 // return to the desired diffuse color
370 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
371 glEnable( GL_DEPTH_TEST );
372 ssgCullAndDraw( scene );
375 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
376 ssgCullAndDraw( lighting );
378 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
380 // need to do this here as hud_and_panel state is static to
381 // main.cxx and HUD and Panel routines have to be called with
382 // knowledge of the the TR struct < see gui.cxx::HighResDump()
383 hud_and_panel->apply();
387 // Update all Visuals (redraws anything graphics related)
388 void fgRenderFrame( void ) {
389 // Update the default (kludged) properties.
392 fgLIGHT *l = &cur_light_params;
393 static double last_visibility = -9999;
395 static GLfloat fog_exp_density;
396 static GLfloat fog_exp2_density;
397 static GLfloat fog_exp2_punch_through;
400 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
401 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
402 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
403 // GLfloat mat_shininess[] = { 10.0 };
404 GLbitfield clear_mask;
406 if ( idle_state != 1000 ) {
407 // still initializing, draw the splash screen
408 if ( fgGetBool("/sim/startup/splash-screen") ) {
412 // idle_state is now 1000 meaning we've finished all our
413 // initializations and are running the main loop, so this will
414 // now work without seg faulting the system.
416 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
417 // FG_Altitude * SG_FEET_TO_METER);
419 // this is just a temporary hack, to make me understand Pui
420 // timerText -> setLabel (ctime (&t->cur_time));
423 // calculate our current position in cartesian space
424 scenery.center = scenery.next_center;
425 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
426 // scenery.center.y(), scenery.center.z());
428 FGViewerRPH *pilot_view =
429 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
431 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
432 cur_fdm_state->get_Lat_geocentric(),
433 cur_fdm_state->get_Altitude() *
435 pilot_view->set_sea_level_radius( cur_fdm_state->
436 get_Sea_level_radius() *
438 pilot_view->set_rph( cur_fdm_state->get_Phi(),
439 cur_fdm_state->get_Theta(),
440 cur_fdm_state->get_Psi() );
442 FGViewerLookAt *chase_view =
443 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
445 sgVec3 po; // chase view pilot_offset
446 sgVec3 wup; // chase view world up
447 sgSetVec3( po, 0.0, 0.0, 100.0 );
448 sgCopyVec3( wup, pilot_view->get_world_up() );
449 sgMat4 CXFM; // chase view + pilot offset xform
451 chase_view->get_view_offset() * SGD_RADIANS_TO_DEGREES -
452 cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES,
454 sgVec3 npo; // new pilot offset after rotation
455 sgVec3 *pPO = PilotOffsetGet();
456 sgXformVec3( po, *pPO, pilot_view->get_UP() );
457 sgXformVec3( npo, po, CXFM );
459 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
460 cur_fdm_state->get_Lat_geocentric(),
461 cur_fdm_state->get_Altitude() *
463 chase_view->set_sea_level_radius( cur_fdm_state->
464 get_Sea_level_radius() *
466 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
467 chase_view->set_view_forward( pilot_view->get_view_pos() );
468 chase_view->set_view_up( wup );
472 sgCopyMat4( rph, pilot_view->get_VIEW() );
473 cout << "RPH Matrix = " << endl;
475 for ( i = 0; i < 4; i++ ) {
476 for ( j = 0; j < 4; j++ ) {
477 printf("%10.4f ", rph[i][j]);
483 sgCopyMat4( la, chase_view->get_VIEW() );
484 cout << "LookAt Matrix = " << endl;
485 for ( i = 0; i < 4; i++ ) {
486 for ( j = 0; j < 4; j++ ) {
487 printf("%10.4f ", la[i][j]);
494 fgReshape( fgGetInt("/sim/startup/xsize"),
495 fgGetInt("/sim/startup/ysize") );
500 if ( ! fgPanelVisible() ) {
502 (GLint)(fgGetInt("/sim/startup/xsize")),
503 (GLint)(fgGetInt("/sim/startup/ysize")) );
506 int( (current_panel->getViewHeight() -
507 current_panel->getYOffset())
508 * (fgGetInt("/sim/startup/ysize") / 768.0) );
510 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
511 (GLint)(fgGetInt("/sim/startup/xsize")),
516 // set the sun position
517 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
519 clear_mask = GL_DEPTH_BUFFER_BIT;
520 if ( fgGetBool("/sim/rendering/wireframe") ) {
521 clear_mask |= GL_COLOR_BUFFER_BIT;
524 if ( fgGetBool("/sim/rendering/skyblend") ) {
525 if ( fgGetBool("/sim/rendering/textures") ) {
526 // glClearColor(black[0], black[1], black[2], black[3]);
527 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
528 l->adj_fog_color[2], l->adj_fog_color[3]);
529 clear_mask |= GL_COLOR_BUFFER_BIT;
532 glClearColor(l->sky_color[0], l->sky_color[1],
533 l->sky_color[2], l->sky_color[3]);
534 clear_mask |= GL_COLOR_BUFFER_BIT;
536 glClear( clear_mask );
538 // Tell GL we are switching to model view parameters
540 // I really should create a derived ssg node or use a call
541 // back or something so that I can draw the sky within the
542 // ssgCullAndDraw() function, but for now I just mimic what
543 // ssg does to set up the model view matrix
544 glMatrixMode(GL_MODELVIEW);
546 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
548 // set the opengl state to known default values
549 default_state->force();
551 // update fog params if visibility has changed
552 #ifndef FG_OLD_WEATHER
553 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
555 thesky->set_visibility( current_weather.get_visibility() );
558 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
559 ( global_multi_loop *
560 fgGetInt("/sim/speed-up") ) /
561 (double)fgGetInt("/sim/model-hz") );
563 double actual_visibility = thesky->get_visibility();
564 // cout << "actual visibility = " << actual_visibility << endl;
566 if ( actual_visibility != last_visibility ) {
567 last_visibility = actual_visibility;
569 // cout << "----> updating fog params" << endl;
572 fog_exp_density = -log(0.01) / actual_visibility;
575 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
576 fog_exp2_punch_through = sqrt( -log(0.01) ) /
577 ( actual_visibility * 1.5 );
580 // Set correct opengl fog density
581 glFogf (GL_FOG_DENSITY, fog_exp2_density);
583 // update the sky dome
584 if ( fgGetBool("/sim/rendering/skyblend") ) {
585 /* cout << "thesky->repaint() sky_color = "
586 << cur_light_params.sky_color[0] << " "
587 << cur_light_params.sky_color[1] << " "
588 << cur_light_params.sky_color[2] << " "
589 << cur_light_params.sky_color[3] << endl;
591 << cur_light_params.fog_color[0] << " "
592 << cur_light_params.fog_color[1] << " "
593 << cur_light_params.fog_color[2] << " "
594 << cur_light_params.fog_color[3] << endl;
595 cout << " sun_angle = " << cur_light_params.sun_angle
596 << " moon_angle = " << cur_light_params.moon_angle
598 thesky->repaint( cur_light_params.sky_color,
599 cur_light_params.adj_fog_color,
600 cur_light_params.sun_angle,
601 cur_light_params.moon_angle,
602 globals->get_ephem()->getNumPlanets(),
603 globals->get_ephem()->getPlanets(),
604 globals->get_ephem()->getNumStars(),
605 globals->get_ephem()->getStars() );
607 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
608 << view_pos[1] << " " << view_pos[2] << endl;
609 cout << " zero_elev = " << zero_elev[0] << " "
610 << zero_elev[1] << " " << zero_elev[2]
611 << " lon = " << cur_fdm_state->get_Longitude()
612 << " lat = " << cur_fdm_state->get_Latitude() << endl;
613 cout << " sun_rot = " << cur_light_params.sun_rotation
614 << " gst = " << SGTime::cur_time_params->getGst() << endl;
615 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
616 << " sun dec = " << globals->get_ephem()->getSunDeclination()
617 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
618 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
620 thesky->reposition( globals->get_current_view()->get_view_pos(),
621 globals->get_current_view()->get_zero_elev(),
622 globals->get_current_view()->get_world_up(),
623 cur_fdm_state->get_Longitude(),
624 cur_fdm_state->get_Latitude(),
625 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
626 cur_light_params.sun_rotation,
627 globals->get_time_params()->getGst(),
628 globals->get_ephem()->getSunRightAscension(),
629 globals->get_ephem()->getSunDeclination(),
631 globals->get_ephem()->getMoonRightAscension(),
632 globals->get_ephem()->getMoonDeclination(),
636 glEnable( GL_DEPTH_TEST );
637 if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
639 glFogi( GL_FOG_MODE, GL_EXP2 );
640 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
643 // set sun/lighting parameters
644 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
646 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
647 // we only update GL_AMBIENT for our lights we will never get
648 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
649 // explicitely to black.
650 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
651 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
652 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
654 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
655 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
656 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
658 // texture parameters
659 // glEnable( GL_TEXTURE_2D );
660 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
661 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
663 // glMatrixMode( GL_PROJECTION );
665 float fov = globals->get_current_view()->get_fov();
666 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
668 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
671 // SG_LOG( SG_ALL, SG_INFO, "visibility is "
672 // << current_weather.get_visibility() );
675 ssgSetNearFar( 10.0f, 120000.0f );
677 ssgSetNearFar( 0.5f, 120000.0f );
680 if ( globals->get_viewmgr()->get_current() == 0 ) {
681 // disable aircraft model
682 acmodel_selector->select(0);
684 // enable aircraft model and set up its position and orientation
685 acmodel_selector->select(1);
687 FGViewerRPH *pilot_view =
688 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
691 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
694 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
697 sgMakeRotMat4( sgROT, -90.0, ownship_up );
701 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
702 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
704 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
706 sgCopyMat4( sgTUX, sgROT );
707 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
708 sgPostMultMat4( sgTUX, sgTRANS );
711 sgSetCoord( &tuxpos, sgTUX );
712 acmodel_pos->setTransform( &tuxpos );
714 // set up moving parts
715 if (flaps_selector != NULL) {
716 flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
719 if (prop_selector != NULL) {
720 int propsel_mask = 0;
721 double rpm = fgGetDouble("/engines/engine0/rpm");
722 for (int i = 0; i < acmodel_npropsettings; i++) {
723 if (rpm >= acmodel_proprpms[i][0] &&
724 rpm <= acmodel_proprpms[i][1]) {
725 propsel_mask |= 1 << i;
728 prop_selector->select(propsel_mask);
732 // $$$ begin - added VS Renganthan 17 Oct 2K
734 // $$$ end - added VS Renganthan 17 Oct 2K
736 # ifdef FG_NETWORK_OLK
737 if ( fgGetBool("/sim/networking/network-olk") ) {
739 other = head->next; /* put listpointer to start */
740 while ( other != tail) { /* display all except myself */
741 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
742 other->fgd_sel->select(1);
743 sgSetCoord( &fgdpos, other->sgFGD_COORD );
744 other->fgd_pos->setTransform( &fgdpos );
749 // fgd_sel->select(1);
750 // sgCopyMat4( sgTUX, current_view.sgVIEW);
752 // sgSetCoord( &fgdpos, sgFGD_VIEW );
753 // fgd_pos->setTransform( &fgdpos);
757 // position tile nodes and update range selectors
758 global_tile_mgr.prep_ssg_nodes();
760 if ( fgGetBool("/sim/rendering/skyblend") ) {
761 // draw the sky backdrop
763 // we need a white diffuse light for the phase of the moon
764 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
768 // return to the desired diffuse color
769 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
772 // draw the ssg scene
773 glEnable( GL_DEPTH_TEST );
774 ssgCullAndDraw( scene );
776 // change state for lighting here
779 // Set punch through fog density
780 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
782 ssgCullAndDraw( lighting );
784 if ( fgGetBool("/sim/rendering/skyblend") ) {
785 // draw the sky cloud layers
786 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
789 // display HUD && Panel
791 glDisable( GL_DEPTH_TEST );
792 // glDisable( GL_CULL_FACE );
793 // glDisable( GL_TEXTURE_2D );
795 // update the input subsystem
796 current_input.update();
798 // update the controls subsystem
801 hud_and_panel->apply();
804 // update the panel subsystem
805 if (current_panel != 0)
806 current_panel->update();
808 // We can do translucent menus, so why not. :-)
810 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
812 // glDisable ( GL_BLEND ) ;
814 // glEnable( GL_FOG );
821 // Update internal time dependent calculations (i.e. flight model)
822 void fgUpdateTimeDepCalcs() {
823 static bool inited = false;
825 fgLIGHT *l = &cur_light_params;
830 if ( !globals->get_freeze() && !initial_freeze ) {
831 // conceptually, this could be done for each fdm instance ...
834 cur_fdm_state->stamp();
840 long elapsed = current - cur_fdm_state->get_time_stamp();
841 cur_fdm_state->set_time_stamp( current );
842 elapsed += cur_fdm_state->get_remainder();
843 // cout << "elapsed = " << elapsed << endl;
844 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
845 multi_loop = (long)(((double)elapsed * 0.000001) /
846 cur_fdm_state->get_delta_t() );
847 cur_fdm_state->set_multi_loop( multi_loop );
848 long remainder = elapsed - (long)( (multi_loop*1000000) *
849 cur_fdm_state->get_delta_t() );
850 cur_fdm_state->set_remainder( remainder );
851 // cout << "remainder = " << remainder << endl;
853 // chop max interations to something reasonable if the sim was
854 // delayed for an excesive amount of time
855 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
856 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
857 cur_fdm_state->set_remainder( 0 );
860 // cout << "multi_loop = " << multi_loop << endl;
861 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
862 // run Autopilot system
863 current_autopilot->run();
866 cur_fdm_state->update( 1 );
868 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
870 cur_fdm_state->update( 0 );
871 FGSteam::update( 0 );
873 //if ( global_tile_mgr.queue_size() == 0 ) {
874 initial_freeze = false;
878 if ( fgGetString("/sim/view-mode") == "pilot" ) {
879 cur_view_fdm = *cur_fdm_state;
883 // update the view angle
884 FGViewer *v = globals->get_current_view();
885 for ( i = 0; i < multi_loop; i++ ) {
886 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
887 v->set_view_offset( v->get_goal_view_offset() );
890 // move current_view.view_offset towards
891 // current_view.goal_view_offset
892 if ( v->get_goal_view_offset() > v->get_view_offset() )
894 if ( v->get_goal_view_offset() - v->get_view_offset() < SGD_PI ){
895 v->inc_view_offset( 0.01 );
897 v->inc_view_offset( -0.01 );
900 if ( v->get_view_offset() - v->get_goal_view_offset() < SGD_PI ){
901 v->inc_view_offset( -0.01 );
903 v->inc_view_offset( 0.01 );
906 if ( v->get_view_offset() > SGD_2PI ) {
907 v->inc_view_offset( -SGD_2PI );
908 } else if ( v->get_view_offset() < 0 ) {
909 v->inc_view_offset( SGD_2PI );
914 double tmp = -(l->sun_rotation + SGD_PI)
915 - (cur_fdm_state->get_Psi() -
916 globals->get_current_view()->get_view_offset() );
917 while ( tmp < 0.0 ) {
920 while ( tmp > SGD_2PI ) {
923 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
924 FG_Psi * SGD_RADIANS_TO_DEGREES, current_view.view_offset * SGD_RADIANS_TO_DEGREES,
925 -(l->sun_rotation+SGD_PI) * SGD_RADIANS_TO_DEGREES, tmp * SGD_RADIANS_TO_DEGREES); */
928 // Update solar system
929 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
930 globals->get_time_params()->getLst(),
931 cur_fdm_state->get_Latitude() );
933 // Update radio stack model
934 current_radiostack->update();
938 void fgInitTimeDepCalcs( void ) {
941 // #ifdef HAVE_SETITIMER
942 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
943 // fgUpdateTimeDepCalcs );
944 // #endif HAVE_SETITIMER
948 static const double alt_adjust_ft = 3.758099;
949 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
952 // What should we do when we have nothing else to do? Let's get ready
953 // for the next move and update the display?
954 static void fgMainLoop( void ) {
955 static long remainder = 0;
957 #ifdef FANCY_FRAME_COUNTER
961 static time_t last_time = 0;
962 static int frames = 0;
963 #endif // FANCY_FRAME_COUNTER
965 SGTime *t = globals->get_time_params();
967 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
968 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
970 #ifdef FG_NETWORK_OLK
971 if ( fgGetBool("/sim/networking/network-olk") ) {
972 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
973 // printf("FGD: Netupdate\n");
974 fgd_send_com( "A", FGFS_host); // Send Mat4 data
975 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
980 #if defined( ENABLE_PLIB_JOYSTICK )
981 // Read joystick and update control settings
982 // if ( fgGetString("/sim/control-mode") == "joystick" )
986 #elif defined( ENABLE_GLUT_JOYSTICK )
987 // Glut joystick support works by feeding a joystick handler
988 // function to glut. This is taken care of once in the joystick
989 // init routine and we don't have to worry about it again.
992 #ifdef FG_OLD_WEATHER
993 current_weather.Update();
996 // Fix elevation. I'm just sticking this here for now, it should
997 // probably move eventually
999 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1001 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1002 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1004 if ( scenery.cur_elev > -9990 ) {
1005 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
1006 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
1007 // now set aircraft altitude above ground
1008 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
1009 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1010 scenery.cur_elev + alt_adjust_m - 3.0,
1011 scenery.cur_elev + alt_adjust_m );
1012 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
1013 scenery.cur_elev + alt_adjust_m );
1015 SG_LOG( SG_ALL, SG_DEBUG,
1016 "<*> resetting altitude to "
1017 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1022 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1024 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1025 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1028 if ( globals->get_warp_delta() != 0 ) {
1029 globals->inc_warp( globals->get_warp_delta() );
1032 t->update( cur_fdm_state->get_Longitude(),
1033 cur_fdm_state->get_Latitude(),
1034 globals->get_warp() );
1036 if ( globals->get_warp_delta() != 0 ) {
1037 fgUpdateSkyAndLightingParams();
1040 // update magvar model
1041 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
1042 cur_fdm_state->get_Latitude(),
1043 cur_fdm_state->get_Altitude()* SG_FEET_TO_METER,
1044 globals->get_time_params()->getJD() );
1046 // Get elapsed time (in usec) for this past frame
1047 elapsed = fgGetTimeInterval();
1048 SG_LOG( SG_ALL, SG_DEBUG,
1049 "Elapsed time interval is = " << elapsed
1050 << ", previous remainder is = " << remainder );
1052 // Calculate frame rate average
1053 #ifdef FANCY_FRAME_COUNTER
1054 /* old fps calculation */
1055 if ( elapsed > 0 ) {
1058 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1059 tmp = general.get_frame(i);
1061 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1062 general.set_frame(i+1,tmp);
1064 tmp = 1000000.0 / (float)elapsed;
1065 general.set_frame(0,tmp);
1066 // printf("frame[0] = %.2f\n", general.frames[0]);
1068 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1069 // printf("ave = %.2f\n", general.frame_rate);
1072 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1073 general.set_frame_rate( frames );
1074 SG_LOG( SG_ALL, SG_DEBUG,
1075 "--> Frame rate is = " << general.get_frame_rate() );
1078 last_time = t->get_cur_time();
1084 // Calculate model iterations needed for next frame
1085 elapsed += remainder;
1087 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1088 fgGetInt("/sim/model-hz"));
1089 remainder = elapsed - ( (global_multi_loop*1000000) /
1090 fgGetInt("/sim/model-hz") );
1091 SG_LOG( SG_ALL, SG_DEBUG,
1092 "Model iterations needed = " << global_multi_loop
1093 << ", new remainder = " << remainder );
1095 // chop max interations to something reasonable if the sim was
1096 // delayed for an excesive amount of time
1097 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1098 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1103 if ( global_multi_loop > 0 ) {
1104 fgUpdateTimeDepCalcs();
1106 SG_LOG( SG_ALL, SG_DEBUG,
1107 "Elapsed time is zero ... we're zinging" );
1110 #if ! defined( macintosh )
1111 // Do any I/O channel work that might need to be done
1115 // see if we need to load any new scenery tiles
1116 global_tile_mgr.update( cur_fdm_state->get_Longitude()
1117 * SGD_RADIANS_TO_DEGREES,
1118 cur_fdm_state->get_Latitude()
1119 * SGD_RADIANS_TO_DEGREES );
1121 // see if we need to load any deferred-load textures
1122 material_lib.load_next_deferred();
1124 // Process/manage pending events
1125 global_events.Process();
1127 // Run audio scheduler
1128 #ifdef ENABLE_AUDIO_SUPPORT
1129 if ( fgGetBool("/sim/sound") && globals->get_soundmgr()->is_working() ) {
1130 if ( fgGetString("/sim/aircraft") == "c172" ) {
1131 // pitch corresponds to rpm
1132 // volume corresponds to manifold pressure
1134 // cout << "AUDIO working = "
1135 // << globals->get_soundmgr()->is_working() << endl;
1138 if ( cur_fdm_state->get_engine(0) != NULL ) {
1139 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1143 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1146 double pitch = 0.3 + rpm_factor * 3.0;
1148 // don't run at absurdly slow rates -- not realistic
1149 // and sounds bad to boot. :-)
1150 if (pitch < 0.7) { pitch = 0.7; }
1151 if (pitch > 5.0) { pitch = 5.0; }
1154 if ( cur_fdm_state->get_engine(0) != NULL ) {
1156 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1161 << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1164 double volume = 0.15 + mp_factor / 2.0;
1166 if ( volume < 0.15 ) { volume = 0.15; }
1167 if ( volume > 0.5 ) { volume = 0.5; }
1168 // cout << "volume = " << volume << endl;
1170 s1->set_pitch( pitch );
1171 s1->set_volume( volume );
1173 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1174 s1->set_pitch( param );
1175 s1->set_volume( param );
1178 globals->get_soundmgr()->update();
1185 SG_LOG( SG_ALL, SG_DEBUG, "" );
1189 // This is the top level master main function that is registered as
1190 // our idle funciton
1193 // The first few passes take care of initialization things (a couple
1194 // per pass) and once everything has been initialized fgMainLoop from
1197 static void fgIdleFunction ( void ) {
1198 // printf("idle state == %d\n", idle_state);
1200 if ( idle_state == 0 ) {
1201 // Initialize the splash screen right away
1202 if ( fgGetBool("/sim/startup/splash-screen") ) {
1207 } else if ( idle_state == 1 ) {
1208 // Start the intro music
1210 if ( fgGetBool("/sim/startup/intro-music") ) {
1211 string lockfile = "/tmp/mpg123.running";
1212 SGPath mp3file( globals->get_fg_root() );
1213 mp3file.append( "Sounds/intro.mp3" );
1215 string command = "(touch " + lockfile + "; mpg123 "
1216 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1218 SG_LOG( SG_GENERAL, SG_INFO,
1219 "Starting intro music: " << mp3file.str() );
1220 system ( command.c_str() );
1225 } else if ( idle_state == 2 ) {
1226 // These are a few miscellaneous things that aren't really
1227 // "subsystems" but still need to be initialized.
1230 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1231 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1236 } else if ( idle_state == 3 ) {
1237 // This is the top level init routine which calls all the
1238 // other subsystem initialization routines. If you are adding
1239 // a subsystem to flightgear, its initialization call should
1240 // located in this routine.
1241 if( !fgInitSubsystems()) {
1242 SG_LOG( SG_GENERAL, SG_ALERT,
1243 "Subsystem initializations failed ..." );
1248 } else if ( idle_state == 4 ) {
1249 // setup OpenGL view parameters
1253 } else if ( idle_state == 5 ) {
1256 } else if ( idle_state == 6 ) {
1257 // Initialize audio support
1258 #ifdef ENABLE_AUDIO_SUPPORT
1261 if ( fgGetBool("/sim/startup/intro-music") ) {
1262 // Let's wait for mpg123 to finish
1263 string lockfile = "/tmp/mpg123.running";
1264 struct stat stat_buf;
1266 SG_LOG( SG_GENERAL, SG_INFO,
1267 "Waiting for mpg123 player to finish ..." );
1268 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1269 // file exist, wait ...
1271 SG_LOG( SG_GENERAL, SG_INFO, ".");
1273 SG_LOG( SG_GENERAL, SG_INFO, "");
1277 if ( fgGetBool("/sim/sound") ) {
1278 globals->get_soundmgr()->init();
1280 s1 = new FGSimpleSound( fgGetString("/sim/sounds/engine",
1281 "Sounds/wasp.wav") );
1282 globals->get_soundmgr()->add( s1, "engine loop" );
1283 globals->get_soundmgr()->play_looped( "engine loop" );
1284 SG_LOG( SG_GENERAL, SG_INFO,
1285 "Rate = " << s1->get_sample()->getRate()
1286 << " Bps = " << s1->get_sample()->getBps()
1287 << " Stereo = " << s1->get_sample()->getStereo() );
1289 s2 = new FGSimpleSound( "Sounds/corflaps.wav" );
1292 // s2 = mmm.make_ident( "JLI" );
1293 s2->set_volume( 0.3 );
1294 globals->get_soundmgr()->add( s2, "flaps" );
1301 cout << "Panel visible = " << fgPanelVisible() << endl;
1302 fgReshape( fgGetInt("/sim/startup/xsize"),
1303 fgGetInt("/sim/startup/ysize") );
1306 if ( idle_state == 1000 ) {
1307 // We've finished all our initialization steps, from now on we
1308 // run the main loop.
1312 if ( fgGetBool("/sim/startup/splash-screen") ) {
1313 fgSplashUpdate(0.0);
1318 // options.cxx needs to see this for toggle_panel()
1319 // Handle new window size or exposure
1320 void fgReshape( int width, int height ) {
1322 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1323 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1324 globals->get_viewmgr()->get_view(i)->
1325 set_win_ratio( (float)height / (float)width );
1328 int((current_panel->getViewHeight() -
1329 current_panel->getYOffset())
1330 * (height / 768.0)) + 1;
1331 globals->get_viewmgr()->get_view(i)->
1332 set_win_ratio( (float)view_h / (float)width );
1336 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1337 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1340 int((current_panel->getViewHeight() - current_panel->getYOffset())
1341 * (height / 768.0)) + 1;
1342 glViewport(0, (GLint)(height - view_h),
1343 (GLint)(width), (GLint)(view_h) );
1346 fgSetInt("/sim/startup/xsize", width);
1347 fgSetInt("/sim/startup/ysize", height);
1349 float fov = globals->get_current_view()->get_fov();
1350 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1356 // Initialize GLUT and define a main window
1357 int fgGlutInit( int *argc, char **argv ) {
1359 #if !defined( macintosh )
1360 // GLUT will extract all glut specific options so later on we only
1361 // need wory about our own.
1362 glutInit(argc, argv);
1365 // Define Display Parameters
1366 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1368 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1369 fgGetInt("/sim/startup/xsize") << "x"
1370 << fgGetInt("/sim/startup/ysize") );
1372 // Define initial window size
1373 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1374 fgGetInt("/sim/startup/ysize") );
1376 // Initialize windows
1377 if ( !fgGetBool("/sim/startup/game-mode")) {
1378 // Open the regular window
1379 glutCreateWindow("FlightGear");
1380 #ifndef GLUT_WRONG_VERSION
1382 // Open the cool new 'game mode' window
1383 char game_mode_str[256];
1384 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1385 fgGetInt("/sim/startup/xsize"),
1386 fgGetInt("/sim/startup/ysize"),
1387 fgGetInt("/sim/rendering/bits-per-pixel"));
1389 SG_LOG( SG_GENERAL, SG_INFO,
1390 "game mode params = " << game_mode_str );
1391 glutGameModeString( game_mode_str );
1392 glutEnterGameMode();
1396 // This seems to be the absolute earliest in the init sequence
1397 // that these calls will return valid info. Too bad it's after
1398 // we've already created and sized out window. :-(
1399 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1400 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1401 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1402 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1405 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1406 general.set_glMaxTexSize( tmp );
1407 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1409 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1410 general.set_glDepthBits( tmp );
1411 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1417 // Initialize GLUT event handlers
1418 int fgGlutInitEvents( void ) {
1419 // call fgReshape() on window resizes
1420 glutReshapeFunc( fgReshape );
1422 // call GLUTkey() on keyboard event
1423 glutKeyboardFunc(GLUTkey);
1424 glutKeyboardUpFunc(GLUTkeyup);
1425 glutSpecialFunc(GLUTspecialkey);
1426 glutSpecialUpFunc(GLUTspecialkeyup);
1428 // call guiMouseFunc() whenever our little rodent is used
1429 glutMouseFunc ( guiMouseFunc );
1430 glutMotionFunc (guiMotionFunc );
1431 glutPassiveMotionFunc (guiMotionFunc );
1433 // call fgMainLoop() whenever there is
1434 // nothing else to do
1435 glutIdleFunc( fgIdleFunction );
1438 glutDisplayFunc( fgRenderFrame );
1445 int main( int argc, char **argv ) {
1447 #if defined( macintosh )
1448 freopen ("stdout.txt", "w", stdout );
1449 freopen ("stderr.txt", "w", stderr );
1450 argc = ccommand( &argv );
1454 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1457 // set default log levels
1458 sglog().setLogLevels( SG_ALL, SG_INFO );
1461 #ifdef FLIGHTGEAR_VERSION
1462 version = FLIGHTGEAR_VERSION;
1464 version = "unknown version";
1466 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1467 << version << endl );
1469 // Allocate global data structures. This needs to happen before
1470 // we parse command line options
1472 globals = new FGGlobals;
1474 // seed the random number generater
1477 SGRoute *route = new SGRoute;
1478 globals->set_route( route );
1480 #ifdef ENABLE_AUDIO_SUPPORT
1481 FGSoundMgr *soundmgr = new FGSoundMgr;
1482 globals->set_soundmgr( soundmgr );
1485 FGViewMgr *viewmgr = new FGViewMgr;
1486 globals->set_viewmgr( viewmgr );
1488 FGViewerRPH *pv = new FGViewerRPH;
1489 globals->get_viewmgr()->add_view( pv );
1491 FGViewerLookAt *chase = new FGViewerLookAt;
1492 globals->get_viewmgr()->add_view( chase );
1494 string_list *col = new string_list;
1495 globals->set_channel_options_list( col );
1497 // set current view to 0 (first) which is our main pilot view
1498 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1500 // Scan the config file(s) and command line options to see if
1501 // fg_root was specified (ignore all other options for now)
1502 fgInitFGRoot(argc, argv);
1504 // Initialize the Aircraft directory to "" (UIUC)
1507 // Load the configuration parameters
1508 if ( !fgInitConfig(argc, argv) ) {
1509 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1513 // Initialize the Window/Graphics environment.
1514 if( !fgGlutInit(&argc, argv) ) {
1515 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1519 // Initialize the various GLUT Event Handlers.
1520 if( !fgGlutInitEvents() ) {
1521 SG_LOG( SG_GENERAL, SG_ALERT,
1522 "GLUT event handler initialization failed ..." );
1526 // Initialize ssg (from plib). Needs to come before we do any
1527 // other ssg stuff, but after opengl/glut has been initialized.
1530 // Initialize the user interface (we need to do this before
1531 // passing off control to glut and before fgInitGeneral to get our
1535 #ifdef GL_EXT_texture_lod_bias
1536 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1540 #ifdef GL_EXT_texture_filter_anisotropic
1541 float max_anisotropy;
1542 glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy );
1543 glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1545 cout << "Max anisotropy = " << max_anisotropy << endl;
1549 // set current_options lon/lat if an airport id is specified
1550 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1551 if ( fgGetString("/sim/startup/airport-id").length() ) {
1552 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1553 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1554 fgGetDouble("/orientation/heading") );
1558 SGPath zone( globals->get_fg_root() );
1559 zone.append( "Timezone" );
1560 SGTime *t = new SGTime( fgGetDouble("/position/longitude") * SGD_DEGREES_TO_RADIANS,
1561 fgGetDouble("/position/latitude") * SGD_DEGREES_TO_RADIANS,
1564 // Handle potential user specified time offsets
1565 time_t cur_time = t->get_cur_time();
1566 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1567 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1568 time_t aircraftLocalTime =
1569 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1571 // Okay, we now have six possible scenarios
1572 int offset = fgGetInt("/sim/startup/time-offset");
1573 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1574 if (offset_type == "system-offset") {
1575 globals->set_warp( offset );
1576 } else if (offset_type == "gmt-offset") {
1577 globals->set_warp( offset - (currGMT - systemLocalTime) );
1578 } else if (offset_type == "latitude-offset") {
1579 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1580 } else if (offset_type == "system") {
1581 globals->set_warp( offset - cur_time );
1582 } else if (offset_type == "gmt") {
1583 globals->set_warp( offset - currGMT );
1584 } else if (offset_type == "latitude") {
1585 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1588 SG_LOG( SG_GENERAL, SG_ALERT,
1589 "Unsupported offset type " << offset_type );
1593 SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = "
1594 << globals->get_warp() );
1596 globals->set_warp_delta( 0 );
1598 t->update( 0.0, 0.0, globals->get_warp() );
1600 globals->set_time_params( t );
1602 // Do some quick general initializations
1603 if( !fgInitGeneral()) {
1604 SG_LOG( SG_GENERAL, SG_ALERT,
1605 "General initializations failed ..." );
1609 SGPath modelpath( globals->get_fg_root() );
1610 ssgModelPath( (char *)modelpath.c_str() );
1613 scene = new ssgRoot;
1614 scene->setName( "Scene" );
1616 lighting = new ssgRoot;
1617 lighting->setName( "Lighting" );
1619 // Initialize the sky
1620 SGPath ephem_data_path( globals->get_fg_root() );
1621 ephem_data_path.append( "Astro" );
1622 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1623 ephem->update( globals->get_time_params()->getMjd(),
1624 globals->get_time_params()->getLst(),
1626 globals->set_ephem( ephem );
1630 SGPath sky_tex_path( globals->get_fg_root() );
1631 sky_tex_path.append( "Textures" );
1632 sky_tex_path.append( "Sky" );
1633 thesky->texture_path( sky_tex_path.str() );
1635 thesky->build( 550.0, 550.0,
1636 globals->get_ephem()->getNumPlanets(),
1637 globals->get_ephem()->getPlanets(), 60000.0,
1638 globals->get_ephem()->getNumStars(),
1639 globals->get_ephem()->getStars(), 60000.0 );
1641 if ( fgGetBool("/environment/clouds/status") ) {
1642 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1643 // SG_CLOUD_OVERCAST );
1644 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1645 SG_CLOUD_MOSTLY_CLOUDY );
1646 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1647 // SG_CLOUD_MOSTLY_SUNNY );
1648 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1652 // Initialize MagVar model
1653 SGMagVar *magvar = new SGMagVar();
1654 globals->set_mag( magvar );
1657 terrain = new ssgBranch;
1658 terrain->setName( "Terrain" );
1659 scene->addKid( terrain );
1662 ground = new ssgBranch;
1663 ground->setName( "Ground Lighting" );
1664 lighting->addKid( ground );
1666 airport = new ssgBranch;
1667 airport->setName( "Airport Lighting" );
1668 lighting->addKid( airport );
1670 // temporary visible aircraft "own ship"
1671 acmodel_selector = new ssgSelector;
1672 acmodel_pos = new ssgTransform;
1674 // Get the model location, and load textures from the same
1675 // directory. Use an absolute path for the model to avoid
1676 // incompatibilities in different versions of PLIB.
1677 string acmodel_path =
1678 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1679 SGPath full_model = globals->get_fg_root();
1680 full_model.append(acmodel_path);
1682 #if !defined( PLIB_1_2_X )
1683 // this should be redundant ... but it breaks for relative paths
1684 // ssgModelPath( (char *)full_model.dir().c_str() );
1687 ssgTexturePath( (char *)full_model.dir().c_str() );
1688 ssgEntity *acmodel_obj = ssgLoad( (char *)full_model.c_str() );
1689 if( !acmodel_obj ) {
1690 // fall back to default
1691 acmodel_obj = ssgLoad( (char *)"Models/Geometry/glider.ac" );
1692 if( !acmodel_obj ) {
1693 SG_LOG( SG_GENERAL, SG_ALERT, "FAILED to LOAD an AC model! ..." );
1698 // find moving parts (if this is an MDL model)
1699 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1700 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1702 acmodel_npropsettings = 0;
1703 if (prop_selector != NULL) {
1704 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1705 kid = prop_selector->getNextKid()) {
1706 int prop_low, prop_high;
1707 if ( sscanf(kid->getName(), "PROP_%d_%d",
1708 &prop_low, &prop_high) == 2 ) {
1709 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1710 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1711 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1712 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1713 acmodel_npropsettings++;
1715 SG_LOG( SG_GENERAL, SG_INFO, "PROPELLER SETTING " << prop_low <<
1721 // align the model properly for FGFS
1722 ssgTransform *acmodel_align = new ssgTransform;
1723 acmodel_align->addKid(acmodel_obj);
1727 float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1728 float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1729 float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1730 float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1731 float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1732 float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1733 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1734 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1735 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1736 acmodel_align->setTransform(res_matrix);
1738 acmodel_pos->addKid( acmodel_align );
1739 acmodel_selector->addKid( acmodel_pos );
1740 //ssgFlatten( acmodel_obj );
1741 //ssgStripify( acmodel_selector );
1742 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1743 scene->addKid( acmodel_selector );
1745 // $$$ begin - added VS Renganthan 17 Oct 2K
1747 // $$$ end - added VS Renganthan 17 Oct 2K
1749 #ifdef FG_NETWORK_OLK
1750 // Do the network intialization
1751 if ( fgGetBool("/sim/networking/network-olk") ) {
1752 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1756 // build our custom render states
1757 fgBuildRenderStates();
1759 // pass control off to the master GLUT event handler
1762 // we never actually get here ... but to avoid compiler warnings,
1768 // $$$ end - added VS Renganathan, 15 Oct 2K
1769 // - added Venky , 12 Nov 2K
1771 void fgLoadDCS(void) {
1773 ssgEntity *ship_obj = NULL;
1776 char obj_filename[25];
1778 for ( int k = 0; k < 32; k++ ) {
1782 SGPath tile_path( globals->get_fg_root());
1783 tile_path.append( "Scenery" );
1784 tile_path.append( "Objects.txt" );
1785 sg_gzifstream in( tile_path.str() );
1786 if ( ! in.is_open() ) {
1787 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1790 SGPath modelpath( globals->get_fg_root() );
1791 modelpath.append( "Models" );
1792 modelpath.append( "Geometry" );
1794 SGPath texturepath( globals->get_fg_root() );
1795 texturepath.append( "Models" );
1796 texturepath.append( "Textures" );
1798 ssgModelPath( (char *)modelpath.c_str() );
1799 ssgTexturePath( (char *)texturepath.c_str() );
1801 ship_sel = new ssgSelector;
1804 while ( ! in.eof() ) {
1806 if ( in.get( c ) && c == '#' ) {
1810 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1811 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1812 int chj=getchar();*/
1814 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1815 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1817 ship_pos[objc] = new ssgTransform;
1819 // type "repeat" in objects.txt to load one more
1820 // instance of the last object.
1822 if ( strcmp(obj_filename,"repeat") != 0) {
1823 ship_obj = ssgLoadOBJ( obj_filename );
1826 if ( ship_obj != NULL ) {
1827 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1828 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1830 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1836 if (in.eof()) break;
1840 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1842 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1843 scene->addKid( ship_sel ); //add selector node to root node
1850 void fgUpdateDCS (void) {
1852 // double eye_lat,eye_lon,eye_alt;
1853 // static double obj_head;
1854 double sl_radius,obj_latgc;
1855 // float nresultmat[4][4];
1856 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1859 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1860 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1862 // Deck should be the first object in objects.txt in case of fdm=ada
1864 if (fgGetString("/sim/flight-model") == "ada") {
1865 obj_lon[0] = fdm->get_aux5()*SGD_DEGREES_TO_RADIANS;
1866 obj_lat[0] = fdm->get_aux6()*SGD_DEGREES_TO_RADIANS;
1867 obj_alt[0] = fdm->get_aux7();
1870 for ( int m = 0; m < objc; m++ ) {
1871 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1874 //Geodetic to Geocentric angles for rotation
1875 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1877 //moving object gbs-posn in cartesian coords
1878 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1879 Point3D obj_pos = sgGeodToCart( obj_posn );
1881 // Translate moving object w.r.t eye
1882 Point3D Objtrans = obj_pos-scenery.center;
1887 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1890 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1892 sgVec3 ship_fwd,ship_rt,ship_up;
1893 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1894 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1895 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1897 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1898 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1899 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1900 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1903 sgCopyMat4( sgTUX, sgROT_hdg );
1904 sgPostMultMat4( sgTUX, sgROT_lat );
1905 sgPostMultMat4( sgTUX, sgROT_lon );
1906 sgPostMultMat4( sgTUX, sgTRANS );
1909 sgSetCoord(&shippos, sgTUX );
1910 ship_pos[m]->setTransform( &shippos );
1912 if ( ship_sel != NULL ) {
1913 ship_sel->select(0xFFFFFFFF);
1917 // $$$ end - added VS Renganathan, 15 Oct 2K
1918 // added Venky , 12 Nov 2K