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 #if defined(__linux__) && defined(__i386__)
29 # include <fpu_control.h>
33 #include <simgear/compiler.h>
34 #include <simgear/misc/exception.hxx>
36 #ifdef SG_MATH_EXCEPTION_CLASH
56 #ifdef HAVE_SYS_STAT_H
57 # include <sys/stat.h> // for stat()
61 # include <unistd.h> // for stat()
64 #include <plib/netChat.h>
68 #include <simgear/constants.h> // for VERSION
69 #include <simgear/debug/logstream.hxx>
70 #include <simgear/math/polar3d.hxx>
71 #include <simgear/math/sg_random.h>
72 #include <simgear/misc/sg_path.hxx>
73 #include <simgear/sky/sky.hxx>
74 #include <simgear/timing/sg_time.hxx>
76 #include <Include/general.hxx>
78 #include <Aircraft/aircraft.hxx>
80 #include <ATC/ATCmgr.hxx>
81 #include <ATC/ATCdisplay.hxx>
82 #include <Autopilot/newauto.hxx>
84 #include <Cockpit/cockpit.hxx>
85 #include <Cockpit/radiostack.hxx>
86 #include <Cockpit/steam.hxx>
88 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
90 #include <GUI/sgVec3Slider.hxx>
91 // #include <Joystick/joystick.hxx>
93 #include <NetworkOLK/network.h>
95 #include <Objects/matlib.hxx>
96 #include <Scenery/scenery.hxx>
97 #include <Scenery/tilemgr.hxx>
98 #ifdef ENABLE_AUDIO_SUPPORT
99 # include <Sound/soundmgr.hxx>
100 # include <Sound/fg_fx.hxx>
101 # include <Sound/morse.hxx>
103 #include <Time/event.hxx>
104 #include <Time/fg_timer.hxx>
105 #include <Time/light.hxx>
106 #include <Time/sunpos.hxx>
107 #include <Time/tmp.hxx>
109 #include <Input/input.hxx>
112 #include <simgear/misc/sgstream.hxx>
113 #include <simgear/math/point3d.hxx>
114 #include <FDM/flight.hxx>
115 #include <FDM/ADA.hxx>
116 #include <Scenery/tileentry.hxx>
118 // Should already be inlcluded by gl.h if needed by your platform so
119 // we shouldn't include this here.
120 // #include <GL/glext.h>
122 // PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
123 // PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
125 float default_attenuation[3] = {1.0, 0.0, 0.0};
126 //Required for using GL_extensions
127 void fgLoadDCS (void);
128 void fgUpdateDCS (void);
129 ssgSelector *ship_sel=NULL;
130 // upto 32 instances of a same object can be loaded.
131 ssgTransform *ship_pos[32];
132 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
134 ssgSelector *lightpoints_brightness = new ssgSelector;
135 ssgTransform *lightpoints_transform = new ssgTransform;
136 FGTileEntry *dummy_tile;
140 #ifndef FG_NEW_ENVIRONMENT
141 # include <WeatherCM/FGLocalWeatherDatabase.h>
143 # include <Environment/environment_mgr.hxx>
148 #include "fg_init.hxx"
150 #include "fg_props.hxx"
151 #include "globals.hxx"
152 #include "splash.hxx"
153 #include "viewmgr.hxx"
154 #include "options.hxx"
158 # include <console.h> // -dw- for command line dialog
162 // This is a record containing a bit of global housekeeping information
165 // Specify our current idle function state. This is used to run all
166 // our initializations out of the glutIdleLoop() so that we can get a
167 // splash screen up and running right away.
168 static int idle_state = 0;
169 static long global_multi_loop;
171 // forward declaration
172 void fgReshape( int width, int height );
175 ssgRoot *scene = NULL;
176 ssgBranch *terrain_branch = NULL;
177 ssgBranch *gnd_lights_branch = NULL;
178 ssgBranch *rwy_lights_branch = NULL;
180 ssgRoot *lighting = NULL;
181 // ssgBranch *airport = NULL;
183 #ifdef FG_NETWORK_OLK
184 ssgSelector *fgd_sel = NULL;
185 ssgTransform *fgd_pos = NULL;
188 // current fdm/position used for view
189 FGInterface cur_view_fdm;
195 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
197 { 1.0f, 0.0f, 0.0f, 0.0f },
198 { 0.0f, 0.0f, -1.0f, 0.0f },
199 { 0.0f, 1.0f, 0.0f, 0.0f },
200 { 0.0f, 0.0f, 0.0f, 1.0f }
203 // The following defines flightgear options. Because glutlib will also
204 // want to parse its own options, those options must not be included here
205 // or they will get parsed by the main program option parser. Hence case
206 // is significant for any option added that might be in conflict with
209 // glutlib parses for:
211 // -direct (invalid in Win32)
215 // -indirect (invalid in Win32)
218 // Note that glutlib depends upon strings while this program's
219 // option parser wants only initial characters followed by numbers
224 ssgSimpleState *default_state;
225 ssgSimpleState *hud_and_panel;
226 ssgSimpleState *menus;
228 void fgBuildRenderStates( void ) {
229 default_state = new ssgSimpleState;
230 default_state->ref();
231 default_state->disable( GL_TEXTURE_2D );
232 default_state->enable( GL_CULL_FACE );
233 default_state->enable( GL_COLOR_MATERIAL );
234 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
235 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
236 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
237 default_state->disable( GL_BLEND );
238 default_state->disable( GL_ALPHA_TEST );
239 default_state->disable( GL_LIGHTING );
241 hud_and_panel = new ssgSimpleState;
242 hud_and_panel->ref();
243 hud_and_panel->disable( GL_CULL_FACE );
244 hud_and_panel->disable( GL_TEXTURE_2D );
245 hud_and_panel->disable( GL_LIGHTING );
246 hud_and_panel->enable( GL_BLEND );
248 menus = new ssgSimpleState;
250 menus->disable( GL_CULL_FACE );
251 menus->disable( GL_TEXTURE_2D );
252 menus->enable( GL_BLEND );
255 // fgFindNode -- a function that finds a named node in an ssg graph
256 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
257 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
259 } else if ( node->isAKindOf(ssgTypeBranch()) ) {
260 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
261 while ( kid != NULL ) {
262 ssgEntity *n = fgFindNode(kid, name);
266 kid = ((ssgBranch*)node)->getNextKid();
273 // fgInitVisuals() -- Initialize various GL/view parameters
274 void fgInitVisuals( void ) {
277 l = &cur_light_params;
279 #ifndef GLUT_WRONG_VERSION
280 // Go full screen if requested ...
281 if ( fgGetBool("/sim/startup/fullscreen") ) {
286 // If enabled, normal vectors specified with glNormal are scaled
287 // to unit length after transformation. See glNormal.
288 // glEnable( GL_NORMALIZE );
290 glEnable( GL_LIGHTING );
291 glEnable( GL_LIGHT0 );
292 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
295 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
296 ssgGetLight( 0 ) -> setPosition( sunpos );
298 // glFogi (GL_FOG_MODE, GL_LINEAR);
299 glFogi (GL_FOG_MODE, GL_EXP2);
300 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
301 (!fgGetBool("/sim/rendering/shading"))) {
302 // if fastest fog requested, or if flat shading force fastest
303 glHint ( GL_FOG_HINT, GL_FASTEST );
304 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
305 glHint ( GL_FOG_HINT, GL_NICEST );
307 if ( fgGetBool("/sim/rendering/wireframe") ) {
309 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
312 // This is the default anyways, but it can't hurt
313 glFrontFace ( GL_CCW );
316 // glEnable(GL_POINT_SMOOTH);
317 // glEnable(GL_LINE_SMOOTH);
318 // glEnable(GL_POLYGON_SMOOTH);
322 // For HiRes screen Dumps using Brian Pauls TR Library
323 void trRenderFrame( void ) {
325 if ( fgPanelVisible() ) {
326 GLfloat height = fgGetInt("/sim/startup/ysize");
328 (current_panel->getViewHeight() - current_panel->getYOffset())
329 * (height / 768.0) + 1;
330 glTranslatef( 0.0, view_h, 0.0 );
333 static double m_log01 = -log( 0.01 );
334 static double sqrt_m_log01 = sqrt( m_log01 );
336 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
337 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
339 fgLIGHT *l = &cur_light_params;
341 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
342 l->adj_fog_color[2], l->adj_fog_color[3]);
344 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
346 // set the opengl state to known default values
347 default_state->force();
350 double actual_visibility = thesky->get_visibility();
351 // GLfloat fog_exp_density = m_log01 / actual_visibility;
352 GLfloat fog_exp2_density = sqrt_m_log01 / actual_visibility;
353 GLfloat fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 1.5 );
356 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
357 glFogi ( GL_FOG_MODE, GL_EXP2 );
358 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
360 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
361 // we only update GL_AMBIENT for our lights we will never get
362 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
363 // explicitely to black.
364 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
366 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
368 // texture parameters
369 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
370 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
372 // we need a white diffuse light for the phase of the moon
373 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
376 // draw the ssg scene
377 // return to the desired diffuse color
378 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
379 glEnable( GL_DEPTH_TEST );
380 ssgCullAndDraw( scene );
383 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
384 ssgCullAndDraw( lighting );
386 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
388 // need to do this here as hud_and_panel state is static to
389 // main.cxx and HUD and Panel routines have to be called with
390 // knowledge of the the TR struct < see gui.cxx::HighResDump()
391 hud_and_panel->apply();
395 // Update all Visuals (redraws anything graphics related)
396 void fgRenderFrame( void ) {
397 static const SGPropertyNode *longitude
398 = fgGetNode("/position/longitude-deg");
399 static const SGPropertyNode *latitude
400 = fgGetNode("/position/latitude-deg");
401 static const SGPropertyNode *altitude
402 = fgGetNode("/position/altitude-ft");
404 // Update the default (kludged) properties.
407 fgLIGHT *l = &cur_light_params;
408 static double last_visibility = -9999;
410 static GLfloat fog_exp_density;
411 static GLfloat fog_exp2_density;
412 static GLfloat fog_exp2_punch_through;
415 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
416 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
417 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
418 // GLfloat mat_shininess[] = { 10.0 };
419 GLbitfield clear_mask;
421 if ( idle_state != 1000 ) {
422 // still initializing, draw the splash screen
423 if ( fgGetBool("/sim/startup/splash-screen") ) {
427 // idle_state is now 1000 meaning we've finished all our
428 // initializations and are running the main loop, so this will
429 // now work without seg faulting the system.
431 // printf("Ground = %.2f Altitude = %.2f\n", scenery.get_cur_elev(),
432 // FG_Altitude * SG_FEET_TO_METER);
434 // this is just a temporary hack, to make me understand Pui
435 // timerText -> setLabel (ctime (&t->cur_time));
438 // calculate our current position in cartesian space
439 scenery.set_center( scenery.get_next_center() );
440 // printf("scenery center = %.2f %.2f %.2f\n", scenery.center.x(),
441 // scenery.center.y(), scenery.center.z());
443 FGViewerRPH *pilot_view =
444 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
446 pilot_view->set_geod_view_pos( longitude->getDoubleValue()
447 * SGD_DEGREES_TO_RADIANS,
448 latitude->getDoubleValue()
449 * SGD_DEGREES_TO_RADIANS,
450 altitude->getDoubleValue()
451 * SG_FEET_TO_METER );
452 pilot_view->set_rph( cur_fdm_state->get_Phi(),
453 cur_fdm_state->get_Theta(),
454 cur_fdm_state->get_Psi() );
456 if (fgGetString("/sim/flight-model") == "ada") {
457 //+ve x is aft, +ve z is up (see viewer.hxx)
458 pilot_view->set_pilot_offset( -5.0, 0.0, 1.0 );
461 FGViewerLookAt *chase_view =
462 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
464 sgVec3 po; // chase view pilot_offset
465 sgVec3 wup; // chase view world up
466 sgSetVec3( po, 0.0, 0.0, 100.0 );
467 sgCopyVec3( wup, pilot_view->get_world_up() );
468 sgMat4 CXFM; // chase view + pilot offset xform
470 chase_view->get_view_offset() * SGD_RADIANS_TO_DEGREES -
471 cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES,
473 sgVec3 npo; // new pilot offset after rotation
474 sgVec3 *pPO = PilotOffsetGet();
475 sgXformVec3( po, *pPO, pilot_view->get_UP() );
476 sgXformVec3( npo, po, CXFM );
478 chase_view->set_geod_view_pos( longitude->getDoubleValue()
479 * SGD_DEGREES_TO_RADIANS,
480 latitude->getDoubleValue()
481 * SGD_DEGREES_TO_RADIANS,
482 altitude->getDoubleValue()
483 * SG_FEET_TO_METER );
484 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
485 chase_view->set_view_forward( pilot_view->get_view_pos() );
486 chase_view->set_view_up( wup );
490 sgCopyMat4( rph, pilot_view->get_VIEW() );
491 cout << "RPH Matrix = " << endl;
493 for ( i = 0; i < 4; i++ ) {
494 for ( j = 0; j < 4; j++ ) {
495 printf("%10.4f ", rph[i][j]);
501 sgCopyMat4( la, chase_view->get_VIEW() );
502 cout << "LookAt Matrix = " << endl;
503 for ( i = 0; i < 4; i++ ) {
504 for ( j = 0; j < 4; j++ ) {
505 printf("%10.4f ", la[i][j]);
512 fgReshape( fgGetInt("/sim/startup/xsize"),
513 fgGetInt("/sim/startup/ysize") );
515 // set the sun position
516 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
518 clear_mask = GL_DEPTH_BUFFER_BIT;
519 if ( fgGetBool("/sim/rendering/wireframe") ) {
520 clear_mask |= GL_COLOR_BUFFER_BIT;
523 if ( fgGetBool("/sim/rendering/skyblend") ) {
524 if ( fgGetBool("/sim/rendering/textures") ) {
525 // glClearColor(black[0], black[1], black[2], black[3]);
526 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
527 l->adj_fog_color[2], l->adj_fog_color[3]);
528 clear_mask |= GL_COLOR_BUFFER_BIT;
531 glClearColor(l->sky_color[0], l->sky_color[1],
532 l->sky_color[2], l->sky_color[3]);
533 clear_mask |= GL_COLOR_BUFFER_BIT;
535 glClear( clear_mask );
537 // Tell GL we are switching to model view parameters
539 // I really should create a derived ssg node or use a call
540 // back or something so that I can draw the sky within the
541 // ssgCullAndDraw() function, but for now I just mimic what
542 // ssg does to set up the model view matrix
543 glMatrixMode(GL_MODELVIEW);
545 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
547 // set the opengl state to known default values
548 default_state->force();
550 // update fog params if visibility has changed
551 thesky->set_visibility(fgGetDouble("/environment/visibility-m"));
553 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
554 ( global_multi_loop * fgGetInt("/sim/speed-up") )
555 / (double)fgGetInt("/sim/model-hz") );
557 double actual_visibility = thesky->get_visibility();
558 // cout << "actual visibility = " << actual_visibility << endl;
560 if ( actual_visibility != last_visibility ) {
561 last_visibility = actual_visibility;
563 // cout << "----> updating fog params" << endl;
566 fog_exp_density = -log(0.01) / actual_visibility;
569 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
570 fog_exp2_punch_through = sqrt( -log(0.01) ) /
571 ( actual_visibility * 1.5 );
574 // Set correct opengl fog density
575 glFogf (GL_FOG_DENSITY, fog_exp2_density);
577 // update the sky dome
578 if ( fgGetBool("/sim/rendering/skyblend") ) {
579 /* cout << "thesky->repaint() sky_color = "
580 << cur_light_params.sky_color[0] << " "
581 << cur_light_params.sky_color[1] << " "
582 << cur_light_params.sky_color[2] << " "
583 << cur_light_params.sky_color[3] << endl;
585 << cur_light_params.fog_color[0] << " "
586 << cur_light_params.fog_color[1] << " "
587 << cur_light_params.fog_color[2] << " "
588 << cur_light_params.fog_color[3] << endl;
589 cout << " sun_angle = " << cur_light_params.sun_angle
590 << " moon_angle = " << cur_light_params.moon_angle
592 thesky->repaint( cur_light_params.sky_color,
593 cur_light_params.adj_fog_color,
594 cur_light_params.sun_angle,
595 cur_light_params.moon_angle,
596 globals->get_ephem()->getNumPlanets(),
597 globals->get_ephem()->getPlanets(),
598 globals->get_ephem()->getNumStars(),
599 globals->get_ephem()->getStars() );
601 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
602 << view_pos[1] << " " << view_pos[2] << endl;
603 cout << " zero_elev = " << zero_elev[0] << " "
604 << zero_elev[1] << " " << zero_elev[2]
605 << " lon = " << cur_fdm_state->get_Longitude()
606 << " lat = " << cur_fdm_state->get_Latitude() << endl;
607 cout << " sun_rot = " << cur_light_params.sun_rotation
608 << " gst = " << SGTime::cur_time_params->getGst() << endl;
609 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
610 << " sun dec = " << globals->get_ephem()->getSunDeclination()
611 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
612 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
614 thesky->reposition( globals->get_current_view()->get_view_pos(),
615 globals->get_current_view()->get_zero_elev(),
616 globals->get_current_view()->get_world_up(),
617 longitude->getDoubleValue()
618 * SGD_DEGREES_TO_RADIANS,
619 latitude->getDoubleValue()
620 * SGD_DEGREES_TO_RADIANS,
621 altitude->getDoubleValue() * SG_FEET_TO_METER,
622 cur_light_params.sun_rotation,
623 globals->get_time_params()->getGst(),
624 globals->get_ephem()->getSunRightAscension(),
625 globals->get_ephem()->getSunDeclination(),
627 globals->get_ephem()->getMoonRightAscension(),
628 globals->get_ephem()->getMoonDeclination(),
632 glEnable( GL_DEPTH_TEST );
633 if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
635 glFogi( GL_FOG_MODE, GL_EXP2 );
636 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
639 // set sun/lighting parameters
640 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
642 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
643 // we only update GL_AMBIENT for our lights we will never get
644 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
645 // explicitely to black.
646 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
647 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
648 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
650 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
651 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
652 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
654 // texture parameters
655 // glEnable( GL_TEXTURE_2D );
656 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
657 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
659 // glMatrixMode( GL_PROJECTION );
661 ssgSetFOV( globals->get_current_view()->get_h_fov(),
662 globals->get_current_view()->get_v_fov() );
664 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
665 - scenery.get_cur_elev();
668 ssgSetNearFar( 10.0f, 120000.0f );
670 ssgSetNearFar( 0.5f, 120000.0f );
673 current_model.update(0); // FIXME: use real delta time
675 // $$$ begin - added VS Renganthan 17 Oct 2K
677 // $$$ end - added VS Renganthan 17 Oct 2K
679 # ifdef FG_NETWORK_OLK
680 if ( fgGetBool("/sim/networking/network-olk") ) {
682 other = head->next; /* put listpointer to start */
683 while ( other != tail) { /* display all except myself */
684 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
685 other->fgd_sel->select(1);
686 sgSetCoord( &fgdpos, other->sgFGD_COORD );
687 other->fgd_pos->setTransform( &fgdpos );
692 // fgd_sel->select(1);
693 // sgCopyMat4( sgTUX, current_view.sgVIEW);
695 // sgSetCoord( &fgdpos, sgFGD_VIEW );
696 // fgd_pos->setTransform( &fgdpos);
700 // position tile nodes and update range selectors
701 global_tile_mgr.prep_ssg_nodes();
703 if ( fgGetBool("/sim/rendering/skyblend") ) {
704 // draw the sky backdrop
706 // we need a white diffuse light for the phase of the moon
707 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
711 // return to the desired diffuse color
712 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
715 // draw the ssg scene
716 glEnable( GL_DEPTH_TEST );
717 ssgCullAndDraw( scene );
719 // change state for lighting here
722 // Set punch through fog density
723 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
725 #ifdef FG_EXPERIMENTAL_LIGHTING
726 // Enable states for drawing points with GL_extension
727 if (glutExtensionSupported("GL_EXT_point_parameters")) {
728 glEnable(GL_POINT_SMOOTH);
729 float quadratic[3] = {1.0, 0.01, 0.0001};
730 // get the address of our OpenGL extensions
732 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
733 wglGetProcAddress("glPointParameterfEXT");
734 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
735 wglGetProcAddress("glPointParameterfvEXT");
737 // makes the points fade as they move away
738 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
739 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
742 // Enable states for drawing runway lights with spherical mapping
743 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
744 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
745 glEnable(GL_TEXTURE_GEN_S);
746 glEnable(GL_TEXTURE_GEN_T);
748 //Maybe this is not the best way, but it works !!
749 glPolygonMode(GL_FRONT, GL_POINT);
751 glEnable(GL_CULL_FACE);
754 glDisable( GL_LIGHTING );
755 // blending function for runway lights
756 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
760 ssgCullAndDraw( lighting );
762 #ifdef FG_EXPERIMENTAL_LIGHTING
763 if (glutExtensionSupported("GL_EXT_point_parameters")) {
764 // Disable states used for runway lighting
765 glPolygonMode(GL_FRONT, GL_FILL);
767 glDisable(GL_TEXTURE_GEN_S);
768 glDisable(GL_TEXTURE_GEN_T);
769 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
770 default_attenuation);
776 if ( fgGetBool("/sim/rendering/skyblend") ) {
777 // draw the sky cloud layers
778 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
781 // display HUD && Panel
783 glDisable( GL_DEPTH_TEST );
784 // glDisable( GL_CULL_FACE );
785 // glDisable( GL_TEXTURE_2D );
787 // update the input subsystem
788 current_input.update(1); // FIXME: use real dt
790 // update the controls subsystem
791 globals->get_controls()->update(1); // FIXME: use real dt
793 hud_and_panel->apply();
796 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
797 // This only works properly if called before the panel call
798 globals->get_ATC_display()->update(1); // FIXME: use real dt
800 // update the panel subsystem
801 if ( current_panel != NULL ) {
802 current_panel->update(1); // FIXME: use real dt
805 // We can do translucent menus, so why not. :-)
807 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
809 // glDisable ( GL_BLEND ) ;
811 // glEnable( GL_FOG );
818 // Update internal time dependent calculations (i.e. flight model)
819 void fgUpdateTimeDepCalcs() {
820 static bool inited = false;
821 static const SGPropertyNode *master_freeze
822 = fgGetNode("/sim/freeze/master");
824 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
826 fgLIGHT *l = &cur_light_params;
831 // Initialize the FDM here if it hasn't been and if we have a
832 // scenery elevation hit.
834 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
835 // << " cur_elev = " << scenery.get_cur_elev() << endl;
837 if ( !cur_fdm_state->get_inited() && scenery.get_cur_elev() > -9990 ) {
838 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
840 cur_fdm_state->init();
841 if ( cur_fdm_state->get_bound() ) {
842 cur_fdm_state->unbind();
844 cur_fdm_state->bind();
847 // conceptually, the following block could be done for each fdm
849 if ( !cur_fdm_state->get_inited() ) {
850 // do nothing, fdm isn't inited yet
851 } else if ( master_freeze->getBoolValue() ) {
852 // we are frozen, run the fdm's with 0 time slices in case
853 // they want to do something with that.
855 cur_fdm_state->update( 0 );
856 FGSteam::update( 0 );
858 // we have been inited, and we are not frozen, we are good to go ...
861 cur_fdm_state->stamp();
867 long elapsed = current - cur_fdm_state->get_time_stamp();
868 cur_fdm_state->set_time_stamp( current );
869 elapsed += cur_fdm_state->get_remainder();
870 // cout << "elapsed = " << elapsed << endl;
871 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
872 multi_loop = (long)(((double)elapsed * 0.000001) /
873 cur_fdm_state->get_delta_t() );
874 cur_fdm_state->set_multi_loop( multi_loop );
875 long remainder = elapsed - (long)( (multi_loop*1000000) *
876 cur_fdm_state->get_delta_t() );
877 cur_fdm_state->set_remainder( remainder );
878 // cout << "remainder = " << remainder << endl;
880 // chop max interations to something reasonable if the sim was
881 // delayed for an excesive amount of time
882 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
883 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
884 cur_fdm_state->set_remainder( 0 );
887 // cout << "multi_loop = " << multi_loop << endl;
888 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
889 // run Autopilot system
890 current_autopilot->run();
893 cur_fdm_state->update( 1 );
895 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
898 if ( fgGetString("/sim/view-mode") == "pilot" ) {
899 cur_view_fdm = *cur_fdm_state;
903 // update the view angle
904 globals->get_current_view()->update(multi_loop);
908 // Update solar system
909 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
910 globals->get_time_params()->getLst(),
911 cur_fdm_state->get_Latitude() );
913 // Update radio stack model
914 current_radiostack->update(multi_loop);
918 void fgInitTimeDepCalcs( void ) {
921 // #ifdef HAVE_SETITIMER
922 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
923 // fgUpdateTimeDepCalcs );
924 // #endif HAVE_SETITIMER
928 static const double alt_adjust_ft = 3.758099;
929 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
932 // What should we do when we have nothing else to do? Let's get ready
933 // for the next move and update the display?
934 static void fgMainLoop( void ) {
935 static const SGPropertyNode *longitude
936 = fgGetNode("/position/longitude-deg");
937 static const SGPropertyNode *latitude
938 = fgGetNode("/position/latitude-deg");
939 static const SGPropertyNode *altitude
940 = fgGetNode("/position/altitude-ft");
941 static const SGPropertyNode *clock_freeze
942 = fgGetNode("/sim/freeze/clock", true);
943 static const SGPropertyNode *cur_time_override
944 = fgGetNode("/sim/time/cur-time-override", true);
946 static long remainder = 0;
948 #ifdef FANCY_FRAME_COUNTER
952 static time_t last_time = 0;
953 static int frames = 0;
954 #endif // FANCY_FRAME_COUNTER
956 SGTime *t = globals->get_time_params();
958 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
959 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
961 #ifdef FG_NETWORK_OLK
962 if ( fgGetBool("/sim/networking/network-olk") ) {
963 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
964 // printf("FGD: Netupdate\n");
965 fgd_send_com( "A", FGFS_host); // Send Mat4 data
966 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
971 #if defined( ENABLE_PLIB_JOYSTICK )
972 // Read joystick and update control settings
973 // if ( fgGetString("/sim/control-mode") == "joystick" )
977 #elif defined( ENABLE_GLUT_JOYSTICK )
978 // Glut joystick support works by feeding a joystick handler
979 // function to glut. This is taken care of once in the joystick
980 // init routine and we don't have to worry about it again.
983 #ifdef FG_NEW_ENVIRONMENT
984 globals->get_environment_mgr()->update(0); // FIXME: use real delta time
987 // Fix elevation. I'm just sticking this here for now, it should
988 // probably move eventually
990 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
991 scenery.get_cur_elev(),
992 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
993 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
995 if ( scenery.get_cur_elev() > -9990 && cur_fdm_state->get_inited() ) {
996 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
997 (scenery.get_cur_elev() + alt_adjust_m - 3.0) ) {
998 // now set aircraft altitude above ground
999 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
1000 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1001 scenery.get_cur_elev() + alt_adjust_m - 3.0,
1002 scenery.get_cur_elev() + alt_adjust_m );
1003 cur_fdm_state->set_Altitude( scenery.get_cur_elev()
1006 SG_LOG( SG_ALL, SG_DEBUG,
1007 "<*> resetting altitude to "
1008 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1013 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1014 scenery.get_cur_elev(),
1015 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1016 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1018 // cout << "Warp = " << globals->get_warp() << endl;
1021 static bool last_clock_freeze = false;
1023 if ( clock_freeze->getBoolValue() ) {
1024 // clock freeze requested
1025 if ( cur_time_override->getLongValue() == 0 ) {
1026 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1027 globals->set_warp( 0 );
1030 // no clock freeze requested
1031 if ( last_clock_freeze == true ) {
1032 // clock just unfroze, let's set warp as the difference
1033 // between frozen time and current time so we don't get a
1034 // time jump (and corresponding sky object and lighting
1036 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1037 fgSetLong( "/sim/time/cur-time-override", 0 );
1039 if ( globals->get_warp_delta() != 0 ) {
1040 globals->inc_warp( globals->get_warp_delta() );
1044 last_clock_freeze = clock_freeze->getBoolValue();
1046 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1047 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1048 cur_time_override->getLongValue(),
1049 globals->get_warp() );
1051 if ( globals->get_warp_delta() != 0 ) {
1052 fgUpdateSkyAndLightingParams();
1055 // update magvar model
1056 globals->get_mag()->update( longitude->getDoubleValue()
1057 * SGD_DEGREES_TO_RADIANS,
1058 latitude->getDoubleValue()
1059 * SGD_DEGREES_TO_RADIANS,
1060 altitude->getDoubleValue() * SG_FEET_TO_METER,
1061 globals->get_time_params()->getJD() );
1063 // Get elapsed time (in usec) for this past frame
1064 elapsed = fgGetTimeInterval();
1065 SG_LOG( SG_ALL, SG_DEBUG,
1066 "Elapsed time interval is = " << elapsed
1067 << ", previous remainder is = " << remainder );
1069 // Calculate frame rate average
1070 #ifdef FANCY_FRAME_COUNTER
1071 /* old fps calculation */
1072 if ( elapsed > 0 ) {
1075 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1076 tmp = general.get_frame(i);
1078 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1079 general.set_frame(i+1,tmp);
1081 tmp = 1000000.0 / (float)elapsed;
1082 general.set_frame(0,tmp);
1083 // printf("frame[0] = %.2f\n", general.frames[0]);
1085 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1086 // printf("ave = %.2f\n", general.frame_rate);
1089 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1090 general.set_frame_rate( frames );
1091 SG_LOG( SG_ALL, SG_DEBUG,
1092 "--> Frame rate is = " << general.get_frame_rate() );
1095 last_time = t->get_cur_time();
1099 // Run ATC subsystem
1100 globals->get_ATC_mgr()->update(1); // FIXME: use real dt
1104 // Calculate model iterations needed for next frame
1105 elapsed += remainder;
1107 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1108 fgGetInt("/sim/model-hz"));
1109 remainder = elapsed - ( (global_multi_loop*1000000) /
1110 fgGetInt("/sim/model-hz") );
1111 SG_LOG( SG_ALL, SG_DEBUG,
1112 "Model iterations needed = " << global_multi_loop
1113 << ", new remainder = " << remainder );
1115 // chop max interations to something reasonable if the sim was
1116 // delayed for an excesive amount of time
1117 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1118 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1123 if ( global_multi_loop > 0 ) {
1124 fgUpdateTimeDepCalcs();
1126 SG_LOG( SG_ALL, SG_DEBUG,
1127 "Elapsed time is zero ... we're zinging" );
1130 #if ! defined( macintosh )
1131 // Do any I/O channel work that might need to be done
1135 // see if we need to load any new scenery tiles
1136 global_tile_mgr.update( longitude->getDoubleValue(),
1137 latitude->getDoubleValue() );
1139 // see if we need to load any deferred-load textures
1140 material_lib.load_next_deferred();
1142 // Process/manage pending events
1143 global_events.Process();
1145 // Run audio scheduler
1146 #ifdef ENABLE_AUDIO_SUPPORT
1147 if ( fgGetBool("/sim/sound/audible")
1148 && globals->get_soundmgr()->is_working() ) {
1149 globals->get_fx()->update(1); // FIXME: use dt
1150 globals->get_soundmgr()->update(1); // FIXME: use dt
1157 SG_LOG( SG_ALL, SG_DEBUG, "" );
1161 // This is the top level master main function that is registered as
1162 // our idle funciton
1165 // The first few passes take care of initialization things (a couple
1166 // per pass) and once everything has been initialized fgMainLoop from
1169 static void fgIdleFunction ( void ) {
1170 // printf("idle state == %d\n", idle_state);
1172 if ( idle_state == 0 ) {
1173 // Initialize the splash screen right away
1174 if ( fgGetBool("/sim/startup/splash-screen") ) {
1179 } else if ( idle_state == 1 ) {
1180 // Initialize audio support
1181 #ifdef ENABLE_AUDIO_SUPPORT
1183 // Start the intro music
1184 if ( fgGetBool("/sim/startup/intro-music") ) {
1185 SGPath mp3file( globals->get_fg_root() );
1186 mp3file.append( "Sounds/intro.mp3" );
1188 SG_LOG( SG_GENERAL, SG_INFO,
1189 "Starting intro music: " << mp3file.str() );
1191 #if defined( __CYGWIN__ )
1192 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1193 #elif defined( WIN32 )
1194 string command = "start /m " + mp3file.str();
1196 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1199 system ( command.c_str() );
1205 } else if ( idle_state == 2 ) {
1206 // These are a few miscellaneous things that aren't really
1207 // "subsystems" but still need to be initialized.
1210 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1211 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1216 } else if ( idle_state == 3 ) {
1217 // This is the top level init routine which calls all the
1218 // other subsystem initialization routines. If you are adding
1219 // a subsystem to flightgear, its initialization call should
1220 // located in this routine.
1221 if( !fgInitSubsystems()) {
1222 SG_LOG( SG_GENERAL, SG_ALERT,
1223 "Subsystem initializations failed ..." );
1228 } else if ( idle_state == 4 ) {
1229 // setup OpenGL view parameters
1233 } else if ( idle_state == 5 ) {
1236 } else if ( idle_state == 6 ) {
1240 cout << "Panel visible = " << fgPanelVisible() << endl;
1241 fgReshape( fgGetInt("/sim/startup/xsize"),
1242 fgGetInt("/sim/startup/ysize") );
1245 if ( idle_state == 1000 ) {
1246 // We've finished all our initialization steps, from now on we
1247 // run the main loop.
1251 if ( fgGetBool("/sim/startup/splash-screen") ) {
1252 fgSplashUpdate(0.0);
1257 // options.cxx needs to see this for toggle_panel()
1258 // Handle new window size or exposure
1259 void fgReshape( int width, int height ) {
1262 if ( (!fgGetBool("/sim/virtual-cockpit"))
1263 && fgPanelVisible() && idle_state == 1000 ) {
1264 view_h = (int)(height * (current_panel->getViewHeight() -
1265 current_panel->getYOffset()) / 768.0);
1271 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1272 globals->get_viewmgr()->get_view(i)->
1273 set_aspect_ratio((float)view_h / (float)width);
1276 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1278 fgSetInt("/sim/startup/xsize", width);
1279 fgSetInt("/sim/startup/ysize", height);
1280 guiInitMouse(width, height);
1282 ssgSetFOV( globals->get_current_view()->get_h_fov(),
1283 globals->get_current_view()->get_v_fov() );
1289 // Initialize GLUT and define a main window
1290 int fgGlutInit( int *argc, char **argv ) {
1292 #if !defined( macintosh )
1293 // GLUT will extract all glut specific options so later on we only
1294 // need wory about our own.
1295 glutInit(argc, argv);
1298 // Define Display Parameters
1299 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1301 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1302 fgGetInt("/sim/startup/xsize") << "x"
1303 << fgGetInt("/sim/startup/ysize") );
1305 // Define initial window size
1306 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1307 fgGetInt("/sim/startup/ysize") );
1309 // Initialize windows
1310 if ( !fgGetBool("/sim/startup/game-mode")) {
1311 // Open the regular window
1312 glutCreateWindow("FlightGear");
1313 #ifndef GLUT_WRONG_VERSION
1315 // Open the cool new 'game mode' window
1316 char game_mode_str[256];
1317 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1318 fgGetInt("/sim/startup/xsize"),
1319 fgGetInt("/sim/startup/ysize"),
1320 fgGetInt("/sim/rendering/bits-per-pixel"));
1322 SG_LOG( SG_GENERAL, SG_INFO,
1323 "game mode params = " << game_mode_str );
1324 glutGameModeString( game_mode_str );
1325 glutEnterGameMode();
1329 // This seems to be the absolute earliest in the init sequence
1330 // that these calls will return valid info. Too bad it's after
1331 // we've already created and sized out window. :-(
1332 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1333 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1334 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1335 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1338 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1339 general.set_glMaxTexSize( tmp );
1340 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1342 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1343 general.set_glDepthBits( tmp );
1344 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1350 // Initialize GLUT event handlers
1351 int fgGlutInitEvents( void ) {
1352 // call fgReshape() on window resizes
1353 glutReshapeFunc( fgReshape );
1355 // call GLUTkey() on keyboard event
1356 glutKeyboardFunc(GLUTkey);
1357 glutKeyboardUpFunc(GLUTkeyup);
1358 glutSpecialFunc(GLUTspecialkey);
1359 glutSpecialUpFunc(GLUTspecialkeyup);
1361 // call guiMouseFunc() whenever our little rodent is used
1362 glutMouseFunc ( guiMouseFunc );
1363 glutMotionFunc (guiMotionFunc );
1364 glutPassiveMotionFunc (guiMotionFunc );
1366 // call fgMainLoop() whenever there is
1367 // nothing else to do
1368 glutIdleFunc( fgIdleFunction );
1371 glutDisplayFunc( fgRenderFrame );
1378 int mainLoop( int argc, char **argv ) {
1380 #if defined( macintosh )
1381 freopen ("stdout.txt", "w", stdout );
1382 freopen ("stderr.txt", "w", stderr );
1383 argc = ccommand( &argv );
1386 // set default log levels
1387 sglog().setLogLevels( SG_ALL, SG_INFO );
1390 #ifdef FLIGHTGEAR_VERSION
1391 version = FLIGHTGEAR_VERSION;
1393 version = "unknown version";
1395 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1396 << version << endl );
1398 // Allocate global data structures. This needs to happen before
1399 // we parse command line options
1401 globals = new FGGlobals;
1403 #if defined(FG_NEW_ENVIRONMENT)
1404 globals->set_environment_mgr(new FGEnvironmentMgr);
1407 // seed the random number generater
1410 SGRoute *route = new SGRoute;
1411 globals->set_route( route );
1413 FGControls *controls = new FGControls;
1414 globals->set_controls( controls );
1416 FGViewMgr *viewmgr = new FGViewMgr;
1417 globals->set_viewmgr( viewmgr );
1419 FGViewerRPH *pv = new FGViewerRPH;
1420 globals->get_viewmgr()->add_view( pv );
1422 FGViewerLookAt *chase = new FGViewerLookAt;
1423 globals->get_viewmgr()->add_view( chase );
1425 string_list *col = new string_list;
1426 globals->set_channel_options_list( col );
1428 // set current view to 0 (first) which is our main pilot view
1429 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1431 // Scan the config file(s) and command line options to see if
1432 // fg_root was specified (ignore all other options for now)
1433 fgInitFGRoot(argc, argv);
1435 // Check for the correct base package version
1436 string base_version = fgBasePackageVersion();
1437 if ( !(base_version == "0.7.9") ) {
1438 // tell the operator how to use this application
1441 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1442 << "Found version " << base_version );
1443 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1447 // Initialize the Aircraft directory to "" (UIUC)
1450 // Load the configuration parameters
1451 if ( !fgInitConfig(argc, argv) ) {
1452 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1456 // Initialize the Window/Graphics environment.
1457 if( !fgGlutInit(&argc, argv) ) {
1458 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1462 // Initialize the various GLUT Event Handlers.
1463 if( !fgGlutInitEvents() ) {
1464 SG_LOG( SG_GENERAL, SG_ALERT,
1465 "GLUT event handler initialization failed ..." );
1469 // Initialize plib net interface
1470 netInit( &argc, argv );
1472 // Initialize ssg (from plib). Needs to come before we do any
1473 // other ssg stuff, but after opengl/glut has been initialized.
1476 // Initialize the user interface (we need to do this before
1477 // passing off control to glut and before fgInitGeneral to get our
1481 #ifdef GL_EXT_texture_lod_bias
1482 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1485 // Set position relative to glide slope if requested
1486 fgSetPosFromGlideSlope();
1488 // set current_options lon/lat if an airport id is specified
1489 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1490 if ( fgGetString("/sim/startup/airport-id").length() ) {
1491 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1492 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1493 fgGetDouble("/orientation/heading-deg") );
1496 SGTime *t = fgInitTime();
1497 globals->set_time_params( t );
1499 // Do some quick general initializations
1500 if( !fgInitGeneral()) {
1501 SG_LOG( SG_GENERAL, SG_ALERT,
1502 "General initializations failed ..." );
1506 SGPath modelpath( globals->get_fg_root() );
1507 ssgModelPath( (char *)modelpath.c_str() );
1510 scene = new ssgRoot;
1511 scene->setName( "Scene" );
1513 lighting = new ssgRoot;
1514 lighting->setName( "Lighting" );
1516 // Initialize the sky
1517 SGPath ephem_data_path( globals->get_fg_root() );
1518 ephem_data_path.append( "Astro" );
1519 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1520 ephem->update( globals->get_time_params()->getMjd(),
1521 globals->get_time_params()->getLst(),
1523 globals->set_ephem( ephem );
1527 SGPath sky_tex_path( globals->get_fg_root() );
1528 sky_tex_path.append( "Textures" );
1529 sky_tex_path.append( "Sky" );
1530 thesky->texture_path( sky_tex_path.str() );
1532 thesky->build( 550.0, 550.0,
1533 globals->get_ephem()->getNumPlanets(),
1534 globals->get_ephem()->getPlanets(), 60000.0,
1535 globals->get_ephem()->getNumStars(),
1536 globals->get_ephem()->getStars(), 60000.0 );
1538 if ( fgGetBool("/environment/clouds/status") ) {
1539 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1540 // SG_CLOUD_OVERCAST );
1541 thesky->add_cloud_layer( fgGetDouble("/environment/clouds/altitude-ft") *
1543 200.0, 50.0, 40000.0,
1544 SG_CLOUD_MOSTLY_CLOUDY );
1545 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1546 // SG_CLOUD_MOSTLY_SUNNY );
1547 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1551 // Initialize MagVar model
1552 SGMagVar *magvar = new SGMagVar();
1553 globals->set_mag( magvar );
1556 terrain_branch = new ssgBranch;
1557 terrain_branch->setName( "Terrain" );
1558 scene->addKid( terrain_branch );
1561 gnd_lights_branch = new ssgBranch;
1562 gnd_lights_branch->setName( "Ground Lighting" );
1563 lighting->addKid( gnd_lights_branch );
1565 rwy_lights_branch = new ssgBranch;
1566 rwy_lights_branch->setName( "Runway Lighting" );
1567 lighting->addKid( rwy_lights_branch );
1569 // airport = new ssgBranch;
1570 // airport->setName( "Airport Lighting" );
1571 // lighting->addKid( airport );
1577 // temporary visible aircraft "own ship"
1578 current_model.init();
1580 #ifdef FG_NETWORK_OLK
1581 // Do the network intialization
1582 if ( fgGetBool("/sim/networking/network-olk") ) {
1583 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1587 // build our custom render states
1588 fgBuildRenderStates();
1590 // pass control off to the master GLUT event handler
1593 // we never actually get here ... but to avoid compiler warnings,
1599 // $$$ end - added VS Renganathan, 15 Oct 2K
1600 // - added Venky , 12 Nov 2K
1602 #if defined(__linux__) && defined(__i386__)
1604 static void handleFPE (int);
1609 fpu_control_t fpe_flags = 0;
1610 _FPU_GETCW(fpe_flags);
1611 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1612 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1613 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1614 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1615 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1616 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1617 _FPU_SETCW(fpe_flags);
1618 signal(SIGFPE, handleFPE);
1625 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1629 // Main entry point; catch any exceptions that have made it this far.
1630 int main ( int argc, char **argv ) {
1632 // Enable floating-point exceptions for Linux/x86
1633 #if defined(__linux__) && defined(__i386__)
1637 // Enable floating-point exceptions for Windows
1638 #if defined( _MSC_VER ) && defined( DEBUG )
1639 // Christian, we should document what this does
1640 _control87( _EM_INEXACT, _MCW_EM );
1643 #if defined( HAVE_BC5PLUS )
1644 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1647 // FIXME: add other, more specific
1650 mainLoop(argc, argv);
1651 } catch (sg_throwable &t) {
1652 SG_LOG(SG_GENERAL, SG_ALERT,
1653 "Fatal error: " << t.getFormattedMessage()
1654 << "\n (received from " << t.getOrigin() << ')');
1662 void fgLoadDCS(void) {
1664 ssgEntity *ship_obj = NULL;
1666 char obj_filename[25];
1668 for ( int k = 0; k < 32; k++ ) {
1672 SGPath tile_path( globals->get_fg_root());
1673 tile_path.append( "Scenery" );
1674 tile_path.append( "Objects.txt" );
1675 sg_gzifstream in( tile_path.str() );
1676 if ( ! in.is_open() ) {
1677 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1680 SGPath modelpath( globals->get_fg_root() );
1681 modelpath.append( "Models" );
1682 modelpath.append( "Geometry" );
1684 SGPath texturepath( globals->get_fg_root() );
1685 texturepath.append( "Models" );
1686 texturepath.append( "Textures" );
1688 ssgModelPath( (char *)modelpath.c_str() );
1689 ssgTexturePath( (char *)texturepath.c_str() );
1691 ship_sel = new ssgSelector;
1694 while ( ! in.eof() ) {
1696 if ( in.get( c ) && c == '#' ) {
1700 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1701 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1702 int chj=getchar();*/
1704 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1705 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1707 ship_pos[objc] = new ssgTransform;
1709 // type "repeat" in objects.txt to load one more
1710 // instance of the last object.
1712 if ( strcmp(obj_filename,"repeat") != 0) {
1713 ship_obj = ssgLoad( obj_filename );
1716 if ( ship_obj != NULL ) {
1717 ship_obj->setName(obj_filename);
1719 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1721 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1722 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1723 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1724 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1727 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1731 // temporary hack for deck lights - ultimately should move to PLib (when??)
1732 //const char *extn = file_extension ( obj_filename ) ;
1734 ssgVertexArray *lights = new ssgVertexArray( 100 );
1735 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1736 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1737 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1738 int ltype[500], light_type;
1739 static int ltcount = 0;
1741 sgVec3 rway_dir,rway_normal,lightpt;
1743 modelpath.append(obj_filename);
1744 sg_gzifstream in1( modelpath.str() );
1745 if ( ! in1.is_open() ) {
1746 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1748 while ( ! in1.eof() ) {
1750 if ( in1.get( c ) && c == '#' ) {
1755 //cout << token << endl;
1756 if ( token == "runway" ) {
1758 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1759 } else if ( token == "edgelight" ) {
1761 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1763 } else if ( token == "taxi" ) {
1765 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1767 } else if ( token == "vasi" ) {
1769 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1771 } else if ( token == "threshold" ) {
1773 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1775 } else if ( token == "rabbit" ) {
1777 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1779 } else if ( token == "ols" ) {
1781 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1783 } else if ( token == "red" ) {
1785 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1787 } else if ( token == "green" ) {
1789 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1791 } else if ( token == "lp" ) {
1793 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1794 lightpoints->add( lightpt );
1795 lightnormals->add( rway_normal );
1796 lightdir->add( rway_dir );
1797 ltype[ltcount]= light_type;
1800 if (in1.eof()) break;
1804 if ( lightpoints->getNum() ) {
1805 ssgBranch *lightpoints_branch;
1806 long int dummy = -999;
1807 dummy_tile = new FGTileEntry((SGBucket)dummy);
1808 dummy_tile->lightmaps_sequence = new ssgSelector;
1809 dummy_tile->ols_transform = new ssgTransform;
1811 // call function to generate the runway lights
1812 lightpoints_branch =
1813 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1815 lightpoints_brightness->addKid(lightpoints_branch);
1816 lightpoints_transform->addKid(lightpoints_brightness);
1817 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1818 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1819 lightpoints_transform->ref();
1820 gnd_lights_branch->addKid( lightpoints_transform );
1824 // end hack for deck lights
1828 if (in.eof()) break;
1832 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1834 terrain_branch->addKid( ship_sel ); //add selector node to root node
1841 void fgUpdateDCS (void) {
1843 // double eye_lat,eye_lon,eye_alt;
1844 // static double obj_head;
1845 double sl_radius,obj_latgc;
1846 // float nresultmat[4][4];
1847 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1850 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1851 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1853 // Deck should be the first object in objects.txt in case of fdm=ada
1855 if (fgGetString("/sim/flight-model") == "ada") {
1856 if ((fdm->get_iaux(1))==1)
1858 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1859 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1860 obj_alt[1] = fdm->get_daux(3);
1861 obj_pitch[1] = fdm->get_faux(1);
1862 obj_roll[1] = fdm->get_faux(2);
1866 for ( int m = 0; m < objc; m++ ) {
1867 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1870 //Geodetic to Geocentric angles for rotation
1871 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1873 //moving object gbs-posn in cartesian coords
1874 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1875 Point3D obj_pos = sgGeodToCart( obj_posn );
1877 // Translate moving object w.r.t eye
1878 Point3D Objtrans = obj_pos-scenery.get_center();
1883 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1886 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1888 sgVec3 ship_fwd,ship_rt,ship_up;
1889 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1890 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1891 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1893 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1894 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1895 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1896 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1897 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1898 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
1901 sgCopyMat4( sgTUX, sgROT_hdg );
1902 sgPostMultMat4( sgTUX, sgROT_pitch );
1903 sgPostMultMat4( sgTUX, sgROT_roll );
1904 sgPostMultMat4( sgTUX, sgROT_lat );
1905 sgPostMultMat4( sgTUX, sgROT_lon );
1906 sgPostMultMat4( sgTUX, sgTRANS );
1909 sgSetCoord(&shippos, sgTUX );
1910 ship_pos[m]->setTransform( &shippos );
1911 // temporary hack for deck lights - ultimately should move to PLib (when ??)
1913 if (lightpoints_transform) {
1914 lightpoints_transform->setTransform( &shippos );
1915 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1916 if ( sun_angle > 89 ) {
1917 lightpoints_brightness->select(0x01);
1919 lightpoints_brightness->select(0x00);
1928 sgXformPnt3( rp, rway_ols, sgTUX );
1929 vp = globals->get_current_view()->get_view_pos();
1930 to[0] = rp[0]-vp[0];
1931 to[1] = rp[1]-vp[1];
1932 to[2] = rp[2]-vp[2];
1933 float dist = sgLengthVec3( to );
1934 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
1936 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
1938 ref_elev = elev - 3.75; // +ve above, -ve below
1942 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1943 // if (ref_elev > 0.51) sel = 0x21;
1944 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
1945 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
1946 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
1947 // if (ref_elev < -0.51) sel = 0x30;
1948 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1949 dummy_tile->lightmaps_sequence->select(sel);
1952 sgCopyVec3 (up, ship_up);
1954 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
1956 sgScaleVec3 (up, 4.0*ref_elev);
1957 dummy_tile->ols_transform->setTransform(up);
1958 //cout << "ref_elev " << ref_elev << endl;
1960 // end hack for deck lights
1963 if ( ship_sel != NULL ) {
1964 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
1968 // $$$ end - added VS Renganathan, 15 Oct 2K
1969 // added Venky , 12 Nov 2K