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>
127 #include "fg_init.hxx"
129 #include "globals.hxx"
130 #include "keyboard.hxx"
131 #include "splash.hxx"
134 # include <console.h> // -dw- for command line dialog
138 // This is a record containing a bit of global housekeeping information
141 // Specify our current idle function state. This is used to run all
142 // our initializations out of the glutIdleLoop() so that we can get a
143 // splash screen up and running right away.
144 static int idle_state = 0;
145 static long global_multi_loop;
147 // attempt to avoid a large bounce at startup
148 static bool initial_freeze = true;
150 // forward declaration
151 void fgReshape( int width, int height );
153 // Global structures for the Audio library
154 #ifdef ENABLE_AUDIO_SUPPORT
155 static FGSimpleSound *s1;
156 static FGSimpleSound *s2;
161 ssgRoot *scene = NULL;
162 ssgBranch *terrain = NULL;
164 // aircraft model stuff
165 ssgSelector *acmodel_selector = NULL;
166 ssgTransform *acmodel_pos = NULL;
167 ssgSelector *prop_selector = NULL;
168 ssgSelector *flaps_selector = NULL;
169 int acmodel_npropsettings;
170 int acmodel_proprpms[4][2]; // different propeller settings
172 ssgRoot *lighting = NULL;
173 ssgBranch *ground = NULL;
174 ssgBranch *airport = NULL;
176 #ifdef FG_NETWORK_OLK
177 ssgSelector *fgd_sel = NULL;
178 ssgTransform *fgd_pos = NULL;
181 // current fdm/position used for view
182 FGInterface cur_view_fdm;
188 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
190 { 1.0f, 0.0f, 0.0f, 0.0f },
191 { 0.0f, 0.0f, -1.0f, 0.0f },
192 { 0.0f, 1.0f, 0.0f, 0.0f },
193 { 0.0f, 0.0f, 0.0f, 1.0f }
196 // The following defines flightgear options. Because glutlib will also
197 // want to parse its own options, those options must not be included here
198 // or they will get parsed by the main program option parser. Hence case
199 // is significant for any option added that might be in conflict with
202 // glutlib parses for:
204 // -direct (invalid in Win32)
208 // -indirect (invalid in Win32)
211 // Note that glutlib depends upon strings while this program's
212 // option parser wants only initial characters followed by numbers
217 ssgSimpleState *default_state;
218 ssgSimpleState *hud_and_panel;
219 ssgSimpleState *menus;
221 void fgBuildRenderStates( void ) {
222 default_state = new ssgSimpleState;
223 default_state->ref();
224 default_state->disable( GL_TEXTURE_2D );
225 default_state->enable( GL_CULL_FACE );
226 default_state->enable( GL_COLOR_MATERIAL );
227 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
228 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
229 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
230 default_state->disable( GL_BLEND );
231 default_state->disable( GL_ALPHA_TEST );
232 default_state->disable( GL_LIGHTING );
234 hud_and_panel = new ssgSimpleState;
235 hud_and_panel->ref();
236 hud_and_panel->disable( GL_CULL_FACE );
237 hud_and_panel->disable( GL_TEXTURE_2D );
238 hud_and_panel->disable( GL_LIGHTING );
239 hud_and_panel->enable( GL_BLEND );
241 menus = new ssgSimpleState;
243 menus->disable( GL_CULL_FACE );
244 menus->disable( GL_TEXTURE_2D );
245 menus->enable( GL_BLEND );
248 // fgFindNode -- a function that finds a named node in an ssg graph
249 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
250 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
252 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
253 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
254 while (kid != NULL) {
255 ssgEntity *n = fgFindNode(kid, name);
259 kid = ((ssgBranch*)node)->getNextKid();
266 // fgInitVisuals() -- Initialize various GL/view parameters
267 void fgInitVisuals( void ) {
270 l = &cur_light_params;
272 #ifndef GLUT_WRONG_VERSION
273 // Go full screen if requested ...
274 if ( fgGetBool("/sim/startup/fullscreen") ) {
279 // If enabled, normal vectors specified with glNormal are scaled
280 // to unit length after transformation. See glNormal.
281 // glEnable( GL_NORMALIZE );
283 glEnable( GL_LIGHTING );
284 glEnable( GL_LIGHT0 );
285 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
288 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
289 ssgGetLight( 0 ) -> setPosition( sunpos );
291 // glFogi (GL_FOG_MODE, GL_LINEAR);
292 glFogi (GL_FOG_MODE, GL_EXP2);
293 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
294 (!fgGetBool("/sim/rendering/shading"))) {
295 // if fastest fog requested, or if flat shading force fastest
296 glHint ( GL_FOG_HINT, GL_FASTEST );
297 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
298 glHint ( GL_FOG_HINT, GL_NICEST );
300 if ( fgGetBool("/sim/rendering/wireframe") ) {
302 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
305 // This is the default anyways, but it can't hurt
306 glFrontFace ( GL_CCW );
309 // glEnable(GL_POINT_SMOOTH);
310 // glEnable(GL_LINE_SMOOTH);
311 // glEnable(GL_POLYGON_SMOOTH);
315 // Update all Visuals (redraws anything graphics related)
316 void fgRenderFrame( void ) {
320 fgLIGHT *l = &cur_light_params;
321 static double last_visibility = -9999;
323 static GLfloat fog_exp_density;
324 static GLfloat fog_exp2_density;
325 static GLfloat fog_exp2_punch_through;
328 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
329 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
330 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
331 // GLfloat mat_shininess[] = { 10.0 };
332 GLbitfield clear_mask;
334 if ( idle_state != 1000 ) {
335 // still initializing, draw the splash screen
336 if ( fgGetBool("/sim/startup/splash-screen") ) {
340 // idle_state is now 1000 meaning we've finished all our
341 // initializations and are running the main loop, so this will
342 // now work without seg faulting the system.
344 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
345 // FG_Altitude * SG_FEET_TO_METER);
347 // this is just a temporary hack, to make me understand Pui
348 // timerText -> setLabel (ctime (&t->cur_time));
351 // calculate our current position in cartesian space
352 scenery.center = scenery.next_center;
353 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
354 // scenery.center.y(), scenery.center.z());
356 FGViewerRPH *pilot_view =
357 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
359 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
360 cur_fdm_state->get_Lat_geocentric(),
361 cur_fdm_state->get_Altitude() *
363 pilot_view->set_sea_level_radius( cur_fdm_state->
364 get_Sea_level_radius() *
366 pilot_view->set_rph( cur_fdm_state->get_Phi(),
367 cur_fdm_state->get_Theta(),
368 cur_fdm_state->get_Psi() );
370 FGViewerLookAt *chase_view =
371 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
373 sgVec3 po; // chase view pilot_offset
374 sgVec3 wup; // chase view world up
375 sgSetVec3( po, 0.0, 0.0, 100.0 );
376 sgCopyVec3( wup, pilot_view->get_world_up() );
377 sgMat4 CXFM; // chase view + pilot offset xform
379 chase_view->get_view_offset() * SGD_RADIANS_TO_DEGREES -
380 cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES,
382 sgVec3 npo; // new pilot offset after rotation
383 sgVec3 *pPO = PilotOffsetGet();
384 sgXformVec3( po, *pPO, pilot_view->get_UP() );
385 sgXformVec3( npo, po, CXFM );
387 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
388 cur_fdm_state->get_Lat_geocentric(),
389 cur_fdm_state->get_Altitude() *
391 chase_view->set_sea_level_radius( cur_fdm_state->
392 get_Sea_level_radius() *
394 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
395 chase_view->set_view_forward( pilot_view->get_view_pos() );
396 chase_view->set_view_up( wup );
400 sgCopyMat4( rph, pilot_view->get_VIEW() );
401 cout << "RPH Matrix = " << endl;
403 for ( i = 0; i < 4; i++ ) {
404 for ( j = 0; j < 4; j++ ) {
405 printf("%10.4f ", rph[i][j]);
411 sgCopyMat4( la, chase_view->get_VIEW() );
412 cout << "LookAt Matrix = " << endl;
413 for ( i = 0; i < 4; i++ ) {
414 for ( j = 0; j < 4; j++ ) {
415 printf("%10.4f ", la[i][j]);
422 fgReshape( fgGetInt("/sim/startup/xsize"),
423 fgGetInt("/sim/startup/ysize") );
428 if ( ! fgPanelVisible() ) {
430 (GLint)(fgGetInt("/sim/startup/xsize")),
431 (GLint)(fgGetInt("/sim/startup/ysize")) );
434 int( (current_panel->getViewHeight() -
435 current_panel->getYOffset())
436 * (fgGetInt("/sim/startup/ysize") / 768.0) );
438 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
439 (GLint)(fgGetInt("/sim/startup/xsize")),
444 // set the sun position
445 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
447 clear_mask = GL_DEPTH_BUFFER_BIT;
448 if ( fgGetBool("/sim/rendering/wireframe") ) {
449 clear_mask |= GL_COLOR_BUFFER_BIT;
452 if ( fgGetBool("/sim/rendering/skyblend") ) {
453 if ( fgGetBool("/sim/rendering/textures") ) {
454 // glClearColor(black[0], black[1], black[2], black[3]);
455 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
456 l->adj_fog_color[2], l->adj_fog_color[3]);
457 clear_mask |= GL_COLOR_BUFFER_BIT;
460 glClearColor(l->sky_color[0], l->sky_color[1],
461 l->sky_color[2], l->sky_color[3]);
462 clear_mask |= GL_COLOR_BUFFER_BIT;
464 glClear( clear_mask );
466 // Tell GL we are switching to model view parameters
468 // I really should create a derived ssg node or use a call
469 // back or something so that I can draw the sky within the
470 // ssgCullAndDraw() function, but for now I just mimic what
471 // ssg does to set up the model view matrix
472 glMatrixMode(GL_MODELVIEW);
474 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
476 // set the opengl state to known default values
477 default_state->force();
479 // update fog params if visibility has changed
480 #ifndef FG_OLD_WEATHER
481 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
483 thesky->set_visibility( current_weather.get_visibility() );
486 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
487 ( global_multi_loop *
488 fgGetInt("/sim/speed-up") ) /
489 (double)fgGetInt("/sim/model-hz") );
491 double actual_visibility = thesky->get_visibility();
492 // cout << "actual visibility = " << actual_visibility << endl;
494 if ( actual_visibility != last_visibility ) {
495 last_visibility = actual_visibility;
497 // cout << "----> updating fog params" << endl;
500 fog_exp_density = -log(0.01) / actual_visibility;
503 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
504 fog_exp2_punch_through = sqrt( -log(0.01) ) /
505 ( actual_visibility * 1.5 );
508 // Set correct opengl fog density
509 glFogf (GL_FOG_DENSITY, fog_exp2_density);
511 // update the sky dome
512 if ( fgGetBool("/sim/rendering/skyblend") ) {
513 /* cout << "thesky->repaint() sky_color = "
514 << cur_light_params.sky_color[0] << " "
515 << cur_light_params.sky_color[1] << " "
516 << cur_light_params.sky_color[2] << " "
517 << cur_light_params.sky_color[3] << endl;
519 << cur_light_params.fog_color[0] << " "
520 << cur_light_params.fog_color[1] << " "
521 << cur_light_params.fog_color[2] << " "
522 << cur_light_params.fog_color[3] << endl;
523 cout << " sun_angle = " << cur_light_params.sun_angle
524 << " moon_angle = " << cur_light_params.moon_angle
526 thesky->repaint( cur_light_params.sky_color,
527 cur_light_params.adj_fog_color,
528 cur_light_params.sun_angle,
529 cur_light_params.moon_angle,
530 globals->get_ephem()->getNumPlanets(),
531 globals->get_ephem()->getPlanets(),
532 globals->get_ephem()->getNumStars(),
533 globals->get_ephem()->getStars() );
535 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
536 << view_pos[1] << " " << view_pos[2] << endl;
537 cout << " zero_elev = " << zero_elev[0] << " "
538 << zero_elev[1] << " " << zero_elev[2]
539 << " lon = " << cur_fdm_state->get_Longitude()
540 << " lat = " << cur_fdm_state->get_Latitude() << endl;
541 cout << " sun_rot = " << cur_light_params.sun_rotation
542 << " gst = " << SGTime::cur_time_params->getGst() << endl;
543 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
544 << " sun dec = " << globals->get_ephem()->getSunDeclination()
545 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
546 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
548 thesky->reposition( globals->get_current_view()->get_view_pos(),
549 globals->get_current_view()->get_zero_elev(),
550 globals->get_current_view()->get_world_up(),
551 cur_fdm_state->get_Longitude(),
552 cur_fdm_state->get_Latitude(),
553 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
554 cur_light_params.sun_rotation,
555 globals->get_time_params()->getGst(),
556 globals->get_ephem()->getSunRightAscension(),
557 globals->get_ephem()->getSunDeclination(),
559 globals->get_ephem()->getMoonRightAscension(),
560 globals->get_ephem()->getMoonDeclination(),
564 glEnable( GL_DEPTH_TEST );
565 if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
567 glFogi( GL_FOG_MODE, GL_EXP2 );
568 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
571 // set sun/lighting parameters
572 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
574 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
575 // we only update GL_AMBIENT for our lights we will never get
576 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
577 // explicitely to black.
578 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
579 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
580 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
582 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
583 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
584 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
586 // texture parameters
587 // glEnable( GL_TEXTURE_2D );
588 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
589 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
591 // glMatrixMode( GL_PROJECTION );
593 float fov = globals->get_current_view()->get_fov();
594 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
596 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
599 // SG_LOG( SG_ALL, SG_INFO, "visibility is "
600 // << current_weather.get_visibility() );
603 ssgSetNearFar( 10.0f, 120000.0f );
605 ssgSetNearFar( 0.5f, 120000.0f );
608 if ( globals->get_viewmgr()->get_current() == 0 ) {
609 // disable aircraft model
610 acmodel_selector->select(0);
612 // enable aircraft model and set up its position and orientation
613 acmodel_selector->select(1);
615 FGViewerRPH *pilot_view =
616 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
619 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
622 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
625 sgMakeRotMat4( sgROT, -90.0, ownship_up );
629 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
630 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
632 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
634 sgCopyMat4( sgTUX, sgROT );
635 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
636 sgPostMultMat4( sgTUX, sgTRANS );
639 sgSetCoord( &tuxpos, sgTUX );
640 acmodel_pos->setTransform( &tuxpos );
642 // set up moving parts
643 if (flaps_selector != NULL) {
644 flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
647 if (prop_selector != NULL) {
648 int propsel_mask = 0;
649 for (int i = 0; i < acmodel_npropsettings; i++) {
650 if (FGBFI::getRPM() >= acmodel_proprpms[i][0] &&
651 FGBFI::getRPM() <= acmodel_proprpms[i][1]) {
652 propsel_mask |= 1 << i;
655 prop_selector->select(propsel_mask);
659 // $$$ begin - added VS Renganthan 17 Oct 2K
661 // $$$ end - added VS Renganthan 17 Oct 2K
663 # ifdef FG_NETWORK_OLK
664 if ( fgGetBool("/sim/networking/network-olk") ) {
666 other = head->next; /* put listpointer to start */
667 while ( other != tail) { /* display all except myself */
668 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
669 other->fgd_sel->select(1);
670 sgSetCoord( &fgdpos, other->sgFGD_COORD );
671 other->fgd_pos->setTransform( &fgdpos );
676 // fgd_sel->select(1);
677 // sgCopyMat4( sgTUX, current_view.sgVIEW);
679 // sgSetCoord( &fgdpos, sgFGD_VIEW );
680 // fgd_pos->setTransform( &fgdpos);
684 // position tile nodes and update range selectors
685 global_tile_mgr.prep_ssg_nodes();
687 if ( fgGetBool("/sim/rendering/skyblend") ) {
688 // draw the sky backdrop
690 // we need a white diffuse light for the phase of the moon
691 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
695 // return to the desired diffuse color
696 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
699 // draw the ssg scene
700 glEnable( GL_DEPTH_TEST );
701 ssgCullAndDraw( scene );
703 // change state for lighting here
706 // Set punch through fog density
707 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
709 ssgCullAndDraw( lighting );
711 if ( fgGetBool("/sim/rendering/skyblend") ) {
712 // draw the sky cloud layers
713 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
716 // display HUD && Panel
718 glDisable( GL_DEPTH_TEST );
719 // glDisable( GL_CULL_FACE );
720 // glDisable( GL_TEXTURE_2D );
722 // update the input subsystem
723 current_input.update();
725 // update the controls subsystem
728 hud_and_panel->apply();
731 // update the panel subsystem
732 if (current_panel != 0)
733 current_panel->update();
735 // We can do translucent menus, so why not. :-)
737 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
739 // glDisable ( GL_BLEND ) ;
741 // glEnable( GL_FOG );
748 // Update internal time dependent calculations (i.e. flight model)
749 void fgUpdateTimeDepCalcs() {
750 static bool inited = false;
752 fgLIGHT *l = &cur_light_params;
757 if ( !globals->get_freeze() && !initial_freeze ) {
758 // conceptually, this could be done for each fdm instance ...
761 cur_fdm_state->stamp();
767 long elapsed = current - cur_fdm_state->get_time_stamp();
768 cur_fdm_state->set_time_stamp( current );
769 elapsed += cur_fdm_state->get_remainder();
770 // cout << "elapsed = " << elapsed << endl;
771 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
772 multi_loop = (long)(((double)elapsed * 0.000001) /
773 cur_fdm_state->get_delta_t() );
774 cur_fdm_state->set_multi_loop( multi_loop );
775 long remainder = elapsed - (long)( (multi_loop*1000000) *
776 cur_fdm_state->get_delta_t() );
777 cur_fdm_state->set_remainder( remainder );
778 // cout << "remainder = " << remainder << endl;
780 // chop max interations to something reasonable if the sim was
781 // delayed for an excesive amount of time
782 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
783 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
784 cur_fdm_state->set_remainder( 0 );
787 // cout << "multi_loop = " << multi_loop << endl;
788 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
789 // run Autopilot system
790 current_autopilot->run();
793 cur_fdm_state->update( 1 );
795 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
797 cur_fdm_state->update( 0 );
798 FGSteam::update( 0 );
800 //if ( global_tile_mgr.queue_size() == 0 ) {
801 initial_freeze = false;
805 if ( fgGetString("/sim/view-mode") == "pilot" ) {
806 cur_view_fdm = *cur_fdm_state;
810 // update the view angle
811 FGViewer *v = globals->get_current_view();
812 for ( i = 0; i < multi_loop; i++ ) {
813 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
814 v->set_view_offset( v->get_goal_view_offset() );
817 // move current_view.view_offset towards
818 // current_view.goal_view_offset
819 if ( v->get_goal_view_offset() > v->get_view_offset() )
821 if ( v->get_goal_view_offset() - v->get_view_offset() < SGD_PI ){
822 v->inc_view_offset( 0.01 );
824 v->inc_view_offset( -0.01 );
827 if ( v->get_view_offset() - v->get_goal_view_offset() < SGD_PI ){
828 v->inc_view_offset( -0.01 );
830 v->inc_view_offset( 0.01 );
833 if ( v->get_view_offset() > SGD_2PI ) {
834 v->inc_view_offset( -SGD_2PI );
835 } else if ( v->get_view_offset() < 0 ) {
836 v->inc_view_offset( SGD_2PI );
841 double tmp = -(l->sun_rotation + SGD_PI)
842 - (cur_fdm_state->get_Psi() -
843 globals->get_current_view()->get_view_offset() );
844 while ( tmp < 0.0 ) {
847 while ( tmp > SGD_2PI ) {
850 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
851 FG_Psi * SGD_RADIANS_TO_DEGREES, current_view.view_offset * SGD_RADIANS_TO_DEGREES,
852 -(l->sun_rotation+SGD_PI) * SGD_RADIANS_TO_DEGREES, tmp * SGD_RADIANS_TO_DEGREES); */
855 // Update solar system
856 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
857 globals->get_time_params()->getLst(),
858 cur_fdm_state->get_Latitude() );
860 // Update radio stack model
861 current_radiostack->update();
865 void fgInitTimeDepCalcs( void ) {
868 // #ifdef HAVE_SETITIMER
869 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
870 // fgUpdateTimeDepCalcs );
871 // #endif HAVE_SETITIMER
875 static const double alt_adjust_ft = 3.758099;
876 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
879 // What should we do when we have nothing else to do? Let's get ready
880 // for the next move and update the display?
881 static void fgMainLoop( void ) {
882 static long remainder = 0;
884 #ifdef FANCY_FRAME_COUNTER
888 static time_t last_time = 0;
889 static int frames = 0;
890 #endif // FANCY_FRAME_COUNTER
892 SGTime *t = globals->get_time_params();
894 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
895 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
897 #ifdef FG_NETWORK_OLK
898 if ( fgGetBool("/sim/networking/network-olk") ) {
899 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
900 // printf("FGD: Netupdate\n");
901 fgd_send_com( "A", FGFS_host); // Send Mat4 data
902 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
907 #if defined( ENABLE_PLIB_JOYSTICK )
908 // Read joystick and update control settings
909 // if ( fgGetString("/sim/control-mode") == "joystick" )
913 #elif defined( ENABLE_GLUT_JOYSTICK )
914 // Glut joystick support works by feeding a joystick handler
915 // function to glut. This is taken care of once in the joystick
916 // init routine and we don't have to worry about it again.
919 #ifdef FG_OLD_WEATHER
920 current_weather.Update();
923 // Fix elevation. I'm just sticking this here for now, it should
924 // probably move eventually
926 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
928 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
929 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
931 if ( scenery.cur_elev > -9990 ) {
932 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
933 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
934 // now set aircraft altitude above ground
935 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
936 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
937 scenery.cur_elev + alt_adjust_m - 3.0,
938 scenery.cur_elev + alt_adjust_m );
939 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
940 scenery.cur_elev + alt_adjust_m );
942 SG_LOG( SG_ALL, SG_DEBUG,
943 "<*> resetting altitude to "
944 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
949 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
951 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
952 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
955 if ( globals->get_warp_delta() != 0 ) {
956 globals->inc_warp( globals->get_warp_delta() );
959 t->update( cur_fdm_state->get_Longitude(),
960 cur_fdm_state->get_Latitude(),
961 globals->get_warp() );
963 if ( globals->get_warp_delta() != 0 ) {
964 fgUpdateSkyAndLightingParams();
967 // update magvar model
968 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
969 cur_fdm_state->get_Latitude(),
970 cur_fdm_state->get_Altitude()* SG_FEET_TO_METER,
971 globals->get_time_params()->getJD() );
973 // Get elapsed time (in usec) for this past frame
974 elapsed = fgGetTimeInterval();
975 SG_LOG( SG_ALL, SG_DEBUG,
976 "Elapsed time interval is = " << elapsed
977 << ", previous remainder is = " << remainder );
979 // Calculate frame rate average
980 #ifdef FANCY_FRAME_COUNTER
981 /* old fps calculation */
985 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
986 tmp = general.get_frame(i);
988 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
989 general.set_frame(i+1,tmp);
991 tmp = 1000000.0 / (float)elapsed;
992 general.set_frame(0,tmp);
993 // printf("frame[0] = %.2f\n", general.frames[0]);
995 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
996 // printf("ave = %.2f\n", general.frame_rate);
999 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1000 general.set_frame_rate( frames );
1001 SG_LOG( SG_ALL, SG_DEBUG,
1002 "--> Frame rate is = " << general.get_frame_rate() );
1005 last_time = t->get_cur_time();
1011 // Calculate model iterations needed for next frame
1012 elapsed += remainder;
1014 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1015 fgGetInt("/sim/model-hz"));
1016 remainder = elapsed - ( (global_multi_loop*1000000) /
1017 fgGetInt("/sim/model-hz") );
1018 SG_LOG( SG_ALL, SG_DEBUG,
1019 "Model iterations needed = " << global_multi_loop
1020 << ", new remainder = " << remainder );
1022 // chop max interations to something reasonable if the sim was
1023 // delayed for an excesive amount of time
1024 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1025 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1030 if ( global_multi_loop > 0 ) {
1031 fgUpdateTimeDepCalcs();
1033 SG_LOG( SG_ALL, SG_DEBUG,
1034 "Elapsed time is zero ... we're zinging" );
1037 #if ! defined( macintosh )
1038 // Do any I/O channel work that might need to be done
1042 // see if we need to load any new scenery tiles
1043 global_tile_mgr.update( cur_fdm_state->get_Longitude()
1044 * SGD_RADIANS_TO_DEGREES,
1045 cur_fdm_state->get_Latitude()
1046 * SGD_RADIANS_TO_DEGREES );
1048 // see if we need to load any deferred-load textures
1049 material_lib.load_next_deferred();
1051 // Process/manage pending events
1052 global_events.Process();
1054 // Run audio scheduler
1055 #ifdef ENABLE_AUDIO_SUPPORT
1056 if ( fgGetBool("/sim/sound") && globals->get_soundmgr()->is_working() ) {
1057 if ( fgGetString("/sim/aircraft") == "c172" ) {
1058 // pitch corresponds to rpm
1059 // volume corresponds to manifold pressure
1061 // cout << "AUDIO working = "
1062 // << globals->get_soundmgr()->is_working() << endl;
1065 if ( cur_fdm_state->get_engine(0) != NULL ) {
1066 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1070 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1073 double pitch = 0.3 + rpm_factor * 3.0;
1075 // don't run at absurdly slow rates -- not realistic
1076 // and sounds bad to boot. :-)
1077 if (pitch < 0.7) { pitch = 0.7; }
1078 if (pitch > 5.0) { pitch = 5.0; }
1081 if ( cur_fdm_state->get_engine(0) != NULL ) {
1083 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1088 << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1091 double volume = 0.15 + mp_factor / 2.0;
1093 if ( volume < 0.15 ) { volume = 0.15; }
1094 if ( volume > 0.5 ) { volume = 0.5; }
1095 // cout << "volume = " << volume << endl;
1097 s1->set_pitch( pitch );
1098 s1->set_volume( volume );
1100 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1101 s1->set_pitch( param );
1102 s1->set_volume( param );
1105 globals->get_soundmgr()->update();
1112 SG_LOG( SG_ALL, SG_DEBUG, "" );
1116 // This is the top level master main function that is registered as
1117 // our idle funciton
1120 // The first few passes take care of initialization things (a couple
1121 // per pass) and once everything has been initialized fgMainLoop from
1124 static void fgIdleFunction ( void ) {
1125 // printf("idle state == %d\n", idle_state);
1127 if ( idle_state == 0 ) {
1128 // Initialize the splash screen right away
1129 if ( fgGetBool("/sim/startup/splash-screen") ) {
1134 } else if ( idle_state == 1 ) {
1135 // Start the intro music
1137 if ( fgGetBool("/sim/startup/intro-music") ) {
1138 string lockfile = "/tmp/mpg123.running";
1139 SGPath mp3file( globals->get_fg_root() );
1140 mp3file.append( "Sounds/intro.mp3" );
1142 string command = "(touch " + lockfile + "; mpg123 "
1143 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1145 SG_LOG( SG_GENERAL, SG_INFO,
1146 "Starting intro music: " << mp3file.str() );
1147 system ( command.c_str() );
1152 } else if ( idle_state == 2 ) {
1153 // These are a few miscellaneous things that aren't really
1154 // "subsystems" but still need to be initialized.
1157 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1158 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1163 } else if ( idle_state == 3 ) {
1164 // This is the top level init routine which calls all the
1165 // other subsystem initialization routines. If you are adding
1166 // a subsystem to flightgear, its initialization call should
1167 // located in this routine.
1168 if( !fgInitSubsystems()) {
1169 SG_LOG( SG_GENERAL, SG_ALERT,
1170 "Subsystem initializations failed ..." );
1175 } else if ( idle_state == 4 ) {
1176 // setup OpenGL view parameters
1180 } else if ( idle_state == 5 ) {
1183 } else if ( idle_state == 6 ) {
1184 // Initialize audio support
1185 #ifdef ENABLE_AUDIO_SUPPORT
1188 if ( fgGetBool("/sim/startup/intro-music") ) {
1189 // Let's wait for mpg123 to finish
1190 string lockfile = "/tmp/mpg123.running";
1191 struct stat stat_buf;
1193 SG_LOG( SG_GENERAL, SG_INFO,
1194 "Waiting for mpg123 player to finish ..." );
1195 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1196 // file exist, wait ...
1198 SG_LOG( SG_GENERAL, SG_INFO, ".");
1200 SG_LOG( SG_GENERAL, SG_INFO, "");
1204 if ( fgGetBool("/sim/sound") ) {
1205 globals->get_soundmgr()->init();
1207 s1 = new FGSimpleSound( fgGetString("/sim/sounds/engine",
1208 "Sounds/wasp.wav") );
1209 globals->get_soundmgr()->add( s1, "engine loop" );
1210 globals->get_soundmgr()->play_looped( "engine loop" );
1211 SG_LOG( SG_GENERAL, SG_INFO,
1212 "Rate = " << s1->get_sample()->getRate()
1213 << " Bps = " << s1->get_sample()->getBps()
1214 << " Stereo = " << s1->get_sample()->getStereo() );
1216 s2 = new FGSimpleSound( "Sounds/corflaps.wav" );
1219 // s2 = mmm.make_ident( "JLI" );
1220 s2->set_volume( 0.3 );
1221 globals->get_soundmgr()->add( s2, "flaps" );
1228 cout << "Panel visible = " << fgPanelVisible() << endl;
1229 fgReshape( fgGetInt("/sim/startup/xsize"),
1230 fgGetInt("/sim/startup/ysize") );
1233 if ( idle_state == 1000 ) {
1234 // We've finished all our initialization steps, from now on we
1235 // run the main loop.
1239 if ( fgGetBool("/sim/startup/splash-screen") ) {
1240 fgSplashUpdate(0.0);
1245 // options.cxx needs to see this for toggle_panel()
1246 // Handle new window size or exposure
1247 void fgReshape( int width, int height ) {
1249 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1250 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1251 globals->get_viewmgr()->get_view(i)->
1252 set_win_ratio( (float)height / (float)width );
1255 int((current_panel->getViewHeight() -
1256 current_panel->getYOffset())
1257 * (height / 768.0)) + 1;
1258 globals->get_viewmgr()->get_view(i)->
1259 set_win_ratio( (float)view_h / (float)width );
1263 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1264 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1267 int((current_panel->getViewHeight() - current_panel->getYOffset())
1268 * (height / 768.0)) + 1;
1269 glViewport(0, (GLint)(height - view_h),
1270 (GLint)(width), (GLint)(view_h) );
1273 fgSetInt("/sim/startup/xsize", width);
1274 fgSetInt("/sim/startup/ysize", height);
1276 float fov = globals->get_current_view()->get_fov();
1277 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1283 // Initialize GLUT and define a main window
1284 int fgGlutInit( int *argc, char **argv ) {
1286 #if !defined( macintosh )
1287 // GLUT will extract all glut specific options so later on we only
1288 // need wory about our own.
1289 glutInit(argc, argv);
1292 // Define Display Parameters
1293 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1295 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1296 fgGetInt("/sim/startup/xsize") << "x"
1297 << fgGetInt("/sim/startup/ysize") );
1299 // Define initial window size
1300 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1301 fgGetInt("/sim/startup/ysize") );
1303 // Initialize windows
1304 if ( !fgGetBool("/sim/startup/game-mode")) {
1305 // Open the regular window
1306 glutCreateWindow("FlightGear");
1307 #ifndef GLUT_WRONG_VERSION
1309 // Open the cool new 'game mode' window
1310 char game_mode_str[256];
1311 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1312 fgGetInt("/sim/startup/xsize"),
1313 fgGetInt("/sim/startup/ysize"),
1314 fgGetInt("/sim/rendering/bits-per-pixel"));
1316 SG_LOG( SG_GENERAL, SG_INFO,
1317 "game mode params = " << game_mode_str );
1318 glutGameModeString( game_mode_str );
1319 glutEnterGameMode();
1323 // This seems to be the absolute earliest in the init sequence
1324 // that these calls will return valid info. Too bad it's after
1325 // we've already created and sized out window. :-(
1326 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1327 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1328 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1329 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1332 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1333 general.set_glMaxTexSize( tmp );
1334 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1336 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1337 general.set_glDepthBits( tmp );
1338 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1344 // Initialize GLUT event handlers
1345 int fgGlutInitEvents( void ) {
1346 // call fgReshape() on window resizes
1347 glutReshapeFunc( fgReshape );
1349 // call GLUTkey() on keyboard event
1350 glutKeyboardFunc(GLUTkey);
1351 glutKeyboardUpFunc(GLUTkeyup);
1352 glutSpecialFunc(GLUTspecialkey);
1353 glutSpecialUpFunc(GLUTspecialkeyup);
1355 // call guiMouseFunc() whenever our little rodent is used
1356 glutMouseFunc ( guiMouseFunc );
1357 glutMotionFunc (guiMotionFunc );
1358 glutPassiveMotionFunc (guiMotionFunc );
1360 // call fgMainLoop() whenever there is
1361 // nothing else to do
1362 glutIdleFunc( fgIdleFunction );
1365 glutDisplayFunc( fgRenderFrame );
1372 int main( int argc, char **argv ) {
1374 #if defined( macintosh )
1375 freopen ("stdout.txt", "w", stdout );
1376 freopen ("stderr.txt", "w", stderr );
1377 argc = ccommand( &argv );
1381 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1384 // set default log levels
1385 sglog().setLogLevels( SG_ALL, SG_INFO );
1388 #ifdef FLIGHTGEAR_VERSION
1389 version = FLIGHTGEAR_VERSION;
1391 version = "unknown version";
1393 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1394 << version << endl );
1396 // Allocate global data structures. This needs to happen before
1397 // we parse command line options
1399 globals = new FGGlobals;
1401 // seed the random number generater
1404 SGRoute *route = new SGRoute;
1405 globals->set_route( route );
1407 #ifdef ENABLE_AUDIO_SUPPORT
1408 FGSoundMgr *soundmgr = new FGSoundMgr;
1409 globals->set_soundmgr( soundmgr );
1412 FGViewMgr *viewmgr = new FGViewMgr;
1413 globals->set_viewmgr( viewmgr );
1415 FGViewerRPH *pv = new FGViewerRPH;
1416 globals->get_viewmgr()->add_view( pv );
1418 FGViewerLookAt *chase = new FGViewerLookAt;
1419 globals->get_viewmgr()->add_view( chase );
1421 string_list *col = new string_list;
1422 globals->set_channel_options_list( col );
1424 // set current view to 0 (first) which is our main pilot view
1425 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1427 // Scan the config file(s) and command line options to see if
1428 // fg_root was specified (ignore all other options for now)
1429 fgInitFGRoot(argc, argv);
1431 // Initialize the Aircraft directory to "" (UIUC)
1434 // Load the configuration parameters
1435 if ( !fgInitConfig(argc, argv) ) {
1436 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1440 // Initialize the Window/Graphics environment.
1441 if( !fgGlutInit(&argc, argv) ) {
1442 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1446 // Initialize the various GLUT Event Handlers.
1447 if( !fgGlutInitEvents() ) {
1448 SG_LOG( SG_GENERAL, SG_ALERT,
1449 "GLUT event handler initialization failed ..." );
1453 // Initialize ssg (from plib). Needs to come before we do any
1454 // other ssg stuff, but after opengl/glut has been initialized.
1457 // Initialize the user interface (we need to do this before
1458 // passing off control to glut and before fgInitGeneral to get our
1462 #ifdef GL_EXT_texture_lod_bias
1463 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1467 #ifdef GL_EXT_texture_filter_anisotropic
1468 float max_anisotropy;
1469 glGetFloatv( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy );
1470 glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT,
1472 cout << "Max anisotropy = " << max_anisotropy << endl;
1476 // set current_options lon/lat if an airport id is specified
1477 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1478 if ( fgGetString("/sim/startup/airport-id").length() ) {
1479 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1480 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1481 fgGetDouble("/orientation/heading") );
1485 SGPath zone( globals->get_fg_root() );
1486 zone.append( "Timezone" );
1487 SGTime *t = new SGTime( fgGetDouble("/position/longitude") * SGD_DEGREES_TO_RADIANS,
1488 fgGetDouble("/position/latitude") * SGD_DEGREES_TO_RADIANS,
1491 // Handle potential user specified time offsets
1492 time_t cur_time = t->get_cur_time();
1493 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1494 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1495 time_t aircraftLocalTime =
1496 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1498 // Okay, we now have six possible scenarios
1499 int offset = fgGetInt("/sim/startup/time-offset");
1500 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1501 if (offset_type == "system-offset") {
1502 globals->set_warp( offset );
1503 } else if (offset_type == "gmt-offset") {
1504 globals->set_warp( offset - (currGMT - systemLocalTime) );
1505 } else if (offset_type == "latitude-offset") {
1506 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1507 } else if (offset_type == "system") {
1508 globals->set_warp( offset - cur_time );
1509 } else if (offset_type == "gmt") {
1510 globals->set_warp( offset - currGMT );
1511 } else if (offset_type == "latitude") {
1512 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1515 SG_LOG( SG_GENERAL, SG_ALERT,
1516 "Unsupported offset type " << offset_type );
1520 SG_LOG( SG_GENERAL, SG_INFO, "After time init, warp = "
1521 << globals->get_warp() );
1523 globals->set_warp_delta( 0 );
1525 t->update( 0.0, 0.0, globals->get_warp() );
1527 globals->set_time_params( t );
1529 // Do some quick general initializations
1530 if( !fgInitGeneral()) {
1531 SG_LOG( SG_GENERAL, SG_ALERT,
1532 "General initializations failed ..." );
1536 SGPath modelpath( globals->get_fg_root() );
1537 ssgModelPath( (char *)modelpath.c_str() );
1540 scene = new ssgRoot;
1541 scene->setName( "Scene" );
1543 lighting = new ssgRoot;
1544 lighting->setName( "Lighting" );
1546 // Initialize the sky
1547 SGPath ephem_data_path( globals->get_fg_root() );
1548 ephem_data_path.append( "Astro" );
1549 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1550 ephem->update( globals->get_time_params()->getMjd(),
1551 globals->get_time_params()->getLst(),
1553 globals->set_ephem( ephem );
1557 SGPath sky_tex_path( globals->get_fg_root() );
1558 sky_tex_path.append( "Textures" );
1559 sky_tex_path.append( "Sky" );
1560 thesky->texture_path( sky_tex_path.str() );
1562 thesky->build( 550.0, 550.0,
1563 globals->get_ephem()->getNumPlanets(),
1564 globals->get_ephem()->getPlanets(), 60000.0,
1565 globals->get_ephem()->getNumStars(),
1566 globals->get_ephem()->getStars(), 60000.0 );
1568 if ( fgGetBool("/environment/clouds/status") ) {
1569 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1570 // SG_CLOUD_OVERCAST );
1571 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1572 SG_CLOUD_MOSTLY_CLOUDY );
1573 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1574 // SG_CLOUD_MOSTLY_SUNNY );
1575 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1579 // Initialize MagVar model
1580 SGMagVar *magvar = new SGMagVar();
1581 globals->set_mag( magvar );
1584 terrain = new ssgBranch;
1585 terrain->setName( "Terrain" );
1586 scene->addKid( terrain );
1589 ground = new ssgBranch;
1590 ground->setName( "Ground Lighting" );
1591 lighting->addKid( ground );
1593 airport = new ssgBranch;
1594 airport->setName( "Airport Lighting" );
1595 lighting->addKid( airport );
1597 // temporary visible aircraft "own ship"
1598 acmodel_selector = new ssgSelector;
1599 acmodel_pos = new ssgTransform;
1601 // Get the model location, and load textures from the same
1602 // directory. Use an absolute path for the model to avoid
1603 // incompatibilities in different versions of PLIB.
1604 string acmodel_path =
1605 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1606 SGPath full_model = globals->get_fg_root();
1607 full_model.append(acmodel_path);
1609 #if !defined( PLIB_1_2_X )
1610 // this should be redundant ... but it breaks for relative paths
1611 // ssgModelPath( (char *)full_model.dir().c_str() );
1614 ssgTexturePath( (char *)full_model.dir().c_str() );
1615 ssgEntity *acmodel_obj = ssgLoad( (char *)full_model.c_str() );
1616 if( !acmodel_obj ) {
1617 // fall back to default
1618 acmodel_obj = ssgLoad( (char *)"Models/Geometry/glider.ac" );
1619 if( !acmodel_obj ) {
1620 SG_LOG( SG_GENERAL, SG_ALERT, "FAILED to LOAD an AC model! ..." );
1625 // find moving parts (if this is an MDL model)
1626 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1627 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1629 acmodel_npropsettings = 0;
1630 if (prop_selector != NULL) {
1631 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1632 kid = prop_selector->getNextKid()) {
1633 int prop_low, prop_high;
1634 if ( sscanf(kid->getName(), "PROP_%d_%d",
1635 &prop_low, &prop_high) == 2 ) {
1636 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1637 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1638 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1639 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1640 acmodel_npropsettings++;
1642 SG_LOG( SG_GENERAL, SG_INFO, "PROPELLER SETTING " << prop_low <<
1648 // align the model properly for FGFS
1649 ssgTransform *acmodel_align = new ssgTransform;
1650 acmodel_align->addKid(acmodel_obj);
1654 float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1655 float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1656 float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1657 float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1658 float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1659 float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1660 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1661 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1662 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1663 acmodel_align->setTransform(res_matrix);
1665 acmodel_pos->addKid( acmodel_align );
1666 acmodel_selector->addKid( acmodel_pos );
1667 //ssgFlatten( acmodel_obj );
1668 //ssgStripify( acmodel_selector );
1669 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1670 scene->addKid( acmodel_selector );
1672 // $$$ begin - added VS Renganthan 17 Oct 2K
1674 // $$$ end - added VS Renganthan 17 Oct 2K
1676 #ifdef FG_NETWORK_OLK
1677 // Do the network intialization
1678 if ( fgGetBool("/sim/networking/network-olk") ) {
1679 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1683 // build our custom render states
1684 fgBuildRenderStates();
1686 // pass control off to the master GLUT event handler
1689 // we never actually get here ... but to avoid compiler warnings,
1695 // $$$ end - added VS Renganathan, 15 Oct 2K
1696 // - added Venky , 12 Nov 2K
1698 void fgLoadDCS(void) {
1700 ssgEntity *ship_obj = NULL;
1703 char obj_filename[25];
1705 for ( int k = 0; k < 32; k++ ) {
1709 SGPath tile_path( globals->get_fg_root());
1710 tile_path.append( "Scenery" );
1711 tile_path.append( "Objects.txt" );
1712 sg_gzifstream in( tile_path.str() );
1713 if ( ! in.is_open() ) {
1714 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1717 SGPath modelpath( globals->get_fg_root() );
1718 modelpath.append( "Models" );
1719 modelpath.append( "Geometry" );
1721 SGPath texturepath( globals->get_fg_root() );
1722 texturepath.append( "Models" );
1723 texturepath.append( "Textures" );
1725 ssgModelPath( (char *)modelpath.c_str() );
1726 ssgTexturePath( (char *)texturepath.c_str() );
1728 ship_sel = new ssgSelector;
1731 while ( ! in.eof() ) {
1733 if ( in.get( c ) && c == '#' ) {
1737 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1738 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1739 int chj=getchar();*/
1741 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1742 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1744 ship_pos[objc] = new ssgTransform;
1746 // type "repeat" in objects.txt to load one more
1747 // instance of the last object.
1749 if ( strcmp(obj_filename,"repeat") != 0) {
1750 ship_obj = ssgLoadOBJ( obj_filename );
1753 if ( ship_obj != NULL ) {
1754 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1755 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1757 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1763 if (in.eof()) break;
1767 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1769 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1770 scene->addKid( ship_sel ); //add selector node to root node
1777 void fgUpdateDCS (void) {
1779 // double eye_lat,eye_lon,eye_alt;
1780 // static double obj_head;
1781 double sl_radius,obj_latgc;
1782 // float nresultmat[4][4];
1783 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1786 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1787 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1789 // Deck should be the first object in objects.txt in case of fdm=ada
1791 if (fgGetString("/sim/flight-model") == "ada") {
1792 obj_lon[0] = fdm->get_aux5()*SGD_DEGREES_TO_RADIANS;
1793 obj_lat[0] = fdm->get_aux6()*SGD_DEGREES_TO_RADIANS;
1794 obj_alt[0] = fdm->get_aux7();
1797 for ( int m = 0; m < objc; m++ ) {
1798 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1801 //Geodetic to Geocentric angles for rotation
1802 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1804 //moving object gbs-posn in cartesian coords
1805 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1806 Point3D obj_pos = sgGeodToCart( obj_posn );
1808 // Translate moving object w.r.t eye
1809 Point3D Objtrans = obj_pos-scenery.center;
1814 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1817 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1819 sgVec3 ship_fwd,ship_rt,ship_up;
1820 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1821 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1822 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1824 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1825 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1826 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1827 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1830 sgCopyMat4( sgTUX, sgROT_hdg );
1831 sgPostMultMat4( sgTUX, sgROT_lat );
1832 sgPostMultMat4( sgTUX, sgROT_lon );
1833 sgPostMultMat4( sgTUX, sgTRANS );
1836 sgSetCoord(&shippos, sgTUX );
1837 ship_pos[m]->setTransform( &shippos );
1839 if ( ship_sel != NULL ) {
1840 ship_sel->select(0xFFFFFFFF);
1844 // $$$ end - added VS Renganathan, 15 Oct 2K
1845 // added Venky , 12 Nov 2K