1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson for OpenGL, started May 1997.
5 // Copyright (C) 1997 - 1999 Curtis L. Olson - curt@flightgear.org
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #ifdef FG_MATH_EXCEPTION_CLASH
38 #include <simgear/xgl/xgl.h>
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h> // for stat()
53 # include <unistd.h> // for stat()
59 #ifdef ENABLE_AUDIO_SUPPORT
64 #include <simgear/constants.h> // for VERSION
65 #include <simgear/debug/logstream.hxx>
66 #include <simgear/math/polar3d.hxx>
67 #include <simgear/math/sg_random.h>
68 #include <simgear/misc/fgpath.hxx>
69 #include <simgear/sky/sky.hxx>
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/timing/lowleveltime.h>
73 #include <Include/general.hxx>
75 #include <Aircraft/aircraft.hxx>
77 #include <Autopilot/newauto.hxx>
78 #include <Cockpit/cockpit.hxx>
79 #include <Cockpit/radiostack.hxx>
80 #include <Cockpit/steam.hxx>
82 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
84 #include <Joystick/joystick.hxx>
86 #include <NetworkOLK/network.h>
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/tilemgr.hxx>
90 #include <Time/event.hxx>
91 #include <Time/fg_timer.hxx>
92 #include <Time/light.hxx>
93 #include <Time/sunpos.hxx>
94 #include <Time/tmp.hxx>
96 // begin - added Venky
97 // $$$ begin - added VS Renganathan
98 #include <simgear/misc/fgstream.hxx>
99 #include <FDM/flight.hxx>
100 #include <FDM/ADA.hxx>
101 void fgLoadDCS (void);
102 void fgUpdateDCS (void);
103 ssgSelector *ship_sel=NULL;
104 // upto 32 instances of a same object can be loaded.
105 ssgTransform *ship_pos[32];
106 double obj_lat[32],obj_lon[32],obj_alt[32];
108 // $$$ end - added VS Renganathan
111 #ifndef FG_OLD_WEATHER
112 # include <WeatherCM/FGLocalWeatherDatabase.h>
114 # include <Weather/weather.hxx>
120 #include "fg_init.hxx"
122 #include "globals.hxx"
123 #include "keyboard.hxx"
124 #include "splash.hxx"
126 // -dw- use custom sioux settings so I can see output window
129 # include <sioux.h> // settings for output window
131 # include <console.h>
135 // This is a record containing a bit of global housekeeping information
138 // Specify our current idle function state. This is used to run all
139 // our initializations out of the glutIdleLoop() so that we can get a
140 // splash screen up and running right away.
141 static int idle_state = 0;
142 static int global_multi_loop;
144 // attempt to avoid a large bounce at startup
145 static bool initial_freeze = true;
150 // forward declaration
151 void fgReshape( int width, int height );
153 // Global structures for the Audio library
154 #ifdef ENABLE_AUDIO_SUPPORT
155 slEnvelope pitch_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
156 slEnvelope volume_envelope ( 1, SL_SAMPLE_ONE_SHOT ) ;
157 slScheduler *audio_sched;
158 smMixer *audio_mixer;
165 ssgRoot *scene = NULL;
166 ssgBranch *terrain = NULL;
167 ssgSelector *penguin_sel = NULL;
168 ssgTransform *penguin_pos = NULL;
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;
180 // current fdm/position used for view
181 FGInterface cur_view_fdm;
187 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
189 { 1.0f, 0.0f, 0.0f, 0.0f },
190 { 0.0f, 0.0f, -1.0f, 0.0f },
191 { 0.0f, 1.0f, 0.0f, 0.0f },
192 { 0.0f, 0.0f, 0.0f, 1.0f }
195 // The following defines flightgear options. Because glutlib will also
196 // want to parse its own options, those options must not be included here
197 // or they will get parsed by the main program option parser. Hence case
198 // is significant for any option added that might be in conflict with
201 // glutlib parses for:
203 // -direct (invalid in Win32)
207 // -indirect (invalid in Win32)
210 // Note that glutlib depends upon strings while this program's
211 // option parser wants only initial characters followed by numbers
216 ssgSimpleState *default_state;
217 ssgSimpleState *hud_and_panel;
218 ssgSimpleState *menus;
220 void fgBuildRenderStates( void ) {
221 default_state = new ssgSimpleState;
222 default_state->ref();
223 default_state->disable( GL_TEXTURE_2D );
224 default_state->enable( GL_CULL_FACE );
225 default_state->enable( GL_COLOR_MATERIAL );
226 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
227 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
228 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
229 default_state->disable( GL_BLEND );
230 default_state->disable( GL_ALPHA_TEST );
231 default_state->disable( GL_LIGHTING );
233 hud_and_panel = new ssgSimpleState;
234 hud_and_panel->ref();
235 hud_and_panel->disable( GL_CULL_FACE );
236 hud_and_panel->disable( GL_TEXTURE_2D );
237 hud_and_panel->disable( GL_LIGHTING );
238 hud_and_panel->enable( GL_BLEND );
240 menus = new ssgSimpleState;
242 menus->disable( GL_CULL_FACE );
243 menus->disable( GL_TEXTURE_2D );
244 menus->enable( GL_BLEND );
248 // fgInitVisuals() -- Initialize various GL/view parameters
249 void fgInitVisuals( void ) {
252 l = &cur_light_params;
254 #ifndef GLUT_WRONG_VERSION
255 // Go full screen if requested ...
256 if ( globals->get_options()->get_fullscreen() ) {
261 // If enabled, normal vectors specified with glNormal are scaled
262 // to unit length after transformation. See glNormal.
263 // glEnable( GL_NORMALIZE );
265 glEnable( GL_LIGHTING );
266 glEnable( GL_LIGHT0 );
267 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
270 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
271 ssgGetLight( 0 ) -> setPosition( sunpos );
273 // glFogi (GL_FOG_MODE, GL_LINEAR);
274 glFogi (GL_FOG_MODE, GL_EXP2);
275 if ( (globals->get_options()->get_fog() == 1) ||
276 (globals->get_options()->get_shading() == 0) ) {
277 // if fastest fog requested, or if flat shading force fastest
278 glHint ( GL_FOG_HINT, GL_FASTEST );
279 } else if ( globals->get_options()->get_fog() == 2 ) {
280 glHint ( GL_FOG_HINT, GL_NICEST );
282 if ( globals->get_options()->get_wireframe() ) {
284 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
287 // This is the default anyways, but it can't hurt
288 glFrontFace ( GL_CCW );
291 // glEnable(GL_POINT_SMOOTH);
292 // glEnable(GL_LINE_SMOOTH);
293 // glEnable(GL_POLYGON_SMOOTH);
297 // Update all Visuals (redraws anything graphics related)
298 void fgRenderFrame( void ) {
302 fgLIGHT *l = &cur_light_params;
303 static double last_visibility = -9999;
305 static GLfloat fog_exp_density;
306 static GLfloat fog_exp2_density;
307 static GLfloat fog_exp2_punch_through;
310 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
311 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
312 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
313 // GLfloat mat_shininess[] = { 10.0 };
314 GLbitfield clear_mask;
316 if ( idle_state != 1000 ) {
317 // still initializing, draw the splash screen
318 if ( globals->get_options()->get_splash_screen() == 1 ) {
322 // idle_state is now 1000 meaning we've finished all our
323 // initializations and are running the main loop, so this will
324 // now work without seg faulting the system.
326 // printf("Ground = %.2f Altitude = %.2f\n", scenery.cur_elev,
327 // FG_Altitude * FEET_TO_METER);
329 // this is just a temporary hack, to make me understand Pui
330 // timerText -> setLabel (ctime (&t->cur_time));
333 // calculate our current position in cartesian space
334 scenery.center = scenery.next_center;
335 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
336 // scenery.center.y(), scenery.center.z());
338 FGViewerRPH *pilot_view =
339 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
341 pilot_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
342 cur_fdm_state->get_Lat_geocentric(),
343 cur_fdm_state->get_Altitude() *
345 pilot_view->set_sea_level_radius( cur_fdm_state->
346 get_Sea_level_radius() *
348 pilot_view->set_rph( cur_fdm_state->get_Phi(),
349 cur_fdm_state->get_Theta(),
350 cur_fdm_state->get_Psi() );
352 FGViewerLookAt *chase_view =
353 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
355 sgVec3 po; // chase view pilot_offset
356 sgVec3 wup; // chase view world up
357 sgSetVec3( po, 0.0, 0.0, 50.0 );
358 sgCopyVec3( wup, pilot_view->get_world_up() );
359 sgMat4 CXFM; // chase view + pilot offset xform
361 chase_view->get_view_offset() * RAD_TO_DEG -
362 cur_fdm_state->get_Psi() * RAD_TO_DEG,
364 sgVec3 npo; // new pilot offset after rotation
365 sgXformVec3( po, po, pilot_view->get_UP() );
366 sgXformVec3( npo, po, CXFM );
368 chase_view->set_geod_view_pos( cur_fdm_state->get_Longitude(),
369 cur_fdm_state->get_Lat_geocentric(),
370 cur_fdm_state->get_Altitude() *
372 chase_view->set_sea_level_radius( cur_fdm_state->
373 get_Sea_level_radius() *
375 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
376 chase_view->set_view_forward( pilot_view->get_view_pos() );
377 chase_view->set_view_up( wup );
381 sgCopyMat4( rph, pilot_view->get_VIEW() );
382 cout << "RPH Matrix = " << endl;
384 for ( i = 0; i < 4; i++ ) {
385 for ( j = 0; j < 4; j++ ) {
386 printf("%10.4f ", rph[i][j]);
392 sgCopyMat4( la, chase_view->get_VIEW() );
393 cout << "LookAt Matrix = " << endl;
394 for ( i = 0; i < 4; i++ ) {
395 for ( j = 0; j < 4; j++ ) {
396 printf("%10.4f ", la[i][j]);
403 fgReshape( globals->get_options()->get_xsize(),
404 globals->get_options()->get_ysize() );
409 if ( ! fgPanelVisible() ) {
411 (GLint)(globals->get_options()->get_xsize()),
412 (GLint)(globals->get_options()->get_ysize()) );
415 int( (current_panel->getViewHeight() -
416 current_panel->getYOffset())
417 * (globals->get_options()->get_ysize() / 768.0) );
419 (GLint)(globals->get_options()->get_ysize() - view_h),
420 (GLint)(globals->get_options()->get_xsize()),
425 // set the sun position
426 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
428 clear_mask = GL_DEPTH_BUFFER_BIT;
429 if ( globals->get_options()->get_wireframe() ) {
430 clear_mask |= GL_COLOR_BUFFER_BIT;
433 if ( globals->get_options()->get_skyblend() ) {
434 if ( globals->get_options()->get_textures() ) {
435 // glClearColor(black[0], black[1], black[2], black[3]);
436 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
437 l->adj_fog_color[2], l->adj_fog_color[3]);
438 clear_mask |= GL_COLOR_BUFFER_BIT;
441 glClearColor(l->sky_color[0], l->sky_color[1],
442 l->sky_color[2], l->sky_color[3]);
443 clear_mask |= GL_COLOR_BUFFER_BIT;
445 glClear( clear_mask );
447 // Tell GL we are switching to model view parameters
449 // I really should create a derived ssg node or use a call
450 // back or something so that I can draw the sky within the
451 // ssgCullAndDraw() function, but for now I just mimic what
452 // ssg does to set up the model view matrix
453 glMatrixMode(GL_MODELVIEW);
455 ssgSetCamera( (sgMat4)globals->get_current_view()->get_VIEW() );
457 // set the opengl state to known default values
458 default_state->force();
460 // update fog params if visibility has changed
461 #ifndef FG_OLD_WEATHER
462 thesky->set_visibility( WeatherDatabase->getWeatherVisibility() );
464 thesky->set_visibility( current_weather.get_visibility() );
467 thesky->modify_vis( cur_fdm_state->get_Altitude() * FEET_TO_METER,
469 ( global_multi_loop *
470 globals->get_options()->get_speed_up() ) /
471 (double)globals->get_options()->get_model_hz() );
473 double actual_visibility = thesky->get_visibility();
474 // cout << "actual visibility = " << actual_visibility << endl;
476 if ( actual_visibility != last_visibility ) {
477 last_visibility = actual_visibility;
479 // cout << "----> updating fog params" << endl;
482 fog_exp_density = -log(0.01 / actual_visibility);
485 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
486 fog_exp2_punch_through = sqrt( -log(0.01) ) /
487 ( actual_visibility * 1.5 );
490 // Set correct opengl fog density
491 glFogf (GL_FOG_DENSITY, fog_exp2_density);
493 // update the sky dome
494 if ( globals->get_options()->get_skyblend() ) {
495 /* cout << "thesky->repaint() sky_color = "
496 << cur_light_params.sky_color[0] << " "
497 << cur_light_params.sky_color[1] << " "
498 << cur_light_params.sky_color[2] << " "
499 << cur_light_params.sky_color[3] << endl;
501 << cur_light_params.fog_color[0] << " "
502 << cur_light_params.fog_color[1] << " "
503 << cur_light_params.fog_color[2] << " "
504 << cur_light_params.fog_color[3] << endl;
505 cout << " sun_angle = " << cur_light_params.sun_angle
506 << " moon_angle = " << cur_light_params.moon_angle
508 thesky->repaint( cur_light_params.sky_color,
509 cur_light_params.adj_fog_color,
510 cur_light_params.sun_angle,
511 cur_light_params.moon_angle,
512 globals->get_ephem()->getNumPlanets(),
513 globals->get_ephem()->getPlanets(),
514 globals->get_ephem()->getNumStars(),
515 globals->get_ephem()->getStars() );
517 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
518 << view_pos[1] << " " << view_pos[2] << endl;
519 cout << " zero_elev = " << zero_elev[0] << " "
520 << zero_elev[1] << " " << zero_elev[2]
521 << " lon = " << cur_fdm_state->get_Longitude()
522 << " lat = " << cur_fdm_state->get_Latitude() << endl;
523 cout << " sun_rot = " << cur_light_params.sun_rotation
524 << " gst = " << SGTime::cur_time_params->getGst() << endl;
525 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
526 << " sun dec = " << globals->get_ephem()->getSunDeclination()
527 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
528 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
530 thesky->reposition( globals->get_current_view()->get_view_pos(),
531 globals->get_current_view()->get_zero_elev(),
532 globals->get_current_view()->get_world_up(),
533 cur_fdm_state->get_Longitude(),
534 cur_fdm_state->get_Latitude(),
535 cur_fdm_state->get_Altitude() * FEET_TO_METER,
536 cur_light_params.sun_rotation,
537 globals->get_time_params()->getGst(),
538 globals->get_ephem()->getSunRightAscension(),
539 globals->get_ephem()->getSunDeclination(),
541 globals->get_ephem()->getMoonRightAscension(),
542 globals->get_ephem()->getMoonDeclination(),
546 glEnable( GL_DEPTH_TEST );
547 if ( globals->get_options()->get_fog() > 0 ) {
549 glFogi( GL_FOG_MODE, GL_EXP2 );
550 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
553 // set lighting parameters
554 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
555 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, l->scene_ambient );
556 glLightfv( GL_LIGHT0, GL_AMBIENT, black );
557 glLightfv( GL_LIGHT0, GL_DIFFUSE, l->scene_diffuse );
558 // glLightfv(GL_LIGHT0, GL_SPECULAR, white );
560 // texture parameters
561 // glEnable( GL_TEXTURE_2D );
562 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
563 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
564 // set base color (I don't think this is doing anything here)
565 // glMaterialfv (GL_FRONT, GL_AMBIENT, white);
566 // (GL_FRONT, GL_DIFFUSE, white);
567 // glMaterialfv (GL_FRONT, GL_SPECULAR, white);
568 // glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess);
571 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
572 ssgGetLight( 0 ) -> setPosition( sunpos );
574 // glMatrixMode( GL_PROJECTION );
576 float fov = globals->get_current_view()->get_fov();
577 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
579 double agl = current_aircraft.fdm_state->get_Altitude() * FEET_TO_METER
582 // FG_LOG( FG_ALL, FG_INFO, "visibility is "
583 // << current_weather.get_visibility() );
586 ssgSetNearFar( 10.0f, 120000.0f );
588 ssgSetNearFar( 0.5f, 120000.0f );
591 if ( globals->get_viewmgr()->get_current() == 0 ) {
593 penguin_sel->select(0);
595 // enable TuX and set up his position and orientation
596 penguin_sel->select(1);
598 FGViewerRPH *pilot_view =
599 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
602 sgMakeTransMat4( sgTRANS, pilot_view->get_view_pos() );
605 sgSetVec3( ownship_up, 0.0, 0.0, 1.0);
608 sgMakeRotMat4( sgROT, -90.0, ownship_up );
612 // sgMultMat4( sgTMP, sgROT, pilot_view.VIEW_ROT );
613 // sgMultMat4( sgTUX, sgTMP, sgTRANS );
615 // sgTUX = ( sgROT * pilot_view.VIEW_ROT ) * sgTRANS
617 sgCopyMat4( sgTUX, sgROT );
618 sgPostMultMat4( sgTUX, pilot_view->get_VIEW_ROT() );
619 sgPostMultMat4( sgTUX, sgTRANS );
622 sgSetCoord( &tuxpos, sgTUX );
623 penguin_pos->setTransform( &tuxpos );
626 // $$$ begin - added VS Renganthan 17 Oct 2K
628 // $$$ end - added VS Renganthan 17 Oct 2K
630 # ifdef FG_NETWORK_OLK
631 if ( globals->get_options()->get_network_olk() ) {
633 other = head->next; /* put listpointer to start */
634 while ( other != tail) { /* display all except myself */
635 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
636 other->fgd_sel->select(1);
637 sgSetCoord( &fgdpos, other->sgFGD_COORD );
638 other->fgd_pos->setTransform( &fgdpos );
643 // fgd_sel->select(1);
644 // sgCopyMat4( sgTUX, current_view.sgVIEW);
646 // sgSetCoord( &fgdpos, sgFGD_VIEW );
647 // fgd_pos->setTransform( &fgdpos);
651 // position tile nodes and update range selectors
652 global_tile_mgr.prep_ssg_nodes();
654 // draw the sky backdrop
657 // draw the ssg scene
658 glEnable( GL_DEPTH_TEST );
659 ssgCullAndDraw( scene );
661 // change state for lighting here
664 // Set punch through fog density
665 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
667 ssgCullAndDraw( lighting );
669 // draw the sky cloud layers
670 thesky->postDraw( cur_fdm_state->get_Altitude() * FEET_TO_METER );
672 // display HUD && Panel
674 glDisable( GL_DEPTH_TEST );
675 // glDisable( GL_CULL_FACE );
676 // glDisable( GL_TEXTURE_2D );
677 hud_and_panel->apply();
680 // We can do translucent menus, so why not. :-)
682 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
684 // glDisable ( GL_BLEND ) ;
686 // glEnable( GL_FOG );
693 // Update internal time dependent calculations (i.e. flight model)
694 void fgUpdateTimeDepCalcs(int multi_loop, int remainder) {
695 static fdm_state_list fdm_list;
696 fgLIGHT *l = &cur_light_params;
699 // update the flight model
700 if ( multi_loop < 0 ) {
704 if ( !globals->get_freeze() && !initial_freeze ) {
705 // run Autopilot system
706 current_autopilot->run();
708 // printf("updating flight model x %d\n", multi_loop);
709 /* fgFDMUpdate( globals->get_options()->get_flight_model(),
711 multi_loop * globals->get_options()->get_speed_up(),
713 cur_fdm_state->update( multi_loop *
714 globals->get_options()->get_speed_up() );
715 FGSteam::update( multi_loop * globals->get_options()->get_speed_up() );
717 // fgFDMUpdate( globals->get_options()->get_flight_model(),
718 // fdm_state, 0, remainder );
719 cur_fdm_state->update( 0 );
720 FGSteam::update( 0 );
722 if ( global_tile_mgr.queue_size() == 0 ) {
723 initial_freeze = false;
727 fdm_list.push_back( *cur_fdm_state );
728 while ( fdm_list.size() > 15 ) {
729 fdm_list.pop_front();
732 if ( globals->get_options()->get_view_mode() == FGOptions::FG_VIEW_PILOT ) {
733 cur_view_fdm = *cur_fdm_state;
735 } else if ( globals->get_options()->get_view_mode()
736 == FGOptions::FG_VIEW_FOLLOW )
738 cur_view_fdm = fdm_list.front();
741 // update the view angle
742 FGViewer *v = globals->get_current_view();
743 for ( i = 0; i < multi_loop; i++ ) {
744 if ( fabs(v->get_goal_view_offset() - v->get_view_offset()) < 0.05 ) {
745 v->set_view_offset( v->get_goal_view_offset() );
748 // move current_view.view_offset towards
749 // current_view.goal_view_offset
750 if ( v->get_goal_view_offset() > v->get_view_offset() )
752 if ( v->get_goal_view_offset() - v->get_view_offset() < FG_PI ){
753 v->inc_view_offset( 0.01 );
755 v->inc_view_offset( -0.01 );
758 if ( v->get_view_offset() - v->get_goal_view_offset() < FG_PI ){
759 v->inc_view_offset( -0.01 );
761 v->inc_view_offset( 0.01 );
764 if ( v->get_view_offset() > FG_2PI ) {
765 v->inc_view_offset( -FG_2PI );
766 } else if ( v->get_view_offset() < 0 ) {
767 v->inc_view_offset( FG_2PI );
772 double tmp = -(l->sun_rotation + FG_PI)
773 - (cur_fdm_state->get_Psi() -
774 globals->get_current_view()->get_view_offset() );
775 while ( tmp < 0.0 ) {
778 while ( tmp > FG_2PI ) {
781 /* printf("Psi = %.2f, viewoffset = %.2f sunrot = %.2f rottosun = %.2f\n",
782 FG_Psi * RAD_TO_DEG, current_view.view_offset * RAD_TO_DEG,
783 -(l->sun_rotation+FG_PI) * RAD_TO_DEG, tmp * RAD_TO_DEG); */
786 // Update solar system
787 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
788 globals->get_time_params()->getLst(),
789 cur_fdm_state->get_Latitude() );
791 // Update radio stack model
792 current_radiostack->update( cur_fdm_state->get_Longitude(),
793 cur_fdm_state->get_Latitude(),
794 cur_fdm_state->get_Altitude() * FEET_TO_METER );
798 void fgInitTimeDepCalcs( void ) {
801 // #ifdef HAVE_SETITIMER
802 // fgTimerInit( 1.0 / globals->get_options()->get_model_hz(),
803 // fgUpdateTimeDepCalcs );
804 // #endif HAVE_SETITIMER
808 static const double alt_adjust_ft = 3.758099;
809 static const double alt_adjust_m = alt_adjust_ft * FEET_TO_METER;
812 // What should we do when we have nothing else to do? Let's get ready
813 // for the next move and update the display?
814 static void fgMainLoop( void ) {
815 static long remainder = 0;
817 #ifdef FANCY_FRAME_COUNTER
821 static time_t last_time = 0;
822 static int frames = 0;
823 #endif // FANCY_FRAME_COUNTER
825 SGTime *t = globals->get_time_params();
827 FG_LOG( FG_ALL, FG_DEBUG, "Running Main Loop");
828 FG_LOG( FG_ALL, FG_DEBUG, "======= ==== ====");
830 #ifdef FG_NETWORK_OLK
831 if ( globals->get_options()->get_network_olk() ) {
832 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
833 // printf("FGD: Netupdate\n");
834 fgd_send_com( "A", FGFS_host); // Send Mat4 data
835 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
840 #if defined( ENABLE_PLIB_JOYSTICK )
841 // Read joystick and update control settings
842 if ( globals->get_options()->get_control_mode() == FGOptions::FG_JOYSTICK )
846 #elif defined( ENABLE_GLUT_JOYSTICK )
847 // Glut joystick support works by feeding a joystick handler
848 // function to glut. This is taken care of once in the joystick
849 // init routine and we don't have to worry about it again.
852 #ifdef FG_OLD_WEATHER
853 current_weather.Update();
856 // Fix elevation. I'm just sticking this here for now, it should
857 // probably move eventually
859 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
861 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
862 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
864 if ( scenery.cur_elev > -9990 ) {
865 if ( cur_fdm_state->get_Altitude() * FEET_TO_METER <
866 (scenery.cur_elev + alt_adjust_m - 3.0) ) {
867 // now set aircraft altitude above ground
868 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
869 cur_fdm_state->get_Altitude() * FEET_TO_METER,
870 scenery.cur_elev + alt_adjust_m - 3.0,
871 scenery.cur_elev + alt_adjust_m );
872 fgFDMForceAltitude( globals->get_options()->get_flight_model(),
873 scenery.cur_elev + alt_adjust_m );
875 FG_LOG( FG_ALL, FG_DEBUG,
876 "<*> resetting altitude to "
877 << cur_fdm_state->get_Altitude() * FEET_TO_METER
880 //fgFDMSetGroundElevation( globals->get_options()->get_flight_model(),
881 // scenery.cur_elev ); // meters
884 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
886 cur_fdm_state->get_Runway_altitude() * FEET_TO_METER,
887 cur_fdm_state->get_Altitude() * FEET_TO_METER); */
890 if ( globals->get_warp_delta() != 0 ) {
891 globals->inc_warp( globals->get_warp_delta() );
894 t->update( cur_fdm_state->get_Longitude(),
895 cur_fdm_state->get_Latitude(),
896 globals->get_warp() );
898 if ( globals->get_warp_delta() != 0 ) {
899 fgUpdateSkyAndLightingParams();
902 // update magvar model
903 globals->get_mag()->update( cur_fdm_state->get_Longitude(),
904 cur_fdm_state->get_Latitude(),
905 cur_fdm_state->get_Altitude()* FEET_TO_METER,
906 globals->get_time_params()->getJD() );
908 // Get elapsed time (in usec) for this past frame
909 elapsed = fgGetTimeInterval();
910 FG_LOG( FG_ALL, FG_DEBUG,
911 "Elapsed time interval is = " << elapsed
912 << ", previous remainder is = " << remainder );
914 // Calculate frame rate average
915 #ifdef FANCY_FRAME_COUNTER
916 /* old fps calculation */
920 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
921 tmp = general.get_frame(i);
923 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
924 general.set_frame(i+1,tmp);
926 tmp = 1000000.0 / (float)elapsed;
927 general.set_frame(0,tmp);
928 // printf("frame[0] = %.2f\n", general.frames[0]);
930 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
931 // printf("ave = %.2f\n", general.frame_rate);
934 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
935 general.set_frame_rate( frames );
936 FG_LOG( FG_ALL, FG_DEBUG,
937 "--> Frame rate is = " << general.get_frame_rate() );
940 last_time = t->get_cur_time();
945 if ( ! use_signals ) {
946 // Calculate model iterations needed for next frame
947 elapsed += remainder;
949 global_multi_loop = (int)(((double)elapsed * 0.000001) *
950 globals->get_options()->get_model_hz());
951 remainder = elapsed - ( (global_multi_loop*1000000) /
952 globals->get_options()->get_model_hz() );
953 FG_LOG( FG_ALL, FG_DEBUG,
954 "Model iterations needed = " << global_multi_loop
955 << ", new remainder = " << remainder );
958 if ( global_multi_loop > 0 ) {
959 fgUpdateTimeDepCalcs(global_multi_loop, remainder);
961 FG_LOG( FG_ALL, FG_DEBUG,
962 "Elapsed time is zero ... we're zinging" );
966 #if ! defined( macintosh )
967 // Do any I/O channel work that might need to be done
971 // see if we need to load any new scenery tiles
972 global_tile_mgr.update( cur_fdm_state->get_Longitude() * RAD_TO_DEG,
973 cur_fdm_state->get_Latitude() * RAD_TO_DEG );
975 // Process/manage pending events
976 global_events.Process();
978 // Run audio scheduler
979 #ifdef ENABLE_AUDIO_SUPPORT
980 if ( globals->get_options()->get_sound() && !audio_sched->not_working() ) {
982 if ( globals->get_options()->get_aircraft() == "c172" ) {
983 // pitch corresponds to rpm
984 // volume corresponds to manifold pressure
987 if ( cur_fdm_state->get_engine(0) != NULL ) {
988 rpm_factor = cur_fdm_state->get_engine(0)->get_RPM() / 2500.0;
992 // cout << "rpm = " << cur_fdm_state->get_engine(0)->get_RPM()
995 double pitch = 0.3 + rpm_factor * 3.0;
997 // don't run at absurdly slow rates -- not realistic
998 // and sounds bad to boot. :-)
999 if (pitch < 0.7) { pitch = 0.7; }
1000 if (pitch > 5.0) { pitch = 5.0; }
1001 // cout << "pitch = " << pitch << endl;
1004 if ( cur_fdm_state->get_engine(0) != NULL ) {
1006 cur_fdm_state->get_engine(0)->get_Manifold_Pressure() / 28;
1011 // << cur_fdm_state->get_engine(0)->get_Manifold_Pressure()
1014 double volume = mp_factor;
1016 if ( volume < 0.3 ) { volume = 0.3; }
1017 if ( volume > 2.0 ) { volume = 2.0; }
1018 // cout << "volume = " << volume << endl;
1020 pitch_envelope.setStep ( 0, 0.01, pitch );
1021 volume_envelope.setStep ( 0, 0.01, volume );
1023 double param = controls.get_throttle( 0 ) * 2.0 + 1.0;
1024 pitch_envelope.setStep ( 0, 0.01, param );
1025 volume_envelope.setStep ( 0, 0.01, param );
1028 audio_sched -> update();
1035 FG_LOG( FG_ALL, FG_DEBUG, "" );
1039 // This is the top level master main function that is registered as
1040 // our idle funciton
1043 // The first few passes take care of initialization things (a couple
1044 // per pass) and once everything has been initialized fgMainLoop from
1047 static void fgIdleFunction ( void ) {
1048 // printf("idle state == %d\n", idle_state);
1050 if ( idle_state == 0 ) {
1051 // Initialize the splash screen right away
1052 if ( globals->get_options()->get_splash_screen() ) {
1057 } else if ( idle_state == 1 ) {
1058 // Start the intro music
1060 if ( globals->get_options()->get_intro_music() ) {
1061 string lockfile = "/tmp/mpg123.running";
1062 FGPath mp3file( globals->get_options()->get_fg_root() );
1063 mp3file.append( "Sounds/intro.mp3" );
1065 string command = "(touch " + lockfile + "; mpg123 "
1066 + mp3file.str() + "> /dev/null 2>&1; /bin/rm "
1068 FG_LOG( FG_GENERAL, FG_INFO,
1069 "Starting intro music: " << mp3file.str() );
1070 system ( command.c_str() );
1075 } else if ( idle_state == 2 ) {
1076 // These are a few miscellaneous things that aren't really
1077 // "subsystems" but still need to be initialized.
1080 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1081 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1086 } else if ( idle_state == 3 ) {
1087 // This is the top level init routine which calls all the
1088 // other subsystem initialization routines. If you are adding
1089 // a subsystem to flightgear, its initialization call should
1090 // located in this routine.
1091 if( !fgInitSubsystems()) {
1092 FG_LOG( FG_GENERAL, FG_ALERT,
1093 "Subsystem initializations failed ..." );
1098 } else if ( idle_state == 4 ) {
1099 // setup OpenGL view parameters
1102 if ( use_signals ) {
1103 // init timer routines, signals, etc. Arrange for an alarm
1104 // signal to be generated, etc.
1105 fgInitTimeDepCalcs();
1109 } else if ( idle_state == 5 ) {
1112 } else if ( idle_state == 6 ) {
1113 // Initialize audio support
1114 #ifdef ENABLE_AUDIO_SUPPORT
1117 if ( globals->get_options()->get_intro_music() ) {
1118 // Let's wait for mpg123 to finish
1119 string lockfile = "/tmp/mpg123.running";
1120 struct stat stat_buf;
1122 FG_LOG( FG_GENERAL, FG_INFO,
1123 "Waiting for mpg123 player to finish ..." );
1124 while ( stat(lockfile.c_str(), &stat_buf) == 0 ) {
1125 // file exist, wait ...
1127 FG_LOG( FG_GENERAL, FG_INFO, ".");
1129 FG_LOG( FG_GENERAL, FG_INFO, "");
1133 if ( globals->get_options()->get_sound() ) {
1134 audio_sched = new slScheduler ( 8000 );
1135 audio_mixer = new smMixer;
1136 audio_mixer -> setMasterVolume ( 80 ) ; /* 80% of max volume. */
1137 audio_sched -> setSafetyMargin ( 1.0 ) ;
1139 FGPath slfile( globals->get_options()->get_fg_root() );
1140 slfile.append( "Sounds/wasp.wav" );
1142 s1 = new slSample ( (char *)slfile.c_str() );
1143 FG_LOG( FG_GENERAL, FG_INFO,
1144 "Rate = " << s1 -> getRate()
1145 << " Bps = " << s1 -> getBps()
1146 << " Stereo = " << s1 -> getStereo() );
1147 audio_sched -> loopSample ( s1 );
1149 if ( audio_sched->not_working() ) {
1152 pitch_envelope.setStep ( 0, 0.01, 0.6 );
1153 volume_envelope.setStep ( 0, 0.01, 0.6 );
1155 audio_sched -> addSampleEnvelope( s1, 0, 0,
1157 SL_PITCH_ENVELOPE );
1158 audio_sched -> addSampleEnvelope( s1, 0, 1,
1160 SL_VOLUME_ENVELOPE );
1163 // strcpy(slfile, path);
1164 // strcat(slfile, "thunder.wav");
1165 // s2 -> loadFile ( slfile );
1166 // s2 -> adjustVolume(0.5);
1167 // audio_sched -> playSample ( s2 );
1174 cout << "Panel visible = " << fgPanelVisible() << endl;
1175 fgReshape( globals->get_options()->get_xsize(),
1176 globals->get_options()->get_ysize() );
1179 if ( idle_state == 1000 ) {
1180 // We've finished all our initialization steps, from now on we
1181 // run the main loop.
1185 if ( globals->get_options()->get_splash_screen() == 1 ) {
1186 fgSplashUpdate(0.0);
1191 // options.cxx needs to see this for toggle_panel()
1192 // Handle new window size or exposure
1193 void fgReshape( int width, int height ) {
1195 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1196 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1197 globals->get_viewmgr()->get_view(i)->
1198 set_win_ratio( (float)height / (float)width );
1201 int((current_panel->getViewHeight() -
1202 current_panel->getYOffset())
1203 * (height / 768.0)) + 1;
1204 globals->get_viewmgr()->get_view(i)->
1205 set_win_ratio( (float)view_h / (float)width );
1209 if ( ! fgPanelVisible() || idle_state != 1000 ) {
1210 glViewport(0, 0 , (GLint)(width), (GLint)(height) );
1213 int((current_panel->getViewHeight() - current_panel->getYOffset())
1214 * (height / 768.0)) + 1;
1215 glViewport(0, (GLint)(height - view_h),
1216 (GLint)(width), (GLint)(view_h) );
1219 globals->get_options()->set_xsize( width );
1220 globals->get_options()->set_ysize( height );
1222 float fov = globals->get_current_view()->get_fov();
1223 ssgSetFOV(fov, fov * globals->get_current_view()->get_win_ratio());
1229 // Initialize GLUT and define a main window
1230 int fgGlutInit( int *argc, char **argv ) {
1232 #if !defined( macintosh )
1233 // GLUT will extract all glut specific options so later on we only
1234 // need wory about our own.
1235 glutInit(argc, argv);
1238 // Define Display Parameters
1239 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1241 FG_LOG( FG_GENERAL, FG_INFO, "Opening a window: " <<
1242 globals->get_options()->get_xsize() << "x"
1243 << globals->get_options()->get_ysize() );
1245 // Define initial window size
1246 glutInitWindowSize( globals->get_options()->get_xsize(),
1247 globals->get_options()->get_ysize() );
1249 // Initialize windows
1250 if ( globals->get_options()->get_game_mode() == 0 ) {
1251 // Open the regular window
1252 glutCreateWindow("FlightGear");
1253 #ifndef GLUT_WRONG_VERSION
1255 // Open the cool new 'game mode' window
1256 char game_mode_str[256];
1257 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1258 globals->get_options()->get_xsize(),
1259 globals->get_options()->get_ysize(),
1260 globals->get_options()->get_bpp());
1262 FG_LOG( FG_GENERAL, FG_INFO,
1263 "game mode params = " << game_mode_str );
1264 glutGameModeString( game_mode_str );
1265 glutEnterGameMode();
1269 // This seems to be the absolute earliest in the init sequence
1270 // that these calls will return valid info. Too bad it's after
1271 // we've already created and sized out window. :-(
1272 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1273 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1274 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1275 FG_LOG( FG_GENERAL, FG_INFO, general.get_glRenderer() );
1278 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1279 general.set_glMaxTexSize( tmp );
1280 FG_LOG ( FG_GENERAL, FG_INFO, "Max texture size = " << tmp );
1282 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1283 general.set_glDepthBits( tmp );
1284 FG_LOG ( FG_GENERAL, FG_INFO, "Depth buffer bits = " << tmp );
1287 // try to determine if we should adjust the initial default
1288 // display resolution. The options class defaults (is
1289 // initialized) to 640x480.
1290 string renderer = general.glRenderer;
1292 // currently we only know how to deal with Mesa/Glide/Voodoo cards
1293 if ( renderer.find( "Glide" ) != string::npos ) {
1294 FG_LOG( FG_GENERAL, FG_INFO, "Detected a Glide driver" );
1295 if ( renderer.find( "FB/8" ) != string::npos ) {
1296 // probably a voodoo-2
1297 if ( renderer.find( "TMU/SLI" ) != string::npos ) {
1298 // probably two SLI'd Voodoo-2's
1299 globals->get_options()->set_xsize( 1024 );
1300 globals->get_options()->set_ysize( 768 );
1301 FG_LOG( FG_GENERAL, FG_INFO,
1302 "It looks like you have two sli'd voodoo-2's." << endl
1303 << "upgrading your win resolution to 1024 x 768" );
1304 glutReshapeWindow(1024, 768);
1306 // probably a single non-SLI'd Voodoo-2
1307 globals->get_options()->set_xsize( 800 );
1308 globals->get_options()->set_ysize( 600 );
1309 FG_LOG( FG_GENERAL, FG_INFO,
1310 "It looks like you have a voodoo-2." << endl
1311 << "upgrading your win resolution to 800 x 600" );
1312 glutReshapeWindow(800, 600);
1314 } else if ( renderer.find( "FB/2" ) != string::npos ) {
1315 // probably a voodoo-1, stick with the default
1318 // we have no special knowledge of this card, stick with the default
1326 // Initialize GLUT event handlers
1327 int fgGlutInitEvents( void ) {
1328 // call fgReshape() on window resizes
1329 glutReshapeFunc( fgReshape );
1331 // call GLUTkey() on keyboard event
1332 glutKeyboardFunc( GLUTkey );
1333 glutSpecialFunc( GLUTspecialkey );
1335 // call guiMouseFunc() whenever our little rodent is used
1336 glutMouseFunc ( guiMouseFunc );
1337 glutMotionFunc (guiMotionFunc );
1338 glutPassiveMotionFunc (guiMotionFunc );
1340 // call fgMainLoop() whenever there is
1341 // nothing else to do
1342 glutIdleFunc( fgIdleFunction );
1345 glutDisplayFunc( fgRenderFrame );
1352 int main( int argc, char **argv ) {
1354 #if defined( macintosh )
1355 freopen ("stdout.txt", "w", stdout );
1356 freopen ("stderr.txt", "w", stderr );
1357 argc = ccommand( &argv );
1361 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1364 // set default log levels
1365 fglog().setLogLevels( FG_ALL, FG_INFO );
1367 FG_LOG( FG_GENERAL, FG_INFO, "FlightGear: Version "
1368 << FLIGHTGEAR_VERSION << endl );
1370 // seed the random number generater
1373 // Allocate global data structures. This needs to happen before
1374 // we parse command line options
1375 globals = new FGGlobals;
1377 SGRoute *route = new SGRoute;
1378 globals->set_route( route );
1380 FGOptions *options = new FGOptions;
1381 globals->set_options( options );
1383 FGViewMgr *viewmgr = new FGViewMgr;
1384 globals->set_viewmgr( viewmgr );
1386 FGViewerRPH *pv = new FGViewerRPH;
1387 globals->get_viewmgr()->add_view( pv );
1389 FGViewerLookAt *chase = new FGViewerLookAt;
1390 globals->get_viewmgr()->add_view( chase );
1392 // set current view to 0 (first) which is our main pilot view
1393 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1395 // Scan the config file(s) and command line options to see if
1396 // fg_root was specified (ignore all other options for now)
1397 fgInitFGRoot(argc, argv);
1399 // cout << "1. airport_id = " << globals->get_options()->get_airport_id() << endl;
1401 // Read global preferences from $FG_ROOT/preferences.xml
1402 FGPath props_path(globals->get_options()->get_fg_root());
1403 props_path.append("preferences.xml");
1404 FG_LOG(FG_INPUT, FG_INFO, "Reading global preferences");
1405 if (!readPropertyList(props_path.str(), ¤t_properties)) {
1406 FG_LOG(FG_INPUT, FG_ALERT, "Failed to read global preferences from "
1407 << props_path.str());
1409 FG_LOG(FG_INPUT, FG_INFO, "Finished Reading global preferences");
1412 // cout << "2. airport_id = " << globals->get_options()->get_airport_id() << endl;
1414 // Initialize the Aircraft directory to "" (UIUC)
1417 // Load the configuration parameters
1418 if ( !fgInitConfig(argc, argv) ) {
1419 FG_LOG( FG_GENERAL, FG_ALERT, "Config option parsing failed ..." );
1423 // Initialize the Window/Graphics environment.
1424 if( !fgGlutInit(&argc, argv) ) {
1425 FG_LOG( FG_GENERAL, FG_ALERT, "GLUT initialization failed ..." );
1429 // Initialize the various GLUT Event Handlers.
1430 if( !fgGlutInitEvents() ) {
1431 FG_LOG( FG_GENERAL, FG_ALERT,
1432 "GLUT event handler initialization failed ..." );
1436 // Initialize ssg (from plib). Needs to come before we do any
1437 // other ssg stuff, but after opengl/glut has been initialized.
1440 // Initialize the user interface (we need to do this before
1441 // passing off control to glut and before fgInitGeneral to get our
1445 // set current_options lon/lat if an airport id is specified
1446 // cout << "3. airport_id = " << globals->get_options()->get_airport_id() << endl;
1447 if ( globals->get_options()->get_airport_id().length() ) {
1448 // fgSetPosFromAirportID( globals->get_options()->get_airport_id() );
1449 fgSetPosFromAirportIDandHdg( globals->get_options()->get_airport_id(),
1450 globals->get_options()->get_heading() );
1454 FGPath zone( globals->get_options()->get_fg_root() );
1455 zone.append( "Timezone" );
1456 SGTime *t = new SGTime( globals->get_options()->get_lon() * DEG_TO_RAD,
1457 globals->get_options()->get_lat() * DEG_TO_RAD,
1460 // Handle potential user specified time offsets
1461 time_t cur_time = t->get_cur_time();
1462 time_t currGMT = sgTimeGetGMT( gmtime(&cur_time) );
1463 time_t systemLocalTime = sgTimeGetGMT( localtime(&cur_time) );
1464 time_t aircraftLocalTime =
1465 sgTimeGetGMT( fgLocaltime(&cur_time, t->get_zonename() ) );
1467 // Okay, we now have six possible scenarios
1468 switch ( globals->get_options()->get_time_offset_type() ) {
1469 case FGOptions::FG_TIME_SYS_OFFSET:
1470 globals->set_warp( globals->get_options()->get_time_offset() );
1472 case FGOptions::FG_TIME_GMT_OFFSET:
1473 globals->set_warp( globals->get_options()->get_time_offset() -
1474 (currGMT - systemLocalTime) );
1476 case FGOptions::FG_TIME_LAT_OFFSET:
1477 globals->set_warp( globals->get_options()->get_time_offset() -
1478 (aircraftLocalTime - systemLocalTime) );
1480 case FGOptions::FG_TIME_SYS_ABSOLUTE:
1481 globals->set_warp( globals->get_options()->get_time_offset() -
1483 //printf("warp = %d\n", warp);
1485 case FGOptions::FG_TIME_GMT_ABSOLUTE:
1486 globals->set_warp( globals->get_options()->get_time_offset() -
1489 case FGOptions::FG_TIME_LAT_ABSOLUTE:
1490 globals->set_warp( globals->get_options()->get_time_offset() -
1491 (aircraftLocalTime - systemLocalTime) -
1495 FG_LOG( FG_GENERAL, FG_ALERT, "Unsupported type" );
1499 FG_LOG( FG_GENERAL, FG_INFO, "After time init, warp = "
1500 << globals->get_warp() );
1502 globals->set_warp_delta( 0 );
1504 t->update( 0.0, 0.0, globals->get_warp() );
1506 globals->set_time_params( t );
1508 // Do some quick general initializations
1509 if( !fgInitGeneral()) {
1510 FG_LOG( FG_GENERAL, FG_ALERT,
1511 "General initializations failed ..." );
1516 // some ssg test stuff (requires data from the plib source
1517 // distribution) specifically from the ssg tux example
1520 FGPath modelpath( globals->get_options()->get_fg_root() );
1521 // modelpath.append( "Models" );
1522 // modelpath.append( "Geometry" );
1524 FGPath texturepath( globals->get_options()->get_fg_root() );
1525 texturepath.append( "Models" );
1526 texturepath.append( "Textures" );
1528 ssgModelPath( (char *)modelpath.c_str() );
1529 ssgTexturePath( (char *)texturepath.c_str() );
1532 scene = new ssgRoot;
1533 scene->setName( "Scene" );
1535 lighting = new ssgRoot;
1536 lighting->setName( "Lighting" );
1538 // Initialize the sky
1539 FGPath ephem_data_path( globals->get_options()->get_fg_root() );
1540 ephem_data_path.append( "Astro" );
1541 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1542 ephem->update( globals->get_time_params()->getMjd(),
1543 globals->get_time_params()->getLst(),
1545 globals->set_ephem( ephem );
1547 FGPath sky_tex_path( globals->get_options()->get_fg_root() );
1548 sky_tex_path.append( "Textures" );
1549 sky_tex_path.append( "Sky" );
1551 thesky->texture_path( sky_tex_path.str() );
1553 thesky->build( 550.0, 550.0,
1554 globals->get_ephem()->getNumPlanets(),
1555 globals->get_ephem()->getPlanets(), 60000.0,
1556 globals->get_ephem()->getNumStars(),
1557 globals->get_ephem()->getStars(), 60000.0 );
1559 if ( globals->get_options()->get_clouds() == true ) {
1560 thesky->add_cloud_layer( 2600.0, 200.0, 50.0, 40000.0,
1561 SG_CLOUD_MOSTLY_SUNNY );
1562 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1564 // thesky->add_cloud_layer( 1000.0, 200.0, 50.0,
1565 // SG_CLOUD_MOSTLY_SUNNY );
1566 // thesky->add_cloud_layer( 1800.0, 400.0, 100.0, SG_CLOUD_OVERCAST );
1567 // thesky->add_cloud_layer( 5000.0, 20.0, 10.0, SG_CLOUD_CIRRUS );
1570 // Initialize MagVar model
1571 SGMagVar *magvar = new SGMagVar();
1572 globals->set_mag( magvar );
1575 terrain = new ssgBranch;
1576 terrain->setName( "Terrain" );
1577 scene->addKid( terrain );
1580 ground = new ssgBranch;
1581 ground->setName( "Ground Lighting" );
1582 lighting->addKid( ground );
1584 airport = new ssgBranch;
1585 airport->setName( "Airport Lighting" );
1586 lighting->addKid( airport );
1588 // temporary visible aircraft "own ship"
1589 penguin_sel = new ssgSelector;
1590 penguin_pos = new ssgTransform;
1592 current_properties.getStringValue("/sim/model/path",
1593 "Models/Geometry/glider.ac");
1594 ssgEntity *tux_obj = ssgLoad((char *)(tux_path.c_str()));
1596 // align the model properly for FGFS
1597 ssgTransform *tux_align = new ssgTransform;
1598 tux_align->addKid(tux_obj);
1603 current_properties.getFloatValue("/sim/model/h-rotation", 0.0);
1605 current_properties.getFloatValue("/sim/model/p-rotation", 0.0);
1607 current_properties.getFloatValue("/sim/model/r-rotation", 0.0);
1609 current_properties.getFloatValue("/sim/model/x-offset", 0.0);
1611 current_properties.getFloatValue("/sim/model/y-offset", 0.0);
1613 current_properties.getFloatValue("/sim/model/z-offset", 0.0);
1614 sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
1615 sgMakeTransMat4(off_matrix, x_off, y_off, z_off);
1616 sgMultMat4(res_matrix, off_matrix, rot_matrix);
1617 tux_align->setTransform(res_matrix);
1619 penguin_pos->addKid( tux_align );
1620 penguin_sel->addKid( penguin_pos );
1621 ssgFlatten( tux_obj );
1622 ssgStripify( penguin_sel );
1623 penguin_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1624 scene->addKid( penguin_sel );
1626 // $$$ begin - added VS Renganthan 17 Oct 2K
1628 // $$$ end - added VS Renganthan 17 Oct 2K
1630 #ifdef FG_NETWORK_OLK
1631 // Do the network intialization
1632 if ( globals->get_options()->get_network_olk() ) {
1633 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1637 // build our custom render states
1638 fgBuildRenderStates();
1640 // pass control off to the master GLUT event handler
1643 // we never actually get here ... but to avoid compiler warnings,
1649 // $$$ end - added VS Renganathan, 15 Oct 2K
1650 // - added Venky , 12 Nov 2K
1652 void fgLoadDCS(void) {
1654 ssgEntity *ship_obj;
1657 char obj_filename[25];
1659 for (int k=0;k<32;k++)
1664 FGPath tile_path( globals->get_options()->get_fg_root());
1665 tile_path.append( "Scenery" );
1666 tile_path.append( "Objects.txt" );
1667 fg_gzifstream in( tile_path.str() );
1668 if ( ! in.is_open() ) {
1669 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << tile_path.str() );
1672 FGPath modelpath( globals->get_options()->get_fg_root() );
1673 modelpath.append( "Models" );
1674 modelpath.append( "Geometry" );
1676 FGPath texturepath( globals->get_options()->get_fg_root() );
1677 texturepath.append( "Models" );
1678 texturepath.append( "Textures" );
1680 ssgModelPath( (char *)modelpath.c_str() );
1681 ssgTexturePath( (char *)texturepath.c_str() );
1683 ship_sel = new ssgSelector;
1686 while ( ! in.eof() )
1689 if ( in.get( c ) && c == '#' )
1696 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1697 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1698 int chj=getchar();*/
1700 obj_lon[objc] *=DEG_TO_RAD;
1701 obj_lat[objc] *=DEG_TO_RAD;
1703 ship_pos[objc] = new ssgTransform;
1706 // type "repeat" in objects.txt to load one more instance of the last object.
1708 if ( strcmp(obj_filename,"repeat") != 0)
1709 ship_obj = ssgLoadOBJ( obj_filename );
1711 if ( ship_obj != NULL )
1713 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1714 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1717 FG_LOG( FG_TERRAIN, FG_ALERT, "Cannot open file: " << obj_filename );
1719 if (in.eof()) break;
1724 ship_sel->clrTraversalMaskBits( SSGTRAV_HOT );
1725 scene->addKid( ship_sel ); //add selector node to root node
1730 void fgUpdateDCS (void) {
1732 double eye_lat,eye_lon,eye_alt;
1733 static double obj_head;
1734 double sl_radius,obj_latgc;
1735 float nresultmat[4][4];
1736 sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1739 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1740 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1742 // Deck should be the first object in objects.txt in case of fdm=ada
1744 if ((globals->get_options()->get_flight_model()) == 4 )
1746 obj_lon[0] = fdm->get_aux5()*DEG_TO_RAD;
1747 obj_lat[0] = fdm->get_aux6()*DEG_TO_RAD;
1748 obj_alt[0] = fdm->get_aux7();
1751 for (int m=0; m<=objc; m++)
1753 //cout << endl << obj_lat[m]*RAD_TO_DEG << " " << obj_lon[m]*RAD_TO_DEG << " " << obj_alt[m] << " " << objc << endl;
1756 //Geodetic to Geocentric angles for rotation
1757 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1759 //moving object gbs-posn in cartesian coords
1760 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1761 Point3D obj_pos = sgGeodToCart( obj_posn );
1763 // Translate moving object w.r.t eye
1764 Point3D Objtrans = obj_pos-scenery.center;
1769 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1772 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1774 sgVec3 ship_fwd,ship_rt,ship_up;
1775 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1776 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1777 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1779 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg;
1780 sgMakeRotMat4( sgROT_lon, obj_lon[m]*RAD_TO_DEG, ship_up );
1781 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*RAD_TO_DEG, ship_rt );
1782 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1785 sgCopyMat4( sgTUX, sgROT_hdg );
1786 sgPostMultMat4( sgTUX, sgROT_lat );
1787 sgPostMultMat4( sgTUX, sgROT_lon );
1788 sgPostMultMat4( sgTUX, sgTRANS );
1791 sgSetCoord(&shippos, sgTUX );
1792 ship_pos[m]->setTransform( &shippos );
1794 if ( ship_sel != NULL )
1795 ship_sel->select(0xFFFFFFFF);
1798 // $$$ end - added VS Renganathan, 15 Oct 2K
1799 // added Venky , 12 Nov 2K