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 FG_MATH_EXCEPTION_CLASH
38 #include <simgear/xgl/xgl.h>
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h> // for stat()
53 # include <unistd.h> // for stat()
59 #ifdef ENABLE_AUDIO_SUPPORT
64 #include <simgear/constants.h> // for VERSION
65 #include <simgear/debug/logstream.hxx>
66 #include <simgear/math/polar3d.hxx>
67 #include <simgear/math/sg_random.h>
68 #include <simgear/misc/fgpath.hxx>
69 #include <simgear/sky/sky.hxx>
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/timing/lowleveltime.h>
73 #include <Include/general.hxx>
75 #include <Aircraft/aircraft.hxx>
77 #include <Autopilot/newauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/radiostack.hxx>
80 #include <Cockpit/steam.hxx>
82 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
84 #include <Joystick/joystick.hxx>
86 #include <NetworkOLK/network.h>
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/tilemgr.hxx>
90 #include <Time/event.hxx>
91 #include <Time/fg_timer.hxx>
92 #include <Time/light.hxx>
93 #include <Time/sunpos.hxx>
94 #include <Time/tmp.hxx>
96 // begin - added Venky
97 // $$$ begin - added VS Renganathan
98 #include <simgear/misc/fgstream.hxx>
99 #include <FDM/flight.hxx>
100 #include <FDM/ADA.hxx>
101 void fgLoadDCS (void);
102 void fgUpdateDCS (void);
103 ssgSelector *ship_sel=NULL;
104 // upto 32 instances of a same object can be loaded.
105 ssgTransform *ship_pos[32];
106 double obj_lat[32],obj_lon[32],obj_alt[32];
108 // $$$ end - added VS Renganathan
111 #ifndef FG_OLD_WEATHER
112 # include <WeatherCM/FGLocalWeatherDatabase.h>
114 # include <Weather/weather.hxx>
120 #include "fg_init.hxx"
122 #include "globals.hxx"
123 #include "keyboard.hxx"
124 #include "splash.hxx"
127 # include <console.h> // -dw- for command line dialog
131 // This is a record containing a bit of global housekeeping information
134 // Specify our current idle function state. This is used to run all
135 // our initializations out of the glutIdleLoop() so that we can get a
136 // splash screen up and running right away.
137 static int idle_state = 0;
138 static long global_multi_loop;
140 // attempt to avoid a large bounce at startup
141 static bool initial_freeze = true;
143 // forward declaration
144 void fgReshape( int width, int height );
146 // Global structures for the Audio library
147 #ifdef ENABLE_AUDIO_SUPPORT
148 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
149 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
150 slScheduler *audio_sched;
151 smMixer *audio_mixer;
158 ssgRoot *scene = NULL;
159 ssgBranch *terrain = NULL;
161 // aircraft model stuff
162 ssgSelector *acmodel_selector = NULL;
163 ssgTransform *acmodel_pos = NULL;
164 ssgSelector *prop_selector = NULL;
165 ssgSelector *flaps_selector = NULL;
166 int acmodel_npropsettings;
167 int acmodel_proprpms[4][2]; // different propeller settings
169 ssgRoot *lighting = NULL;
170 ssgBranch *ground = NULL;
171 ssgBranch *airport = NULL;
173 #ifdef FG_NETWORK_OLK
174 ssgSelector *fgd_sel = NULL;
175 ssgTransform *fgd_pos = NULL;
178 // current fdm/position used for view
179 FGInterface cur_view_fdm;
185 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
187 { 1.0f, 0.0f, 0.0f, 0.0f },
188 { 0.0f, 0.0f, -1.0f, 0.0f },
189 { 0.0f, 1.0f, 0.0f, 0.0f },
190 { 0.0f, 0.0f, 0.0f, 1.0f }
193 // The following defines flightgear options. Because glutlib will also
194 // want to parse its own options, those options must not be included here
195 // or they will get parsed by the main program option parser. Hence case
196 // is significant for any option added that might be in conflict with
199 // glutlib parses for:
201 // -direct (invalid in Win32)
205 // -indirect (invalid in Win32)
208 // Note that glutlib depends upon strings while this program's
209 // option parser wants only initial characters followed by numbers
214 ssgSimpleState *default_state;
215 ssgSimpleState *hud_and_panel;
216 ssgSimpleState *menus;
218 void fgBuildRenderStates( void ) {
219 default_state = new ssgSimpleState;
220 default_state->ref();
221 default_state->disable( GL_TEXTURE_2D );
222 default_state->enable( GL_CULL_FACE );
223 default_state->enable( GL_COLOR_MATERIAL );
224 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
225 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
226 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
227 default_state->disable( GL_BLEND );
228 default_state->disable( GL_ALPHA_TEST );
229 default_state->disable( GL_LIGHTING );
231 hud_and_panel = new ssgSimpleState;
232 hud_and_panel->ref();
233 hud_and_panel->disable( GL_CULL_FACE );
234 hud_and_panel->disable( GL_TEXTURE_2D );
235 hud_and_panel->disable( GL_LIGHTING );
236 hud_and_panel->enable( GL_BLEND );
238 menus = new ssgSimpleState;
240 menus->disable( GL_CULL_FACE );
241 menus->disable( GL_TEXTURE_2D );
242 menus->enable( GL_BLEND );
245 // fgFindNode -- a function that finds a named node in an ssg graph
246 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
247 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
249 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
250 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
251 while (kid != NULL) {
252 ssgEntity *n = fgFindNode(kid, name);
256 kid = ((ssgBranch*)node)->getNextKid();
263 // fgInitVisuals() -- Initialize various GL/view parameters
264 void fgInitVisuals( void ) {
267 l = &cur_light_params;
269 #ifndef GLUT_WRONG_VERSION
270 // Go full screen if requested ...
271 if ( fgGetBool("/sim/startup/fullscreen") ) {
276 // If enabled, normal vectors specified with glNormal are scaled
277 // to unit length after transformation. See glNormal.
278 // glEnable( GL_NORMALIZE );
280 glEnable( GL_LIGHTING );
281 glEnable( GL_LIGHT0 );
282 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
285 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
286 ssgGetLight( 0 ) -> setPosition( sunpos );
288 // glFogi (GL_FOG_MODE, GL_LINEAR);
289 glFogi (GL_FOG_MODE, GL_EXP2);
290 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
291 (!fgGetBool("/sim/rendering/shading"))) {
292 // if fastest fog requested, or if flat shading force fastest
293 glHint ( GL_FOG_HINT, GL_FASTEST );
294 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
295 glHint ( GL_FOG_HINT, GL_NICEST );
297 if ( fgGetBool("/sim/rendering/wireframe") ) {
299 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
302 // This is the default anyways, but it can't hurt
303 glFrontFace ( GL_CCW );
306 // glEnable(GL_POINT_SMOOTH);
307 // glEnable(GL_LINE_SMOOTH);
308 // glEnable(GL_POLYGON_SMOOTH);
312 // Update all Visuals (redraws anything graphics related)
313 void fgRenderFrame( void ) {
317 fgLIGHT *l = &cur_light_params;
318 static double last_visibility = -9999;
320 static GLfloat fog_exp_density;
321 static GLfloat fog_exp2_density;
322 static GLfloat fog_exp2_punch_through;
325 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
326 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
327 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
328 // GLfloat mat_shininess[] = { 10.0 };
329 GLbitfield clear_mask;
331 if ( idle_state != 1000 ) {
332 // still initializing, draw the splash screen
333 if ( fgGetBool("/sim/startup/splash-screen") ) {
337 // idle_state is now 1000 meaning we've finished all our
338 // initializations and are running the main loop, so this will
339 // now work without seg faulting the system.
341 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
342 // FG_Altitude * FEET_TO_METER);
344 // this is just a temporary hack, to make me understand Pui
345 // timerText -> setLabel (ctime (&t->cur_time));
348 // calculate our current position in cartesian space
349 scenery.center = scenery.next_center;
350 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
351 // scenery.center.y(), scenery.center.z());
353 FGViewerRPH *pilot_view =
354 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
356 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
357 cur_fdm_state->get_Lat_geocentric(),
358 cur_fdm_state->get_Altitude() *
360 pilot_view->set_sea_level_radius( cur_fdm_state->
361 get_Sea_level_radius() *
363 pilot_view->set_rph( cur_fdm_state->get_Phi(),
364 cur_fdm_state->get_Theta(),
365 cur_fdm_state->get_Psi() );
367 FGViewerLookAt *chase_view =
368 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
370 sgVec3 po; // chase view pilot_offset
371 sgVec3 wup; // chase view world up
372 sgSetVec3( po, 0.0, 0.0, 50.0 );
373 sgCopyVec3( wup, pilot_view->get_world_up() );
374 sgMat4 CXFM; // chase view + pilot offset xform
376 chase_view->get_view_offset() * RAD_TO_DEG -
377 cur_fdm_state->get_Psi() * RAD_TO_DEG,
379 sgVec3 npo; // new pilot offset after rotation
380 sgXformVec3( po, po, pilot_view->get_UP() );
381 sgXformVec3( npo, po, CXFM );
383 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
384 cur_fdm_state->get_Lat_geocentric(),
385 cur_fdm_state->get_Altitude() *
387 chase_view->set_sea_level_radius( cur_fdm_state->
388 get_Sea_level_radius() *
390 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
391 chase_view->set_view_forward( pilot_view->get_view_pos() );
392 chase_view->set_view_up( wup );
396 sgCopyMat4( rph, pilot_view->get_VIEW() );
397 cout << "RPH Matrix = " << endl;
399 for ( i = 0; i < 4; i++ ) {
400 for ( j = 0; j < 4; j++ ) {
401 printf("%10.4f ", rph[i][j]);
407 sgCopyMat4( la, chase_view->get_VIEW() );
408 cout << "LookAt Matrix = " << endl;
409 for ( i = 0; i < 4; i++ ) {
410 for ( j = 0; j < 4; j++ ) {
411 printf("%10.4f ", la[i][j]);
418 fgReshape( fgGetInt("/sim/startup/xsize"),
419 fgGetInt("/sim/startup/ysize") );
424 if ( ! fgPanelVisible() ) {
426 (GLint)(fgGetInt("/sim/startup/xsize")),
427 (GLint)(fgGetInt("/sim/startup/ysize")) );
430 int( (current_panel->getViewHeight() -
431 current_panel->getYOffset())
432 * (fgGetInt("/sim/startup/ysize") / 768.0) );
434 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
435 (GLint)(fgGetInt("/sim/startup/xsize")),
440 // set the sun position
441 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
443 clear_mask = GL_DEPTH_BUFFER_BIT;
444 if ( fgGetBool("/sim/rendering/wireframe") ) {
445 clear_mask |= GL_COLOR_BUFFER_BIT;
448 if ( fgGetBool("/sim/rendering/skyblend") ) {
449 if ( fgGetBool("/sim/rendering/textures") ) {
450 // glClearColor(black[0], black[1], black[2], black[3]);
451 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
452 l->adj_fog_color[2], l->adj_fog_color[3]);
453 clear_mask |= GL_COLOR_BUFFER_BIT;
456 glClearColor(l->sky_color[0], l->sky_color[1],
457 l->sky_color[2], l->sky_color[3]);
458 clear_mask |= GL_COLOR_BUFFER_BIT;
460 glClear( clear_mask );
462 // Tell GL we are switching to model view parameters
464 // I really should create a derived ssg node or use a call
465 // back or something so that I can draw the sky within the
466 // ssgCullAndDraw() function, but for now I just mimic what
467 // ssg does to set up the model view matrix
468 glMatrixMode(GL_MODELVIEW);
470 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
472 // set the opengl state to known default values
473 default_state->force();
475 // update fog params if visibility has changed
476 #ifndef FG_OLD_WEATHER
477 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
479 thesky->set_visibility( current_weather.get_visibility() );
482 thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
484 ( global_multi_loop *
485 fgGetInt("/sim/speed-up") ) /
486 (double)fgGetInt("/sim/model-hz") );
488 double actual_visibility = thesky->get_visibility();
489 // cout << "actual visibility = " << actual_visibility << endl;
491 if ( actual_visibility != last_visibility ) {
492 last_visibility = actual_visibility;
494 // cout << "----> updating fog params" << endl;
497 fog_exp_density = -log(0.01 / actual_visibility);
500 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
501 fog_exp2_punch_through = sqrt( -log(0.01) ) /
502 ( actual_visibility * 1.5 );
505 // Set correct opengl fog density
506 glFogf (GL_FOG_DENSITY, fog_exp2_density);
508 // update the sky dome
509 if ( fgGetBool("/sim/rendering/skyblend") ) {
510 /* cout << "thesky->repaint() sky_color = "
511 << cur_light_params.sky_color[0] << " "
512 << cur_light_params.sky_color[1] << " "
513 << cur_light_params.sky_color[2] << " "
514 << cur_light_params.sky_color[3] << endl;
516 << cur_light_params.fog_color[0] << " "
517 << cur_light_params.fog_color[1] << " "
518 << cur_light_params.fog_color[2] << " "
519 << cur_light_params.fog_color[3] << endl;
520 cout << " sun_angle = " << cur_light_params.sun_angle
521 << " moon_angle = " << cur_light_params.moon_angle
523 thesky->repaint( cur_light_params.sky_color,
524 cur_light_params.adj_fog_color,
525 cur_light_params.sun_angle,
526 cur_light_params.moon_angle,
527 globals->get_ephem()->getNumPlanets(),
528 globals->get_ephem()->getPlanets(),
529 globals->get_ephem()->getNumStars(),
530 globals->get_ephem()->getStars() );
532 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
533 << view_pos[1] << " " << view_pos[2] << endl;
534 cout << " zero_elev = " << zero_elev[0] << " "
535 << zero_elev[1] << " " << zero_elev[2]
536 << " lon = " << cur_fdm_state->get_Longitude()
537 << " lat = " << cur_fdm_state->get_Latitude() << endl;
538 cout << " sun_rot = " << cur_light_params.sun_rotation
539 << " gst = " << SGTime::cur_time_params->getGst() << endl;
540 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
541 << " sun dec = " << globals->get_ephem()->getSunDeclination()
542 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
543 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
545 thesky->reposition( globals->get_current_view()->get_view_pos(),
546 globals->get_current_view()->get_zero_elev(),
547 globals->get_current_view()->get_world_up(),
548 cur_fdm_state->get_Longitude(),
549 cur_fdm_state->get_Latitude(),
550 cur_fdm_state->get_Altitude() * FEET_TO_METER,
551 cur_light_params.sun_rotation,
552 globals->get_time_params()->getGst(),
553 globals->get_ephem()->getSunRightAscension(),
554 globals->get_ephem()->getSunDeclination(),
556 globals->get_ephem()->getMoonRightAscension(),
557 globals->get_ephem()->getMoonDeclination(),
561 glEnable( GL_DEPTH_TEST );
562 if ( fgGetString("/sim/rendering/fog") != "disabled" ) {
564 glFogi( GL_FOG_MODE, GL_EXP2 );
565 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
568 // set lighting parameters
569 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
570 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
571 glLightfv( GL_LIGHT0, GL_AMBIENT, black );
572 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
573 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
575 // texture parameters
576 // glEnable( GL_TEXTURE_2D );
577 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
578 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
579 // set base color (I don't think this is doing anything here)
580 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
581 // (GL_FRONT, GL_DIFFUSE, white);
582 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
583 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
586 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
587 ssgGetLight( 0 ) -> setPosition( sunpos );
589 // glMatrixMode( GL_PROJECTION );
591 float fov = globals->get_current_view()->get_fov();
592 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
594 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
597 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
598 // << current_weather.get_visibility() );
601 ssgSetNearFar( 10.0f, 120000.0f );
603 ssgSetNearFar( 0.5f, 120000.0f );
606 if ( globals->get_viewmgr()->get_current() == 0 ) {
607 // disable aircraft model
608 acmodel_selector->select(0);
610 // enable aircraft model and set up its position and orientation
611 acmodel_selector->select(1);
613 FGViewerRPH *pilot_view =
614 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
617 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
620 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
623 sgMakeRotMat4( sgROT, -90.0, ownship_up );
627 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
628 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
630 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
632 sgCopyMat4( sgTUX, sgROT );
633 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
634 sgPostMultMat4( sgTUX, sgTRANS );
637 sgSetCoord( &tuxpos, sgTUX );
638 acmodel_pos->setTransform( &tuxpos );
640 // set up moving parts
641 if (flaps_selector != NULL) {
642 flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
645 if (prop_selector != NULL) {
646 int propsel_mask = 0;
647 for (int i = 0; i < acmodel_npropsettings; i++) {
648 if (FGBFI::getRPM() >= acmodel_proprpms[i][0] &&
649 FGBFI::getRPM() <= acmodel_proprpms[i][1]) {
650 propsel_mask |= 1 << i;
653 prop_selector->select(propsel_mask);
657 // $$$ begin - added VS Renganthan 17 Oct 2K
659 // $$$ end - added VS Renganthan 17 Oct 2K
661 # ifdef FG_NETWORK_OLK
662 if ( fgGetBool("/sim/networking/network-olk") ) {
664 other = head->next; /* put listpointer to start */
665 while ( other != tail) { /* display all except myself */
666 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
667 other->fgd_sel->select(1);
668 sgSetCoord( &fgdpos, other->sgFGD_COORD );
669 other->fgd_pos->setTransform( &fgdpos );
674 // fgd_sel->select(1);
675 // sgCopyMat4( sgTUX, current_view.sgVIEW);
677 // sgSetCoord( &fgdpos, sgFGD_VIEW );
678 // fgd_pos->setTransform( &fgdpos);
682 // position tile nodes and update range selectors
683 global_tile_mgr.prep_ssg_nodes();
685 // draw the sky backdrop
688 // draw the ssg scene
689 glEnable( GL_DEPTH_TEST );
690 ssgCullAndDraw( scene );
692 // change state for lighting here
695 // Set punch through fog density
696 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
698 ssgCullAndDraw( lighting );
700 // draw the sky cloud layers
701 thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
703 // display HUD && Panel
705 glDisable( GL_DEPTH_TEST );
706 // glDisable( GL_CULL_FACE );
707 // glDisable( GL_TEXTURE_2D );
709 // update the controls subsystem
712 hud_and_panel->apply();
715 // update the panel subsystem
716 if (current_panel != 0)
717 current_panel->update();
719 // We can do translucent menus, so why not. :-)
721 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
723 // glDisable ( GL_BLEND ) ;
725 // glEnable( GL_FOG );
732 // Update internal time dependent calculations (i.e. flight model)
733 void fgUpdateTimeDepCalcs() {
734 static bool inited = false;
736 fgLIGHT *l = &cur_light_params;
741 if ( !globals->get_freeze() && !initial_freeze ) {
742 // conceptually, this could be done for each fdm instance ...
745 cur_fdm_state->stamp();
751 long elapsed = current - cur_fdm_state->get_time_stamp();
752 cur_fdm_state->set_time_stamp( current );
753 elapsed += cur_fdm_state->get_remainder();
754 // cout << "elapsed = " << elapsed << endl;
755 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
756 multi_loop = (long)(((double)elapsed * 0.000001) /
757 cur_fdm_state->get_delta_t() );
758 cur_fdm_state->set_multi_loop( multi_loop );
759 long remainder = elapsed - ( (multi_loop*1000000) *
760 cur_fdm_state->get_delta_t() );
761 cur_fdm_state->set_remainder( remainder );
762 // cout << "remainder = " << remainder << endl;
764 // chop max interations to something reasonable if the sim was
765 // delayed for an excesive amount of time
766 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
767 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
768 cur_fdm_state->set_remainder( 0 );
771 // cout << "multi_loop = " << multi_loop << endl;
772 for ( i = 0; i < multi_loop; ++i ) {
773 // run Autopilot system
774 current_autopilot->run();
777 cur_fdm_state->update( 1 * fgGetInt("/sim/speed-up") );
779 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
781 cur_fdm_state->update( 0 );
782 FGSteam::update( 0 );
784 if ( global_tile_mgr.queue_size() == 0 ) {
785 initial_freeze = false;
789 if ( fgGetString("/sim/view-mode") == "pilot" ) {
790 cur_view_fdm = *cur_fdm_state;
794 // update the view angle
795 FGViewer *v = globals->get_current_view();
796 for ( i = 0; i < multi_loop; i++ ) {
797 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
798 v->set_view_offset( v->get_goal_view_offset() );
801 // move current_view.view_offset towards
802 // current_view.goal_view_offset
803 if ( v->get_goal_view_offset() > v->get_view_offset() )
805 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
806 v->inc_view_offset( 0.01 );
808 v->inc_view_offset( -0.01 );
811 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
812 v->inc_view_offset( -0.01 );
814 v->inc_view_offset( 0.01 );
817 if ( v->get_view_offset() > FG_2PI ) {
818 v->inc_view_offset( -FG_2PI );
819 } else if ( v->get_view_offset() < 0 ) {
820 v->inc_view_offset( FG_2PI );
825 double tmp = -(l->sun_rotation + FG_PI)
826 - (cur_fdm_state->get_Psi() -
827 globals->get_current_view()->get_view_offset() );
828 while ( tmp < 0.0 ) {
831 while ( tmp > FG_2PI ) {
834 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
835 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
836 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
839 // Update solar system
840 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
841 globals->get_time_params()->getLst(),
842 cur_fdm_state->get_Latitude() );
844 // Update radio stack model
845 current_radiostack->update();
849 void fgInitTimeDepCalcs( void ) {
852 // #ifdef HAVE_SETITIMER
853 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
854 // fgUpdateTimeDepCalcs );
855 // #endif HAVE_SETITIMER
859 static const double alt_adjust_ft = 3.758099;
860 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
863 // What should we do when we have nothing else to do? Let's get ready
864 // for the next move and update the display?
865 static void fgMainLoop( void ) {
866 static long remainder = 0;
868 #ifdef FANCY_FRAME_COUNTER
872 static time_t last_time = 0;
873 static int frames = 0;
874 #endif // FANCY_FRAME_COUNTER
876 SGTime *t = globals->get_time_params();
878 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
879 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
881 #ifdef FG_NETWORK_OLK
882 if ( fgGetBool("/sim/networking/network-olk") ) {
883 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
884 // printf("FGD: Netupdate\n");
885 fgd_send_com( "A", FGFS_host); // Send Mat4 data
886 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
891 #if defined( ENABLE_PLIB_JOYSTICK )
892 // Read joystick and update control settings
893 if ( fgGetString("/sim/control-mode") == "joystick" )
897 #elif defined( ENABLE_GLUT_JOYSTICK )
898 // Glut joystick support works by feeding a joystick handler
899 // function to glut. This is taken care of once in the joystick
900 // init routine and we don't have to worry about it again.
903 #ifdef FG_OLD_WEATHER
904 current_weather.Update();
907 // Fix elevation. I'm just sticking this here for now, it should
908 // probably move eventually
910 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
912 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
913 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
915 if ( scenery.cur_elev > -9990 ) {
916 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
917 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
918 // now set aircraft altitude above ground
919 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
920 cur_fdm_state->get_Altitude() * FEET_TO_METER,
921 scenery.cur_elev + alt_adjust_m - 3.0,
922 scenery.cur_elev + alt_adjust_m );
923 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
924 scenery.cur_elev + alt_adjust_m );
926 FG_LOG( FG_ALL, FG_DEBUG,
927 "<*> resetting altitude to "
928 << cur_fdm_state->get_Altitude() * FEET_TO_METER
933 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
935 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
936 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
939 if ( globals->get_warp_delta() != 0 ) {
940 globals->inc_warp( globals->get_warp_delta() );
943 t->update( cur_fdm_state->get_Longitude(),
944 cur_fdm_state->get_Latitude(),
945 globals->get_warp() );
947 if ( globals->get_warp_delta() != 0 ) {
948 fgUpdateSkyAndLightingParams();
951 // update magvar model
952 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
953 cur_fdm_state->get_Latitude(),
954 cur_fdm_state->get_Altitude()* FEET_TO_METER,
955 globals->get_time_params()->getJD() );
957 // Get elapsed time (in usec) for this past frame
958 elapsed = fgGetTimeInterval();
959 FG_LOG( FG_ALL, FG_DEBUG,
960 "Elapsed time interval is = " << elapsed
961 << ", previous remainder is = " << remainder );
963 // Calculate frame rate average
964 #ifdef FANCY_FRAME_COUNTER
965 /* old fps calculation */
969 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
970 tmp = general.get_frame(i);
972 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
973 general.set_frame(i+1,tmp);
975 tmp = 1000000.0 / (float)elapsed;
976 general.set_frame(0,tmp);
977 // printf("frame[0] = %.2f\n", general.frames[0]);
979 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
980 // printf("ave = %.2f\n", general.frame_rate);
983 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
984 general.set_frame_rate( frames );
985 FG_LOG( FG_ALL, FG_DEBUG,
986 "--> Frame rate is = " << general.get_frame_rate() );
989 last_time = t->get_cur_time();
995 // Calculate model iterations needed for next frame
996 elapsed += remainder;
998 global_multi_loop = (long)(((double)elapsed * 0.000001) *
999 fgGetInt("/sim/model-hz"));
1000 remainder = elapsed - ( (global_multi_loop*1000000) /
1001 fgGetInt("/sim/model-hz") );
1002 FG_LOG( FG_ALL, FG_DEBUG,
1003 "Model iterations needed = " << global_multi_loop
1004 << ", new remainder = " << remainder );
1006 // chop max interations to something reasonable if the sim was
1007 // delayed for an excesive amount of time
1008 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1009 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1014 if ( global_multi_loop > 0 ) {
1015 fgUpdateTimeDepCalcs();
1017 FG_LOG( FG_ALL, FG_DEBUG,
1018 "Elapsed time is zero ... we're zinging" );
1021 #if ! defined( macintosh )
1022 // Do any I/O channel work that might need to be done
1026 // see if we need to load any new scenery tiles
1027 global_tile_mgr.update( cur_fdm_state->get_Longitude() * RAD_TO_DEG,
1028 cur_fdm_state->get_Latitude() * RAD_TO_DEG );
1030 // Process/manage pending events
1031 global_events.Process();
1033 // Run audio scheduler
1034 #ifdef ENABLE_AUDIO_SUPPORT
1035 if ( fgGetBool("/sim/sound") && !audio_sched->not_working() ) {
1037 if ( fgGetString("/sim/aircraft") == "c172" ) {
1038 // pitch corresponds to rpm
1039 // volume corresponds to manifold pressure
1042 if ( cur_fdm_state->get_engine(0) != NULL ) {
1043 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1047 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1050 double pitch = 0.3 + rpm_factor * 3.0;
1052 // don't run at absurdly slow rates -- not realistic
1053 // and sounds bad to boot. :-)
1054 if (pitch < 0.7) { pitch = 0.7; }
1055 if (pitch > 5.0) { pitch = 5.0; }
1056 // cout << "pitch = " << pitch << endl;
1059 if ( cur_fdm_state->get_engine(0) != NULL ) {
1061 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 28;
1066 // << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1069 double volume = mp_factor;
1071 if ( volume < 0.3 ) { volume = 0.3; }
1072 if ( volume > 2.0 ) { volume = 2.0; }
1073 // cout << "volume = " << volume << endl;
1075 pitch_envelope.setStep ( 0, 0.01, pitch );
1076 volume_envelope.setStep ( 0, 0.01, volume );
1078 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1079 pitch_envelope.setStep ( 0, 0.01, param );
1080 volume_envelope.setStep ( 0, 0.01, param );
1083 audio_sched -> update();
1090 FG_LOG( FG_ALL, FG_DEBUG, "" );
1094 // This is the top level master main function that is registered as
1095 // our idle funciton
1098 // The first few passes take care of initialization things (a couple
1099 // per pass) and once everything has been initialized fgMainLoop from
1102 static void fgIdleFunction ( void ) {
1103 // printf("idle state == %d\n", idle_state);
1105 if ( idle_state == 0 ) {
1106 // Initialize the splash screen right away
1107 if ( fgGetBool("/sim/startup/splash-screen") ) {
1112 } else if ( idle_state == 1 ) {
1113 // Start the intro music
1115 if ( fgGetBool("/sim/startup/intro-music") ) {
1116 string lockfile = "/tmp/mpg123.running";
1117 FGPath mp3file( globals->get_fg_root() );
1118 mp3file.append( "Sounds/intro.mp3" );
1120 string command = "(touch " + lockfile + "; mpg123 "
1121 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1123 FG_LOG( FG_GENERAL, FG_INFO,
1124 "Starting intro music: " << mp3file.str() );
1125 system ( command.c_str() );
1130 } else if ( idle_state == 2 ) {
1131 // These are a few miscellaneous things that aren't really
1132 // "subsystems" but still need to be initialized.
1135 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1136 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1141 } else if ( idle_state == 3 ) {
1142 // This is the top level init routine which calls all the
1143 // other subsystem initialization routines. If you are adding
1144 // a subsystem to flightgear, its initialization call should
1145 // located in this routine.
1146 if( !fgInitSubsystems()) {
1147 FG_LOG( FG_GENERAL, FG_ALERT,
1148 "Subsystem initializations failed ..." );
1153 } else if ( idle_state == 4 ) {
1154 // setup OpenGL view parameters
1158 } else if ( idle_state == 5 ) {
1161 } else if ( idle_state == 6 ) {
1162 // Initialize audio support
1163 #ifdef ENABLE_AUDIO_SUPPORT
1166 if ( fgGetBool("/sim/startup/intro-music") ) {
1167 // Let's wait for mpg123 to finish
1168 string lockfile = "/tmp/mpg123.running";
1169 struct stat stat_buf;
1171 FG_LOG( FG_GENERAL, FG_INFO,
1172 "Waiting for mpg123 player to finish ..." );
1173 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1174 // file exist, wait ...
1176 FG_LOG( FG_GENERAL, FG_INFO, ".");
1178 FG_LOG( FG_GENERAL, FG_INFO, "");
1182 if ( fgGetBool("/sim/sound") ) {
1183 audio_sched = new slScheduler ( 8000 );
1184 audio_mixer = new smMixer;
1185 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1186 audio_sched -> setSafetyMargin ( 1.0 ) ;
1188 FGPath slfile( globals->get_fg_root() );
1189 slfile.append( "Sounds/wasp.wav" );
1191 s1 = new slSample ( (char *)slfile.c_str() );
1192 FG_LOG( FG_GENERAL, FG_INFO,
1193 "Rate = " << s1 -> getRate()
1194 << " Bps = " << s1 -> getBps()
1195 << " Stereo = " << s1 -> getStereo() );
1196 audio_sched -> loopSample ( s1 );
1198 if ( audio_sched->not_working() ) {
1201 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1202 volume_envelope.setStep ( 0, 0.01, 0.6 );
1204 audio_sched -> addSampleEnvelope( s1, 0, 0,
1206 SL_PITCH_ENVELOPE );
1207 audio_sched -> addSampleEnvelope( s1, 0, 1,
1209 SL_VOLUME_ENVELOPE );
1212 // strcpy(slfile, path);
1213 // strcat(slfile, "thunder.wav");
1214 // s2 -> loadFile ( slfile );
1215 // s2 -> adjustVolume(0.5);
1216 // audio_sched -> playSample ( s2 );
1223 cout << "Panel visible = " << fgPanelVisible() << endl;
1224 fgReshape( fgGetInt("/sim/startup/xsize"),
1225 fgGetInt("/sim/startup/ysize") );
1228 if ( idle_state == 1000 ) {
1229 // We've finished all our initialization steps, from now on we
1230 // run the main loop.
1234 if ( fgGetBool("/sim/startup/splash-screen") ) {
1235 fgSplashUpdate(0.0);
1240 // options.cxx needs to see this for toggle_panel()
1241 // Handle new window size or exposure
1242 void fgReshape( int width, int height ) {
1244 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1245 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1246 globals->get_viewmgr()->get_view(i)->
1247 set_win_ratio( (float)height / (float)width );
1250 int((current_panel->getViewHeight() -
1251 current_panel->getYOffset())
1252 * (height / 768.0)) + 1;
1253 globals->get_viewmgr()->get_view(i)->
1254 set_win_ratio( (float)view_h / (float)width );
1258 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1259 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1262 int((current_panel->getViewHeight() - current_panel->getYOffset())
1263 * (height / 768.0)) + 1;
1264 glViewport(0, (GLint)(height - view_h),
1265 (GLint)(width), (GLint)(view_h) );
1268 fgSetInt("/sim/startup/xsize", width);
1269 fgSetInt("/sim/startup/ysize", height);
1271 float fov = globals->get_current_view()->get_fov();
1272 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1278 // Initialize GLUT and define a main window
1279 int fgGlutInit( int *argc, char **argv ) {
1281 #if !defined( macintosh )
1282 // GLUT will extract all glut specific options so later on we only
1283 // need wory about our own.
1284 glutInit(argc, argv);
1287 // Define Display Parameters
1288 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1290 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1291 fgGetInt("/sim/startup/xsize") << "x"
1292 << fgGetInt("/sim/startup/ysize") );
1294 // Define initial window size
1295 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1296 fgGetInt("/sim/startup/ysize") );
1298 // Initialize windows
1299 if ( !fgGetBool("/sim/startup/game-mode")) {
1300 // Open the regular window
1301 glutCreateWindow("FlightGear");
1302 #ifndef GLUT_WRONG_VERSION
1304 // Open the cool new 'game mode' window
1305 char game_mode_str[256];
1306 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1307 fgGetInt("/sim/startup/xsize"),
1308 fgGetInt("/sim/startup/ysize"),
1309 fgGetInt("/sim/rendering/bits-per-pixel"));
1311 FG_LOG( FG_GENERAL, FG_INFO,
1312 "game mode params = " << game_mode_str );
1313 glutGameModeString( game_mode_str );
1314 glutEnterGameMode();
1318 // This seems to be the absolute earliest in the init sequence
1319 // that these calls will return valid info. Too bad it's after
1320 // we've already created and sized out window. :-(
1321 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1322 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1323 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1324 FG_LOG( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1327 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1328 general.set_glMaxTexSize( tmp );
1329 FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1331 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1332 general.set_glDepthBits( tmp );
1333 FG_LOG ( FG_GENERAL, FG_INFO, "Depth buffer bits = " << tmp );
1339 // Initialize GLUT event handlers
1340 int fgGlutInitEvents( void ) {
1341 // call fgReshape() on window resizes
1342 glutReshapeFunc( fgReshape );
1344 // call GLUTkey() on keyboard event
1345 glutKeyboardFunc( GLUTkey );
1346 glutSpecialFunc( GLUTspecialkey );
1348 // call guiMouseFunc() whenever our little rodent is used
1349 glutMouseFunc ( guiMouseFunc );
1350 glutMotionFunc (guiMotionFunc );
1351 glutPassiveMotionFunc (guiMotionFunc );
1353 // call fgMainLoop() whenever there is
1354 // nothing else to do
1355 glutIdleFunc( fgIdleFunction );
1358 glutDisplayFunc( fgRenderFrame );
1365 int main( int argc, char **argv ) {
1367 #if defined( macintosh )
1368 freopen ("stdout.txt", "w", stdout );
1369 freopen ("stderr.txt", "w", stderr );
1370 argc = ccommand( &argv );
1374 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1377 // set default log levels
1378 fglog().setLogLevels( FG_ALL, FG_INFO );
1381 #ifdef FLIGHTGEAR_VERSION
1382 version = FLIGHTGEAR_VERSION;
1384 version = "unknown version";
1386 FG_LOG( FG_GENERAL, FG_INFO, "FlightGear: Version "
1387 << version << endl );
1389 // Allocate global data structures. This needs to happen before
1390 // we parse command line options
1392 SGPropertyNode *props = new SGPropertyNode;
1393 globals = new FGGlobals;
1394 globals->set_props( props );
1396 // seed the random number generater
1399 SGRoute *route = new SGRoute;
1400 globals->set_route( route );
1402 FGViewMgr *viewmgr = new FGViewMgr;
1403 globals->set_viewmgr( viewmgr );
1405 FGViewerRPH *pv = new FGViewerRPH;
1406 globals->get_viewmgr()->add_view( pv );
1408 FGViewerLookAt *chase = new FGViewerLookAt;
1409 globals->get_viewmgr()->add_view( chase );
1411 // set current view to 0 (first) which is our main pilot view
1412 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1414 // Scan the config file(s) and command line options to see if
1415 // fg_root was specified (ignore all other options for now)
1416 fgInitFGRoot(argc, argv);
1418 // Initialize the Aircraft directory to "" (UIUC)
1421 // Load the configuration parameters
1422 if ( !fgInitConfig(argc, argv) ) {
1423 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1427 // Initialize the Window/Graphics environment.
1428 if( !fgGlutInit(&argc, argv) ) {
1429 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1433 // Initialize the various GLUT Event Handlers.
1434 if( !fgGlutInitEvents() ) {
1435 FG_LOG( FG_GENERAL, FG_ALERT,
1436 "GLUT event handler initialization failed ..." );
1440 // Initialize ssg (from plib). Needs to come before we do any
1441 // other ssg stuff, but after opengl/glut has been initialized.
1444 // Initialize the user interface (we need to do this before
1445 // passing off control to glut and before fgInitGeneral to get our
1449 // set current_options lon/lat if an airport id is specified
1450 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1451 if ( fgGetString("/sim/startup/airport-id").length() ) {
1452 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1453 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1454 fgGetDouble("/orientation/heading") );
1458 FGPath zone( globals->get_fg_root() );
1459 zone.append( "Timezone" );
1460 SGTime *t = new SGTime( fgGetDouble("/position/longitude") * DEG_TO_RAD,
1461 fgGetDouble("/position/latitude") * DEG_TO_RAD,
1464 // Handle potential user specified time offsets
1465 time_t cur_time = t->get_cur_time();
1466 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1467 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1468 time_t aircraftLocalTime =
1469 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1471 // Okay, we now have six possible scenarios
1472 int offset = fgGetInt("/sim/startup/time-offset");
1473 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1474 if (offset_type == "system-offset") {
1475 globals->set_warp( offset );
1476 } else if (offset_type == "gmt-offset") {
1477 globals->set_warp( offset - (currGMT - systemLocalTime) );
1478 } else if (offset_type == "latitude-offset") {
1479 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1480 } else if (offset_type == "system") {
1481 globals->set_warp( offset - cur_time );
1482 } else if (offset_type == "gmt") {
1483 globals->set_warp( offset - currGMT );
1484 } else if (offset_type == "latitude") {
1485 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1488 FG_LOG( FG_GENERAL, FG_ALERT,
1489 "Unsupported offset type " << offset_type );
1493 FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = "
1494 << globals->get_warp() );
1496 globals->set_warp_delta( 0 );
1498 t->update( 0.0, 0.0, globals->get_warp() );
1500 globals->set_time_params( t );
1502 // Do some quick general initializations
1503 if( !fgInitGeneral()) {
1504 FG_LOG( FG_GENERAL, FG_ALERT,
1505 "General initializations failed ..." );
1509 FGPath modelpath( globals->get_fg_root() );
1510 ssgModelPath( (char *)modelpath.c_str() );
1513 scene = new ssgRoot;
1514 scene->setName( "Scene" );
1516 lighting = new ssgRoot;
1517 lighting->setName( "Lighting" );
1519 // Initialize the sky
1520 FGPath ephem_data_path( globals->get_fg_root() );
1521 ephem_data_path.append( "Astro" );
1522 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1523 ephem->update( globals->get_time_params()->getMjd(),
1524 globals->get_time_params()->getLst(),
1526 globals->set_ephem( ephem );
1528 FGPath sky_tex_path( globals->get_fg_root() );
1529 sky_tex_path.append( "Textures" );
1530 sky_tex_path.append( "Sky" );
1532 thesky->texture_path( sky_tex_path.str() );
1534 thesky->build( 550.0, 550.0,
1535 globals->get_ephem()->getNumPlanets(),
1536 globals->get_ephem()->getPlanets(), 60000.0,
1537 globals->get_ephem()->getNumStars(),
1538 globals->get_ephem()->getStars(), 60000.0 );
1540 if ( fgGetBool("/environment/clouds/status") ) {
1541 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1542 SG_CLOUD_MOSTLY_SUNNY );
1543 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1545 // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1546 // SG_CLOUD_MOSTLY_SUNNY );
1547 // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1548 // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1551 // Initialize MagVar model
1552 SGMagVar *magvar = new SGMagVar();
1553 globals->set_mag( magvar );
1556 terrain = new ssgBranch;
1557 terrain->setName( "Terrain" );
1558 scene->addKid( terrain );
1561 ground = new ssgBranch;
1562 ground->setName( "Ground Lighting" );
1563 lighting->addKid( ground );
1565 airport = new ssgBranch;
1566 airport->setName( "Airport Lighting" );
1567 lighting->addKid( airport );
1569 // temporary visible aircraft "own ship"
1570 acmodel_selector = new ssgSelector;
1571 acmodel_pos = new ssgTransform;
1573 string acmodel_path =
1574 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1576 string full_model = globals->get_fg_root() + "/"
1578 int pos = full_model.rfind("/");
1580 FGPath texturepath( full_model.substr(0, pos) );
1581 cout << "Texture path = " << texturepath.str() << endl;
1582 ssgTexturePath( (char *)texturepath.c_str() );
1584 ssgEntity *acmodel_obj = ssgLoad((char *)(acmodel_path.c_str()));
1586 // find moving parts (if this is an MDL model)
1587 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1588 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1590 acmodel_npropsettings = 0;
1591 if (prop_selector != NULL) {
1592 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1593 kid = prop_selector->getNextKid()) {
1594 int prop_low, prop_high;
1595 if ( sscanf(kid->getName(), "PROP_%d_%d",
1596 &prop_low, &prop_high) == 2 ) {
1597 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1598 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1599 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1600 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1601 acmodel_npropsettings++;
1603 FG_LOG( FG_GENERAL, FG_INFO, "PROPELLER SETTING " << prop_low <<
1609 // align the model properly for FGFS
1610 ssgTransform *acmodel_align = new ssgTransform;
1611 acmodel_align->addKid(acmodel_obj);
1615 float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1616 float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1617 float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1618 float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1619 float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1620 float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1621 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1622 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1623 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1624 acmodel_align->setTransform(res_matrix);
1626 acmodel_pos->addKid( acmodel_align );
1627 acmodel_selector->addKid( acmodel_pos );
1628 //ssgFlatten( acmodel_obj );
1629 //ssgStripify( acmodel_selector );
1630 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1631 scene->addKid( acmodel_selector );
1633 // $$$ begin - added VS Renganthan 17 Oct 2K
1635 // $$$ end - added VS Renganthan 17 Oct 2K
1637 #ifdef FG_NETWORK_OLK
1638 // Do the network intialization
1639 if ( fgGetBool("/sim/networking/network-olk") ) {
1640 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1644 // build our custom render states
1645 fgBuildRenderStates();
1647 // pass control off to the master GLUT event handler
1650 // we never actually get here ... but to avoid compiler warnings,
1656 // $$$ end - added VS Renganathan, 15 Oct 2K
1657 // - added Venky , 12 Nov 2K
1659 void fgLoadDCS(void) {
1661 ssgEntity *ship_obj = NULL;
1664 char obj_filename[25];
1666 for (int k=0;k<32;k++)
1671 FGPath tile_path( globals->get_fg_root());
1672 tile_path.append( "Scenery" );
1673 tile_path.append( "Objects.txt" );
1674 fg_gzifstream in( tile_path.str() );
1675 if ( ! in.is_open() ) {
1676 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1679 FGPath modelpath( globals->get_fg_root() );
1680 modelpath.append( "Models" );
1681 modelpath.append( "Geometry" );
1683 FGPath texturepath( globals->get_fg_root() );
1684 texturepath.append( "Models" );
1685 texturepath.append( "Textures" );
1687 ssgModelPath( (char *)modelpath.c_str() );
1688 ssgTexturePath( (char *)texturepath.c_str() );
1690 ship_sel = new ssgSelector;
1693 while ( ! in.eof() )
1696 if ( in.get( c ) && c == '#' )
1703 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1704 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1705 int chj=getchar();*/
1707 obj_lon[objc] *=DEG_TO_RAD;
1708 obj_lat[objc] *=DEG_TO_RAD;
1710 ship_pos[objc] = new ssgTransform;
1713 // type "repeat" in objects.txt to load one more instance of the last object.
1715 if ( strcmp(obj_filename,"repeat") != 0)
1716 ship_obj = ssgLoadOBJ( obj_filename );
1718 if ( ship_obj != NULL )
1720 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1721 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1724 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << obj_filename );
1726 if (in.eof()) break;
1731 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1732 scene->addKid( ship_sel ); //add selector node to root node
1737 void fgUpdateDCS (void) {
1739 // double eye_lat,eye_lon,eye_alt;
1740 // static double obj_head;
1741 double sl_radius,obj_latgc;
1742 // float nresultmat[4][4];
1743 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1746 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1747 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1749 // Deck should be the first object in objects.txt in case of fdm=ada
1751 if (fgGetString("/sim/flight-model") == "ada")
1753 obj_lon[0] = fdm->get_aux5()*DEG_TO_RAD;
1754 obj_lat[0] = fdm->get_aux6()*DEG_TO_RAD;
1755 obj_alt[0] = fdm->get_aux7();
1758 for (int m=0; m<=objc; m++)
1760 //cout << endl << obj_lat[m]*RAD_TO_DEG << " " << obj_lon[m]*RAD_TO_DEG << " " << obj_alt[m] << " " << objc << endl;
1763 //Geodetic to Geocentric angles for rotation
1764 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1766 //moving object gbs-posn in cartesian coords
1767 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1768 Point3D obj_pos = sgGeodToCart( obj_posn );
1770 // Translate moving object w.r.t eye
1771 Point3D Objtrans = obj_pos-scenery.center;
1776 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1779 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1781 sgVec3 ship_fwd,ship_rt,ship_up;
1782 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1783 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1784 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1786 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1787 sgMakeRotMat4( sgROT_lon, obj_lon[m]*RAD_TO_DEG, ship_up );
1788 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1789 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1792 sgCopyMat4( sgTUX, sgROT_hdg );
1793 sgPostMultMat4( sgTUX, sgROT_lat );
1794 sgPostMultMat4( sgTUX, sgROT_lon );
1795 sgPostMultMat4( sgTUX, sgTRANS );
1798 sgSetCoord(&shippos, sgTUX );
1799 ship_pos[m]->setTransform( &shippos );
1801 if ( ship_sel != NULL )
1802 ship_sel->select(0xFFFFFFFF);
1805 // $$$ end - added VS Renganathan, 15 Oct 2K
1806 // added Venky , 12 Nov 2K