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 ssgRoot *lighting = NULL;
199 // ssgBranch *airport = NULL;
201 #ifdef FG_NETWORK_OLK
202 ssgSelector *fgd_sel = NULL;
203 ssgTransform *fgd_pos = NULL;
206 // current fdm/position used for view
207 FGInterface cur_view_fdm;
213 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
215 { 1.0f, 0.0f, 0.0f, 0.0f },
216 { 0.0f, 0.0f, -1.0f, 0.0f },
217 { 0.0f, 1.0f, 0.0f, 0.0f },
218 { 0.0f, 0.0f, 0.0f, 1.0f }
221 // The following defines flightgear options. Because glutlib will also
222 // want to parse its own options, those options must not be included here
223 // or they will get parsed by the main program option parser. Hence case
224 // is significant for any option added that might be in conflict with
227 // glutlib parses for:
229 // -direct (invalid in Win32)
233 // -indirect (invalid in Win32)
236 // Note that glutlib depends upon strings while this program's
237 // option parser wants only initial characters followed by numbers
242 ssgSimpleState *default_state;
243 ssgSimpleState *hud_and_panel;
244 ssgSimpleState *menus;
246 SGTimeStamp last_time_stamp;
247 SGTimeStamp current_time_stamp;
249 void fgBuildRenderStates( void ) {
250 default_state = new ssgSimpleState;
251 default_state->ref();
252 default_state->disable( GL_TEXTURE_2D );
253 default_state->enable( GL_CULL_FACE );
254 default_state->enable( GL_COLOR_MATERIAL );
255 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
256 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
257 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
258 default_state->disable( GL_BLEND );
259 default_state->disable( GL_ALPHA_TEST );
260 default_state->disable( GL_LIGHTING );
262 hud_and_panel = new ssgSimpleState;
263 hud_and_panel->ref();
264 hud_and_panel->disable( GL_CULL_FACE );
265 hud_and_panel->disable( GL_TEXTURE_2D );
266 hud_and_panel->disable( GL_LIGHTING );
267 hud_and_panel->enable( GL_BLEND );
269 menus = new ssgSimpleState;
271 menus->disable( GL_CULL_FACE );
272 menus->disable( GL_TEXTURE_2D );
273 menus->enable( GL_BLEND );
277 // fgInitVisuals() -- Initialize various GL/view parameters
278 void fgInitVisuals( void ) {
281 l = &cur_light_params;
283 #ifndef GLUT_WRONG_VERSION
284 // Go full screen if requested ...
285 if ( fgGetBool("/sim/startup/fullscreen") ) {
290 // If enabled, normal vectors specified with glNormal are scaled
291 // to unit length after transformation. Enabling this has
292 // performance implications. See the docs for glNormal.
293 // glEnable( GL_NORMALIZE );
295 glEnable( GL_LIGHTING );
296 glEnable( GL_LIGHT0 );
297 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
300 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
301 ssgGetLight( 0 ) -> setPosition( sunpos );
303 glFogi (GL_FOG_MODE, GL_EXP2);
304 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
305 (!fgGetBool("/sim/rendering/shading"))) {
306 // if fastest fog requested, or if flat shading force fastest
307 glHint ( GL_FOG_HINT, GL_FASTEST );
308 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
309 glHint ( GL_FOG_HINT, GL_NICEST );
311 if ( fgGetBool("/sim/rendering/wireframe") ) {
313 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
316 // This is the default anyways, but it can't hurt
317 glFrontFace ( GL_CCW );
320 // glEnable(GL_POINT_SMOOTH);
321 // glEnable(GL_LINE_SMOOTH);
322 // glEnable(GL_POLYGON_SMOOTH);
326 // For HiRes screen Dumps using Brian Pauls TR Library
327 void trRenderFrame( void ) {
329 if ( fgPanelVisible() ) {
330 GLfloat height = fgGetInt("/sim/startup/ysize");
332 (current_panel->getViewHeight() - current_panel->getYOffset())
333 * (height / 768.0) + 1;
334 glTranslatef( 0.0, view_h, 0.0 );
337 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
338 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
340 fgLIGHT *l = &cur_light_params;
342 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
343 l->adj_fog_color[2], l->adj_fog_color[3]);
345 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
347 // set the opengl state to known default values
348 default_state->force();
351 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
352 glFogi ( GL_FOG_MODE, GL_EXP2 );
353 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
355 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
356 // we only update GL_AMBIENT for our lights we will never get
357 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
358 // explicitely to black.
359 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
361 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
363 // texture parameters
364 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
365 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
367 // we need a white diffuse light for the phase of the moon
368 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
371 // draw the ssg scene
372 // return to the desired diffuse color
373 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
374 glEnable( GL_DEPTH_TEST );
375 ssgSetNearFar( scene_nearplane, scene_farplane );
376 ssgCullAndDraw( globals->get_scene_graph() );
379 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
380 ssgSetNearFar( scene_nearplane, scene_farplane );
381 ssgCullAndDraw( lighting );
383 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
385 globals->get_model_mgr()->draw();
386 globals->get_aircraft_model()->draw();
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() {
398 // Process/manage pending events
399 global_events.update( delta_time_sec );
401 static const SGPropertyNode *longitude
402 = fgGetNode("/position/longitude-deg");
403 static const SGPropertyNode *latitude
404 = fgGetNode("/position/latitude-deg");
405 static const SGPropertyNode *altitude
406 = fgGetNode("/position/altitude-ft");
407 static const SGPropertyNode *groundlevel_nearplane
408 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
410 // Update the default (kludged) properties.
413 FGViewer *current__view = globals->get_current_view();
415 fgLIGHT *l = &cur_light_params;
416 static double last_visibility = -9999;
419 double actual_visibility = thesky->get_visibility();
420 if ( actual_visibility != last_visibility ) {
421 last_visibility = actual_visibility;
423 fog_exp_density = m_log01 / actual_visibility;
424 fog_exp2_density = sqrt_m_log01 / actual_visibility;
425 fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 2.5 );
429 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
430 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
431 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
432 // GLfloat mat_shininess[] = { 10.0 };
433 GLbitfield clear_mask;
435 if ( idle_state != 1000 ) {
436 // still initializing, draw the splash screen
437 if ( fgGetBool("/sim/startup/splash-screen") ) {
440 // Keep resetting sim time while the sim is initializing
441 globals->set_sim_time_sec( 0.0 );
443 // idle_state is now 1000 meaning we've finished all our
444 // initializations and are running the main loop, so this will
445 // now work without seg faulting the system.
447 // calculate our current position in cartesian space
448 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
451 fgReshape( fgGetInt("/sim/startup/xsize"),
452 fgGetInt("/sim/startup/ysize") );
454 // set the sun position
455 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
457 clear_mask = GL_DEPTH_BUFFER_BIT;
458 if ( fgGetBool("/sim/rendering/wireframe") ) {
459 clear_mask |= GL_COLOR_BUFFER_BIT;
462 if ( fgGetBool("/sim/rendering/skyblend") ) {
463 if ( fgGetBool("/sim/rendering/textures") ) {
464 // glClearColor(black[0], black[1], black[2], black[3]);
465 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
466 l->adj_fog_color[2], l->adj_fog_color[3]);
467 clear_mask |= GL_COLOR_BUFFER_BIT;
470 glClearColor(l->sky_color[0], l->sky_color[1],
471 l->sky_color[2], l->sky_color[3]);
472 clear_mask |= GL_COLOR_BUFFER_BIT;
474 glClear( clear_mask );
476 // Tell GL we are switching to model view parameters
478 // I really should create a derived ssg node or use a call
479 // back or something so that I can draw the sky within the
480 // ssgCullAndDraw() function, but for now I just mimic what
481 // ssg does to set up the model view matrix
482 glMatrixMode(GL_MODELVIEW);
484 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
486 // set the opengl state to known default values
487 default_state->force();
489 // update fog params if visibility has changed
490 double visibility_meters = fgGetDouble("/environment/visibility-m");
491 thesky->set_visibility(visibility_meters);
493 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
494 ( global_multi_loop * fgGetInt("/sim/speed-up") )
495 / (double)fgGetInt("/sim/model-hz") );
497 // Set correct opengl fog density
498 glFogf (GL_FOG_DENSITY, fog_exp2_density);
500 // update the sky dome
501 if ( fgGetBool("/sim/rendering/skyblend") ) {
502 /* cout << "thesky->repaint() sky_color = "
503 << cur_light_params.sky_color[0] << " "
504 << cur_light_params.sky_color[1] << " "
505 << cur_light_params.sky_color[2] << " "
506 << cur_light_params.sky_color[3] << endl;
508 << cur_light_params.fog_color[0] << " "
509 << cur_light_params.fog_color[1] << " "
510 << cur_light_params.fog_color[2] << " "
511 << cur_light_params.fog_color[3] << endl;
512 cout << " sun_angle = " << cur_light_params.sun_angle
513 << " moon_angle = " << cur_light_params.moon_angle
515 thesky->repaint( cur_light_params.sky_color,
516 cur_light_params.adj_fog_color,
517 cur_light_params.sun_angle,
518 cur_light_params.moon_angle,
519 globals->get_ephem()->getNumPlanets(),
520 globals->get_ephem()->getPlanets(),
521 globals->get_ephem()->getNumStars(),
522 globals->get_ephem()->getStars() );
524 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
525 << view_pos[1] << " " << view_pos[2] << endl;
526 cout << " zero_elev = " << zero_elev[0] << " "
527 << zero_elev[1] << " " << zero_elev[2]
528 << " lon = " << cur_fdm_state->get_Longitude()
529 << " lat = " << cur_fdm_state->get_Latitude() << endl;
530 cout << " sun_rot = " << cur_light_params.sun_rotation
531 << " gst = " << SGTime::cur_time_params->getGst() << endl;
532 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
533 << " sun dec = " << globals->get_ephem()->getSunDeclination()
534 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
535 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
537 thesky->reposition( current__view->get_view_pos(),
538 current__view->get_zero_elev(),
539 current__view->get_world_up(),
540 longitude->getDoubleValue()
541 * SGD_DEGREES_TO_RADIANS,
542 latitude->getDoubleValue()
543 * SGD_DEGREES_TO_RADIANS,
544 altitude->getDoubleValue() * SG_FEET_TO_METER,
545 cur_light_params.sun_rotation,
546 globals->get_time_params()->getGst(),
547 globals->get_ephem()->getSunRightAscension(),
548 globals->get_ephem()->getSunDeclination(),
550 globals->get_ephem()->getMoonRightAscension(),
551 globals->get_ephem()->getMoonDeclination(),
555 glEnable( GL_DEPTH_TEST );
556 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
558 glFogi( GL_FOG_MODE, GL_EXP2 );
559 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
562 // set sun/lighting parameters
563 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
565 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
566 // we only update GL_AMBIENT for our lights we will never get
567 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
568 // explicitely to black.
569 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
570 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
571 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
573 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
574 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
575 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
577 // texture parameters
578 // glEnable( GL_TEXTURE_2D );
579 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
580 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
582 // glMatrixMode( GL_PROJECTION );
584 ssgSetFOV( current__view->get_h_fov(),
585 current__view->get_v_fov() );
588 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
589 - globals->get_scenery()->get_cur_elev();
592 scene_nearplane = 10.0f;
593 scene_farplane = 120000.0f;
595 scene_nearplane = groundlevel_nearplane->getDoubleValue();
596 scene_farplane = 120000.0f;
599 ssgSetNearFar( scene_nearplane, scene_farplane );
601 // $$$ begin - added VS Renganthan 17 Oct 2K
604 // $$$ end - added VS Renganthan 17 Oct 2K
606 # ifdef FG_NETWORK_OLK
607 if ( fgGetBool("/sim/networking/network-olk") ) {
609 other = head->next; /* put listpointer to start */
610 while ( other != tail) { /* display all except myself */
611 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
612 other->fgd_sel->select(1);
613 sgSetCoord( &fgdpos, other->sgFGD_COORD );
614 other->fgd_pos->setTransform( &fgdpos );
619 // fgd_sel->select(1);
620 // sgCopyMat4( sgTUX, current_view.sgVIEW);
622 // sgSetCoord( &fgdpos, sgFGD_VIEW );
623 // fgd_pos->setTransform( &fgdpos);
627 // position tile nodes and update range selectors
628 global_tile_mgr.prep_ssg_nodes(visibility_meters);
630 if ( fgGetBool("/sim/rendering/skyblend") ) {
631 // draw the sky backdrop
633 // we need a white diffuse light for the phase of the moon
634 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
638 // return to the desired diffuse color
639 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
642 // draw the ssg scene
643 glEnable( GL_DEPTH_TEST );
645 ssgSetNearFar( scene_nearplane, scene_farplane );
646 ssgCullAndDraw( globals->get_scene_graph() );
648 // change state for lighting here
651 // Set punch through fog density
652 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
654 #ifdef FG_EXPERIMENTAL_LIGHTING
655 // Enable states for drawing points with GL_extension
656 if (glutExtensionSupported("GL_EXT_point_parameters")) {
657 glEnable(GL_POINT_SMOOTH);
658 float quadratic[3] = {1.0, 0.01, 0.0001};
659 // get the address of our OpenGL extensions
661 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
662 wglGetProcAddress("glPointParameterfEXT");
663 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
664 wglGetProcAddress("glPointParameterfvEXT");
666 // makes the points fade as they move away
667 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
668 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
671 // Enable states for drawing runway lights with spherical mapping
672 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
673 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
674 glEnable(GL_TEXTURE_GEN_S);
675 glEnable(GL_TEXTURE_GEN_T);
677 //Maybe this is not the best way, but it works !!
678 glPolygonMode(GL_FRONT, GL_POINT);
680 glEnable(GL_CULL_FACE);
683 glDisable( GL_LIGHTING );
684 // blending function for runway lights
685 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
689 ssgSetNearFar( scene_nearplane, scene_farplane );
690 ssgCullAndDraw( lighting );
693 #ifdef FG_EXPERIMENTAL_LIGHTING
694 if (glutExtensionSupported("GL_EXT_point_parameters")) {
695 // Disable states used for runway lighting
696 glPolygonMode(GL_FRONT, GL_FILL);
698 glDisable(GL_TEXTURE_GEN_S);
699 glDisable(GL_TEXTURE_GEN_T);
700 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
701 default_attenuation);
707 if ( fgGetBool("/sim/rendering/skyblend") ) {
708 // draw the sky cloud layers
709 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
712 globals->get_model_mgr()->draw();
713 globals->get_aircraft_model()->draw();
715 // display HUD && Panel
717 glDisable( GL_DEPTH_TEST );
718 // glDisable( GL_CULL_FACE );
719 // glDisable( GL_TEXTURE_2D );
721 // update the input subsystem
722 current_input.update(delta_time_sec);
724 // update the controls subsystem
725 globals->get_controls()->update(delta_time_sec);
727 hud_and_panel->apply();
730 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
731 // This only works properly if called before the panel call
732 globals->get_ATC_display()->update(delta_time_sec);
734 // update the panel subsystem
735 if ( current_panel != NULL ) {
736 current_panel->update(delta_time_sec);
739 // We can do translucent menus, so why not. :-)
741 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
743 // glDisable ( GL_BLEND ) ;
745 // glEnable( GL_FOG );
747 globals->get_logger()->update(delta_time_sec);
754 // Update internal time dependent calculations (i.e. flight model)
755 // FIXME: this distinction is obsolete; all subsystems now get delta
757 void fgUpdateTimeDepCalcs() {
758 static bool inited = false;
760 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
762 fgLIGHT *l = &cur_light_params;
767 // Initialize the FDM here if it hasn't been and if we have a
768 // scenery elevation hit.
770 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
771 // << " cur_elev = " << scenery.get_cur_elev() << endl;
773 if ( !cur_fdm_state->get_inited() &&
774 globals->get_scenery()->get_cur_elev() > -9990 )
776 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
778 cur_fdm_state->init();
779 if ( cur_fdm_state->get_bound() ) {
780 cur_fdm_state->unbind();
782 cur_fdm_state->bind();
785 // conceptually, the following block could be done for each fdm
787 if ( !cur_fdm_state->get_inited() ) {
788 // do nothing, fdm isn't inited yet
790 // we have been inited, and we are good to go ...
796 globals->get_autopilot()->update(delta_time_sec);
797 cur_fdm_state->update(delta_time_sec);
798 FGSteam::update(delta_time_sec);
801 if ( !strcmp(fgGetString("/sim/view-mode"), "pilot") ) {
802 cur_view_fdm = *cur_fdm_state;
806 globals->get_model_mgr()->update(delta_time_sec);
807 globals->get_aircraft_model()->update(delta_time_sec);
809 // update the view angle
810 globals->get_viewmgr()->update(delta_time_sec);
814 // Update solar system
815 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
816 globals->get_time_params()->getLst(),
817 cur_fdm_state->get_Latitude() );
819 // Update radio stack model
820 current_radiostack->update(delta_time_sec);
824 void fgInitTimeDepCalcs( void ) {
829 static const double alt_adjust_ft = 3.758099;
830 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
833 // What should we do when we have nothing else to do? Let's get ready
834 // for the next move and update the display?
835 static void fgMainLoop( void ) {
837 // Update the elapsed time.
838 current_time_stamp.stamp();
839 delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
840 last_time_stamp = current_time_stamp;
841 globals->inc_sim_time_sec( delta_time_sec );
843 static const SGPropertyNode *longitude
844 = fgGetNode("/position/longitude-deg");
845 static const SGPropertyNode *latitude
846 = fgGetNode("/position/latitude-deg");
847 static const SGPropertyNode *altitude
848 = fgGetNode("/position/altitude-ft");
849 static const SGPropertyNode *clock_freeze
850 = fgGetNode("/sim/freeze/clock", true);
851 static const SGPropertyNode *cur_time_override
852 = fgGetNode("/sim/time/cur-time-override", true);
854 static long remainder = 0;
856 #ifdef FANCY_FRAME_COUNTER
860 static time_t last_time = 0;
861 static int frames = 0;
862 #endif // FANCY_FRAME_COUNTER
864 SGTime *t = globals->get_time_params();
866 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
867 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
869 #ifdef FG_NETWORK_OLK
870 if ( fgGetBool("/sim/networking/network-olk") ) {
871 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
872 // printf("FGD: Netupdate\n");
873 fgd_send_com( "A", FGFS_host); // Send Mat4 data
874 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
879 #if defined( ENABLE_PLIB_JOYSTICK )
880 // Read joystick and update control settings
881 // if ( fgGetString("/sim/control-mode") == "joystick" )
885 #elif defined( ENABLE_GLUT_JOYSTICK )
886 // Glut joystick support works by feeding a joystick handler
887 // function to glut. This is taken care of once in the joystick
888 // init routine and we don't have to worry about it again.
892 globals->get_environment_mgr()->update(delta_time_sec);
895 // Fix elevation. I'm just sticking this here for now, it should
896 // probably move eventually
898 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
899 scenery.get_cur_elev(),
900 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
901 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
903 if ( globals->get_scenery()->get_cur_elev() > -9990
904 && cur_fdm_state->get_inited() )
906 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
907 (globals->get_scenery()->get_cur_elev() + alt_adjust_m - 3.0) ) {
908 // now set aircraft altitude above ground
909 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
910 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
911 globals->get_scenery()->get_cur_elev() + alt_adjust_m - 3.0,
912 globals->get_scenery()->get_cur_elev() + alt_adjust_m );
913 cur_fdm_state->set_Altitude( globals->get_scenery()->get_cur_elev()
916 SG_LOG( SG_ALL, SG_DEBUG,
917 "<*> resetting altitude to "
918 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
923 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
924 scenery.get_cur_elev(),
925 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
926 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
928 // cout << "Warp = " << globals->get_warp() << endl;
931 static bool last_clock_freeze = false;
933 if ( clock_freeze->getBoolValue() ) {
934 // clock freeze requested
935 if ( cur_time_override->getLongValue() == 0 ) {
936 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
937 globals->set_warp( 0 );
940 // no clock freeze requested
941 if ( last_clock_freeze == true ) {
942 // clock just unfroze, let's set warp as the difference
943 // between frozen time and current time so we don't get a
944 // time jump (and corresponding sky object and lighting
946 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
947 fgSetLong( "/sim/time/cur-time-override", 0 );
949 if ( globals->get_warp_delta() != 0 ) {
950 globals->inc_warp( globals->get_warp_delta() );
954 last_clock_freeze = clock_freeze->getBoolValue();
956 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
957 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
958 cur_time_override->getLongValue(),
959 globals->get_warp() );
961 if ( globals->get_warp_delta() != 0 ) {
962 fgUpdateSkyAndLightingParams();
965 // update magvar model
966 globals->get_mag()->update( longitude->getDoubleValue()
967 * SGD_DEGREES_TO_RADIANS,
968 latitude->getDoubleValue()
969 * SGD_DEGREES_TO_RADIANS,
970 altitude->getDoubleValue() * SG_FEET_TO_METER,
971 globals->get_time_params()->getJD() );
973 // Get elapsed time (in usec) for this past frame
974 elapsed = fgGetTimeInterval();
975 SG_LOG( SG_ALL, SG_DEBUG,
976 "Elapsed time interval is = " << elapsed
977 << ", previous remainder is = " << remainder );
979 // Calculate frame rate average
980 #ifdef FANCY_FRAME_COUNTER
981 /* old fps calculation */
985 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
986 tmp = general.get_frame(i);
988 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
989 general.set_frame(i+1,tmp);
991 tmp = 1000000.0 / (float)elapsed;
992 general.set_frame(0,tmp);
993 // printf("frame[0] = %.2f\n", general.frames[0]);
995 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
996 // printf("ave = %.2f\n", general.frame_rate);
999 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1000 general.set_frame_rate( frames );
1001 SG_LOG( SG_ALL, SG_DEBUG,
1002 "--> Frame rate is = " << general.get_frame_rate() );
1005 last_time = t->get_cur_time();
1009 // Run ATC subsystem
1010 globals->get_ATC_mgr()->update(delta_time_sec);
1012 // Run the AI subsystem
1013 // globals->get_AI_mgr()->update(delta_time_sec);
1017 // Calculate model iterations needed for next frame
1018 elapsed += remainder;
1020 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1021 fgGetInt("/sim/model-hz"));
1022 remainder = elapsed - ( (global_multi_loop*1000000) /
1023 fgGetInt("/sim/model-hz") );
1024 SG_LOG( SG_ALL, SG_DEBUG,
1025 "Model iterations needed = " << global_multi_loop
1026 << ", new remainder = " << remainder );
1028 // chop max interations to something reasonable if the sim was
1029 // delayed for an excesive amount of time
1030 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1031 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1036 if ( global_multi_loop > 0 ) {
1037 fgUpdateTimeDepCalcs();
1039 SG_LOG( SG_ALL, SG_DEBUG,
1040 "Elapsed time is zero ... we're zinging" );
1043 #if ! defined( macintosh )
1044 // Do any I/O channel work that might need to be done
1048 // see if we need to load any deferred-load textures
1049 material_lib.load_next_deferred();
1051 // Run audio scheduler
1052 #ifdef ENABLE_AUDIO_SUPPORT
1053 if ( fgGetBool("/sim/sound/audible")
1054 && globals->get_soundmgr()->is_working() ) {
1055 globals->get_fx()->update(1); // FIXME: use dt
1056 globals->get_soundmgr()->update(1); // FIXME: use dt
1063 // see if we need to load any new scenery tiles
1064 double visibility_meters = fgGetDouble("/environment/visibility-m");
1065 global_tile_mgr.update( longitude->getDoubleValue(),
1066 latitude->getDoubleValue(), visibility_meters );
1068 SG_LOG( SG_ALL, SG_DEBUG, "" );
1072 // This is the top level master main function that is registered as
1073 // our idle funciton
1075 // The first few passes take care of initialization things (a couple
1076 // per pass) and once everything has been initialized fgMainLoop from
1079 static void fgIdleFunction ( void ) {
1080 // printf("idle state == %d\n", idle_state);
1082 if ( idle_state == 0 ) {
1083 // Initialize the splash screen right away
1084 if ( fgGetBool("/sim/startup/splash-screen") ) {
1089 } else if ( idle_state == 1 ) {
1090 // Initialize audio support
1091 #ifdef ENABLE_AUDIO_SUPPORT
1093 // Start the intro music
1094 if ( fgGetBool("/sim/startup/intro-music") ) {
1095 SGPath mp3file( globals->get_fg_root() );
1096 mp3file.append( "Sounds/intro.mp3" );
1098 SG_LOG( SG_GENERAL, SG_INFO,
1099 "Starting intro music: " << mp3file.str() );
1101 #if defined( __CYGWIN__ )
1102 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1103 #elif defined( WIN32 )
1104 string command = "start /m " + mp3file.str();
1106 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1109 system ( command.c_str() );
1112 // This is an 'easter egg' which is kind of a hard thing to
1113 // hide in an open source project -- so I won't try very hard
1114 // to hide it. If you are looking at this now, please, you
1115 // don't want to ruin the surprise. :-) Just forget about it
1116 // and don't look any further; unless it is causing an actual
1117 // problem for you, which it shouldn't, and I hope it doesn't!
1119 if ( globals->get_time_params()->getGmt()->tm_mon == 4
1120 && globals->get_time_params()->getGmt()->tm_mday == 19 )
1122 string url = "http://www.flightgear.org/Music/invasion.mp3";
1123 #if defined( __CYGWIN__ ) || defined( WIN32 )
1124 string command = "start /m " + url;
1126 string command = "mpg123 " + url + "> /dev/null 2>&1";
1128 system( command.c_str() );
1134 } else if ( idle_state == 2 ) {
1135 // These are a few miscellaneous things that aren't really
1136 // "subsystems" but still need to be initialized.
1139 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1140 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1145 } else if ( idle_state == 3 ) {
1146 // This is the top level init routine which calls all the
1147 // other subsystem initialization routines. If you are adding
1148 // a subsystem to flightgear, its initialization call should
1149 // located in this routine.
1150 if( !fgInitSubsystems()) {
1151 SG_LOG( SG_GENERAL, SG_ALERT,
1152 "Subsystem initializations failed ..." );
1157 } else if ( idle_state == 4 ) {
1158 // setup OpenGL view parameters
1162 } else if ( idle_state == 5 ) {
1165 } else if ( idle_state == 6 ) {
1169 cout << "Panel visible = " << fgPanelVisible() << endl;
1170 fgReshape( fgGetInt("/sim/startup/xsize"),
1171 fgGetInt("/sim/startup/ysize") );
1174 if ( idle_state == 1000 ) {
1175 // We've finished all our initialization steps, from now on we
1176 // run the main loop.
1178 glutIdleFunc(fgMainLoop);
1180 if ( fgGetBool("/sim/startup/splash-screen") ) {
1181 fgSplashUpdate(0.0);
1186 // options.cxx needs to see this for toggle_panel()
1187 // Handle new window size or exposure
1188 void fgReshape( int width, int height ) {
1191 if ( (!fgGetBool("/sim/virtual-cockpit"))
1192 && fgPanelVisible() && idle_state == 1000 ) {
1193 view_h = (int)(height * (current_panel->getViewHeight() -
1194 current_panel->getYOffset()) / 768.0);
1200 FGViewMgr *viewmgr = globals->get_viewmgr();
1201 for ( int i = 0; i < viewmgr->size(); ++i ) {
1202 viewmgr->get_view(i)->
1203 set_aspect_ratio((float)view_h / (float)width);
1206 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1208 fgSetInt("/sim/startup/xsize", width);
1209 fgSetInt("/sim/startup/ysize", height);
1210 guiInitMouse(width, height);
1212 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1213 viewmgr->get_current_view()->get_v_fov() );
1218 // Initialize GLUT and define a main window
1219 int fgGlutInit( int *argc, char **argv ) {
1221 #if !defined( macintosh )
1222 // GLUT will extract all glut specific options so later on we only
1223 // need wory about our own.
1224 glutInit(argc, argv);
1227 // Define Display Parameters
1228 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1230 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1231 fgGetInt("/sim/startup/xsize") << "x"
1232 << fgGetInt("/sim/startup/ysize") );
1234 // Define initial window size
1235 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1236 fgGetInt("/sim/startup/ysize") );
1238 // Initialize windows
1239 if ( !fgGetBool("/sim/startup/game-mode")) {
1240 // Open the regular window
1241 glutCreateWindow("FlightGear");
1242 #ifndef GLUT_WRONG_VERSION
1244 // Open the cool new 'game mode' window
1245 char game_mode_str[256];
1246 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1247 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1248 #ifndef ENUM_CURRENT_SETTINGS
1249 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1250 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1254 dm.dmSize = sizeof(DEVMODE);
1255 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1256 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1257 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1258 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1259 fgGetInt("/sim/startup/ysize") );
1260 sprintf( game_mode_str, "%dx%d:%d@%d",
1264 dm.dmDisplayFrequency );
1266 // Open the cool new 'game mode' window
1267 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1268 fgGetInt("/sim/startup/xsize"),
1269 fgGetInt("/sim/startup/ysize"),
1270 fgGetInt("/sim/rendering/bits-per-pixel"));
1272 #endif // HAVE_WINDOWS_H
1273 SG_LOG( SG_GENERAL, SG_INFO,
1274 "game mode params = " << game_mode_str );
1275 glutGameModeString( game_mode_str );
1276 glutEnterGameMode();
1277 #endif // GLUT_WRONG_VERSION
1280 // This seems to be the absolute earliest in the init sequence
1281 // that these calls will return valid info. Too bad it's after
1282 // we've already created and sized out window. :-(
1283 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1284 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1285 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1286 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1289 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1290 general.set_glMaxTexSize( tmp );
1291 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1293 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1294 general.set_glDepthBits( tmp );
1295 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1301 // Initialize GLUT event handlers
1302 int fgGlutInitEvents( void ) {
1303 // call fgReshape() on window resizes
1304 glutReshapeFunc( fgReshape );
1306 // keyboard and mouse callbacks are set in FGInput::init
1308 // call fgMainLoop() whenever there is
1309 // nothing else to do
1310 glutIdleFunc( fgIdleFunction );
1313 glutDisplayFunc( fgRenderFrame );
1320 int mainLoop( int argc, char **argv ) {
1322 #if defined( macintosh )
1323 freopen ("stdout.txt", "w", stdout );
1324 freopen ("stderr.txt", "w", stderr );
1325 argc = ccommand( &argv );
1328 // set default log levels
1329 sglog().setLogLevels( SG_ALL, SG_INFO );
1332 #ifdef FLIGHTGEAR_VERSION
1333 version = FLIGHTGEAR_VERSION;
1335 version = "unknown version";
1337 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1338 << version << endl );
1340 // Allocate global data structures. This needs to happen before
1341 // we parse command line options
1343 globals = new FGGlobals;
1345 #ifndef FG_WEATHERCM
1346 globals->set_environment_mgr(new FGEnvironmentMgr);
1349 // seed the random number generater
1352 SGRoute *route = new SGRoute;
1353 globals->set_route( route );
1355 FGControls *controls = new FGControls;
1356 globals->set_controls( controls );
1358 string_list *col = new string_list;
1359 globals->set_channel_options_list( col );
1361 // Scan the config file(s) and command line options to see if
1362 // fg_root was specified (ignore all other options for now)
1363 fgInitFGRoot(argc, argv);
1365 // Check for the correct base package version
1366 string base_version = fgBasePackageVersion();
1367 if ( !(base_version == "0.7.9") ) {
1368 // tell the operator how to use this application
1371 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1372 << "Found version " << base_version << " at: "
1373 << globals->get_fg_root() );
1374 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1378 // Initialize the Aircraft directory to "" (UIUC)
1381 // Load the configuration parameters
1382 if ( !fgInitConfig(argc, argv) ) {
1383 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1387 // Initialize the Window/Graphics environment.
1388 if( !fgGlutInit(&argc, argv) ) {
1389 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1393 // Initialize the various GLUT Event Handlers.
1394 if( !fgGlutInitEvents() ) {
1395 SG_LOG( SG_GENERAL, SG_ALERT,
1396 "GLUT event handler initialization failed ..." );
1400 // Initialize plib net interface
1401 netInit( &argc, argv );
1403 // Initialize ssg (from plib). Needs to come before we do any
1404 // other ssg stuff, but after opengl/glut has been initialized.
1407 // Initialize the user interface (we need to do this before
1408 // passing off control to glut and before fgInitGeneral to get our
1412 #ifdef GL_EXT_texture_lod_bias
1413 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1416 // Set position relative to glide slope if requested
1417 fgSetPosFromGlideSlope();
1419 // If we have an explicit, in-range lon/lat, use it.
1420 // If not, check for an airport-id and use that.
1421 // If not, default to the middle of the KSFO field.
1422 // The default values for lon/lat are deliberately out of range
1423 // so that the airport-id can take effect; valid lon/lat will
1424 // override airport-id, however.
1425 double lon_deg = fgGetDouble("/position/longitude-deg");
1426 double lat_deg = fgGetDouble("/position/latitude-deg");
1427 if (lon_deg < -180 || lon_deg > 180 || lat_deg < -90 || lat_deg > 90) {
1428 if ( fgGetString("/sim/startup/airport-id")[0] != '\0' ) {
1429 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1430 fgGetDouble("/orientation/heading-deg") );
1431 // set tower position (a little off the heading for single
1433 fgSetTowerPosFromAirportID( fgGetString("/sim/startup/airport-id"),
1434 fgGetDouble("orientation/heading") );
1436 // Default to middle of KSFO field
1437 fgSetDouble("/position/longitude-deg", -122.374843);
1438 fgSetDouble("/position/latitude-deg", 37.619002);
1442 SGTime *t = fgInitTime();
1443 globals->set_time_params( t );
1445 // Do some quick general initializations
1446 if( !fgInitGeneral()) {
1447 SG_LOG( SG_GENERAL, SG_ALERT,
1448 "General initializations failed ..." );
1452 SGPath modelpath( globals->get_fg_root() );
1453 ssgModelPath( (char *)modelpath.c_str() );
1456 globals->set_scene_graph(new ssgRoot);
1457 globals->get_scene_graph()->setName( "Scene" );
1459 lighting = new ssgRoot;
1460 lighting->setName( "Lighting" );
1463 globals->set_terrain_branch(new ssgBranch);
1464 globals->get_terrain_branch()->setName( "Terrain" );
1465 globals->get_scene_graph()->addKid( globals->get_terrain_branch() );
1467 globals->set_models_branch(new ssgBranch);
1468 globals->get_models_branch()->setName( "Models" );
1469 globals->get_scene_graph()->addKid( globals->get_models_branch() );
1471 globals->set_aircraft_branch(new ssgBranch);
1472 globals->get_aircraft_branch()->setName( "Aircraft" );
1473 globals->get_scene_graph()->addKid( globals->get_aircraft_branch() );
1476 globals->set_gnd_lights_branch(new ssgBranch);
1477 globals->get_gnd_lights_branch()->setName( "Ground Lighting" );
1478 lighting->addKid( globals->get_gnd_lights_branch() );
1480 globals->set_rwy_lights_branch(new ssgBranch);
1481 globals->get_rwy_lights_branch()->setName( "Runway Lighting" );
1482 lighting->addKid( globals->get_rwy_lights_branch() );
1484 ////////////////////////////////////////////////////////////////////
1485 // Initialize the general model subsystem.
1486 ////////////////////////////////////////////////////////////////////
1488 globals->set_model_mgr(new FGModelMgr);
1489 globals->get_model_mgr()->init();
1490 globals->get_model_mgr()->bind();
1492 ////////////////////////////////////////////////////////////////////
1493 // Initialize the 3D aircraft model subsystem.
1494 ////////////////////////////////////////////////////////////////////
1496 globals->set_aircraft_model(new FGAircraftModel);
1497 globals->get_aircraft_model()->init();
1498 globals->get_aircraft_model()->bind();
1500 ////////////////////////////////////////////////////////////////////
1501 // Initialize the view manager subsystem.
1502 ////////////////////////////////////////////////////////////////////
1504 FGViewMgr *viewmgr = new FGViewMgr;
1505 globals->set_viewmgr( viewmgr );
1510 // Initialize the sky
1511 SGPath ephem_data_path( globals->get_fg_root() );
1512 ephem_data_path.append( "Astro" );
1513 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1514 ephem->update( globals->get_time_params()->getMjd(),
1515 globals->get_time_params()->getLst(),
1517 globals->set_ephem( ephem );
1521 SGPath sky_tex_path( globals->get_fg_root() );
1522 sky_tex_path.append( "Textures" );
1523 sky_tex_path.append( "Sky" );
1524 thesky->texture_path( sky_tex_path.str() );
1526 thesky->build( 550.0, 550.0,
1527 globals->get_ephem()->getNumPlanets(),
1528 globals->get_ephem()->getPlanets(), 60000.0,
1529 globals->get_ephem()->getNumStars(),
1530 globals->get_ephem()->getStars(), 60000.0 );
1532 if ( fgGetBool("/environment/clouds/status") ) {
1533 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1534 // SG_CLOUD_OVERCAST );
1535 thesky->add_cloud_layer( fgGetDouble("/environment/clouds/altitude-ft") *
1537 200.0, 50.0, 40000.0,
1538 SG_CLOUD_MOSTLY_CLOUDY );
1539 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1540 // SG_CLOUD_MOSTLY_SUNNY );
1541 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1545 // Initialize MagVar model
1546 SGMagVar *magvar = new SGMagVar();
1547 globals->set_mag( magvar );
1549 // airport = new ssgBranch;
1550 // airport->setName( "Airport Lighting" );
1551 // lighting->addKid( airport );
1557 #ifdef FG_NETWORK_OLK
1558 // Do the network intialization
1559 if ( fgGetBool("/sim/networking/network-olk") ) {
1560 printf("Multipilot mode %s\n",
1561 fg_net_init( globals->get_scene_graph() ) );
1565 // build our custom render states
1566 fgBuildRenderStates();
1568 // pass control off to the master GLUT event handler
1571 // we never actually get here ... but to avoid compiler warnings,
1577 // $$$ end - added VS Renganathan, 15 Oct 2K
1578 // - added Venky , 12 Nov 2K
1580 #if defined(__linux__) && defined(__i386__)
1582 static void handleFPE (int);
1587 fpu_control_t fpe_flags = 0;
1588 _FPU_GETCW(fpe_flags);
1589 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1590 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1591 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1592 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1593 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1594 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1595 _FPU_SETCW(fpe_flags);
1596 signal(SIGFPE, handleFPE);
1603 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1607 // Main entry point; catch any exceptions that have made it this far.
1608 int main ( int argc, char **argv ) {
1610 // Enable floating-point exceptions for Linux/x86
1611 #if defined(__linux__) && defined(__i386__)
1615 // Enable floating-point exceptions for Windows
1616 #if defined( _MSC_VER ) && defined( DEBUG )
1617 // Christian, we should document what this does
1618 _control87( _EM_INEXACT, _MCW_EM );
1621 #if defined( HAVE_BC5PLUS )
1622 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1625 // FIXME: add other, more specific
1628 mainLoop(argc, argv);
1629 } catch (sg_throwable &t) {
1630 // We must use cerr rather than
1631 // logging, since logging may be
1633 cerr << "Fatal error: " << t.getFormattedMessage()
1634 << "\n (received from " << t.getOrigin() << ')' << endl;
1642 void fgLoadDCS(void) {
1644 ssgEntity *ship_obj = NULL;
1646 char obj_filename[25];
1648 for ( int k = 0; k < 32; k++ ) {
1652 SGPath tile_path( globals->get_fg_root());
1653 tile_path.append( "Scenery" );
1654 tile_path.append( "Objects.txt" );
1655 sg_gzifstream in( tile_path.str() );
1656 if ( ! in.is_open() ) {
1657 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1660 SGPath modelpath( globals->get_fg_root() );
1661 modelpath.append( "Models" );
1662 modelpath.append( "Geometry" );
1664 SGPath texturepath( globals->get_fg_root() );
1665 texturepath.append( "Models" );
1666 texturepath.append( "Textures" );
1668 ssgModelPath( (char *)modelpath.c_str() );
1669 ssgTexturePath( (char *)texturepath.c_str() );
1671 ship_sel = new ssgSelector;
1674 while ( ! in.eof() ) {
1676 if ( in.get( c ) && c == '#' ) {
1680 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1681 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1682 int chj=getchar();*/
1684 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1685 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1687 ship_pos[objc] = new ssgTransform;
1689 // type "repeat" in objects.txt to load one more
1690 // instance of the last object.
1692 if ( strcmp(obj_filename,"repeat") != 0) {
1693 ship_obj = ssgLoad( obj_filename );
1696 if ( ship_obj != NULL ) {
1697 ship_obj->setName(obj_filename);
1699 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1701 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1702 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1703 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1704 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1707 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1711 // temporary hack for deck lights - ultimately should move to PLib (when??)
1712 //const char *extn = file_extension ( obj_filename ) ;
1714 ssgVertexArray *lights = new ssgVertexArray( 100 );
1715 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1716 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1717 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1718 int ltype[500], light_type;
1719 static int ltcount = 0;
1721 sgVec3 rway_dir,rway_normal,lightpt;
1723 modelpath.append(obj_filename);
1724 sg_gzifstream in1( modelpath.str() );
1725 if ( ! in1.is_open() ) {
1726 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1728 while ( ! in1.eof() ) {
1730 if ( in1.get( c ) && c == '#' ) {
1735 //cout << token << endl;
1736 if ( token == "runway" ) {
1738 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1739 } else if ( token == "edgelight" ) {
1741 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1743 } else if ( token == "taxi" ) {
1745 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1747 } else if ( token == "vasi" ) {
1749 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1751 } else if ( token == "threshold" ) {
1753 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1755 } else if ( token == "rabbit" ) {
1757 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1759 } else if ( token == "ols" ) {
1761 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1763 } else if ( token == "red" ) {
1765 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1767 } else if ( token == "green" ) {
1769 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1771 } else if ( token == "lp" ) {
1773 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1774 lightpoints->add( lightpt );
1775 lightnormals->add( rway_normal );
1776 lightdir->add( rway_dir );
1777 ltype[ltcount]= light_type;
1780 if (in1.eof()) break;
1784 if ( lightpoints->getNum() ) {
1785 ssgBranch *lightpoints_branch;
1786 long int dummy = -999;
1787 dummy_tile = new FGTileEntry((SGBucket)dummy);
1788 dummy_tile->lightmaps_sequence = new ssgSelector;
1789 dummy_tile->ols_transform = new ssgTransform;
1791 // call function to generate the runway lights
1792 lightpoints_branch =
1793 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1795 lightpoints_brightness->addKid(lightpoints_branch);
1796 lightpoints_transform->addKid(lightpoints_brightness);
1797 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1798 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1799 lightpoints_transform->ref();
1800 globals->get_gnd_lights_branch()->addKid( lightpoints_transform );
1804 // end hack for deck lights
1808 if (in.eof()) break;
1812 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1814 globals->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node
1821 void fgUpdateDCS (void) {
1823 // double eye_lat,eye_lon,eye_alt;
1824 // static double obj_head;
1825 double sl_radius,obj_latgc;
1826 // float nresultmat[4][4];
1827 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1830 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1831 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1833 // Deck should be the first object in objects.txt in case of fdm=ada
1835 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
1836 if ((fdm->get_iaux(1))==1)
1838 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1839 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1840 obj_alt[1] = fdm->get_daux(3);
1841 obj_pitch[1] = fdm->get_faux(1);
1842 obj_roll[1] = fdm->get_faux(2);
1846 for ( int m = 0; m < objc; m++ ) {
1847 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1850 //Geodetic to Geocentric angles for rotation
1851 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1853 //moving object gbs-posn in cartesian coords
1854 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1855 Point3D obj_pos = sgGeodToCart( obj_posn );
1857 // Translate moving object w.r.t eye
1858 Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
1863 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1866 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1868 sgVec3 ship_fwd,ship_rt,ship_up;
1869 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1870 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1871 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1873 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1874 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1875 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1876 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1877 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1878 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
1881 sgCopyMat4( sgTUX, sgROT_hdg );
1882 sgPostMultMat4( sgTUX, sgROT_pitch );
1883 sgPostMultMat4( sgTUX, sgROT_roll );
1884 sgPostMultMat4( sgTUX, sgROT_lat );
1885 sgPostMultMat4( sgTUX, sgROT_lon );
1886 sgPostMultMat4( sgTUX, sgTRANS );
1889 sgSetCoord(&shippos, sgTUX );
1890 ship_pos[m]->setTransform( &shippos );
1891 // temporary hack for deck lights - ultimately should move to PLib (when ??)
1893 if (lightpoints_transform) {
1894 lightpoints_transform->setTransform( &shippos );
1895 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1896 if ( sun_angle > 89 ) {
1897 lightpoints_brightness->select(0x01);
1899 lightpoints_brightness->select(0x00);
1908 sgXformPnt3( rp, rway_ols, sgTUX );
1909 vp = globals->get_current_view()->get_view_pos();
1910 to[0] = rp[0]-vp[0];
1911 to[1] = rp[1]-vp[1];
1912 to[2] = rp[2]-vp[2];
1913 float dist = sgLengthVec3( to );
1914 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
1916 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
1918 ref_elev = elev - 3.75; // +ve above, -ve below
1922 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1923 // if (ref_elev > 0.51) sel = 0x21;
1924 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
1925 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
1926 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
1927 // if (ref_elev < -0.51) sel = 0x30;
1928 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1929 dummy_tile->lightmaps_sequence->select(sel);
1932 sgCopyVec3 (up, ship_up);
1934 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
1936 sgScaleVec3 (up, 4.0*ref_elev);
1937 dummy_tile->ols_transform->setTransform(up);
1938 //cout << "ref_elev " << ref_elev << endl;
1940 // end hack for deck lights
1943 if ( ship_sel != NULL ) {
1944 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
1948 // $$$ end - added VS Renganathan, 15 Oct 2K
1949 // added Venky , 12 Nov 2K