1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
5 // Copyright (C) 1997 - 2002 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>
36 #ifndef SG_HAVE_NATIVE_SGI_COMPILERS
41 #include <simgear/misc/exception.hxx>
42 #include <simgear/ephemeris/ephemeris.hxx>
43 #include <simgear/route/route.hxx>
45 #ifdef SG_MATH_EXCEPTION_CLASH
58 #include <string.h> // for strcmp()
65 #ifdef HAVE_SYS_STAT_H
66 # include <sys/stat.h> // for stat()
70 # include <unistd.h> // for stat()
73 #include <plib/netChat.h>
77 #include <simgear/constants.h> // for VERSION
78 #include <simgear/debug/logstream.hxx>
79 #include <simgear/math/polar3d.hxx>
80 #include <simgear/math/sg_random.h>
81 #include <simgear/misc/sg_path.hxx>
82 #include <simgear/sky/sky.hxx>
83 #include <simgear/timing/sg_time.hxx>
85 #include <Include/general.hxx>
87 #include <Aircraft/aircraft.hxx>
89 #include <ATC/ATCmgr.hxx>
90 #include <ATC/ATCdisplay.hxx>
91 #include <ATC/AIMgr.hxx>
93 #include <Autopilot/newauto.hxx>
95 #include <Cockpit/cockpit.hxx>
96 #include <Cockpit/radiostack.hxx>
97 #include <Cockpit/steam.hxx>
99 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
101 #include <Model/acmodel.hxx>
102 #include <Model/modelmgr.hxx>
103 #ifdef FG_NETWORK_OLK
104 #include <NetworkOLK/network.h>
106 #include <Objects/matlib.hxx>
107 #include <Scenery/scenery.hxx>
108 #include <Scenery/tilemgr.hxx>
109 #ifdef ENABLE_AUDIO_SUPPORT
110 # include <Sound/soundmgr.hxx>
111 # include <Sound/fg_fx.hxx>
112 # include <Sound/morse.hxx>
114 #include <Time/FGEventMgr.hxx>
115 #include <Time/fg_timer.hxx>
116 #include <Time/light.hxx>
117 #include <Time/sunpos.hxx>
118 #include <Time/tmp.hxx>
120 #include <Input/input.hxx>
123 #include <simgear/misc/sgstream.hxx>
124 #include <simgear/math/point3d.hxx>
125 #include <FDM/flight.hxx>
126 #include <FDM/ADA.hxx>
127 #include <Scenery/tileentry.hxx>
130 // PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
131 // PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
133 float default_attenuation[3] = {1.0, 0.0, 0.0};
134 //Required for using GL_extensions
135 void fgLoadDCS (void);
136 void fgUpdateDCS (void);
137 ssgSelector *ship_sel=NULL;
138 // upto 32 instances of a same object can be loaded.
139 ssgTransform *ship_pos[32];
140 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
142 ssgSelector *lightpoints_brightness = new ssgSelector;
143 ssgTransform *lightpoints_transform = new ssgTransform;
144 FGTileEntry *dummy_tile;
147 // Clip plane settings...
148 float scene_nearplane = 0.5f;
149 float scene_farplane = 120000.0f;
151 static double delta_time_sec = 0;
155 # include <WeatherCM/FGLocalWeatherDatabase.h>
157 # include <Environment/environment_mgr.hxx>
162 #include "fg_init.hxx"
164 #include "fg_props.hxx"
165 #include "globals.hxx"
166 #include "splash.hxx"
167 #include "viewmgr.hxx"
168 #include "options.hxx"
169 #include "logger.hxx"
172 # include <console.h> // -dw- for command line dialog
176 FGEventMgr global_events;
178 // This is a record containing a bit of global housekeeping information
181 // Specify our current idle function state. This is used to run all
182 // our initializations out of the glutIdleLoop() so that we can get a
183 // splash screen up and running right away.
184 static int idle_state = 0;
185 static long global_multi_loop;
187 // forward declaration
188 void fgReshape( int width, int height );
190 // fog constants. I'm a little nervous about putting actual code out
191 // here but it seems to work (?)
192 static const double m_log01 = -log( 0.01 );
193 static const double sqrt_m_log01 = sqrt( m_log01 );
194 static GLfloat fog_exp_density;
195 static GLfloat fog_exp2_density;
196 static GLfloat fog_exp2_punch_through;
198 #ifdef FG_NETWORK_OLK
199 ssgSelector *fgd_sel = NULL;
200 ssgTransform *fgd_pos = NULL;
203 // current fdm/position used for view
204 FGInterface cur_view_fdm;
210 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
212 { 1.0f, 0.0f, 0.0f, 0.0f },
213 { 0.0f, 0.0f, -1.0f, 0.0f },
214 { 0.0f, 1.0f, 0.0f, 0.0f },
215 { 0.0f, 0.0f, 0.0f, 1.0f }
218 // The following defines flightgear options. Because glutlib will also
219 // want to parse its own options, those options must not be included here
220 // or they will get parsed by the main program option parser. Hence case
221 // is significant for any option added that might be in conflict with
224 // glutlib parses for:
226 // -direct (invalid in Win32)
230 // -indirect (invalid in Win32)
233 // Note that glutlib depends upon strings while this program's
234 // option parser wants only initial characters followed by numbers
239 ssgSimpleState *default_state;
240 ssgSimpleState *hud_and_panel;
241 ssgSimpleState *menus;
243 SGTimeStamp last_time_stamp;
244 SGTimeStamp current_time_stamp;
246 void fgBuildRenderStates( void ) {
247 default_state = new ssgSimpleState;
248 default_state->ref();
249 default_state->disable( GL_TEXTURE_2D );
250 default_state->enable( GL_CULL_FACE );
251 default_state->enable( GL_COLOR_MATERIAL );
252 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
253 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
254 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
255 default_state->disable( GL_BLEND );
256 default_state->disable( GL_ALPHA_TEST );
257 default_state->disable( GL_LIGHTING );
259 hud_and_panel = new ssgSimpleState;
260 hud_and_panel->ref();
261 hud_and_panel->disable( GL_CULL_FACE );
262 hud_and_panel->disable( GL_TEXTURE_2D );
263 hud_and_panel->disable( GL_LIGHTING );
264 hud_and_panel->enable( GL_BLEND );
266 menus = new ssgSimpleState;
268 menus->disable( GL_CULL_FACE );
269 menus->disable( GL_TEXTURE_2D );
270 menus->enable( GL_BLEND );
274 // fgInitVisuals() -- Initialize various GL/view parameters
275 void fgInitVisuals( void ) {
278 l = &cur_light_params;
280 #ifndef GLUT_WRONG_VERSION
281 // Go full screen if requested ...
282 if ( fgGetBool("/sim/startup/fullscreen") ) {
287 // If enabled, normal vectors specified with glNormal are scaled
288 // to unit length after transformation. Enabling this has
289 // performance implications. See the docs for glNormal.
290 // glEnable( GL_NORMALIZE );
292 glEnable( GL_LIGHTING );
293 glEnable( GL_LIGHT0 );
294 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
297 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
298 ssgGetLight( 0 ) -> setPosition( sunpos );
300 glFogi (GL_FOG_MODE, GL_EXP2);
301 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
302 (!fgGetBool("/sim/rendering/shading"))) {
303 // if fastest fog requested, or if flat shading force fastest
304 glHint ( GL_FOG_HINT, GL_FASTEST );
305 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
306 glHint ( GL_FOG_HINT, GL_NICEST );
308 if ( fgGetBool("/sim/rendering/wireframe") ) {
310 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
313 // This is the default anyways, but it can't hurt
314 glFrontFace ( GL_CCW );
317 // glEnable(GL_POINT_SMOOTH);
318 // glEnable(GL_LINE_SMOOTH);
319 // glEnable(GL_POLYGON_SMOOTH);
323 // For HiRes screen Dumps using Brian Pauls TR Library
324 void trRenderFrame( void ) {
326 if ( fgPanelVisible() ) {
327 GLfloat height = fgGetInt("/sim/startup/ysize");
329 (current_panel->getViewHeight() - current_panel->getYOffset())
330 * (height / 768.0) + 1;
331 glTranslatef( 0.0, view_h, 0.0 );
334 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
335 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
337 fgLIGHT *l = &cur_light_params;
339 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
340 l->adj_fog_color[2], l->adj_fog_color[3]);
342 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
344 // set the opengl state to known default values
345 default_state->force();
348 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
349 glFogi ( GL_FOG_MODE, GL_EXP2 );
350 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
352 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
353 // we only update GL_AMBIENT for our lights we will never get
354 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
355 // explicitely to black.
356 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
358 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
360 // texture parameters
361 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
362 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
364 // we need a white diffuse light for the phase of the moon
365 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
368 // draw the ssg scene
369 // return to the desired diffuse color
370 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
371 glEnable( GL_DEPTH_TEST );
372 ssgSetNearFar( scene_nearplane, scene_farplane );
373 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
376 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
377 ssgSetNearFar( scene_nearplane, scene_farplane );
378 ssgCullAndDraw( globals->get_scenery()->get_lighting() );
380 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
382 globals->get_model_mgr()->draw();
383 globals->get_aircraft_model()->draw();
385 // need to do this here as hud_and_panel state is static to
386 // main.cxx and HUD and Panel routines have to be called with
387 // knowledge of the the TR struct < see gui.cxx::HighResDump()
388 hud_and_panel->apply();
392 // Update all Visuals (redraws anything graphics related)
393 void fgRenderFrame() {
395 // Process/manage pending events
396 global_events.update( delta_time_sec );
398 static const SGPropertyNode *longitude
399 = fgGetNode("/position/longitude-deg");
400 static const SGPropertyNode *latitude
401 = fgGetNode("/position/latitude-deg");
402 static const SGPropertyNode *altitude
403 = fgGetNode("/position/altitude-ft");
404 static const SGPropertyNode *groundlevel_nearplane
405 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
407 // Update the default (kludged) properties.
410 FGViewer *current__view = globals->get_current_view();
412 fgLIGHT *l = &cur_light_params;
413 static double last_visibility = -9999;
416 double actual_visibility = thesky->get_visibility();
417 if ( actual_visibility != last_visibility ) {
418 last_visibility = actual_visibility;
420 fog_exp_density = m_log01 / actual_visibility;
421 fog_exp2_density = sqrt_m_log01 / actual_visibility;
422 fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 2.5 );
426 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
427 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
428 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
429 // GLfloat mat_shininess[] = { 10.0 };
430 GLbitfield clear_mask;
432 if ( idle_state != 1000 ) {
433 // still initializing, draw the splash screen
434 if ( fgGetBool("/sim/startup/splash-screen") ) {
437 // Keep resetting sim time while the sim is initializing
438 globals->set_sim_time_sec( 0.0 );
440 // idle_state is now 1000 meaning we've finished all our
441 // initializations and are running the main loop, so this will
442 // now work without seg faulting the system.
444 // calculate our current position in cartesian space
445 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
448 fgReshape( fgGetInt("/sim/startup/xsize"),
449 fgGetInt("/sim/startup/ysize") );
451 // set the sun position
452 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
454 clear_mask = GL_DEPTH_BUFFER_BIT;
455 if ( fgGetBool("/sim/rendering/wireframe") ) {
456 clear_mask |= GL_COLOR_BUFFER_BIT;
459 if ( fgGetBool("/sim/rendering/skyblend") ) {
460 if ( fgGetBool("/sim/rendering/textures") ) {
461 // glClearColor(black[0], black[1], black[2], black[3]);
462 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
463 l->adj_fog_color[2], l->adj_fog_color[3]);
464 clear_mask |= GL_COLOR_BUFFER_BIT;
467 glClearColor(l->sky_color[0], l->sky_color[1],
468 l->sky_color[2], l->sky_color[3]);
469 clear_mask |= GL_COLOR_BUFFER_BIT;
471 glClear( clear_mask );
473 // Tell GL we are switching to model view parameters
475 // I really should create a derived ssg node or use a call
476 // back or something so that I can draw the sky within the
477 // ssgCullAndDraw() function, but for now I just mimic what
478 // ssg does to set up the model view matrix
479 glMatrixMode(GL_MODELVIEW);
481 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
483 // set the opengl state to known default values
484 default_state->force();
486 // update fog params if visibility has changed
487 double visibility_meters = fgGetDouble("/environment/visibility-m");
488 thesky->set_visibility(visibility_meters);
490 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
491 ( global_multi_loop * fgGetInt("/sim/speed-up") )
492 / (double)fgGetInt("/sim/model-hz") );
494 // Set correct opengl fog density
495 glFogf (GL_FOG_DENSITY, fog_exp2_density);
497 // update the sky dome
498 if ( fgGetBool("/sim/rendering/skyblend") ) {
499 /* cout << "thesky->repaint() sky_color = "
500 << cur_light_params.sky_color[0] << " "
501 << cur_light_params.sky_color[1] << " "
502 << cur_light_params.sky_color[2] << " "
503 << cur_light_params.sky_color[3] << endl;
505 << cur_light_params.fog_color[0] << " "
506 << cur_light_params.fog_color[1] << " "
507 << cur_light_params.fog_color[2] << " "
508 << cur_light_params.fog_color[3] << endl;
509 cout << " sun_angle = " << cur_light_params.sun_angle
510 << " moon_angle = " << cur_light_params.moon_angle
512 thesky->repaint( cur_light_params.sky_color,
513 cur_light_params.adj_fog_color,
514 cur_light_params.sun_angle,
515 cur_light_params.moon_angle,
516 globals->get_ephem()->getNumPlanets(),
517 globals->get_ephem()->getPlanets(),
518 globals->get_ephem()->getNumStars(),
519 globals->get_ephem()->getStars() );
521 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
522 << view_pos[1] << " " << view_pos[2] << endl;
523 cout << " zero_elev = " << zero_elev[0] << " "
524 << zero_elev[1] << " " << zero_elev[2]
525 << " lon = " << cur_fdm_state->get_Longitude()
526 << " lat = " << cur_fdm_state->get_Latitude() << endl;
527 cout << " sun_rot = " << cur_light_params.sun_rotation
528 << " gst = " << SGTime::cur_time_params->getGst() << endl;
529 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
530 << " sun dec = " << globals->get_ephem()->getSunDeclination()
531 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
532 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
534 thesky->reposition( current__view->get_view_pos(),
535 current__view->get_zero_elev(),
536 current__view->get_world_up(),
537 longitude->getDoubleValue()
538 * SGD_DEGREES_TO_RADIANS,
539 latitude->getDoubleValue()
540 * SGD_DEGREES_TO_RADIANS,
541 altitude->getDoubleValue() * SG_FEET_TO_METER,
542 cur_light_params.sun_rotation,
543 globals->get_time_params()->getGst(),
544 globals->get_ephem()->getSunRightAscension(),
545 globals->get_ephem()->getSunDeclination(),
547 globals->get_ephem()->getMoonRightAscension(),
548 globals->get_ephem()->getMoonDeclination(),
552 glEnable( GL_DEPTH_TEST );
553 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
555 glFogi( GL_FOG_MODE, GL_EXP2 );
556 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
559 // set sun/lighting parameters
560 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
562 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
563 // we only update GL_AMBIENT for our lights we will never get
564 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
565 // explicitely to black.
566 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
567 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
568 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
570 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
571 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
572 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
574 // texture parameters
575 // glEnable( GL_TEXTURE_2D );
576 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
577 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
579 // glMatrixMode( GL_PROJECTION );
581 ssgSetFOV( current__view->get_h_fov(),
582 current__view->get_v_fov() );
585 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
586 - globals->get_scenery()->get_cur_elev();
589 scene_nearplane = 10.0f;
590 scene_farplane = 120000.0f;
592 scene_nearplane = groundlevel_nearplane->getDoubleValue();
593 scene_farplane = 120000.0f;
596 ssgSetNearFar( scene_nearplane, scene_farplane );
598 // $$$ begin - added VS Renganthan 17 Oct 2K
601 // $$$ end - added VS Renganthan 17 Oct 2K
603 # ifdef FG_NETWORK_OLK
604 if ( fgGetBool("/sim/networking/network-olk") ) {
606 other = head->next; /* put listpointer to start */
607 while ( other != tail) { /* display all except myself */
608 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
609 other->fgd_sel->select(1);
610 sgSetCoord( &fgdpos, other->sgFGD_COORD );
611 other->fgd_pos->setTransform( &fgdpos );
616 // fgd_sel->select(1);
617 // sgCopyMat4( sgTUX, current_view.sgVIEW);
619 // sgSetCoord( &fgdpos, sgFGD_VIEW );
620 // fgd_pos->setTransform( &fgdpos);
624 // position tile nodes and update range selectors
625 global_tile_mgr.prep_ssg_nodes(visibility_meters);
627 if ( fgGetBool("/sim/rendering/skyblend") ) {
628 // draw the sky backdrop
630 // we need a white diffuse light for the phase of the moon
631 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
635 // return to the desired diffuse color
636 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
639 // draw the ssg scene
640 glEnable( GL_DEPTH_TEST );
642 ssgSetNearFar( scene_nearplane, scene_farplane );
643 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
645 // change state for lighting here
648 // Set punch through fog density
649 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
651 #ifdef FG_EXPERIMENTAL_LIGHTING
652 // Enable states for drawing points with GL_extension
653 if (glutExtensionSupported("GL_EXT_point_parameters")) {
654 glEnable(GL_POINT_SMOOTH);
655 float quadratic[3] = {1.0, 0.01, 0.0001};
656 // get the address of our OpenGL extensions
658 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
659 wglGetProcAddress("glPointParameterfEXT");
660 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
661 wglGetProcAddress("glPointParameterfvEXT");
663 // makes the points fade as they move away
664 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
665 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
668 // Enable states for drawing runway lights with spherical mapping
669 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
670 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
671 glEnable(GL_TEXTURE_GEN_S);
672 glEnable(GL_TEXTURE_GEN_T);
674 //Maybe this is not the best way, but it works !!
675 glPolygonMode(GL_FRONT, GL_POINT);
677 glEnable(GL_CULL_FACE);
680 glDisable( GL_LIGHTING );
681 // blending function for runway lights
682 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
686 ssgSetNearFar( scene_nearplane, scene_farplane );
687 ssgCullAndDraw( globals->get_scenery()->get_lighting() );
690 #ifdef FG_EXPERIMENTAL_LIGHTING
691 if (glutExtensionSupported("GL_EXT_point_parameters")) {
692 // Disable states used for runway lighting
693 glPolygonMode(GL_FRONT, GL_FILL);
695 glDisable(GL_TEXTURE_GEN_S);
696 glDisable(GL_TEXTURE_GEN_T);
697 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
698 default_attenuation);
704 if ( fgGetBool("/sim/rendering/skyblend") ) {
705 // draw the sky cloud layers
706 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
709 globals->get_model_mgr()->draw();
710 globals->get_aircraft_model()->draw();
712 // display HUD && Panel
714 glDisable( GL_DEPTH_TEST );
715 // glDisable( GL_CULL_FACE );
716 // glDisable( GL_TEXTURE_2D );
718 // update the input subsystem
719 current_input.update(delta_time_sec);
721 // update the controls subsystem
722 globals->get_controls()->update(delta_time_sec);
724 hud_and_panel->apply();
727 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
728 // This only works properly if called before the panel call
729 globals->get_ATC_display()->update(delta_time_sec);
731 // update the panel subsystem
732 if ( current_panel != NULL ) {
733 current_panel->update(delta_time_sec);
736 // We can do translucent menus, so why not. :-)
738 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
740 // glDisable ( GL_BLEND ) ;
742 // glEnable( GL_FOG );
744 globals->get_logger()->update(delta_time_sec);
751 // Update internal time dependent calculations (i.e. flight model)
752 // FIXME: this distinction is obsolete; all subsystems now get delta
754 void fgUpdateTimeDepCalcs() {
755 static bool inited = false;
757 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
759 fgLIGHT *l = &cur_light_params;
764 // Initialize the FDM here if it hasn't been and if we have a
765 // scenery elevation hit.
767 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
768 // << " cur_elev = " << scenery.get_cur_elev() << endl;
770 if ( !cur_fdm_state->get_inited() &&
771 globals->get_scenery()->get_cur_elev() > -9990 )
773 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
775 cur_fdm_state->init();
776 if ( cur_fdm_state->get_bound() ) {
777 cur_fdm_state->unbind();
779 cur_fdm_state->bind();
782 // conceptually, the following block could be done for each fdm
784 if ( !cur_fdm_state->get_inited() ) {
785 // do nothing, fdm isn't inited yet
787 // we have been inited, and we are good to go ...
793 globals->get_autopilot()->update(delta_time_sec);
794 cur_fdm_state->update(delta_time_sec);
795 FGSteam::update(delta_time_sec);
798 if ( !strcmp(fgGetString("/sim/view-mode"), "pilot") ) {
799 cur_view_fdm = *cur_fdm_state;
803 globals->get_model_mgr()->update(delta_time_sec);
804 globals->get_aircraft_model()->update(delta_time_sec);
806 // update the view angle
807 globals->get_viewmgr()->update(delta_time_sec);
811 // Update solar system
812 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
813 globals->get_time_params()->getLst(),
814 cur_fdm_state->get_Latitude() );
816 // Update radio stack model
817 current_radiostack->update(delta_time_sec);
821 void fgInitTimeDepCalcs( void ) {
826 static const double alt_adjust_ft = 3.758099;
827 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
830 // What should we do when we have nothing else to do? Let's get ready
831 // for the next move and update the display?
832 static void fgMainLoop( void ) {
834 // Update the elapsed time.
835 current_time_stamp.stamp();
836 delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
837 last_time_stamp = current_time_stamp;
838 globals->inc_sim_time_sec( delta_time_sec );
840 static const SGPropertyNode *longitude
841 = fgGetNode("/position/longitude-deg");
842 static const SGPropertyNode *latitude
843 = fgGetNode("/position/latitude-deg");
844 static const SGPropertyNode *altitude
845 = fgGetNode("/position/altitude-ft");
846 static const SGPropertyNode *clock_freeze
847 = fgGetNode("/sim/freeze/clock", true);
848 static const SGPropertyNode *cur_time_override
849 = fgGetNode("/sim/time/cur-time-override", true);
851 static long remainder = 0;
853 #ifdef FANCY_FRAME_COUNTER
857 static time_t last_time = 0;
858 static int frames = 0;
859 #endif // FANCY_FRAME_COUNTER
861 SGTime *t = globals->get_time_params();
863 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
864 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
866 #ifdef FG_NETWORK_OLK
867 if ( fgGetBool("/sim/networking/network-olk") ) {
868 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
869 // printf("FGD: Netupdate\n");
870 fgd_send_com( "A", FGFS_host); // Send Mat4 data
871 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
876 #if defined( ENABLE_PLIB_JOYSTICK )
877 // Read joystick and update control settings
878 // if ( fgGetString("/sim/control-mode") == "joystick" )
882 #elif defined( ENABLE_GLUT_JOYSTICK )
883 // Glut joystick support works by feeding a joystick handler
884 // function to glut. This is taken care of once in the joystick
885 // init routine and we don't have to worry about it again.
889 globals->get_environment_mgr()->update(delta_time_sec);
892 // Fix elevation. I'm just sticking this here for now, it should
893 // probably move eventually
895 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
896 scenery.get_cur_elev(),
897 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
898 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
900 if ( globals->get_scenery()->get_cur_elev() > -9990
901 && cur_fdm_state->get_inited() )
903 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
904 (globals->get_scenery()->get_cur_elev() + alt_adjust_m - 3.0) ) {
905 // now set aircraft altitude above ground
906 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
907 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
908 globals->get_scenery()->get_cur_elev() + alt_adjust_m - 3.0,
909 globals->get_scenery()->get_cur_elev() + alt_adjust_m );
910 cur_fdm_state->set_Altitude( globals->get_scenery()->get_cur_elev()
913 SG_LOG( SG_ALL, SG_DEBUG,
914 "<*> resetting altitude to "
915 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
920 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
921 scenery.get_cur_elev(),
922 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
923 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
925 // cout << "Warp = " << globals->get_warp() << endl;
928 static bool last_clock_freeze = false;
930 if ( clock_freeze->getBoolValue() ) {
931 // clock freeze requested
932 if ( cur_time_override->getLongValue() == 0 ) {
933 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
934 globals->set_warp( 0 );
937 // no clock freeze requested
938 if ( last_clock_freeze == true ) {
939 // clock just unfroze, let's set warp as the difference
940 // between frozen time and current time so we don't get a
941 // time jump (and corresponding sky object and lighting
943 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
944 fgSetLong( "/sim/time/cur-time-override", 0 );
946 if ( globals->get_warp_delta() != 0 ) {
947 globals->inc_warp( globals->get_warp_delta() );
951 last_clock_freeze = clock_freeze->getBoolValue();
953 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
954 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
955 cur_time_override->getLongValue(),
956 globals->get_warp() );
958 if ( globals->get_warp_delta() != 0 ) {
959 fgUpdateSkyAndLightingParams();
962 // update magvar model
963 globals->get_mag()->update( longitude->getDoubleValue()
964 * SGD_DEGREES_TO_RADIANS,
965 latitude->getDoubleValue()
966 * SGD_DEGREES_TO_RADIANS,
967 altitude->getDoubleValue() * SG_FEET_TO_METER,
968 globals->get_time_params()->getJD() );
970 // Get elapsed time (in usec) for this past frame
971 elapsed = fgGetTimeInterval();
972 SG_LOG( SG_ALL, SG_DEBUG,
973 "Elapsed time interval is = " << elapsed
974 << ", previous remainder is = " << remainder );
976 // Calculate frame rate average
977 #ifdef FANCY_FRAME_COUNTER
978 /* old fps calculation */
982 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
983 tmp = general.get_frame(i);
985 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
986 general.set_frame(i+1,tmp);
988 tmp = 1000000.0 / (float)elapsed;
989 general.set_frame(0,tmp);
990 // printf("frame[0] = %.2f\n", general.frames[0]);
992 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
993 // printf("ave = %.2f\n", general.frame_rate);
996 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
997 general.set_frame_rate( frames );
998 SG_LOG( SG_ALL, SG_DEBUG,
999 "--> Frame rate is = " << general.get_frame_rate() );
1002 last_time = t->get_cur_time();
1006 // Run ATC subsystem
1007 globals->get_ATC_mgr()->update(delta_time_sec);
1009 // Run the AI subsystem
1010 // globals->get_AI_mgr()->update(delta_time_sec);
1014 // Calculate model iterations needed for next frame
1015 elapsed += remainder;
1017 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1018 fgGetInt("/sim/model-hz"));
1019 remainder = elapsed - ( (global_multi_loop*1000000) /
1020 fgGetInt("/sim/model-hz") );
1021 SG_LOG( SG_ALL, SG_DEBUG,
1022 "Model iterations needed = " << global_multi_loop
1023 << ", new remainder = " << remainder );
1025 // chop max interations to something reasonable if the sim was
1026 // delayed for an excesive amount of time
1027 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1028 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1033 if ( global_multi_loop > 0 ) {
1034 fgUpdateTimeDepCalcs();
1036 SG_LOG( SG_ALL, SG_DEBUG,
1037 "Elapsed time is zero ... we're zinging" );
1040 #if ! defined( macintosh )
1041 // Do any I/O channel work that might need to be done
1045 // see if we need to load any deferred-load textures
1046 material_lib.load_next_deferred();
1048 // Run audio scheduler
1049 #ifdef ENABLE_AUDIO_SUPPORT
1050 if ( fgGetBool("/sim/sound/audible")
1051 && globals->get_soundmgr()->is_working() ) {
1052 globals->get_fx()->update(1); // FIXME: use dt
1053 globals->get_soundmgr()->update(1); // FIXME: use dt
1060 // see if we need to load any new scenery tiles
1061 double visibility_meters = fgGetDouble("/environment/visibility-m");
1062 global_tile_mgr.update( longitude->getDoubleValue(),
1063 latitude->getDoubleValue(), visibility_meters );
1065 SG_LOG( SG_ALL, SG_DEBUG, "" );
1069 // This is the top level master main function that is registered as
1070 // our idle funciton
1072 // The first few passes take care of initialization things (a couple
1073 // per pass) and once everything has been initialized fgMainLoop from
1076 static void fgIdleFunction ( void ) {
1077 // printf("idle state == %d\n", idle_state);
1079 if ( idle_state == 0 ) {
1080 // Initialize the splash screen right away
1081 if ( fgGetBool("/sim/startup/splash-screen") ) {
1086 } else if ( idle_state == 1 ) {
1087 // Initialize audio support
1088 #ifdef ENABLE_AUDIO_SUPPORT
1090 // Start the intro music
1091 if ( fgGetBool("/sim/startup/intro-music") ) {
1092 SGPath mp3file( globals->get_fg_root() );
1093 mp3file.append( "Sounds/intro.mp3" );
1095 SG_LOG( SG_GENERAL, SG_INFO,
1096 "Starting intro music: " << mp3file.str() );
1098 #if defined( __CYGWIN__ )
1099 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1100 #elif defined( WIN32 )
1101 string command = "start /m " + mp3file.str();
1103 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1106 system ( command.c_str() );
1109 // This is an 'easter egg' which is kind of a hard thing to
1110 // hide in an open source project -- so I won't try very hard
1111 // to hide it. If you are looking at this now, please, you
1112 // don't want to ruin the surprise. :-) Just forget about it
1113 // and don't look any further; unless it is causing an actual
1114 // problem for you, which it shouldn't, and I hope it doesn't!
1116 if ( globals->get_time_params()->getGmt()->tm_mon == 4
1117 && globals->get_time_params()->getGmt()->tm_mday == 19 )
1119 string url = "http://www.flightgear.org/Music/invasion.mp3";
1120 #if defined( __CYGWIN__ ) || defined( WIN32 )
1121 string command = "start /m " + url;
1123 string command = "mpg123 " + url + "> /dev/null 2>&1";
1125 system( command.c_str() );
1131 } else if ( idle_state == 2 ) {
1132 // These are a few miscellaneous things that aren't really
1133 // "subsystems" but still need to be initialized.
1136 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1137 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1142 } else if ( idle_state == 3 ) {
1143 // This is the top level init routine which calls all the
1144 // other subsystem initialization routines. If you are adding
1145 // a subsystem to flightgear, its initialization call should
1146 // located in this routine.
1147 if( !fgInitSubsystems()) {
1148 SG_LOG( SG_GENERAL, SG_ALERT,
1149 "Subsystem initializations failed ..." );
1154 } else if ( idle_state == 4 ) {
1155 // setup OpenGL view parameters
1159 } else if ( idle_state == 5 ) {
1162 } else if ( idle_state == 6 ) {
1166 cout << "Panel visible = " << fgPanelVisible() << endl;
1167 fgReshape( fgGetInt("/sim/startup/xsize"),
1168 fgGetInt("/sim/startup/ysize") );
1171 if ( idle_state == 1000 ) {
1172 // We've finished all our initialization steps, from now on we
1173 // run the main loop.
1175 glutIdleFunc(fgMainLoop);
1177 if ( fgGetBool("/sim/startup/splash-screen") ) {
1178 fgSplashUpdate(0.0);
1183 // options.cxx needs to see this for toggle_panel()
1184 // Handle new window size or exposure
1185 void fgReshape( int width, int height ) {
1188 if ( (!fgGetBool("/sim/virtual-cockpit"))
1189 && fgPanelVisible() && idle_state == 1000 ) {
1190 view_h = (int)(height * (current_panel->getViewHeight() -
1191 current_panel->getYOffset()) / 768.0);
1197 FGViewMgr *viewmgr = globals->get_viewmgr();
1198 for ( int i = 0; i < viewmgr->size(); ++i ) {
1199 viewmgr->get_view(i)->
1200 set_aspect_ratio((float)view_h / (float)width);
1203 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1205 fgSetInt("/sim/startup/xsize", width);
1206 fgSetInt("/sim/startup/ysize", height);
1207 guiInitMouse(width, height);
1209 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1210 viewmgr->get_current_view()->get_v_fov() );
1215 // Initialize GLUT and define a main window
1216 int fgGlutInit( int *argc, char **argv ) {
1218 #if !defined( macintosh )
1219 // GLUT will extract all glut specific options so later on we only
1220 // need wory about our own.
1221 glutInit(argc, argv);
1224 // Define Display Parameters
1225 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1227 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1228 fgGetInt("/sim/startup/xsize") << "x"
1229 << fgGetInt("/sim/startup/ysize") );
1231 // Define initial window size
1232 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1233 fgGetInt("/sim/startup/ysize") );
1235 // Initialize windows
1236 if ( !fgGetBool("/sim/startup/game-mode")) {
1237 // Open the regular window
1238 glutCreateWindow("FlightGear");
1239 #ifndef GLUT_WRONG_VERSION
1241 // Open the cool new 'game mode' window
1242 char game_mode_str[256];
1243 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1244 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1245 #ifndef ENUM_CURRENT_SETTINGS
1246 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1247 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1251 dm.dmSize = sizeof(DEVMODE);
1252 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1253 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1254 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1255 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1256 fgGetInt("/sim/startup/ysize") );
1257 sprintf( game_mode_str, "%dx%d:%d@%d",
1261 dm.dmDisplayFrequency );
1263 // Open the cool new 'game mode' window
1264 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1265 fgGetInt("/sim/startup/xsize"),
1266 fgGetInt("/sim/startup/ysize"),
1267 fgGetInt("/sim/rendering/bits-per-pixel"));
1269 #endif // HAVE_WINDOWS_H
1270 SG_LOG( SG_GENERAL, SG_INFO,
1271 "game mode params = " << game_mode_str );
1272 glutGameModeString( game_mode_str );
1273 glutEnterGameMode();
1274 #endif // GLUT_WRONG_VERSION
1277 // This seems to be the absolute earliest in the init sequence
1278 // that these calls will return valid info. Too bad it's after
1279 // we've already created and sized out window. :-(
1280 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1281 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1282 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1283 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1286 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1287 general.set_glMaxTexSize( tmp );
1288 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1290 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1291 general.set_glDepthBits( tmp );
1292 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1298 // Initialize GLUT event handlers
1299 int fgGlutInitEvents( void ) {
1300 // call fgReshape() on window resizes
1301 glutReshapeFunc( fgReshape );
1303 // keyboard and mouse callbacks are set in FGInput::init
1305 // call fgMainLoop() whenever there is
1306 // nothing else to do
1307 glutIdleFunc( fgIdleFunction );
1310 glutDisplayFunc( fgRenderFrame );
1317 int mainLoop( int argc, char **argv ) {
1319 #if defined( macintosh )
1320 freopen ("stdout.txt", "w", stdout );
1321 freopen ("stderr.txt", "w", stderr );
1322 argc = ccommand( &argv );
1325 // set default log levels
1326 sglog().setLogLevels( SG_ALL, SG_INFO );
1329 #ifdef FLIGHTGEAR_VERSION
1330 version = FLIGHTGEAR_VERSION;
1332 version = "unknown version";
1334 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1336 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR );
1338 // Allocate global data structures. This needs to happen before
1339 // we parse command line options
1341 globals = new FGGlobals;
1343 #ifndef FG_WEATHERCM
1344 globals->set_environment_mgr(new FGEnvironmentMgr);
1347 // seed the random number generater
1350 SGRoute *route = new SGRoute;
1351 globals->set_route( route );
1353 FGControls *controls = new FGControls;
1354 globals->set_controls( controls );
1356 string_list *col = new string_list;
1357 globals->set_channel_options_list( col );
1359 // Scan the config file(s) and command line options to see if
1360 // fg_root was specified (ignore all other options for now)
1361 fgInitFGRoot(argc, argv);
1363 // Check for the correct base package version
1364 string base_version = fgBasePackageVersion();
1365 if ( !(base_version == "0.7.9") ) {
1366 // tell the operator how to use this application
1369 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1370 << "Found version " << base_version << " at: "
1371 << globals->get_fg_root() );
1372 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1376 // Initialize the Aircraft directory to "" (UIUC)
1379 // Load the configuration parameters
1380 if ( !fgInitConfig(argc, argv) ) {
1381 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1385 // Initialize the Window/Graphics environment.
1386 if( !fgGlutInit(&argc, argv) ) {
1387 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1391 // Initialize the various GLUT Event Handlers.
1392 if( !fgGlutInitEvents() ) {
1393 SG_LOG( SG_GENERAL, SG_ALERT,
1394 "GLUT event handler initialization failed ..." );
1398 // Initialize plib net interface
1399 netInit( &argc, argv );
1401 // Initialize ssg (from plib). Needs to come before we do any
1402 // other ssg stuff, but after opengl/glut has been initialized.
1405 // Initialize the user interface (we need to do this before
1406 // passing off control to glut and before fgInitGeneral to get our
1410 #ifdef GL_EXT_texture_lod_bias
1411 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1414 // Set position relative to glide slope if requested
1415 fgSetPosFromGlideSlope();
1417 // If we have an explicit, in-range lon/lat, use it.
1418 // If not, check for an airport-id and use that.
1419 // If not, default to the middle of the KSFO field.
1420 // The default values for lon/lat are deliberately out of range
1421 // so that the airport-id can take effect; valid lon/lat will
1422 // override airport-id, however.
1423 double lon_deg = fgGetDouble("/position/longitude-deg");
1424 double lat_deg = fgGetDouble("/position/latitude-deg");
1425 if (lon_deg < -180 || lon_deg > 180 || lat_deg < -90 || lat_deg > 90) {
1426 if ( fgGetString("/sim/startup/airport-id")[0] != '\0' ) {
1427 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1428 fgGetDouble("/orientation/heading-deg") );
1429 // set tower position (a little off the heading for single
1431 fgSetTowerPosFromAirportID( fgGetString("/sim/startup/airport-id"),
1432 fgGetDouble("orientation/heading") );
1434 // Default to middle of KSFO field
1435 fgSetDouble("/position/longitude-deg", -122.374843);
1436 fgSetDouble("/position/latitude-deg", 37.619002);
1440 SGTime *t = fgInitTime();
1441 globals->set_time_params( t );
1443 // Do some quick general initializations
1444 if( !fgInitGeneral()) {
1445 SG_LOG( SG_GENERAL, SG_ALERT,
1446 "General initializations failed ..." );
1450 SGPath modelpath( globals->get_fg_root() );
1451 ssgModelPath( (char *)modelpath.c_str() );
1453 // Initialize the global scenery manager
1454 globals->set_scenery( new FGScenery );
1455 globals->get_scenery()->init();
1456 globals->get_scenery()->bind();
1458 ////////////////////////////////////////////////////////////////////
1459 // Initialize the general model subsystem.
1460 ////////////////////////////////////////////////////////////////////
1462 globals->set_model_mgr(new FGModelMgr);
1463 globals->get_model_mgr()->init();
1464 globals->get_model_mgr()->bind();
1466 ////////////////////////////////////////////////////////////////////
1467 // Initialize the 3D aircraft model subsystem.
1468 ////////////////////////////////////////////////////////////////////
1470 globals->set_aircraft_model(new FGAircraftModel);
1471 globals->get_aircraft_model()->init();
1472 globals->get_aircraft_model()->bind();
1474 ////////////////////////////////////////////////////////////////////
1475 // Initialize the view manager subsystem.
1476 ////////////////////////////////////////////////////////////////////
1478 FGViewMgr *viewmgr = new FGViewMgr;
1479 globals->set_viewmgr( viewmgr );
1484 // Initialize the sky
1485 SGPath ephem_data_path( globals->get_fg_root() );
1486 ephem_data_path.append( "Astro" );
1487 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1488 ephem->update( globals->get_time_params()->getMjd(),
1489 globals->get_time_params()->getLst(),
1491 globals->set_ephem( ephem );
1495 SGPath sky_tex_path( globals->get_fg_root() );
1496 sky_tex_path.append( "Textures" );
1497 sky_tex_path.append( "Sky" );
1498 thesky->texture_path( sky_tex_path.str() );
1500 thesky->build( 550.0, 550.0,
1501 globals->get_ephem()->getNumPlanets(),
1502 globals->get_ephem()->getPlanets(), 60000.0,
1503 globals->get_ephem()->getNumStars(),
1504 globals->get_ephem()->getStars(), 60000.0 );
1506 if ( fgGetBool("/environment/clouds/status") ) {
1507 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1508 // SG_CLOUD_OVERCAST );
1509 thesky->add_cloud_layer( fgGetDouble("/environment/clouds/altitude-ft") *
1511 200.0, 50.0, 40000.0,
1512 SG_CLOUD_MOSTLY_CLOUDY );
1513 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1514 // SG_CLOUD_MOSTLY_SUNNY );
1515 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1519 // Initialize MagVar model
1520 SGMagVar *magvar = new SGMagVar();
1521 globals->set_mag( magvar );
1523 // airport = new ssgBranch;
1524 // airport->setName( "Airport Lighting" );
1525 // lighting->addKid( airport );
1531 #ifdef FG_NETWORK_OLK
1532 // Do the network intialization
1533 if ( fgGetBool("/sim/networking/network-olk") ) {
1534 printf("Multipilot mode %s\n",
1535 fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1539 // build our custom render states
1540 fgBuildRenderStates();
1542 // pass control off to the master GLUT event handler
1545 // we never actually get here ... but to avoid compiler warnings,
1551 // $$$ end - added VS Renganathan, 15 Oct 2K
1552 // - added Venky , 12 Nov 2K
1554 #if defined(__linux__) && defined(__i386__)
1556 static void handleFPE (int);
1561 fpu_control_t fpe_flags = 0;
1562 _FPU_GETCW(fpe_flags);
1563 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1564 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1565 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1566 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1567 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1568 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1569 _FPU_SETCW(fpe_flags);
1570 signal(SIGFPE, handleFPE);
1577 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1581 // Main entry point; catch any exceptions that have made it this far.
1582 int main ( int argc, char **argv ) {
1584 // Enable floating-point exceptions for Linux/x86
1585 #if defined(__linux__) && defined(__i386__)
1589 // Enable floating-point exceptions for Windows
1590 #if defined( _MSC_VER ) && defined( DEBUG )
1591 // Christian, we should document what this does
1592 _control87( _EM_INEXACT, _MCW_EM );
1595 #if defined( HAVE_BC5PLUS )
1596 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1599 // FIXME: add other, more specific
1602 mainLoop(argc, argv);
1603 } catch (sg_throwable &t) {
1604 // We must use cerr rather than
1605 // logging, since logging may be
1607 cerr << "Fatal error: " << t.getFormattedMessage()
1608 << "\n (received from " << t.getOrigin() << ')' << endl;
1616 void fgLoadDCS(void) {
1618 ssgEntity *ship_obj = NULL;
1620 char obj_filename[25];
1622 for ( int k = 0; k < 32; k++ ) {
1626 SGPath tile_path( globals->get_fg_root());
1627 tile_path.append( "Scenery" );
1628 tile_path.append( "Objects.txt" );
1629 sg_gzifstream in( tile_path.str() );
1630 if ( ! in.is_open() ) {
1631 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1634 SGPath modelpath( globals->get_fg_root() );
1635 modelpath.append( "Models" );
1636 modelpath.append( "Geometry" );
1638 SGPath texturepath( globals->get_fg_root() );
1639 texturepath.append( "Models" );
1640 texturepath.append( "Textures" );
1642 ssgModelPath( (char *)modelpath.c_str() );
1643 ssgTexturePath( (char *)texturepath.c_str() );
1645 ship_sel = new ssgSelector;
1648 while ( ! in.eof() ) {
1650 if ( in.get( c ) && c == '#' ) {
1654 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1655 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1656 int chj=getchar();*/
1658 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1659 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1661 ship_pos[objc] = new ssgTransform;
1663 // type "repeat" in objects.txt to load one more
1664 // instance of the last object.
1666 if ( strcmp(obj_filename,"repeat") != 0) {
1667 ship_obj = ssgLoad( obj_filename );
1670 if ( ship_obj != NULL ) {
1671 ship_obj->setName(obj_filename);
1673 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1675 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1676 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1677 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1678 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1681 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1685 // temporary hack for deck lights - ultimately should move to PLib (when??)
1686 //const char *extn = file_extension ( obj_filename ) ;
1688 ssgVertexArray *lights = new ssgVertexArray( 100 );
1689 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1690 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1691 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1692 int ltype[500], light_type;
1693 static int ltcount = 0;
1695 sgVec3 rway_dir,rway_normal,lightpt;
1697 modelpath.append(obj_filename);
1698 sg_gzifstream in1( modelpath.str() );
1699 if ( ! in1.is_open() ) {
1700 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1702 while ( ! in1.eof() ) {
1704 if ( in1.get( c ) && c == '#' ) {
1709 //cout << token << endl;
1710 if ( token == "runway" ) {
1712 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1713 } else if ( token == "edgelight" ) {
1715 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1717 } else if ( token == "taxi" ) {
1719 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1721 } else if ( token == "vasi" ) {
1723 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1725 } else if ( token == "threshold" ) {
1727 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1729 } else if ( token == "rabbit" ) {
1731 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1733 } else if ( token == "ols" ) {
1735 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1737 } else if ( token == "red" ) {
1739 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1741 } else if ( token == "green" ) {
1743 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1745 } else if ( token == "lp" ) {
1747 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1748 lightpoints->add( lightpt );
1749 lightnormals->add( rway_normal );
1750 lightdir->add( rway_dir );
1751 ltype[ltcount]= light_type;
1754 if (in1.eof()) break;
1758 if ( lightpoints->getNum() ) {
1759 ssgBranch *lightpoints_branch;
1760 long int dummy = -999;
1761 dummy_tile = new FGTileEntry((SGBucket)dummy);
1762 dummy_tile->lightmaps_sequence = new ssgSelector;
1763 dummy_tile->ols_transform = new ssgTransform;
1765 // call function to generate the runway lights
1766 lightpoints_branch =
1767 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1769 lightpoints_brightness->addKid(lightpoints_branch);
1770 lightpoints_transform->addKid(lightpoints_brightness);
1771 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1772 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1773 lightpoints_transform->ref();
1774 globals->get_scenery()->get_gnd_lights_branch()->addKid( lightpoints_transform );
1778 // end hack for deck lights
1782 if (in.eof()) break;
1786 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1788 globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node
1795 void fgUpdateDCS (void) {
1797 // double eye_lat,eye_lon,eye_alt;
1798 // static double obj_head;
1799 double sl_radius,obj_latgc;
1800 // float nresultmat[4][4];
1801 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1804 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1805 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1807 // Deck should be the first object in objects.txt in case of fdm=ada
1809 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
1810 if ((fdm->get_iaux(1))==1)
1812 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1813 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1814 obj_alt[1] = fdm->get_daux(3);
1815 obj_pitch[1] = fdm->get_faux(1);
1816 obj_roll[1] = fdm->get_faux(2);
1820 for ( int m = 0; m < objc; m++ ) {
1821 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1824 //Geodetic to Geocentric angles for rotation
1825 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1827 //moving object gbs-posn in cartesian coords
1828 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1829 Point3D obj_pos = sgGeodToCart( obj_posn );
1831 // Translate moving object w.r.t eye
1832 Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
1837 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1840 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1842 sgVec3 ship_fwd,ship_rt,ship_up;
1843 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1844 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1845 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1847 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1848 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1849 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1850 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1851 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1852 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
1855 sgCopyMat4( sgTUX, sgROT_hdg );
1856 sgPostMultMat4( sgTUX, sgROT_pitch );
1857 sgPostMultMat4( sgTUX, sgROT_roll );
1858 sgPostMultMat4( sgTUX, sgROT_lat );
1859 sgPostMultMat4( sgTUX, sgROT_lon );
1860 sgPostMultMat4( sgTUX, sgTRANS );
1863 sgSetCoord(&shippos, sgTUX );
1864 ship_pos[m]->setTransform( &shippos );
1865 // temporary hack for deck lights - ultimately should move to PLib (when ??)
1867 if (lightpoints_transform) {
1868 lightpoints_transform->setTransform( &shippos );
1869 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1870 if ( sun_angle > 89 ) {
1871 lightpoints_brightness->select(0x01);
1873 lightpoints_brightness->select(0x00);
1882 sgXformPnt3( rp, rway_ols, sgTUX );
1883 vp = globals->get_current_view()->get_view_pos();
1884 to[0] = rp[0]-vp[0];
1885 to[1] = rp[1]-vp[1];
1886 to[2] = rp[2]-vp[2];
1887 float dist = sgLengthVec3( to );
1888 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
1890 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
1892 ref_elev = elev - 3.75; // +ve above, -ve below
1896 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1897 // if (ref_elev > 0.51) sel = 0x21;
1898 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
1899 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
1900 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
1901 // if (ref_elev < -0.51) sel = 0x30;
1902 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1903 dummy_tile->lightmaps_sequence->select(sel);
1906 sgCopyVec3 (up, ship_up);
1908 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
1910 sgScaleVec3 (up, 4.0*ref_elev);
1911 dummy_tile->ols_transform->setTransform(up);
1912 //cout << "ref_elev " << ref_elev << endl;
1914 // end hack for deck lights
1917 if ( ship_sel != NULL ) {
1918 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
1922 // $$$ end - added VS Renganathan, 15 Oct 2K
1923 // added Venky , 12 Nov 2K