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 <GUI/sgVec3Slider.hxx>
85 #include <Joystick/joystick.hxx>
87 #include <NetworkOLK/network.h>
89 #include <Scenery/scenery.hxx>
90 #include <Scenery/tilemgr.hxx>
91 #include <Time/event.hxx>
92 #include <Time/fg_timer.hxx>
93 #include <Time/light.hxx>
94 #include <Time/sunpos.hxx>
95 #include <Time/tmp.hxx>
97 // begin - added Venky
98 // $$$ begin - added VS Renganathan
99 #include <simgear/misc/fgstream.hxx>
100 #include <FDM/flight.hxx>
101 #include <FDM/ADA.hxx>
102 void fgLoadDCS (void);
103 void fgUpdateDCS (void);
104 ssgSelector *ship_sel=NULL;
105 // upto 32 instances of a same object can be loaded.
106 ssgTransform *ship_pos[32];
107 double obj_lat[32],obj_lon[32],obj_alt[32];
109 // $$$ end - added VS Renganathan
112 #ifndef FG_OLD_WEATHER
113 # include <WeatherCM/FGLocalWeatherDatabase.h>
115 # include <Weather/weather.hxx>
121 #include "fg_init.hxx"
123 #include "globals.hxx"
124 #include "keyboard.hxx"
125 #include "splash.hxx"
128 # include <console.h> // -dw- for command line dialog
132 // This is a record containing a bit of global housekeeping information
135 // Specify our current idle function state. This is used to run all
136 // our initializations out of the glutIdleLoop() so that we can get a
137 // splash screen up and running right away.
138 static int idle_state = 0;
139 static long global_multi_loop;
141 // attempt to avoid a large bounce at startup
142 static bool initial_freeze = true;
144 // forward declaration
145 void fgReshape( int width, int height );
147 // Global structures for the Audio library
148 #ifdef ENABLE_AUDIO_SUPPORT
149 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
150 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
151 slScheduler *audio_sched;
152 smMixer *audio_mixer;
159 ssgRoot *scene = NULL;
160 ssgBranch *terrain = NULL;
162 // aircraft model stuff
163 ssgSelector *acmodel_selector = NULL;
164 ssgTransform *acmodel_pos = NULL;
165 ssgSelector *prop_selector = NULL;
166 ssgSelector *flaps_selector = NULL;
167 int acmodel_npropsettings;
168 int acmodel_proprpms[4][2]; // different propeller settings
170 ssgRoot *lighting = NULL;
171 ssgBranch *ground = NULL;
172 ssgBranch *airport = NULL;
174 #ifdef FG_NETWORK_OLK
175 ssgSelector *fgd_sel = NULL;
176 ssgTransform *fgd_pos = NULL;
179 // current fdm/position used for view
180 FGInterface cur_view_fdm;
186 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
188 { 1.0f, 0.0f, 0.0f, 0.0f },
189 { 0.0f, 0.0f, -1.0f, 0.0f },
190 { 0.0f, 1.0f, 0.0f, 0.0f },
191 { 0.0f, 0.0f, 0.0f, 1.0f }
194 // The following defines flightgear options. Because glutlib will also
195 // want to parse its own options, those options must not be included here
196 // or they will get parsed by the main program option parser. Hence case
197 // is significant for any option added that might be in conflict with
200 // glutlib parses for:
202 // -direct (invalid in Win32)
206 // -indirect (invalid in Win32)
209 // Note that glutlib depends upon strings while this program's
210 // option parser wants only initial characters followed by numbers
215 ssgSimpleState *default_state;
216 ssgSimpleState *hud_and_panel;
217 ssgSimpleState *menus;
219 void fgBuildRenderStates( void ) {
220 default_state = new ssgSimpleState;
221 default_state->ref();
222 default_state->disable( GL_TEXTURE_2D );
223 default_state->enable( GL_CULL_FACE );
224 default_state->enable( GL_COLOR_MATERIAL );
225 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
226 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
227 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
228 default_state->disable( GL_BLEND );
229 default_state->disable( GL_ALPHA_TEST );
230 default_state->disable( GL_LIGHTING );
232 hud_and_panel = new ssgSimpleState;
233 hud_and_panel->ref();
234 hud_and_panel->disable( GL_CULL_FACE );
235 hud_and_panel->disable( GL_TEXTURE_2D );
236 hud_and_panel->disable( GL_LIGHTING );
237 hud_and_panel->enable( GL_BLEND );
239 menus = new ssgSimpleState;
241 menus->disable( GL_CULL_FACE );
242 menus->disable( GL_TEXTURE_2D );
243 menus->enable( GL_BLEND );
246 // fgFindNode -- a function that finds a named node in an ssg graph
247 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
248 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
250 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
251 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
252 while (kid != NULL) {
253 ssgEntity *n = fgFindNode(kid, name);
257 kid = ((ssgBranch*)node)->getNextKid();
264 // fgInitVisuals() -- Initialize various GL/view parameters
265 void fgInitVisuals( void ) {
268 l = &cur_light_params;
270 #ifndef GLUT_WRONG_VERSION
271 // Go full screen if requested ...
272 if ( fgGetBool("/sim/startup/fullscreen") ) {
277 // If enabled, normal vectors specified with glNormal are scaled
278 // to unit length after transformation. See glNormal.
279 // glEnable( GL_NORMALIZE );
281 glEnable( GL_LIGHTING );
282 glEnable( GL_LIGHT0 );
283 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
286 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
287 ssgGetLight( 0 ) -> setPosition( sunpos );
289 // glFogi (GL_FOG_MODE, GL_LINEAR);
290 glFogi (GL_FOG_MODE, GL_EXP2);
291 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
292 (!fgGetBool("/sim/rendering/shading"))) {
293 // if fastest fog requested, or if flat shading force fastest
294 glHint ( GL_FOG_HINT, GL_FASTEST );
295 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
296 glHint ( GL_FOG_HINT, GL_NICEST );
298 if ( fgGetBool("/sim/rendering/wireframe") ) {
300 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
303 // This is the default anyways, but it can't hurt
304 glFrontFace ( GL_CCW );
307 // glEnable(GL_POINT_SMOOTH);
308 // glEnable(GL_LINE_SMOOTH);
309 // glEnable(GL_POLYGON_SMOOTH);
313 // Update all Visuals (redraws anything graphics related)
314 void fgRenderFrame( void ) {
318 fgLIGHT *l = &cur_light_params;
319 static double last_visibility = -9999;
321 static GLfloat fog_exp_density;
322 static GLfloat fog_exp2_density;
323 static GLfloat fog_exp2_punch_through;
326 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
327 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
328 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
329 // GLfloat mat_shininess[] = { 10.0 };
330 GLbitfield clear_mask;
332 if ( idle_state != 1000 ) {
333 // still initializing, draw the splash screen
334 if ( fgGetBool("/sim/startup/splash-screen") ) {
338 // idle_state is now 1000 meaning we've finished all our
339 // initializations and are running the main loop, so this will
340 // now work without seg faulting the system.
342 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
343 // FG_Altitude * FEET_TO_METER);
345 // this is just a temporary hack, to make me understand Pui
346 // timerText -> setLabel (ctime (&t->cur_time));
349 // calculate our current position in cartesian space
350 scenery.center = scenery.next_center;
351 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
352 // scenery.center.y(), scenery.center.z());
354 FGViewerRPH *pilot_view =
355 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
357 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
358 cur_fdm_state->get_Lat_geocentric(),
359 cur_fdm_state->get_Altitude() *
361 pilot_view->set_sea_level_radius( cur_fdm_state->
362 get_Sea_level_radius() *
364 pilot_view->set_rph( cur_fdm_state->get_Phi(),
365 cur_fdm_state->get_Theta(),
366 cur_fdm_state->get_Psi() );
368 FGViewerLookAt *chase_view =
369 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
371 sgVec3 po; // chase view pilot_offset
372 sgVec3 wup; // chase view world up
373 sgSetVec3( po, 0.0, 0.0, 50.0 );
374 sgCopyVec3( wup, pilot_view->get_world_up() );
375 sgMat4 CXFM; // chase view + pilot offset xform
377 chase_view->get_view_offset() * RAD_TO_DEG -
378 cur_fdm_state->get_Psi() * RAD_TO_DEG,
380 sgVec3 npo; // new pilot offset after rotation
381 sgVec3 *pPO = PilotOffsetGet();
382 sgXformVec3( po, *pPO, pilot_view->get_UP() );
383 sgXformVec3( npo, po, CXFM );
385 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
386 cur_fdm_state->get_Lat_geocentric(),
387 cur_fdm_state->get_Altitude() *
389 chase_view->set_sea_level_radius( cur_fdm_state->
390 get_Sea_level_radius() *
392 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
393 chase_view->set_view_forward( pilot_view->get_view_pos() );
394 chase_view->set_view_up( wup );
398 sgCopyMat4( rph, pilot_view->get_VIEW() );
399 cout << "RPH Matrix = " << endl;
401 for ( i = 0; i < 4; i++ ) {
402 for ( j = 0; j < 4; j++ ) {
403 printf("%10.4f ", rph[i][j]);
409 sgCopyMat4( la, chase_view->get_VIEW() );
410 cout << "LookAt Matrix = " << endl;
411 for ( i = 0; i < 4; i++ ) {
412 for ( j = 0; j < 4; j++ ) {
413 printf("%10.4f ", la[i][j]);
420 fgReshape( fgGetInt("/sim/startup/xsize"),
421 fgGetInt("/sim/startup/ysize") );
426 if ( ! fgPanelVisible() ) {
428 (GLint)(fgGetInt("/sim/startup/xsize")),
429 (GLint)(fgGetInt("/sim/startup/ysize")) );
432 int( (current_panel->getViewHeight() -
433 current_panel->getYOffset())
434 * (fgGetInt("/sim/startup/ysize") / 768.0) );
436 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
437 (GLint)(fgGetInt("/sim/startup/xsize")),
442 // set the sun position
443 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
445 clear_mask = GL_DEPTH_BUFFER_BIT;
446 if ( fgGetBool("/sim/rendering/wireframe") ) {
447 clear_mask |= GL_COLOR_BUFFER_BIT;
450 if ( fgGetBool("/sim/rendering/skyblend") ) {
451 if ( fgGetBool("/sim/rendering/textures") ) {
452 // glClearColor(black[0], black[1], black[2], black[3]);
453 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
454 l->adj_fog_color[2], l->adj_fog_color[3]);
455 clear_mask |= GL_COLOR_BUFFER_BIT;
458 glClearColor(l->sky_color[0], l->sky_color[1],
459 l->sky_color[2], l->sky_color[3]);
460 clear_mask |= GL_COLOR_BUFFER_BIT;
462 glClear( clear_mask );
464 // Tell GL we are switching to model view parameters
466 // I really should create a derived ssg node or use a call
467 // back or something so that I can draw the sky within the
468 // ssgCullAndDraw() function, but for now I just mimic what
469 // ssg does to set up the model view matrix
470 glMatrixMode(GL_MODELVIEW);
472 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
474 // set the opengl state to known default values
475 default_state->force();
477 // update fog params if visibility has changed
478 #ifndef FG_OLD_WEATHER
479 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
481 thesky->set_visibility( current_weather.get_visibility() );
484 thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
485 ( global_multi_loop *
486 fgGetInt("/sim/speed-up") ) /
487 (double)fgGetInt("/sim/model-hz") );
489 double actual_visibility = thesky->get_visibility();
490 // cout << "actual visibility = " << actual_visibility << endl;
492 if ( actual_visibility != last_visibility ) {
493 last_visibility = actual_visibility;
495 // cout << "----> updating fog params" << endl;
498 fog_exp_density = -log(0.01 / actual_visibility);
501 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
502 fog_exp2_punch_through = sqrt( -log(0.01) ) /
503 ( actual_visibility * 1.5 );
506 // Set correct opengl fog density
507 glFogf (GL_FOG_DENSITY, fog_exp2_density);
509 // update the sky dome
510 if ( fgGetBool("/sim/rendering/skyblend") ) {
511 /* cout << "thesky->repaint() sky_color = "
512 << cur_light_params.sky_color[0] << " "
513 << cur_light_params.sky_color[1] << " "
514 << cur_light_params.sky_color[2] << " "
515 << cur_light_params.sky_color[3] << endl;
517 << cur_light_params.fog_color[0] << " "
518 << cur_light_params.fog_color[1] << " "
519 << cur_light_params.fog_color[2] << " "
520 << cur_light_params.fog_color[3] << endl;
521 cout << " sun_angle = " << cur_light_params.sun_angle
522 << " moon_angle = " << cur_light_params.moon_angle
524 thesky->repaint( cur_light_params.sky_color,
525 cur_light_params.adj_fog_color,
526 cur_light_params.sun_angle,
527 cur_light_params.moon_angle,
528 globals->get_ephem()->getNumPlanets(),
529 globals->get_ephem()->getPlanets(),
530 globals->get_ephem()->getNumStars(),
531 globals->get_ephem()->getStars() );
533 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
534 << view_pos[1] << " " << view_pos[2] << endl;
535 cout << " zero_elev = " << zero_elev[0] << " "
536 << zero_elev[1] << " " << zero_elev[2]
537 << " lon = " << cur_fdm_state->get_Longitude()
538 << " lat = " << cur_fdm_state->get_Latitude() << endl;
539 cout << " sun_rot = " << cur_light_params.sun_rotation
540 << " gst = " << SGTime::cur_time_params->getGst() << endl;
541 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
542 << " sun dec = " << globals->get_ephem()->getSunDeclination()
543 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
544 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
546 thesky->reposition( globals->get_current_view()->get_view_pos(),
547 globals->get_current_view()->get_zero_elev(),
548 globals->get_current_view()->get_world_up(),
549 cur_fdm_state->get_Longitude(),
550 cur_fdm_state->get_Latitude(),
551 cur_fdm_state->get_Altitude() * FEET_TO_METER,
552 cur_light_params.sun_rotation,
553 globals->get_time_params()->getGst(),
554 globals->get_ephem()->getSunRightAscension(),
555 globals->get_ephem()->getSunDeclination(),
557 globals->get_ephem()->getMoonRightAscension(),
558 globals->get_ephem()->getMoonDeclination(),
562 glEnable( GL_DEPTH_TEST );
563 if ( fgGetString("/sim/rendering/fog") != "disabled" ) {
565 glFogi( GL_FOG_MODE, GL_EXP2 );
566 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
569 // set lighting parameters
570 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
571 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
572 glLightfv( GL_LIGHT0, GL_AMBIENT, black );
573 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
574 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
576 // texture parameters
577 // glEnable( GL_TEXTURE_2D );
578 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
579 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
580 // set base color (I don't think this is doing anything here)
581 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
582 // (GL_FRONT, GL_DIFFUSE, white);
583 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
584 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
587 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
588 ssgGetLight( 0 ) -> setPosition( sunpos );
590 // glMatrixMode( GL_PROJECTION );
592 float fov = globals->get_current_view()->get_fov();
593 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
595 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
598 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
599 // << current_weather.get_visibility() );
602 ssgSetNearFar( 10.0f, 120000.0f );
604 ssgSetNearFar( 0.5f, 120000.0f );
607 if ( globals->get_viewmgr()->get_current() == 0 ) {
608 // disable aircraft model
609 acmodel_selector->select(0);
611 // enable aircraft model and set up its position and orientation
612 acmodel_selector->select(1);
614 FGViewerRPH *pilot_view =
615 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
618 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
621 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
624 sgMakeRotMat4( sgROT, -90.0, ownship_up );
628 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
629 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
631 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
633 sgCopyMat4( sgTUX, sgROT );
634 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
635 sgPostMultMat4( sgTUX, sgTRANS );
638 sgSetCoord( &tuxpos, sgTUX );
639 acmodel_pos->setTransform( &tuxpos );
641 // set up moving parts
642 if (flaps_selector != NULL) {
643 flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
646 if (prop_selector != NULL) {
647 int propsel_mask = 0;
648 for (int i = 0; i < acmodel_npropsettings; i++) {
649 if (FGBFI::getRPM() >= acmodel_proprpms[i][0] &&
650 FGBFI::getRPM() <= acmodel_proprpms[i][1]) {
651 propsel_mask |= 1 << i;
654 prop_selector->select(propsel_mask);
658 // $$$ begin - added VS Renganthan 17 Oct 2K
660 // $$$ end - added VS Renganthan 17 Oct 2K
662 # ifdef FG_NETWORK_OLK
663 if ( fgGetBool("/sim/networking/network-olk") ) {
665 other = head->next; /* put listpointer to start */
666 while ( other != tail) { /* display all except myself */
667 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
668 other->fgd_sel->select(1);
669 sgSetCoord( &fgdpos, other->sgFGD_COORD );
670 other->fgd_pos->setTransform( &fgdpos );
675 // fgd_sel->select(1);
676 // sgCopyMat4( sgTUX, current_view.sgVIEW);
678 // sgSetCoord( &fgdpos, sgFGD_VIEW );
679 // fgd_pos->setTransform( &fgdpos);
683 // position tile nodes and update range selectors
684 global_tile_mgr.prep_ssg_nodes();
686 if ( fgGetBool("/sim/rendering/skyblend") ) {
687 // draw the sky backdrop
691 // draw the ssg scene
692 glEnable( GL_DEPTH_TEST );
693 ssgCullAndDraw( scene );
695 // change state for lighting here
698 // Set punch through fog density
699 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
701 ssgCullAndDraw( lighting );
703 if ( fgGetBool("/sim/rendering/skyblend") ) {
704 // draw the sky cloud layers
705 thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
708 // display HUD && Panel
710 glDisable( GL_DEPTH_TEST );
711 // glDisable( GL_CULL_FACE );
712 // glDisable( GL_TEXTURE_2D );
714 // update the controls subsystem
717 hud_and_panel->apply();
720 // update the panel subsystem
721 if (current_panel != 0)
722 current_panel->update();
724 // We can do translucent menus, so why not. :-)
726 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
728 // glDisable ( GL_BLEND ) ;
730 // glEnable( GL_FOG );
737 // Update internal time dependent calculations (i.e. flight model)
738 void fgUpdateTimeDepCalcs() {
739 static bool inited = false;
741 fgLIGHT *l = &cur_light_params;
746 if ( !globals->get_freeze() && !initial_freeze ) {
747 // conceptually, this could be done for each fdm instance ...
750 cur_fdm_state->stamp();
756 long elapsed = current - cur_fdm_state->get_time_stamp();
757 cur_fdm_state->set_time_stamp( current );
758 elapsed += cur_fdm_state->get_remainder();
759 // cout << "elapsed = " << elapsed << endl;
760 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
761 multi_loop = (long)(((double)elapsed * 0.000001) /
762 cur_fdm_state->get_delta_t() );
763 cur_fdm_state->set_multi_loop( multi_loop );
764 long remainder = elapsed - ( (multi_loop*1000000) *
765 cur_fdm_state->get_delta_t() );
766 cur_fdm_state->set_remainder( remainder );
767 // cout << "remainder = " << remainder << endl;
769 // chop max interations to something reasonable if the sim was
770 // delayed for an excesive amount of time
771 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
772 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
773 cur_fdm_state->set_remainder( 0 );
776 // cout << "multi_loop = " << multi_loop << endl;
777 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
778 // run Autopilot system
779 current_autopilot->run();
782 cur_fdm_state->update( 1 );
784 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
786 cur_fdm_state->update( 0 );
787 FGSteam::update( 0 );
789 if ( global_tile_mgr.queue_size() == 0 ) {
790 initial_freeze = false;
794 if ( fgGetString("/sim/view-mode") == "pilot" ) {
795 cur_view_fdm = *cur_fdm_state;
799 // update the view angle
800 FGViewer *v = globals->get_current_view();
801 for ( i = 0; i < multi_loop; i++ ) {
802 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
803 v->set_view_offset( v->get_goal_view_offset() );
806 // move current_view.view_offset towards
807 // current_view.goal_view_offset
808 if ( v->get_goal_view_offset() > v->get_view_offset() )
810 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
811 v->inc_view_offset( 0.01 );
813 v->inc_view_offset( -0.01 );
816 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
817 v->inc_view_offset( -0.01 );
819 v->inc_view_offset( 0.01 );
822 if ( v->get_view_offset() > FG_2PI ) {
823 v->inc_view_offset( -FG_2PI );
824 } else if ( v->get_view_offset() < 0 ) {
825 v->inc_view_offset( FG_2PI );
830 double tmp = -(l->sun_rotation + FG_PI)
831 - (cur_fdm_state->get_Psi() -
832 globals->get_current_view()->get_view_offset() );
833 while ( tmp < 0.0 ) {
836 while ( tmp > FG_2PI ) {
839 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
840 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
841 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
844 // Update solar system
845 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
846 globals->get_time_params()->getLst(),
847 cur_fdm_state->get_Latitude() );
849 // Update radio stack model
850 current_radiostack->update();
854 void fgInitTimeDepCalcs( void ) {
857 // #ifdef HAVE_SETITIMER
858 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
859 // fgUpdateTimeDepCalcs );
860 // #endif HAVE_SETITIMER
864 static const double alt_adjust_ft = 3.758099;
865 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
868 // What should we do when we have nothing else to do? Let's get ready
869 // for the next move and update the display?
870 static void fgMainLoop( void ) {
871 static long remainder = 0;
873 #ifdef FANCY_FRAME_COUNTER
877 static time_t last_time = 0;
878 static int frames = 0;
879 #endif // FANCY_FRAME_COUNTER
881 SGTime *t = globals->get_time_params();
883 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
884 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
886 #ifdef FG_NETWORK_OLK
887 if ( fgGetBool("/sim/networking/network-olk") ) {
888 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
889 // printf("FGD: Netupdate\n");
890 fgd_send_com( "A", FGFS_host); // Send Mat4 data
891 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
896 #if defined( ENABLE_PLIB_JOYSTICK )
897 // Read joystick and update control settings
898 if ( fgGetString("/sim/control-mode") == "joystick" )
902 #elif defined( ENABLE_GLUT_JOYSTICK )
903 // Glut joystick support works by feeding a joystick handler
904 // function to glut. This is taken care of once in the joystick
905 // init routine and we don't have to worry about it again.
908 #ifdef FG_OLD_WEATHER
909 current_weather.Update();
912 // Fix elevation. I'm just sticking this here for now, it should
913 // probably move eventually
915 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
917 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
918 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
920 if ( scenery.cur_elev > -9990 ) {
921 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
922 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
923 // now set aircraft altitude above ground
924 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
925 cur_fdm_state->get_Altitude() * FEET_TO_METER,
926 scenery.cur_elev + alt_adjust_m - 3.0,
927 scenery.cur_elev + alt_adjust_m );
928 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
929 scenery.cur_elev + alt_adjust_m );
931 FG_LOG( FG_ALL, FG_DEBUG,
932 "<*> resetting altitude to "
933 << cur_fdm_state->get_Altitude() * FEET_TO_METER
938 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
940 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
941 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
944 if ( globals->get_warp_delta() != 0 ) {
945 globals->inc_warp( globals->get_warp_delta() );
948 t->update( cur_fdm_state->get_Longitude(),
949 cur_fdm_state->get_Latitude(),
950 globals->get_warp() );
952 if ( globals->get_warp_delta() != 0 ) {
953 fgUpdateSkyAndLightingParams();
956 // update magvar model
957 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
958 cur_fdm_state->get_Latitude(),
959 cur_fdm_state->get_Altitude()* FEET_TO_METER,
960 globals->get_time_params()->getJD() );
962 // Get elapsed time (in usec) for this past frame
963 elapsed = fgGetTimeInterval();
964 FG_LOG( FG_ALL, FG_DEBUG,
965 "Elapsed time interval is = " << elapsed
966 << ", previous remainder is = " << remainder );
968 // Calculate frame rate average
969 #ifdef FANCY_FRAME_COUNTER
970 /* old fps calculation */
974 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
975 tmp = general.get_frame(i);
977 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
978 general.set_frame(i+1,tmp);
980 tmp = 1000000.0 / (float)elapsed;
981 general.set_frame(0,tmp);
982 // printf("frame[0] = %.2f\n", general.frames[0]);
984 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
985 // printf("ave = %.2f\n", general.frame_rate);
988 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
989 general.set_frame_rate( frames );
990 FG_LOG( FG_ALL, FG_DEBUG,
991 "--> Frame rate is = " << general.get_frame_rate() );
994 last_time = t->get_cur_time();
1000 // Calculate model iterations needed for next frame
1001 elapsed += remainder;
1003 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1004 fgGetInt("/sim/model-hz"));
1005 remainder = elapsed - ( (global_multi_loop*1000000) /
1006 fgGetInt("/sim/model-hz") );
1007 FG_LOG( FG_ALL, FG_DEBUG,
1008 "Model iterations needed = " << global_multi_loop
1009 << ", new remainder = " << remainder );
1011 // chop max interations to something reasonable if the sim was
1012 // delayed for an excesive amount of time
1013 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1014 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1019 if ( global_multi_loop > 0 ) {
1020 fgUpdateTimeDepCalcs();
1022 FG_LOG( FG_ALL, FG_DEBUG,
1023 "Elapsed time is zero ... we're zinging" );
1026 #if ! defined( macintosh )
1027 // Do any I/O channel work that might need to be done
1031 // see if we need to load any new scenery tiles
1032 global_tile_mgr.update( cur_fdm_state->get_Longitude() * RAD_TO_DEG,
1033 cur_fdm_state->get_Latitude() * RAD_TO_DEG );
1035 // Process/manage pending events
1036 global_events.Process();
1038 // Run audio scheduler
1039 #ifdef ENABLE_AUDIO_SUPPORT
1040 if ( fgGetBool("/sim/sound") && !audio_sched->not_working() ) {
1042 if ( fgGetString("/sim/aircraft") == "c172" ) {
1043 // pitch corresponds to rpm
1044 // volume corresponds to manifold pressure
1047 if ( cur_fdm_state->get_engine(0) != NULL ) {
1048 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1052 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1055 double pitch = 0.3 + rpm_factor * 3.0;
1057 // don't run at absurdly slow rates -- not realistic
1058 // and sounds bad to boot. :-)
1059 if (pitch < 0.7) { pitch = 0.7; }
1060 if (pitch > 5.0) { pitch = 5.0; }
1061 // cout << "pitch = " << pitch << endl;
1064 if ( cur_fdm_state->get_engine(0) != NULL ) {
1066 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1071 << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1074 double volume = 0.3 + mp_factor;
1076 if ( volume < 0.3 ) { volume = 0.3; }
1077 if ( volume > 1.0 ) { volume = 1.0; }
1078 // cout << "volume = " << volume << endl;
1080 pitch_envelope.setStep ( 0, 0.01, pitch );
1081 volume_envelope.setStep ( 0, 0.01, volume );
1083 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1084 pitch_envelope.setStep ( 0, 0.01, param );
1085 volume_envelope.setStep ( 0, 0.01, param );
1088 audio_sched -> update();
1095 FG_LOG( FG_ALL, FG_DEBUG, "" );
1099 // This is the top level master main function that is registered as
1100 // our idle funciton
1103 // The first few passes take care of initialization things (a couple
1104 // per pass) and once everything has been initialized fgMainLoop from
1107 static void fgIdleFunction ( void ) {
1108 // printf("idle state == %d\n", idle_state);
1110 if ( idle_state == 0 ) {
1111 // Initialize the splash screen right away
1112 if ( fgGetBool("/sim/startup/splash-screen") ) {
1117 } else if ( idle_state == 1 ) {
1118 // Start the intro music
1120 if ( fgGetBool("/sim/startup/intro-music") ) {
1121 string lockfile = "/tmp/mpg123.running";
1122 FGPath mp3file( globals->get_fg_root() );
1123 mp3file.append( "Sounds/intro.mp3" );
1125 string command = "(touch " + lockfile + "; mpg123 "
1126 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1128 FG_LOG( FG_GENERAL, FG_INFO,
1129 "Starting intro music: " << mp3file.str() );
1130 system ( command.c_str() );
1135 } else if ( idle_state == 2 ) {
1136 // These are a few miscellaneous things that aren't really
1137 // "subsystems" but still need to be initialized.
1140 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1141 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1146 } else if ( idle_state == 3 ) {
1147 // This is the top level init routine which calls all the
1148 // other subsystem initialization routines. If you are adding
1149 // a subsystem to flightgear, its initialization call should
1150 // located in this routine.
1151 if( !fgInitSubsystems()) {
1152 FG_LOG( FG_GENERAL, FG_ALERT,
1153 "Subsystem initializations failed ..." );
1158 } else if ( idle_state == 4 ) {
1159 // setup OpenGL view parameters
1163 } else if ( idle_state == 5 ) {
1166 } else if ( idle_state == 6 ) {
1167 // Initialize audio support
1168 #ifdef ENABLE_AUDIO_SUPPORT
1171 if ( fgGetBool("/sim/startup/intro-music") ) {
1172 // Let's wait for mpg123 to finish
1173 string lockfile = "/tmp/mpg123.running";
1174 struct stat stat_buf;
1176 FG_LOG( FG_GENERAL, FG_INFO,
1177 "Waiting for mpg123 player to finish ..." );
1178 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1179 // file exist, wait ...
1181 FG_LOG( FG_GENERAL, FG_INFO, ".");
1183 FG_LOG( FG_GENERAL, FG_INFO, "");
1187 if ( fgGetBool("/sim/sound") ) {
1188 audio_sched = new slScheduler ( 8000 );
1189 audio_mixer = new smMixer;
1190 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1191 audio_sched -> setSafetyMargin ( 1.0 ) ;
1193 FGPath slfile( globals->get_fg_root() );
1194 slfile.append( "Sounds/wasp.wav" );
1196 s1 = new slSample ( (char *)slfile.c_str() );
1197 FG_LOG( FG_GENERAL, FG_INFO,
1198 "Rate = " << s1 -> getRate()
1199 << " Bps = " << s1 -> getBps()
1200 << " Stereo = " << s1 -> getStereo() );
1201 audio_sched -> loopSample ( s1 );
1203 if ( audio_sched->not_working() ) {
1206 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1207 volume_envelope.setStep ( 0, 0.01, 0.6 );
1209 audio_sched -> addSampleEnvelope( s1, 0, 0,
1211 SL_PITCH_ENVELOPE );
1212 audio_sched -> addSampleEnvelope( s1, 0, 1,
1214 SL_VOLUME_ENVELOPE );
1217 // strcpy(slfile, path);
1218 // strcat(slfile, "thunder.wav");
1219 // s2 -> loadFile ( slfile );
1220 // s2 -> adjustVolume(0.5);
1221 // audio_sched -> playSample ( s2 );
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 FG_LOG( FG_GENERAL, FG_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 FG_LOG( FG_GENERAL, FG_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 FG_LOG( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1332 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1333 general.set_glMaxTexSize( tmp );
1334 FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1336 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1337 general.set_glDepthBits( tmp );
1338 FG_LOG ( FG_GENERAL, FG_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 glutSpecialFunc( GLUTspecialkey );
1353 // call guiMouseFunc() whenever our little rodent is used
1354 glutMouseFunc ( guiMouseFunc );
1355 glutMotionFunc (guiMotionFunc );
1356 glutPassiveMotionFunc (guiMotionFunc );
1358 // call fgMainLoop() whenever there is
1359 // nothing else to do
1360 glutIdleFunc( fgIdleFunction );
1363 glutDisplayFunc( fgRenderFrame );
1370 int main( int argc, char **argv ) {
1372 #if defined( macintosh )
1373 freopen ("stdout.txt", "w", stdout );
1374 freopen ("stderr.txt", "w", stderr );
1375 argc = ccommand( &argv );
1379 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1382 // set default log levels
1383 fglog().setLogLevels( FG_ALL, FG_INFO );
1386 #ifdef FLIGHTGEAR_VERSION
1387 version = FLIGHTGEAR_VERSION;
1389 version = "unknown version";
1391 FG_LOG( FG_GENERAL, FG_INFO, "FlightGear: Version "
1392 << version << endl );
1394 // Allocate global data structures. This needs to happen before
1395 // we parse command line options
1397 SGPropertyNode *props = new SGPropertyNode;
1398 globals = new FGGlobals;
1399 globals->set_props( props );
1401 // seed the random number generater
1404 SGRoute *route = new SGRoute;
1405 globals->set_route( route );
1407 FGViewMgr *viewmgr = new FGViewMgr;
1408 globals->set_viewmgr( viewmgr );
1410 FGViewerRPH *pv = new FGViewerRPH;
1411 globals->get_viewmgr()->add_view( pv );
1413 FGViewerLookAt *chase = new FGViewerLookAt;
1414 globals->get_viewmgr()->add_view( chase );
1416 string_list *col = new string_list;
1417 globals->set_channel_options_list( col );
1419 // set current view to 0 (first) which is our main pilot view
1420 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1422 // Scan the config file(s) and command line options to see if
1423 // fg_root was specified (ignore all other options for now)
1424 fgInitFGRoot(argc, argv);
1426 // Initialize the Aircraft directory to "" (UIUC)
1429 // Load the configuration parameters
1430 if ( !fgInitConfig(argc, argv) ) {
1431 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1435 // Initialize the Window/Graphics environment.
1436 if( !fgGlutInit(&argc, argv) ) {
1437 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1441 // Initialize the various GLUT Event Handlers.
1442 if( !fgGlutInitEvents() ) {
1443 FG_LOG( FG_GENERAL, FG_ALERT,
1444 "GLUT event handler initialization failed ..." );
1448 // Initialize ssg (from plib). Needs to come before we do any
1449 // other ssg stuff, but after opengl/glut has been initialized.
1452 // Initialize the user interface (we need to do this before
1453 // passing off control to glut and before fgInitGeneral to get our
1457 // set current_options lon/lat if an airport id is specified
1458 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1459 if ( fgGetString("/sim/startup/airport-id").length() ) {
1460 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1461 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1462 fgGetDouble("/orientation/heading") );
1466 FGPath zone( globals->get_fg_root() );
1467 zone.append( "Timezone" );
1468 SGTime *t = new SGTime( fgGetDouble("/position/longitude") * DEG_TO_RAD,
1469 fgGetDouble("/position/latitude") * DEG_TO_RAD,
1472 // Handle potential user specified time offsets
1473 time_t cur_time = t->get_cur_time();
1474 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1475 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1476 time_t aircraftLocalTime =
1477 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1479 // Okay, we now have six possible scenarios
1480 int offset = fgGetInt("/sim/startup/time-offset");
1481 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1482 if (offset_type == "system-offset") {
1483 globals->set_warp( offset );
1484 } else if (offset_type == "gmt-offset") {
1485 globals->set_warp( offset - (currGMT - systemLocalTime) );
1486 } else if (offset_type == "latitude-offset") {
1487 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1488 } else if (offset_type == "system") {
1489 globals->set_warp( offset - cur_time );
1490 } else if (offset_type == "gmt") {
1491 globals->set_warp( offset - currGMT );
1492 } else if (offset_type == "latitude") {
1493 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1496 FG_LOG( FG_GENERAL, FG_ALERT,
1497 "Unsupported offset type " << offset_type );
1501 FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = "
1502 << globals->get_warp() );
1504 globals->set_warp_delta( 0 );
1506 t->update( 0.0, 0.0, globals->get_warp() );
1508 globals->set_time_params( t );
1510 // Do some quick general initializations
1511 if( !fgInitGeneral()) {
1512 FG_LOG( FG_GENERAL, FG_ALERT,
1513 "General initializations failed ..." );
1517 FGPath modelpath( globals->get_fg_root() );
1518 ssgModelPath( (char *)modelpath.c_str() );
1521 scene = new ssgRoot;
1522 scene->setName( "Scene" );
1524 lighting = new ssgRoot;
1525 lighting->setName( "Lighting" );
1527 // Initialize the sky
1528 FGPath ephem_data_path( globals->get_fg_root() );
1529 ephem_data_path.append( "Astro" );
1530 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1531 ephem->update( globals->get_time_params()->getMjd(),
1532 globals->get_time_params()->getLst(),
1534 globals->set_ephem( ephem );
1536 FGPath sky_tex_path( globals->get_fg_root() );
1537 sky_tex_path.append( "Textures" );
1538 sky_tex_path.append( "Sky" );
1540 thesky->texture_path( sky_tex_path.str() );
1542 thesky->build( 550.0, 550.0,
1543 globals->get_ephem()->getNumPlanets(),
1544 globals->get_ephem()->getPlanets(), 60000.0,
1545 globals->get_ephem()->getNumStars(),
1546 globals->get_ephem()->getStars(), 60000.0 );
1548 if ( fgGetBool("/environment/clouds/status") ) {
1549 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1550 SG_CLOUD_MOSTLY_SUNNY );
1551 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1553 // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1554 // SG_CLOUD_MOSTLY_SUNNY );
1555 // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1556 // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1559 // Initialize MagVar model
1560 SGMagVar *magvar = new SGMagVar();
1561 globals->set_mag( magvar );
1564 terrain = new ssgBranch;
1565 terrain->setName( "Terrain" );
1566 scene->addKid( terrain );
1569 ground = new ssgBranch;
1570 ground->setName( "Ground Lighting" );
1571 lighting->addKid( ground );
1573 airport = new ssgBranch;
1574 airport->setName( "Airport Lighting" );
1575 lighting->addKid( airport );
1577 // temporary visible aircraft "own ship"
1578 acmodel_selector = new ssgSelector;
1579 acmodel_pos = new ssgTransform;
1581 string acmodel_path =
1582 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1584 string full_model = globals->get_fg_root() + "/"
1586 int pos = full_model.rfind("/");
1588 FGPath texturepath( full_model.substr(0, pos) );
1589 cout << "Texture path = " << texturepath.str() << endl;
1590 ssgTexturePath( (char *)texturepath.c_str() );
1592 ssgEntity *acmodel_obj = ssgLoad((char *)(acmodel_path.c_str()));
1594 // find moving parts (if this is an MDL model)
1595 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1596 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1598 acmodel_npropsettings = 0;
1599 if (prop_selector != NULL) {
1600 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1601 kid = prop_selector->getNextKid()) {
1602 int prop_low, prop_high;
1603 if ( sscanf(kid->getName(), "PROP_%d_%d",
1604 &prop_low, &prop_high) == 2 ) {
1605 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1606 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1607 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1608 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1609 acmodel_npropsettings++;
1611 FG_LOG( FG_GENERAL, FG_INFO, "PROPELLER SETTING " << prop_low <<
1617 // align the model properly for FGFS
1618 ssgTransform *acmodel_align = new ssgTransform;
1619 acmodel_align->addKid(acmodel_obj);
1623 float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1624 float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1625 float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1626 float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1627 float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1628 float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1629 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1630 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1631 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1632 acmodel_align->setTransform(res_matrix);
1634 acmodel_pos->addKid( acmodel_align );
1635 acmodel_selector->addKid( acmodel_pos );
1636 //ssgFlatten( acmodel_obj );
1637 //ssgStripify( acmodel_selector );
1638 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1639 scene->addKid( acmodel_selector );
1641 // $$$ begin - added VS Renganthan 17 Oct 2K
1643 // $$$ end - added VS Renganthan 17 Oct 2K
1645 #ifdef FG_NETWORK_OLK
1646 // Do the network intialization
1647 if ( fgGetBool("/sim/networking/network-olk") ) {
1648 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1652 // build our custom render states
1653 fgBuildRenderStates();
1655 // pass control off to the master GLUT event handler
1658 // we never actually get here ... but to avoid compiler warnings,
1664 // $$$ end - added VS Renganathan, 15 Oct 2K
1665 // - added Venky , 12 Nov 2K
1667 void fgLoadDCS(void) {
1669 ssgEntity *ship_obj = NULL;
1672 char obj_filename[25];
1674 for (int k=0;k<32;k++)
1679 FGPath tile_path( globals->get_fg_root());
1680 tile_path.append( "Scenery" );
1681 tile_path.append( "Objects.txt" );
1682 fg_gzifstream in( tile_path.str() );
1683 if ( ! in.is_open() ) {
1684 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1687 FGPath modelpath( globals->get_fg_root() );
1688 modelpath.append( "Models" );
1689 modelpath.append( "Geometry" );
1691 FGPath texturepath( globals->get_fg_root() );
1692 texturepath.append( "Models" );
1693 texturepath.append( "Textures" );
1695 ssgModelPath( (char *)modelpath.c_str() );
1696 ssgTexturePath( (char *)texturepath.c_str() );
1698 ship_sel = new ssgSelector;
1701 while ( ! in.eof() )
1704 if ( in.get( c ) && c == '#' )
1711 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1712 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1713 int chj=getchar();*/
1715 obj_lon[objc] *=DEG_TO_RAD;
1716 obj_lat[objc] *=DEG_TO_RAD;
1718 ship_pos[objc] = new ssgTransform;
1721 // type "repeat" in objects.txt to load one more instance of the last object.
1723 if ( strcmp(obj_filename,"repeat") != 0)
1724 ship_obj = ssgLoadOBJ( obj_filename );
1726 if ( ship_obj != NULL )
1728 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1729 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1732 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << obj_filename );
1734 if (in.eof()) break;
1739 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1740 scene->addKid( ship_sel ); //add selector node to root node
1745 void fgUpdateDCS (void) {
1747 // double eye_lat,eye_lon,eye_alt;
1748 // static double obj_head;
1749 double sl_radius,obj_latgc;
1750 // float nresultmat[4][4];
1751 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1754 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1755 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1757 // Deck should be the first object in objects.txt in case of fdm=ada
1759 if (fgGetString("/sim/flight-model") == "ada")
1761 obj_lon[0] = fdm->get_aux5()*DEG_TO_RAD;
1762 obj_lat[0] = fdm->get_aux6()*DEG_TO_RAD;
1763 obj_alt[0] = fdm->get_aux7();
1766 for (int m=0; m<=objc; m++)
1768 //cout << endl << obj_lat[m]*RAD_TO_DEG << " " << obj_lon[m]*RAD_TO_DEG << " " << obj_alt[m] << " " << objc << endl;
1771 //Geodetic to Geocentric angles for rotation
1772 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1774 //moving object gbs-posn in cartesian coords
1775 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1776 Point3D obj_pos = sgGeodToCart( obj_posn );
1778 // Translate moving object w.r.t eye
1779 Point3D Objtrans = obj_pos-scenery.center;
1784 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1787 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1789 sgVec3 ship_fwd,ship_rt,ship_up;
1790 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1791 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1792 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1794 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1795 sgMakeRotMat4( sgROT_lon, obj_lon[m]*RAD_TO_DEG, ship_up );
1796 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1797 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1800 sgCopyMat4( sgTUX, sgROT_hdg );
1801 sgPostMultMat4( sgTUX, sgROT_lat );
1802 sgPostMultMat4( sgTUX, sgROT_lon );
1803 sgPostMultMat4( sgTUX, sgTRANS );
1806 sgSetCoord(&shippos, sgTUX );
1807 ship_pos[m]->setTransform( &shippos );
1809 if ( ship_sel != NULL )
1810 ship_sel->select(0xFFFFFFFF);
1813 // $$$ end - added VS Renganathan, 15 Oct 2K
1814 // added Venky , 12 Nov 2K