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 #include <simgear/constants.h> // for VERSION
60 #include <simgear/debug/logstream.hxx>
61 #include <simgear/math/polar3d.hxx>
62 #include <simgear/math/sg_random.h>
63 #include <simgear/misc/fgpath.hxx>
64 #include <simgear/sky/sky.hxx>
65 #include <simgear/timing/sg_time.hxx>
66 #include <simgear/timing/lowleveltime.h>
68 #include <Include/general.hxx>
70 #include <Aircraft/aircraft.hxx>
72 #include <Autopilot/newauto.hxx>
73 #include <Cockpit/cockpit.hxx>
74 #include <Cockpit/radiostack.hxx>
75 #include <Cockpit/steam.hxx>
77 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
79 #include <GUI/sgVec3Slider.hxx>
80 #include <Joystick/joystick.hxx>
82 #include <NetworkOLK/network.h>
84 #include <Scenery/scenery.hxx>
85 #include <Scenery/tilemgr.hxx>
86 #include <Time/event.hxx>
87 #include <Time/fg_timer.hxx>
88 #include <Time/light.hxx>
89 #include <Time/sunpos.hxx>
90 #include <Time/tmp.hxx>
92 // begin - added Venky
93 // $$$ begin - added VS Renganathan
94 #include <simgear/misc/fgstream.hxx>
95 #include <FDM/flight.hxx>
96 #include <FDM/ADA.hxx>
97 void fgLoadDCS (void);
98 void fgUpdateDCS (void);
99 ssgSelector *ship_sel=NULL;
100 // upto 32 instances of a same object can be loaded.
101 ssgTransform *ship_pos[32];
102 double obj_lat[32],obj_lon[32],obj_alt[32];
104 // $$$ end - added VS Renganathan
107 #ifndef FG_OLD_WEATHER
108 # include <WeatherCM/FGLocalWeatherDatabase.h>
110 # include <Weather/weather.hxx>
116 #include "fg_init.hxx"
118 #include "globals.hxx"
119 #include "keyboard.hxx"
121 #include "splash.hxx"
123 #ifdef ENABLE_AUDIO_SUPPORT
124 # include "soundmgr.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 static FGSimpleSound *s1;
150 static FGSimpleSound *s2;
155 ssgRoot *scene = NULL;
156 ssgBranch *terrain = NULL;
158 // aircraft model stuff
159 ssgSelector *acmodel_selector = NULL;
160 ssgTransform *acmodel_pos = NULL;
161 ssgSelector *prop_selector = NULL;
162 ssgSelector *flaps_selector = NULL;
163 int acmodel_npropsettings;
164 int acmodel_proprpms[4][2]; // different propeller settings
166 ssgRoot *lighting = NULL;
167 ssgBranch *ground = NULL;
168 ssgBranch *airport = NULL;
170 #ifdef FG_NETWORK_OLK
171 ssgSelector *fgd_sel = NULL;
172 ssgTransform *fgd_pos = NULL;
175 // current fdm/position used for view
176 FGInterface cur_view_fdm;
182 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
184 { 1.0f, 0.0f, 0.0f, 0.0f },
185 { 0.0f, 0.0f, -1.0f, 0.0f },
186 { 0.0f, 1.0f, 0.0f, 0.0f },
187 { 0.0f, 0.0f, 0.0f, 1.0f }
190 // The following defines flightgear options. Because glutlib will also
191 // want to parse its own options, those options must not be included here
192 // or they will get parsed by the main program option parser. Hence case
193 // is significant for any option added that might be in conflict with
196 // glutlib parses for:
198 // -direct (invalid in Win32)
202 // -indirect (invalid in Win32)
205 // Note that glutlib depends upon strings while this program's
206 // option parser wants only initial characters followed by numbers
211 ssgSimpleState *default_state;
212 ssgSimpleState *hud_and_panel;
213 ssgSimpleState *menus;
215 void fgBuildRenderStates( void ) {
216 default_state = new ssgSimpleState;
217 default_state->ref();
218 default_state->disable( GL_TEXTURE_2D );
219 default_state->enable( GL_CULL_FACE );
220 default_state->enable( GL_COLOR_MATERIAL );
221 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
222 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
223 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
224 default_state->disable( GL_BLEND );
225 default_state->disable( GL_ALPHA_TEST );
226 default_state->disable( GL_LIGHTING );
228 hud_and_panel = new ssgSimpleState;
229 hud_and_panel->ref();
230 hud_and_panel->disable( GL_CULL_FACE );
231 hud_and_panel->disable( GL_TEXTURE_2D );
232 hud_and_panel->disable( GL_LIGHTING );
233 hud_and_panel->enable( GL_BLEND );
235 menus = new ssgSimpleState;
237 menus->disable( GL_CULL_FACE );
238 menus->disable( GL_TEXTURE_2D );
239 menus->enable( GL_BLEND );
242 // fgFindNode -- a function that finds a named node in an ssg graph
243 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
244 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
246 } else if ( node->isAKindOf( ssgTypeBranch() ) ) {
247 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
248 while (kid != NULL) {
249 ssgEntity *n = fgFindNode(kid, name);
253 kid = ((ssgBranch*)node)->getNextKid();
260 // fgInitVisuals() -- Initialize various GL/view parameters
261 void fgInitVisuals( void ) {
264 l = &cur_light_params;
266 #ifndef GLUT_WRONG_VERSION
267 // Go full screen if requested ...
268 if ( fgGetBool("/sim/startup/fullscreen") ) {
273 // If enabled, normal vectors specified with glNormal are scaled
274 // to unit length after transformation. See glNormal.
275 // glEnable( GL_NORMALIZE );
277 glEnable( GL_LIGHTING );
278 glEnable( GL_LIGHT0 );
279 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
282 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
283 ssgGetLight( 0 ) -> setPosition( sunpos );
285 // glFogi (GL_FOG_MODE, GL_LINEAR);
286 glFogi (GL_FOG_MODE, GL_EXP2);
287 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
288 (!fgGetBool("/sim/rendering/shading"))) {
289 // if fastest fog requested, or if flat shading force fastest
290 glHint ( GL_FOG_HINT, GL_FASTEST );
291 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
292 glHint ( GL_FOG_HINT, GL_NICEST );
294 if ( fgGetBool("/sim/rendering/wireframe") ) {
296 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
299 // This is the default anyways, but it can't hurt
300 glFrontFace ( GL_CCW );
303 // glEnable(GL_POINT_SMOOTH);
304 // glEnable(GL_LINE_SMOOTH);
305 // glEnable(GL_POLYGON_SMOOTH);
309 // Update all Visuals (redraws anything graphics related)
310 void fgRenderFrame( void ) {
314 fgLIGHT *l = &cur_light_params;
315 static double last_visibility = -9999;
317 static GLfloat fog_exp_density;
318 static GLfloat fog_exp2_density;
319 static GLfloat fog_exp2_punch_through;
322 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
323 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
324 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
325 // GLfloat mat_shininess[] = { 10.0 };
326 GLbitfield clear_mask;
328 if ( idle_state != 1000 ) {
329 // still initializing, draw the splash screen
330 if ( fgGetBool("/sim/startup/splash-screen") ) {
334 // idle_state is now 1000 meaning we've finished all our
335 // initializations and are running the main loop, so this will
336 // now work without seg faulting the system.
338 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
339 // FG_Altitude * FEET_TO_METER);
341 // this is just a temporary hack, to make me understand Pui
342 // timerText -> setLabel (ctime (&t->cur_time));
345 // calculate our current position in cartesian space
346 scenery.center = scenery.next_center;
347 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
348 // scenery.center.y(), scenery.center.z());
350 FGViewerRPH *pilot_view =
351 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
353 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
354 cur_fdm_state->get_Lat_geocentric(),
355 cur_fdm_state->get_Altitude() *
357 pilot_view->set_sea_level_radius( cur_fdm_state->
358 get_Sea_level_radius() *
360 pilot_view->set_rph( cur_fdm_state->get_Phi(),
361 cur_fdm_state->get_Theta(),
362 cur_fdm_state->get_Psi() );
364 FGViewerLookAt *chase_view =
365 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
367 sgVec3 po; // chase view pilot_offset
368 sgVec3 wup; // chase view world up
369 sgSetVec3( po, 0.0, 0.0, 50.0 );
370 sgCopyVec3( wup, pilot_view->get_world_up() );
371 sgMat4 CXFM; // chase view + pilot offset xform
373 chase_view->get_view_offset() * RAD_TO_DEG -
374 cur_fdm_state->get_Psi() * RAD_TO_DEG,
376 sgVec3 npo; // new pilot offset after rotation
377 sgVec3 *pPO = PilotOffsetGet();
378 sgXformVec3( po, *pPO, pilot_view->get_UP() );
379 sgXformVec3( npo, po, CXFM );
381 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
382 cur_fdm_state->get_Lat_geocentric(),
383 cur_fdm_state->get_Altitude() *
385 chase_view->set_sea_level_radius( cur_fdm_state->
386 get_Sea_level_radius() *
388 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
389 chase_view->set_view_forward( pilot_view->get_view_pos() );
390 chase_view->set_view_up( wup );
394 sgCopyMat4( rph, pilot_view->get_VIEW() );
395 cout << "RPH Matrix = " << endl;
397 for ( i = 0; i < 4; i++ ) {
398 for ( j = 0; j < 4; j++ ) {
399 printf("%10.4f ", rph[i][j]);
405 sgCopyMat4( la, chase_view->get_VIEW() );
406 cout << "LookAt Matrix = " << endl;
407 for ( i = 0; i < 4; i++ ) {
408 for ( j = 0; j < 4; j++ ) {
409 printf("%10.4f ", la[i][j]);
416 fgReshape( fgGetInt("/sim/startup/xsize"),
417 fgGetInt("/sim/startup/ysize") );
422 if ( ! fgPanelVisible() ) {
424 (GLint)(fgGetInt("/sim/startup/xsize")),
425 (GLint)(fgGetInt("/sim/startup/ysize")) );
428 int( (current_panel->getViewHeight() -
429 current_panel->getYOffset())
430 * (fgGetInt("/sim/startup/ysize") / 768.0) );
432 (GLint)(fgGetInt("/sim/startup/ysize") - view_h),
433 (GLint)(fgGetInt("/sim/startup/xsize")),
438 // set the sun position
439 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
441 clear_mask = GL_DEPTH_BUFFER_BIT;
442 if ( fgGetBool("/sim/rendering/wireframe") ) {
443 clear_mask |= GL_COLOR_BUFFER_BIT;
446 if ( fgGetBool("/sim/rendering/skyblend") ) {
447 if ( fgGetBool("/sim/rendering/textures") ) {
448 // glClearColor(black[0], black[1], black[2], black[3]);
449 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
450 l->adj_fog_color[2], l->adj_fog_color[3]);
451 clear_mask |= GL_COLOR_BUFFER_BIT;
454 glClearColor(l->sky_color[0], l->sky_color[1],
455 l->sky_color[2], l->sky_color[3]);
456 clear_mask |= GL_COLOR_BUFFER_BIT;
458 glClear( clear_mask );
460 // Tell GL we are switching to model view parameters
462 // I really should create a derived ssg node or use a call
463 // back or something so that I can draw the sky within the
464 // ssgCullAndDraw() function, but for now I just mimic what
465 // ssg does to set up the model view matrix
466 glMatrixMode(GL_MODELVIEW);
468 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
470 // set the opengl state to known default values
471 default_state->force();
473 // update fog params if visibility has changed
474 #ifndef FG_OLD_WEATHER
475 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
477 thesky->set_visibility( current_weather.get_visibility() );
480 thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
481 ( global_multi_loop *
482 fgGetInt("/sim/speed-up") ) /
483 (double)fgGetInt("/sim/model-hz") );
485 double actual_visibility = thesky->get_visibility();
486 // cout << "actual visibility = " << actual_visibility << endl;
488 if ( actual_visibility != last_visibility ) {
489 last_visibility = actual_visibility;
491 // cout << "----> updating fog params" << endl;
494 fog_exp_density = -log(0.01 / actual_visibility);
497 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
498 fog_exp2_punch_through = sqrt( -log(0.01) ) /
499 ( actual_visibility * 1.5 );
502 // Set correct opengl fog density
503 glFogf (GL_FOG_DENSITY, fog_exp2_density);
505 // update the sky dome
506 if ( fgGetBool("/sim/rendering/skyblend") ) {
507 /* cout << "thesky->repaint() sky_color = "
508 << cur_light_params.sky_color[0] << " "
509 << cur_light_params.sky_color[1] << " "
510 << cur_light_params.sky_color[2] << " "
511 << cur_light_params.sky_color[3] << endl;
513 << cur_light_params.fog_color[0] << " "
514 << cur_light_params.fog_color[1] << " "
515 << cur_light_params.fog_color[2] << " "
516 << cur_light_params.fog_color[3] << endl;
517 cout << " sun_angle = " << cur_light_params.sun_angle
518 << " moon_angle = " << cur_light_params.moon_angle
520 thesky->repaint( cur_light_params.sky_color,
521 cur_light_params.adj_fog_color,
522 cur_light_params.sun_angle,
523 cur_light_params.moon_angle,
524 globals->get_ephem()->getNumPlanets(),
525 globals->get_ephem()->getPlanets(),
526 globals->get_ephem()->getNumStars(),
527 globals->get_ephem()->getStars() );
529 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
530 << view_pos[1] << " " << view_pos[2] << endl;
531 cout << " zero_elev = " << zero_elev[0] << " "
532 << zero_elev[1] << " " << zero_elev[2]
533 << " lon = " << cur_fdm_state->get_Longitude()
534 << " lat = " << cur_fdm_state->get_Latitude() << endl;
535 cout << " sun_rot = " << cur_light_params.sun_rotation
536 << " gst = " << SGTime::cur_time_params->getGst() << endl;
537 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
538 << " sun dec = " << globals->get_ephem()->getSunDeclination()
539 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
540 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
542 thesky->reposition( globals->get_current_view()->get_view_pos(),
543 globals->get_current_view()->get_zero_elev(),
544 globals->get_current_view()->get_world_up(),
545 cur_fdm_state->get_Longitude(),
546 cur_fdm_state->get_Latitude(),
547 cur_fdm_state->get_Altitude() * FEET_TO_METER,
548 cur_light_params.sun_rotation,
549 globals->get_time_params()->getGst(),
550 globals->get_ephem()->getSunRightAscension(),
551 globals->get_ephem()->getSunDeclination(),
553 globals->get_ephem()->getMoonRightAscension(),
554 globals->get_ephem()->getMoonDeclination(),
558 glEnable( GL_DEPTH_TEST );
559 if ( fgGetString("/sim/rendering/fog") != "disabled" ) {
561 glFogi( GL_FOG_MODE, GL_EXP2 );
562 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
565 // set lighting parameters
566 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
567 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
568 glLightfv( GL_LIGHT0, GL_AMBIENT, black );
569 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
570 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
572 // texture parameters
573 // glEnable( GL_TEXTURE_2D );
574 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
575 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
576 // set base color (I don't think this is doing anything here)
577 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
578 // (GL_FRONT, GL_DIFFUSE, white);
579 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
580 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
583 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
584 ssgGetLight( 0 ) -> setPosition( sunpos );
586 // glMatrixMode( GL_PROJECTION );
588 float fov = globals->get_current_view()->get_fov();
589 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
591 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
594 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
595 // << current_weather.get_visibility() );
598 ssgSetNearFar( 10.0f, 120000.0f );
600 ssgSetNearFar( 0.5f, 120000.0f );
603 if ( globals->get_viewmgr()->get_current() == 0 ) {
604 // disable aircraft model
605 acmodel_selector->select(0);
607 // enable aircraft model and set up its position and orientation
608 acmodel_selector->select(1);
610 FGViewerRPH *pilot_view =
611 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
614 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
617 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
620 sgMakeRotMat4( sgROT, -90.0, ownship_up );
624 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
625 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
627 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
629 sgCopyMat4( sgTUX, sgROT );
630 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
631 sgPostMultMat4( sgTUX, sgTRANS );
634 sgSetCoord( &tuxpos, sgTUX );
635 acmodel_pos->setTransform( &tuxpos );
637 // set up moving parts
638 if (flaps_selector != NULL) {
639 flaps_selector->select( (controls.get_flaps() > 0.5f) ? 1 : 2 );
642 if (prop_selector != NULL) {
643 int propsel_mask = 0;
644 for (int i = 0; i < acmodel_npropsettings; i++) {
645 if (FGBFI::getRPM() >= acmodel_proprpms[i][0] &&
646 FGBFI::getRPM() <= acmodel_proprpms[i][1]) {
647 propsel_mask |= 1 << i;
650 prop_selector->select(propsel_mask);
654 // $$$ begin - added VS Renganthan 17 Oct 2K
656 // $$$ end - added VS Renganthan 17 Oct 2K
658 # ifdef FG_NETWORK_OLK
659 if ( fgGetBool("/sim/networking/network-olk") ) {
661 other = head->next; /* put listpointer to start */
662 while ( other != tail) { /* display all except myself */
663 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
664 other->fgd_sel->select(1);
665 sgSetCoord( &fgdpos, other->sgFGD_COORD );
666 other->fgd_pos->setTransform( &fgdpos );
671 // fgd_sel->select(1);
672 // sgCopyMat4( sgTUX, current_view.sgVIEW);
674 // sgSetCoord( &fgdpos, sgFGD_VIEW );
675 // fgd_pos->setTransform( &fgdpos);
679 // position tile nodes and update range selectors
680 global_tile_mgr.prep_ssg_nodes();
682 if ( fgGetBool("/sim/rendering/skyblend") ) {
683 // draw the sky backdrop
687 // draw the ssg scene
688 glEnable( GL_DEPTH_TEST );
689 ssgCullAndDraw( scene );
691 // change state for lighting here
694 // Set punch through fog density
695 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
697 ssgCullAndDraw( lighting );
699 if ( fgGetBool("/sim/rendering/skyblend") ) {
700 // draw the sky cloud layers
701 thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
704 // display HUD && Panel
706 glDisable( GL_DEPTH_TEST );
707 // glDisable( GL_CULL_FACE );
708 // glDisable( GL_TEXTURE_2D );
710 // update the controls subsystem
713 hud_and_panel->apply();
716 // update the panel subsystem
717 if (current_panel != 0)
718 current_panel->update();
720 // We can do translucent menus, so why not. :-)
722 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
724 // glDisable ( GL_BLEND ) ;
726 // glEnable( GL_FOG );
733 // Update internal time dependent calculations (i.e. flight model)
734 void fgUpdateTimeDepCalcs() {
735 static bool inited = false;
737 fgLIGHT *l = &cur_light_params;
742 if ( !globals->get_freeze() && !initial_freeze ) {
743 // conceptually, this could be done for each fdm instance ...
746 cur_fdm_state->stamp();
752 long elapsed = current - cur_fdm_state->get_time_stamp();
753 cur_fdm_state->set_time_stamp( current );
754 elapsed += cur_fdm_state->get_remainder();
755 // cout << "elapsed = " << elapsed << endl;
756 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
757 multi_loop = (long)(((double)elapsed * 0.000001) /
758 cur_fdm_state->get_delta_t() );
759 cur_fdm_state->set_multi_loop( multi_loop );
760 long remainder = elapsed - ( (multi_loop*1000000) *
761 cur_fdm_state->get_delta_t() );
762 cur_fdm_state->set_remainder( remainder );
763 // cout << "remainder = " << remainder << endl;
765 // chop max interations to something reasonable if the sim was
766 // delayed for an excesive amount of time
767 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
768 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
769 cur_fdm_state->set_remainder( 0 );
772 // cout << "multi_loop = " << multi_loop << endl;
773 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
774 // run Autopilot system
775 current_autopilot->run();
778 cur_fdm_state->update( 1 );
780 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
782 cur_fdm_state->update( 0 );
783 FGSteam::update( 0 );
785 if ( global_tile_mgr.queue_size() == 0 ) {
786 initial_freeze = false;
790 if ( fgGetString("/sim/view-mode") == "pilot" ) {
791 cur_view_fdm = *cur_fdm_state;
795 // update the view angle
796 FGViewer *v = globals->get_current_view();
797 for ( i = 0; i < multi_loop; i++ ) {
798 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
799 v->set_view_offset( v->get_goal_view_offset() );
802 // move current_view.view_offset towards
803 // current_view.goal_view_offset
804 if ( v->get_goal_view_offset() > v->get_view_offset() )
806 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
807 v->inc_view_offset( 0.01 );
809 v->inc_view_offset( -0.01 );
812 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
813 v->inc_view_offset( -0.01 );
815 v->inc_view_offset( 0.01 );
818 if ( v->get_view_offset() > FG_2PI ) {
819 v->inc_view_offset( -FG_2PI );
820 } else if ( v->get_view_offset() < 0 ) {
821 v->inc_view_offset( FG_2PI );
826 double tmp = -(l->sun_rotation + FG_PI)
827 - (cur_fdm_state->get_Psi() -
828 globals->get_current_view()->get_view_offset() );
829 while ( tmp < 0.0 ) {
832 while ( tmp > FG_2PI ) {
835 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
836 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
837 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
840 // Update solar system
841 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
842 globals->get_time_params()->getLst(),
843 cur_fdm_state->get_Latitude() );
845 // Update radio stack model
846 current_radiostack->update();
850 void fgInitTimeDepCalcs( void ) {
853 // #ifdef HAVE_SETITIMER
854 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
855 // fgUpdateTimeDepCalcs );
856 // #endif HAVE_SETITIMER
860 static const double alt_adjust_ft = 3.758099;
861 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
864 // What should we do when we have nothing else to do? Let's get ready
865 // for the next move and update the display?
866 static void fgMainLoop( void ) {
867 static long remainder = 0;
869 #ifdef FANCY_FRAME_COUNTER
873 static time_t last_time = 0;
874 static int frames = 0;
875 #endif // FANCY_FRAME_COUNTER
877 SGTime *t = globals->get_time_params();
879 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
880 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
882 #ifdef FG_NETWORK_OLK
883 if ( fgGetBool("/sim/networking/network-olk") ) {
884 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
885 // printf("FGD: Netupdate\n");
886 fgd_send_com( "A", FGFS_host); // Send Mat4 data
887 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
892 #if defined( ENABLE_PLIB_JOYSTICK )
893 // Read joystick and update control settings
894 if ( fgGetString("/sim/control-mode") == "joystick" )
898 #elif defined( ENABLE_GLUT_JOYSTICK )
899 // Glut joystick support works by feeding a joystick handler
900 // function to glut. This is taken care of once in the joystick
901 // init routine and we don't have to worry about it again.
904 #ifdef FG_OLD_WEATHER
905 current_weather.Update();
908 // Fix elevation. I'm just sticking this here for now, it should
909 // probably move eventually
911 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
913 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
914 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
916 if ( scenery.cur_elev > -9990 ) {
917 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
918 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
919 // now set aircraft altitude above ground
920 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
921 cur_fdm_state->get_Altitude() * FEET_TO_METER,
922 scenery.cur_elev + alt_adjust_m - 3.0,
923 scenery.cur_elev + alt_adjust_m );
924 fgFDMForceAltitude( fgGetString("/sim/flight-model"),
925 scenery.cur_elev + alt_adjust_m );
927 FG_LOG( FG_ALL, FG_DEBUG,
928 "<*> resetting altitude to "
929 << cur_fdm_state->get_Altitude() * FEET_TO_METER
934 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
936 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
937 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
940 if ( globals->get_warp_delta() != 0 ) {
941 globals->inc_warp( globals->get_warp_delta() );
944 t->update( cur_fdm_state->get_Longitude(),
945 cur_fdm_state->get_Latitude(),
946 globals->get_warp() );
948 if ( globals->get_warp_delta() != 0 ) {
949 fgUpdateSkyAndLightingParams();
952 // update magvar model
953 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
954 cur_fdm_state->get_Latitude(),
955 cur_fdm_state->get_Altitude()* FEET_TO_METER,
956 globals->get_time_params()->getJD() );
958 // Get elapsed time (in usec) for this past frame
959 elapsed = fgGetTimeInterval();
960 FG_LOG( FG_ALL, FG_DEBUG,
961 "Elapsed time interval is = " << elapsed
962 << ", previous remainder is = " << remainder );
964 // Calculate frame rate average
965 #ifdef FANCY_FRAME_COUNTER
966 /* old fps calculation */
970 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
971 tmp = general.get_frame(i);
973 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
974 general.set_frame(i+1,tmp);
976 tmp = 1000000.0 / (float)elapsed;
977 general.set_frame(0,tmp);
978 // printf("frame[0] = %.2f\n", general.frames[0]);
980 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
981 // printf("ave = %.2f\n", general.frame_rate);
984 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
985 general.set_frame_rate( frames );
986 FG_LOG( FG_ALL, FG_DEBUG,
987 "--> Frame rate is = " << general.get_frame_rate() );
990 last_time = t->get_cur_time();
996 // Calculate model iterations needed for next frame
997 elapsed += remainder;
999 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1000 fgGetInt("/sim/model-hz"));
1001 remainder = elapsed - ( (global_multi_loop*1000000) /
1002 fgGetInt("/sim/model-hz") );
1003 FG_LOG( FG_ALL, FG_DEBUG,
1004 "Model iterations needed = " << global_multi_loop
1005 << ", new remainder = " << remainder );
1007 // chop max interations to something reasonable if the sim was
1008 // delayed for an excesive amount of time
1009 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1010 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1015 if ( global_multi_loop > 0 ) {
1016 fgUpdateTimeDepCalcs();
1018 FG_LOG( FG_ALL, FG_DEBUG,
1019 "Elapsed time is zero ... we're zinging" );
1022 #if ! defined( macintosh )
1023 // Do any I/O channel work that might need to be done
1027 // see if we need to load any new scenery tiles
1028 global_tile_mgr.update( cur_fdm_state->get_Longitude() * RAD_TO_DEG,
1029 cur_fdm_state->get_Latitude() * RAD_TO_DEG );
1031 // Process/manage pending events
1032 global_events.Process();
1034 // Run audio scheduler
1035 #ifdef ENABLE_AUDIO_SUPPORT
1036 if ( fgGetBool("/sim/sound") && globals->get_soundmgr()->is_working() ) {
1037 if ( fgGetString("/sim/aircraft") == "c172" ) {
1038 // pitch corresponds to rpm
1039 // volume corresponds to manifold pressure
1041 // cout << "AUDIO working = "
1042 // << globals->get_soundmgr()->is_working() << endl;
1045 if ( cur_fdm_state->get_engine(0) != NULL ) {
1046 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
1050 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
1053 double pitch = 0.3 + rpm_factor * 3.0;
1055 // don't run at absurdly slow rates -- not realistic
1056 // and sounds bad to boot. :-)
1057 if (pitch < 0.7) { pitch = 0.7; }
1058 if (pitch > 5.0) { pitch = 5.0; }
1061 if ( cur_fdm_state->get_engine(0) != NULL ) {
1063 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 100;
1068 << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1071 double volume = 0.3 + mp_factor;
1073 if ( volume < 0.3 ) { volume = 0.3; }
1074 if ( volume > 1.0 ) { volume = 1.0; }
1075 // cout << "volume = " << volume << endl;
1077 s1->set_pitch( pitch );
1078 s1->set_volume( volume );
1080 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1081 s1->set_pitch( param );
1082 s1->set_volume( param );
1085 globals->get_soundmgr()->update();
1092 FG_LOG( FG_ALL, FG_DEBUG, "" );
1096 // This is the top level master main function that is registered as
1097 // our idle funciton
1100 // The first few passes take care of initialization things (a couple
1101 // per pass) and once everything has been initialized fgMainLoop from
1104 static void fgIdleFunction ( void ) {
1105 // printf("idle state == %d\n", idle_state);
1107 if ( idle_state == 0 ) {
1108 // Initialize the splash screen right away
1109 if ( fgGetBool("/sim/startup/splash-screen") ) {
1114 } else if ( idle_state == 1 ) {
1115 // Start the intro music
1117 if ( fgGetBool("/sim/startup/intro-music") ) {
1118 string lockfile = "/tmp/mpg123.running";
1119 FGPath mp3file( globals->get_fg_root() );
1120 mp3file.append( "Sounds/intro.mp3" );
1122 string command = "(touch " + lockfile + "; mpg123 "
1123 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1125 FG_LOG( FG_GENERAL, FG_INFO,
1126 "Starting intro music: " << mp3file.str() );
1127 system ( command.c_str() );
1132 } else if ( idle_state == 2 ) {
1133 // These are a few miscellaneous things that aren't really
1134 // "subsystems" but still need to be initialized.
1137 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1138 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1143 } else if ( idle_state == 3 ) {
1144 // This is the top level init routine which calls all the
1145 // other subsystem initialization routines. If you are adding
1146 // a subsystem to flightgear, its initialization call should
1147 // located in this routine.
1148 if( !fgInitSubsystems()) {
1149 FG_LOG( FG_GENERAL, FG_ALERT,
1150 "Subsystem initializations failed ..." );
1155 } else if ( idle_state == 4 ) {
1156 // setup OpenGL view parameters
1160 } else if ( idle_state == 5 ) {
1163 } else if ( idle_state == 6 ) {
1164 // Initialize audio support
1165 #ifdef ENABLE_AUDIO_SUPPORT
1168 if ( fgGetBool("/sim/startup/intro-music") ) {
1169 // Let's wait for mpg123 to finish
1170 string lockfile = "/tmp/mpg123.running";
1171 struct stat stat_buf;
1173 FG_LOG( FG_GENERAL, FG_INFO,
1174 "Waiting for mpg123 player to finish ..." );
1175 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1176 // file exist, wait ...
1178 FG_LOG( FG_GENERAL, FG_INFO, ".");
1180 FG_LOG( FG_GENERAL, FG_INFO, "");
1184 if ( fgGetBool("/sim/sound") ) {
1185 globals->get_soundmgr()->init();
1187 s1 = new FGSimpleSound( "Sounds/wasp.wav" );
1188 globals->get_soundmgr()->add( s1, "engine loop" );
1189 globals->get_soundmgr()->play_looped( "engine loop" );
1190 FG_LOG( FG_GENERAL, FG_INFO,
1191 "Rate = " << s1->get_sample()->getRate()
1192 << " Bps = " << s1->get_sample()->getBps()
1193 << " Stereo = " << s1->get_sample()->getStereo() );
1195 // s2 = new FGSimpleSound( "Sounds/corflaps.wav" );
1196 // s2->set_volume( 2.0 );
1199 s2 = mmm.make_ident( "JLI" );
1200 globals->get_soundmgr()->add( s2, "flaps" );
1207 cout << "Panel visible = " << fgPanelVisible() << endl;
1208 fgReshape( fgGetInt("/sim/startup/xsize"),
1209 fgGetInt("/sim/startup/ysize") );
1212 if ( idle_state == 1000 ) {
1213 // We've finished all our initialization steps, from now on we
1214 // run the main loop.
1218 if ( fgGetBool("/sim/startup/splash-screen") ) {
1219 fgSplashUpdate(0.0);
1224 // options.cxx needs to see this for toggle_panel()
1225 // Handle new window size or exposure
1226 void fgReshape( int width, int height ) {
1228 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1229 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1230 globals->get_viewmgr()->get_view(i)->
1231 set_win_ratio( (float)height / (float)width );
1234 int((current_panel->getViewHeight() -
1235 current_panel->getYOffset())
1236 * (height / 768.0)) + 1;
1237 globals->get_viewmgr()->get_view(i)->
1238 set_win_ratio( (float)view_h / (float)width );
1242 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1243 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1246 int((current_panel->getViewHeight() - current_panel->getYOffset())
1247 * (height / 768.0)) + 1;
1248 glViewport(0, (GLint)(height - view_h),
1249 (GLint)(width), (GLint)(view_h) );
1252 fgSetInt("/sim/startup/xsize", width);
1253 fgSetInt("/sim/startup/ysize", height);
1255 float fov = globals->get_current_view()->get_fov();
1256 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1262 // Initialize GLUT and define a main window
1263 int fgGlutInit( int *argc, char **argv ) {
1265 #if !defined( macintosh )
1266 // GLUT will extract all glut specific options so later on we only
1267 // need wory about our own.
1268 glutInit(argc, argv);
1271 // Define Display Parameters
1272 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1274 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1275 fgGetInt("/sim/startup/xsize") << "x"
1276 << fgGetInt("/sim/startup/ysize") );
1278 // Define initial window size
1279 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1280 fgGetInt("/sim/startup/ysize") );
1282 // Initialize windows
1283 if ( !fgGetBool("/sim/startup/game-mode")) {
1284 // Open the regular window
1285 glutCreateWindow("FlightGear");
1286 #ifndef GLUT_WRONG_VERSION
1288 // Open the cool new 'game mode' window
1289 char game_mode_str[256];
1290 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1291 fgGetInt("/sim/startup/xsize"),
1292 fgGetInt("/sim/startup/ysize"),
1293 fgGetInt("/sim/rendering/bits-per-pixel"));
1295 FG_LOG( FG_GENERAL, FG_INFO,
1296 "game mode params = " << game_mode_str );
1297 glutGameModeString( game_mode_str );
1298 glutEnterGameMode();
1302 // This seems to be the absolute earliest in the init sequence
1303 // that these calls will return valid info. Too bad it's after
1304 // we've already created and sized out window. :-(
1305 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1306 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1307 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1308 FG_LOG( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1311 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1312 general.set_glMaxTexSize( tmp );
1313 FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1315 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1316 general.set_glDepthBits( tmp );
1317 FG_LOG ( FG_GENERAL, FG_INFO, "Depth buffer bits = " << tmp );
1323 // Initialize GLUT event handlers
1324 int fgGlutInitEvents( void ) {
1325 // call fgReshape() on window resizes
1326 glutReshapeFunc( fgReshape );
1328 // call GLUTkey() on keyboard event
1329 glutKeyboardFunc( GLUTkey );
1330 glutSpecialFunc( GLUTspecialkey );
1332 // call guiMouseFunc() whenever our little rodent is used
1333 glutMouseFunc ( guiMouseFunc );
1334 glutMotionFunc (guiMotionFunc );
1335 glutPassiveMotionFunc (guiMotionFunc );
1337 // call fgMainLoop() whenever there is
1338 // nothing else to do
1339 glutIdleFunc( fgIdleFunction );
1342 glutDisplayFunc( fgRenderFrame );
1349 int main( int argc, char **argv ) {
1351 #if defined( macintosh )
1352 freopen ("stdout.txt", "w", stdout );
1353 freopen ("stderr.txt", "w", stderr );
1354 argc = ccommand( &argv );
1358 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1361 // set default log levels
1362 fglog().setLogLevels( FG_ALL, FG_INFO );
1365 #ifdef FLIGHTGEAR_VERSION
1366 version = FLIGHTGEAR_VERSION;
1368 version = "unknown version";
1370 FG_LOG( FG_GENERAL, FG_INFO, "FlightGear: Version "
1371 << version << endl );
1373 // Allocate global data structures. This needs to happen before
1374 // we parse command line options
1376 SGPropertyNode *props = new SGPropertyNode;
1377 globals = new FGGlobals;
1378 globals->set_props( props );
1380 // seed the random number generater
1383 SGRoute *route = new SGRoute;
1384 globals->set_route( route );
1386 #ifdef ENABLE_AUDIO_SUPPORT
1387 FGSoundMgr *soundmgr = new FGSoundMgr;
1388 globals->set_soundmgr( soundmgr );
1391 FGViewMgr *viewmgr = new FGViewMgr;
1392 globals->set_viewmgr( viewmgr );
1394 FGViewerRPH *pv = new FGViewerRPH;
1395 globals->get_viewmgr()->add_view( pv );
1397 FGViewerLookAt *chase = new FGViewerLookAt;
1398 globals->get_viewmgr()->add_view( chase );
1400 string_list *col = new string_list;
1401 globals->set_channel_options_list( col );
1403 // set current view to 0 (first) which is our main pilot view
1404 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1406 // Scan the config file(s) and command line options to see if
1407 // fg_root was specified (ignore all other options for now)
1408 fgInitFGRoot(argc, argv);
1410 // Initialize the Aircraft directory to "" (UIUC)
1413 // Load the configuration parameters
1414 if ( !fgInitConfig(argc, argv) ) {
1415 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1419 // Initialize the Window/Graphics environment.
1420 if( !fgGlutInit(&argc, argv) ) {
1421 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1425 // Initialize the various GLUT Event Handlers.
1426 if( !fgGlutInitEvents() ) {
1427 FG_LOG( FG_GENERAL, FG_ALERT,
1428 "GLUT event handler initialization failed ..." );
1432 // Initialize ssg (from plib). Needs to come before we do any
1433 // other ssg stuff, but after opengl/glut has been initialized.
1436 // Initialize the user interface (we need to do this before
1437 // passing off control to glut and before fgInitGeneral to get our
1441 // set current_options lon/lat if an airport id is specified
1442 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1443 if ( fgGetString("/sim/startup/airport-id").length() ) {
1444 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1445 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1446 fgGetDouble("/orientation/heading") );
1450 FGPath zone( globals->get_fg_root() );
1451 zone.append( "Timezone" );
1452 SGTime *t = new SGTime( fgGetDouble("/position/longitude") * DEG_TO_RAD,
1453 fgGetDouble("/position/latitude") * DEG_TO_RAD,
1456 // Handle potential user specified time offsets
1457 time_t cur_time = t->get_cur_time();
1458 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1459 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1460 time_t aircraftLocalTime =
1461 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1463 // Okay, we now have six possible scenarios
1464 int offset = fgGetInt("/sim/startup/time-offset");
1465 const string &offset_type = fgGetString("/sim/startup/time-offset-type");
1466 if (offset_type == "system-offset") {
1467 globals->set_warp( offset );
1468 } else if (offset_type == "gmt-offset") {
1469 globals->set_warp( offset - (currGMT - systemLocalTime) );
1470 } else if (offset_type == "latitude-offset") {
1471 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) );
1472 } else if (offset_type == "system") {
1473 globals->set_warp( offset - cur_time );
1474 } else if (offset_type == "gmt") {
1475 globals->set_warp( offset - currGMT );
1476 } else if (offset_type == "latitude") {
1477 globals->set_warp( offset - (aircraftLocalTime - systemLocalTime) -
1480 FG_LOG( FG_GENERAL, FG_ALERT,
1481 "Unsupported offset type " << offset_type );
1485 FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = "
1486 << globals->get_warp() );
1488 globals->set_warp_delta( 0 );
1490 t->update( 0.0, 0.0, globals->get_warp() );
1492 globals->set_time_params( t );
1494 // Do some quick general initializations
1495 if( !fgInitGeneral()) {
1496 FG_LOG( FG_GENERAL, FG_ALERT,
1497 "General initializations failed ..." );
1501 FGPath modelpath( globals->get_fg_root() );
1502 ssgModelPath( (char *)modelpath.c_str() );
1505 scene = new ssgRoot;
1506 scene->setName( "Scene" );
1508 lighting = new ssgRoot;
1509 lighting->setName( "Lighting" );
1511 // Initialize the sky
1512 FGPath ephem_data_path( globals->get_fg_root() );
1513 ephem_data_path.append( "Astro" );
1514 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1515 ephem->update( globals->get_time_params()->getMjd(),
1516 globals->get_time_params()->getLst(),
1518 globals->set_ephem( ephem );
1520 FGPath sky_tex_path( globals->get_fg_root() );
1521 sky_tex_path.append( "Textures" );
1522 sky_tex_path.append( "Sky" );
1524 thesky->texture_path( sky_tex_path.str() );
1526 thesky->build( 550.0, 550.0,
1527 globals->get_ephem()->getNumPlanets(),
1528 globals->get_ephem()->getPlanets(), 60000.0,
1529 globals->get_ephem()->getNumStars(),
1530 globals->get_ephem()->getStars(), 60000.0 );
1532 if ( fgGetBool("/environment/clouds/status") ) {
1533 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1534 SG_CLOUD_MOSTLY_SUNNY );
1535 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1537 // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1538 // SG_CLOUD_MOSTLY_SUNNY );
1539 // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1540 // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1543 // Initialize MagVar model
1544 SGMagVar *magvar = new SGMagVar();
1545 globals->set_mag( magvar );
1548 terrain = new ssgBranch;
1549 terrain->setName( "Terrain" );
1550 scene->addKid( terrain );
1553 ground = new ssgBranch;
1554 ground->setName( "Ground Lighting" );
1555 lighting->addKid( ground );
1557 airport = new ssgBranch;
1558 airport->setName( "Airport Lighting" );
1559 lighting->addKid( airport );
1561 // temporary visible aircraft "own ship"
1562 acmodel_selector = new ssgSelector;
1563 acmodel_pos = new ssgTransform;
1565 string acmodel_path =
1566 fgGetString("/sim/model/path", "Models/Geometry/glider.ac");
1568 string full_model = globals->get_fg_root() + "/"
1570 int pos = full_model.rfind("/");
1572 FGPath texturepath( full_model.substr(0, pos) );
1573 cout << "Texture path = " << texturepath.str() << endl;
1574 ssgTexturePath( (char *)texturepath.c_str() );
1576 ssgEntity *acmodel_obj = ssgLoad((char *)(acmodel_path.c_str()));
1578 // find moving parts (if this is an MDL model)
1579 flaps_selector = (ssgSelector*)fgFindNode( acmodel_obj, "FLAPS" );
1580 prop_selector = (ssgSelector*)fgFindNode( acmodel_obj, "PROP" );
1582 acmodel_npropsettings = 0;
1583 if (prop_selector != NULL) {
1584 for (ssgEntity* kid = prop_selector->getKid(0); kid != NULL;
1585 kid = prop_selector->getNextKid()) {
1586 int prop_low, prop_high;
1587 if ( sscanf(kid->getName(), "PROP_%d_%d",
1588 &prop_low, &prop_high) == 2 ) {
1589 prop_low = (int)((float)prop_low * (5000.0f / 32767.0f));
1590 prop_high = (int)((float)prop_high * (5000.0f / 32767.0f));
1591 acmodel_proprpms[acmodel_npropsettings][0] = prop_low ;
1592 acmodel_proprpms[acmodel_npropsettings][1] = prop_high;
1593 acmodel_npropsettings++;
1595 FG_LOG( FG_GENERAL, FG_INFO, "PROPELLER SETTING " << prop_low <<
1601 // align the model properly for FGFS
1602 ssgTransform *acmodel_align = new ssgTransform;
1603 acmodel_align->addKid(acmodel_obj);
1607 float h_rot = fgGetFloat("/sim/model/h-rotation", 0.0);
1608 float p_rot = fgGetFloat("/sim/model/p-rotation", 0.0);
1609 float r_rot = fgGetFloat("/sim/model/r-rotation", 0.0);
1610 float x_off = fgGetFloat("/sim/model/x-offset", 0.0);
1611 float y_off = fgGetFloat("/sim/model/y-offset", 0.0);
1612 float z_off = fgGetFloat("/sim/model/z-offset", 0.0);
1613 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1614 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1615 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1616 acmodel_align->setTransform(res_matrix);
1618 acmodel_pos->addKid( acmodel_align );
1619 acmodel_selector->addKid( acmodel_pos );
1620 //ssgFlatten( acmodel_obj );
1621 //ssgStripify( acmodel_selector );
1622 acmodel_selector->clrTraversalMaskBits( SSGTRAV_HOT );
1623 scene->addKid( acmodel_selector );
1625 // $$$ begin - added VS Renganthan 17 Oct 2K
1627 // $$$ end - added VS Renganthan 17 Oct 2K
1629 #ifdef FG_NETWORK_OLK
1630 // Do the network intialization
1631 if ( fgGetBool("/sim/networking/network-olk") ) {
1632 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1636 // build our custom render states
1637 fgBuildRenderStates();
1639 // pass control off to the master GLUT event handler
1642 // we never actually get here ... but to avoid compiler warnings,
1648 // $$$ end - added VS Renganathan, 15 Oct 2K
1649 // - added Venky , 12 Nov 2K
1651 void fgLoadDCS(void) {
1653 ssgEntity *ship_obj = NULL;
1656 char obj_filename[25];
1658 for (int k=0;k<32;k++)
1663 FGPath tile_path( globals->get_fg_root());
1664 tile_path.append( "Scenery" );
1665 tile_path.append( "Objects.txt" );
1666 fg_gzifstream in( tile_path.str() );
1667 if ( ! in.is_open() ) {
1668 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1671 FGPath modelpath( globals->get_fg_root() );
1672 modelpath.append( "Models" );
1673 modelpath.append( "Geometry" );
1675 FGPath texturepath( globals->get_fg_root() );
1676 texturepath.append( "Models" );
1677 texturepath.append( "Textures" );
1679 ssgModelPath( (char *)modelpath.c_str() );
1680 ssgTexturePath( (char *)texturepath.c_str() );
1682 ship_sel = new ssgSelector;
1685 while ( ! in.eof() )
1688 if ( in.get( c ) && c == '#' )
1695 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1696 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1697 int chj=getchar();*/
1699 obj_lon[objc] *=DEG_TO_RAD;
1700 obj_lat[objc] *=DEG_TO_RAD;
1702 ship_pos[objc] = new ssgTransform;
1705 // type "repeat" in objects.txt to load one more instance of the last object.
1707 if ( strcmp(obj_filename,"repeat") != 0)
1708 ship_obj = ssgLoadOBJ( obj_filename );
1710 if ( ship_obj != NULL )
1712 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1713 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1716 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << obj_filename );
1718 if (in.eof()) break;
1723 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1724 scene->addKid( ship_sel ); //add selector node to root node
1729 void fgUpdateDCS (void) {
1731 // double eye_lat,eye_lon,eye_alt;
1732 // static double obj_head;
1733 double sl_radius,obj_latgc;
1734 // float nresultmat[4][4];
1735 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1738 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1739 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1741 // Deck should be the first object in objects.txt in case of fdm=ada
1743 if (fgGetString("/sim/flight-model") == "ada")
1745 obj_lon[0] = fdm->get_aux5()*DEG_TO_RAD;
1746 obj_lat[0] = fdm->get_aux6()*DEG_TO_RAD;
1747 obj_alt[0] = fdm->get_aux7();
1750 for (int m=0; m<=objc; m++)
1752 //cout << endl << obj_lat[m]*RAD_TO_DEG << " " << obj_lon[m]*RAD_TO_DEG << " " << obj_alt[m] << " " << objc << endl;
1755 //Geodetic to Geocentric angles for rotation
1756 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1758 //moving object gbs-posn in cartesian coords
1759 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1760 Point3D obj_pos = sgGeodToCart( obj_posn );
1762 // Translate moving object w.r.t eye
1763 Point3D Objtrans = obj_pos-scenery.center;
1768 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1771 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1773 sgVec3 ship_fwd,ship_rt,ship_up;
1774 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1775 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1776 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1778 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1779 sgMakeRotMat4( sgROT_lon, obj_lon[m]*RAD_TO_DEG, ship_up );
1780 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1781 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1784 sgCopyMat4( sgTUX, sgROT_hdg );
1785 sgPostMultMat4( sgTUX, sgROT_lat );
1786 sgPostMultMat4( sgTUX, sgROT_lon );
1787 sgPostMultMat4( sgTUX, sgTRANS );
1790 sgSetCoord(&shippos, sgTUX );
1791 ship_pos[m]->setTransform( &shippos );
1793 if ( ship_sel != NULL )
1794 ship_sel->select(0xFFFFFFFF);
1797 // $$$ end - added VS Renganathan, 15 Oct 2K
1798 // added Venky , 12 Nov 2K