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>
39 #include <simgear/misc/exception.hxx>
40 #include <simgear/ephemeris/ephemeris.hxx>
41 #include <simgear/route/route.hxx>
42 #include <simgear/screen/extensions.hxx>
44 #include <Environment/environment_mgr.hxx>
46 #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>
78 #include <simgear/constants.h> // for VERSION
79 #include <simgear/debug/logstream.hxx>
80 #include <simgear/math/polar3d.hxx>
81 #include <simgear/math/sg_random.h>
82 #include <simgear/misc/sg_path.hxx>
83 #include <simgear/scene/material/matlib.hxx>
84 #include <simgear/scene/model/animation.hxx>
85 #include <simgear/scene/model/location.hxx>
86 #include <simgear/scene/model/model.hxx>
87 #include <simgear/scene/model/modellib.hxx>
88 #ifdef FG_USE_CLOUDS_3D
89 # include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
90 # include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
92 #include <simgear/scene/sky/sky.hxx>
93 #include <simgear/timing/sg_time.hxx>
95 #include <Include/general.hxx>
97 #include <Aircraft/aircraft.hxx>
99 #include <ATC/ATCmgr.hxx>
100 #include <ATC/ATCdisplay.hxx>
101 #include <ATC/AIMgr.hxx>
103 #include <Autopilot/newauto.hxx>
105 #include <Cockpit/hud.hxx>
106 #include <Cockpit/cockpit.hxx>
107 #include <Cockpit/radiostack.hxx>
109 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
111 #include <Model/acmodel.hxx>
112 #include <Model/modelmgr.hxx>
113 #include <Model/panelnode.hxx>
114 #ifdef FG_NETWORK_OLK
115 #include <NetworkOLK/network.h>
119 #include <MultiPlayer/multiplaytxmgr.hxx>
120 #include <MultiPlayer/multiplayrxmgr.hxx>
123 #include <Scenery/scenery.hxx>
124 #include <Scenery/tilemgr.hxx>
125 #ifdef ENABLE_AUDIO_SUPPORT
126 # include <Sound/fg_fx.hxx>
127 # include <Sound/morse.hxx>
129 #include <Systems/system_mgr.hxx>
130 #include <Instrumentation/instrument_mgr.hxx>
131 #include <Time/FGEventMgr.hxx>
132 #include <Time/fg_timer.hxx>
133 #include <Time/light.hxx>
134 #include <Time/sunpos.hxx>
135 #include <Time/tmp.hxx>
138 #include <simgear/misc/sgstream.hxx>
139 #include <simgear/math/point3d.hxx>
140 #include <FDM/flight.hxx>
141 #include <FDM/ADA.hxx>
142 #include <Scenery/tileentry.hxx>
144 #include "fg_commands.hxx"
147 typedef void (APIENTRY * PFNGLPOINTPARAMETERFEXTPROC)(GLenum pname,
149 typedef void (APIENTRY * PFNGLPOINTPARAMETERFVEXTPROC)(GLenum pname,
150 const GLfloat *params);
152 PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
153 PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
157 typedef void (* OpenGLFuncExt)(GLenum pname, GLfloat param);
158 typedef void (* OpenGLFuncExtv)(GLenum pname, const GLfloat *params);
160 OpenGLFuncExt glPointParameterfEXT = 0;
161 OpenGLFuncExtv glPointParameterfvEXT = 0;
164 float default_attenuation[3] = {1.0, 0.0, 0.0};
165 //Required for using GL_extensions
166 void fgLoadDCS (void);
167 void fgUpdateDCS (void);
168 ssgSelector *ship_sel=NULL;
169 // upto 32 instances of a same object can be loaded.
170 ssgTransform *ship_pos[32];
171 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
173 ssgSelector *lightpoints_brightness = new ssgSelector;
174 ssgTransform *lightpoints_transform = new ssgTransform;
175 FGTileEntry *dummy_tile;
178 // Clip plane settings...
179 float scene_nearplane = 0.5f;
180 float scene_farplane = 120000.0f;
182 static double delta_time_sec = 0;
186 # include <WeatherCM/FGLocalWeatherDatabase.h>
191 #include "fg_init.hxx"
193 #include "fg_props.hxx"
194 #include "globals.hxx"
195 #include "splash.hxx"
196 #include "viewmgr.hxx"
197 #include "options.hxx"
198 #include "logger.hxx"
201 # include <console.h> // -dw- for command line dialog
205 FGEventMgr global_events;
207 // This is a record containing a bit of global housekeeping information
210 // Specify our current idle function state. This is used to run all
211 // our initializations out of the glutIdleLoop() so that we can get a
212 // splash screen up and running right away.
213 static int idle_state = 0;
214 static long global_multi_loop;
216 // fog constants. I'm a little nervous about putting actual code out
217 // here but it seems to work (?)
218 static const double m_log01 = -log( 0.01 );
219 static const double sqrt_m_log01 = sqrt( m_log01 );
220 static GLfloat fog_exp_density;
221 static GLfloat fog_exp2_density;
222 static GLfloat rwy_exp2_punch_through;
223 static GLfloat taxi_exp2_punch_through;
224 static GLfloat ground_exp2_punch_through;
226 #ifdef FG_NETWORK_OLK
227 ssgSelector *fgd_sel = NULL;
228 ssgTransform *fgd_pos = NULL;
234 #ifdef FG_USE_CLOUDS_3D
235 SkySceneLoader *sgClouds3d;
236 bool _bcloud_orig = true;
240 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
242 { 1.0f, 0.0f, 0.0f, 0.0f },
243 { 0.0f, 0.0f, -1.0f, 0.0f },
244 { 0.0f, 1.0f, 0.0f, 0.0f },
245 { 0.0f, 0.0f, 0.0f, 1.0f }
248 // The following defines flightgear options. Because glutlib will also
249 // want to parse its own options, those options must not be included here
250 // or they will get parsed by the main program option parser. Hence case
251 // is significant for any option added that might be in conflict with
254 // glutlib parses for:
256 // -direct (invalid in Win32)
260 // -indirect (invalid in Win32)
263 // Note that glutlib depends upon strings while this program's
264 // option parser wants only initial characters followed by numbers
269 ssgSimpleState *cloud3d_imposter_state;
270 ssgSimpleState *default_state;
271 ssgSimpleState *hud_and_panel;
272 ssgSimpleState *menus;
274 SGTimeStamp last_time_stamp;
275 SGTimeStamp current_time_stamp;
278 void fgBuildRenderStates( void ) {
279 default_state = new ssgSimpleState;
280 default_state->ref();
281 default_state->disable( GL_TEXTURE_2D );
282 default_state->enable( GL_CULL_FACE );
283 default_state->enable( GL_COLOR_MATERIAL );
284 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
285 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
286 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
287 default_state->disable( GL_BLEND );
288 default_state->disable( GL_ALPHA_TEST );
289 default_state->disable( GL_LIGHTING );
291 cloud3d_imposter_state = new ssgSimpleState;
292 cloud3d_imposter_state->ref();
293 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
294 cloud3d_imposter_state->enable( GL_CULL_FACE );
295 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
296 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
297 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
298 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
299 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
300 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
301 cloud3d_imposter_state->enable( GL_BLEND );
302 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
303 cloud3d_imposter_state->disable( GL_LIGHTING );
305 hud_and_panel = new ssgSimpleState;
306 hud_and_panel->ref();
307 hud_and_panel->disable( GL_CULL_FACE );
308 hud_and_panel->disable( GL_TEXTURE_2D );
309 hud_and_panel->disable( GL_LIGHTING );
310 hud_and_panel->enable( GL_BLEND );
312 menus = new ssgSimpleState;
314 menus->disable( GL_CULL_FACE );
315 menus->disable( GL_TEXTURE_2D );
316 menus->enable( GL_BLEND );
320 // fgInitVisuals() -- Initialize various GL/view parameters
321 void fgInitVisuals( void ) {
324 l = &cur_light_params;
326 #ifndef GLUT_WRONG_VERSION
327 // Go full screen if requested ...
328 if ( fgGetBool("/sim/startup/fullscreen") ) {
333 // If enabled, normal vectors specified with glNormal are scaled
334 // to unit length after transformation. Enabling this has
335 // performance implications. See the docs for glNormal.
336 // glEnable( GL_NORMALIZE );
338 glEnable( GL_LIGHTING );
339 glEnable( GL_LIGHT0 );
340 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
343 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
344 ssgGetLight( 0 ) -> setPosition( sunpos );
346 glFogi (GL_FOG_MODE, GL_EXP2);
347 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
348 (!fgGetBool("/sim/rendering/shading"))) {
349 // if fastest fog requested, or if flat shading force fastest
350 glHint ( GL_FOG_HINT, GL_FASTEST );
351 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
352 glHint ( GL_FOG_HINT, GL_NICEST );
354 if ( fgGetBool("/sim/rendering/wireframe") ) {
356 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
359 // This is the default anyways, but it can't hurt
360 glFrontFace ( GL_CCW );
363 // glEnable(GL_POINT_SMOOTH);
364 // glEnable(GL_LINE_SMOOTH);
365 // glEnable(GL_POLYGON_SMOOTH);
369 // For HiRes screen Dumps using Brian Pauls TR Library
370 void trRenderFrame( void ) {
372 if ( fgPanelVisible() ) {
373 GLfloat height = fgGetInt("/sim/startup/ysize");
375 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
376 * (height / 768.0) + 1;
377 glTranslatef( 0.0, view_h, 0.0 );
380 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
381 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
383 fgLIGHT *l = &cur_light_params;
385 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
386 l->adj_fog_color[2], l->adj_fog_color[3]);
388 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
390 // set the opengl state to known default values
391 default_state->force();
394 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
395 glFogi ( GL_FOG_MODE, GL_EXP2 );
396 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
398 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
399 // we only update GL_AMBIENT for our lights we will never get
400 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
401 // explicitely to black.
402 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
403 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
405 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
407 // texture parameters
408 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
409 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
411 // we need a white diffuse light for the phase of the moon
412 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
415 // draw the ssg scene
416 // return to the desired diffuse color
417 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
418 glEnable( GL_DEPTH_TEST );
419 ssgSetNearFar( scene_nearplane, scene_farplane );
420 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
423 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
424 ssgSetNearFar( scene_nearplane, scene_farplane );
425 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
427 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
429 if (fgGetBool("/environment/clouds/status"))
430 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
432 globals->get_model_mgr()->draw();
433 globals->get_aircraft_model()->draw();
437 // Update all Visuals (redraws anything graphics related)
438 void fgRenderFrame() {
440 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
441 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
443 // Process/manage pending events
444 global_events.update( delta_time_sec );
446 // static const SGPropertyNode *longitude
447 // = fgGetNode("/position/longitude-deg");
448 // static const SGPropertyNode *latitude
449 // = fgGetNode("/position/latitude-deg");
450 // static const SGPropertyNode *altitude
451 // = fgGetNode("/position/altitude-ft");
452 static const SGPropertyNode *groundlevel_nearplane
453 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
455 // Update the default (kludged) properties.
458 FGViewer *current__view = globals->get_current_view();
460 fgLIGHT *l = &cur_light_params;
461 static double last_visibility = -9999;
464 double actual_visibility;
465 if (fgGetBool("/environment/clouds/status"))
466 actual_visibility = thesky->get_visibility();
468 actual_visibility = fgGetDouble("/environment/visibility-m");
469 if ( actual_visibility != last_visibility ) {
470 last_visibility = actual_visibility;
472 fog_exp_density = m_log01 / actual_visibility;
473 fog_exp2_density = sqrt_m_log01 / actual_visibility;
474 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
475 if ( actual_visibility < 8000 ) {
476 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
477 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
479 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
480 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
485 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
486 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
487 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
488 // GLfloat mat_shininess[] = { 10.0 };
489 GLbitfield clear_mask;
491 if ( idle_state != 1000 ) {
492 // still initializing, draw the splash screen
493 if ( fgGetBool("/sim/startup/splash-screen") ) {
494 fgSplashUpdate(0.0, 1.0);
496 // Keep resetting sim time while the sim is initializing
497 globals->set_sim_time_sec( 0.0 );
498 SGAnimation::set_sim_time_sec( 0.0 );
500 // idle_state is now 1000 meaning we've finished all our
501 // initializations and are running the main loop, so this will
502 // now work without seg faulting the system.
504 // calculate our current position in cartesian space
505 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
508 fgReshape( fgGetInt("/sim/startup/xsize"),
509 fgGetInt("/sim/startup/ysize") );
511 if ( fgGetBool("/sim/rendering/clouds3d") ) {
512 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
513 cloud3d_imposter_state->force();
515 glColor4f( 1.0, 1.0, 1.0, 1.0 );
516 glEnable(GL_DEPTH_TEST);
518 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
520 #ifdef FG_USE_CLOUDS_3D
521 if ( _bcloud_orig ) {
522 Point3D c = globals->get_scenery()->get_center();
523 sgClouds3d->Set_Cloud_Orig( &c );
524 _bcloud_orig = false;
526 sgClouds3d->Update( current__view->get_absolute_view_pos() );
528 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
529 glDisable(GL_DEPTH_TEST);
532 clear_mask = GL_DEPTH_BUFFER_BIT;
533 if ( fgGetBool("/sim/rendering/wireframe") ) {
534 clear_mask |= GL_COLOR_BUFFER_BIT;
537 if ( fgGetBool("/sim/rendering/skyblend") ) {
538 if ( fgGetBool("/sim/rendering/textures") ) {
539 // glClearColor(black[0], black[1], black[2], black[3]);
540 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
541 l->adj_fog_color[2], l->adj_fog_color[3]);
542 clear_mask |= GL_COLOR_BUFFER_BIT;
545 glClearColor(l->sky_color[0], l->sky_color[1],
546 l->sky_color[2], l->sky_color[3]);
547 clear_mask |= GL_COLOR_BUFFER_BIT;
549 glClear( clear_mask );
551 // Tell GL we are switching to model view parameters
553 // I really should create a derived ssg node or use a call
554 // back or something so that I can draw the sky within the
555 // ssgCullAndDraw() function, but for now I just mimic what
556 // ssg does to set up the model view matrix
557 glMatrixMode(GL_MODELVIEW);
559 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
561 // set the opengl state to known default values
562 default_state->force();
564 // update fog params if visibility has changed
565 double visibility_meters = fgGetDouble("/environment/visibility-m");
566 thesky->set_visibility(visibility_meters);
568 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
569 ( global_multi_loop * fgGetInt("/sim/speed-up") )
570 / (double)fgGetInt("/sim/model-hz") );
572 // Set correct opengl fog density
573 glFogf (GL_FOG_DENSITY, fog_exp2_density);
575 // update the sky dome
576 if ( fgGetBool("/sim/rendering/skyblend") ) {
578 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
579 << cur_light_params.sky_color[0] << " "
580 << cur_light_params.sky_color[1] << " "
581 << cur_light_params.sky_color[2] << " "
582 << cur_light_params.sky_color[3] );
583 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
584 << cur_light_params.fog_color[0] << " "
585 << cur_light_params.fog_color[1] << " "
586 << cur_light_params.fog_color[2] << " "
587 << cur_light_params.fog_color[3] );
588 SG_LOG( SG_GENERAL, SG_BULK,
589 " sun_angle = " << cur_light_params.sun_angle
590 << " moon_angle = " << cur_light_params.moon_angle );
592 thesky->repaint( cur_light_params.sky_color,
593 cur_light_params.adj_fog_color,
594 cur_light_params.cloud_color,
595 cur_light_params.sun_angle,
596 cur_light_params.moon_angle,
597 globals->get_ephem()->getNumPlanets(),
598 globals->get_ephem()->getPlanets(),
599 globals->get_ephem()->getNumStars(),
600 globals->get_ephem()->getStars() );
603 SG_LOG( SG_GENERAL, SG_BULK,
604 "thesky->reposition( view_pos = " << view_pos[0] << " "
605 << view_pos[1] << " " << view_pos[2] );
606 SG_LOG( SG_GENERAL, SG_BULK,
607 " zero_elev = " << zero_elev[0] << " "
608 << zero_elev[1] << " " << zero_elev[2]
609 << " lon = " << cur_fdm_state->get_Longitude()
610 << " lat = " << cur_fdm_state->get_Latitude() );
611 SG_LOG( SG_GENERAL, SG_BULK,
612 " sun_rot = " << cur_light_params.sun_rotation
613 << " gst = " << SGTime::cur_time_params->getGst() );
614 SG_LOG( SG_GENERAL, SG_BULK,
615 " sun ra = " << globals->get_ephem()->getSunRightAscension()
616 << " sun dec = " << globals->get_ephem()->getSunDeclination()
617 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
618 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
621 // The sun and moon distances are scaled down versions
622 // of the actual distance to get both the moon and the sun
623 // within the range of the far clip plane.
624 // Moon distance: 384,467 kilometers
625 // Sun distance: 150,000,000 kilometers
626 double sun_horiz_eff, moon_horiz_eff;
627 if (fgGetBool("/sim/rendering/horizon-effect")) {
628 sun_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.sun_angle*2)/2,0.33)/3;
629 moon_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.moon_angle*2)/2,0.33)/3;
631 sun_horiz_eff = moon_horiz_eff = 1.0;
633 thesky->reposition( current__view->get_view_pos(),
634 current__view->get_zero_elev(),
635 current__view->get_world_up(),
636 current__view->getLongitude_deg()
637 * SGD_DEGREES_TO_RADIANS,
638 current__view->getLatitude_deg()
639 * SGD_DEGREES_TO_RADIANS,
640 current__view->getAltitudeASL_ft()
642 cur_light_params.sun_rotation,
643 globals->get_time_params()->getGst(),
644 globals->get_ephem()->getSunRightAscension(),
645 globals->get_ephem()->getSunDeclination(),
646 50000.0 * sun_horiz_eff,
647 globals->get_ephem()->getMoonRightAscension(),
648 globals->get_ephem()->getMoonDeclination(),
649 40000.0 * moon_horiz_eff );
652 glEnable( GL_DEPTH_TEST );
653 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
655 glFogi( GL_FOG_MODE, GL_EXP2 );
656 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
659 // set sun/lighting parameters
660 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
662 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
663 // we only update GL_AMBIENT for our lights we will never get
664 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
665 // explicitely to black.
666 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
668 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
669 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
670 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular );
672 // texture parameters
673 // glEnable( GL_TEXTURE_2D );
674 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
675 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
677 // glMatrixMode( GL_PROJECTION );
679 ssgSetFOV( current__view->get_h_fov(),
680 current__view->get_v_fov() );
683 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
684 - globals->get_scenery()->get_cur_elev();
687 scene_nearplane = 10.0f;
688 scene_farplane = 120000.0f;
690 scene_nearplane = groundlevel_nearplane->getDoubleValue();
691 scene_farplane = 120000.0f;
694 ssgSetNearFar( scene_nearplane, scene_farplane );
696 // $$$ begin - added VS Renganthan 17 Oct 2K
699 // $$$ end - added VS Renganthan 17 Oct 2K
701 # ifdef FG_NETWORK_OLK
702 if ( fgGetBool("/sim/networking/network-olk") ) {
704 other = head->next; /* put listpointer to start */
705 while ( other != tail) { /* display all except myself */
706 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
707 other->fgd_sel->select(1);
708 sgSetCoord( &fgdpos, other->sgFGD_COORD );
709 other->fgd_pos->setTransform( &fgdpos );
714 // fgd_sel->select(1);
715 // sgCopyMat4( sgTUX, current_view.sgVIEW);
717 // sgSetCoord( &fgdpos, sgFGD_VIEW );
718 // fgd_pos->setTransform( &fgdpos);
723 // Update any multiplayer models
724 globals->get_multiplayer_rx_mgr()->Update();
727 if ( fgGetBool("/sim/rendering/skyblend") &&
728 fgGetBool("/sim/rendering/draw-otw") )
730 // draw the sky backdrop
732 // we need a white diffuse light for the phase of the moon
733 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
737 // return to the desired diffuse color
738 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
741 // draw the ssg scene
742 glEnable( GL_DEPTH_TEST );
744 ssgSetNearFar( scene_nearplane, scene_farplane );
746 if ( fgGetBool("/sim/rendering/wireframe") ) {
748 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
750 if ( fgGetBool("/sim/rendering/draw-otw") ) {
751 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
754 // This is a bit kludgy. Every 200 frames, do an extra
755 // traversal of the scene graph without drawing anything, but
756 // with the field-of-view set to 360x360 degrees. This
757 // ensures that out-of-range random objects that are not in
758 // the current view frustum will still be freed properly.
759 static int counter = 0;
761 if (counter == 200) {
764 // No need to put the near plane too close;
765 // this way, at least the aircraft can be
767 f.setNearFar(1000, 1000000);
769 ssgGetModelviewMatrix(m);
770 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
774 // change state for lighting here
776 // draw runway lighting
777 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
778 ssgSetNearFar( scene_nearplane, scene_farplane );
780 if (fgGetBool("/sim/rendering/enhanced-lighting")) {
782 // Enable states for drawing points with GL_extension
783 glEnable(GL_POINT_SMOOTH);
785 if ( fgGetBool("/sim/rendering/distance-attenuation")
786 && glutExtensionSupported("GL_EXT_point_parameters") )
788 // Enable states for drawing points with GL_extension
789 glEnable(GL_POINT_SMOOTH);
791 float quadratic[3] = {1.0, 0.001, 0.0000001};
792 // makes the points fade as they move away
793 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
794 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
799 // blending function for runway lights
800 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
803 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
804 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
805 glEnable(GL_TEXTURE_GEN_S);
806 glEnable(GL_TEXTURE_GEN_T);
807 glPolygonMode(GL_FRONT, GL_POINT);
809 // draw runway lighting
810 if ( fgGetBool("/sim/rendering/draw-otw") ) {
811 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
814 // change punch through and then draw taxi lighting
815 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
817 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
818 // glFogfv ( GL_FOG_COLOR, taxi_fog );
819 if ( fgGetBool("/sim/rendering/draw-otw") ) {
820 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
824 glPolygonMode(GL_FRONT, GL_FILL);
825 glDisable(GL_TEXTURE_GEN_S);
826 glDisable(GL_TEXTURE_GEN_T);
828 //static int _frame_count = 0;
829 //if (_frame_count % 30 == 0) {
830 // printf("SSG: %s\n", ssgShowStats());
838 if (fgGetBool("/sim/rendering/enhanced-lighting")) {
839 if ( fgGetBool("/sim/rendering/distance-attenuation")
840 && glutExtensionSupported("GL_EXT_point_parameters") )
842 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
843 default_attenuation);
847 glDisable(GL_POINT_SMOOTH);
850 // draw ground lighting
851 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
852 if ( fgGetBool("/sim/rendering/draw-otw") ) {
853 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
856 if ( fgGetBool("/sim/rendering/skyblend") ) {
857 // draw the sky cloud layers
858 if ( fgGetBool("/environment/clouds/status") &&
859 fgGetBool("/sim/rendering/draw-otw") )
861 thesky->postDraw( cur_fdm_state->get_Altitude()
862 * SG_FEET_TO_METER );
866 if ( fgGetBool("/sim/rendering/clouds3d") &&
867 fgGetBool("/sim/rendering/draw-otw") )
870 glDisable( GL_LIGHTING );
871 // cout << "drawing new clouds" << endl;
873 glEnable(GL_DEPTH_TEST);
875 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
878 glEnable( GL_TEXTURE_2D );
879 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
880 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
881 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
882 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
885 #ifdef FG_USE_CLOUDS_3D
886 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
889 glEnable( GL_LIGHTING );
890 glEnable( GL_DEPTH_TEST );
891 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
894 if ( fgGetBool("/sim/rendering/draw-otw") ) {
895 globals->get_model_mgr()->draw();
896 globals->get_aircraft_model()->draw();
899 // display HUD && Panel
901 glDisable( GL_DEPTH_TEST );
902 // glDisable( GL_CULL_FACE );
903 // glDisable( GL_TEXTURE_2D );
905 // update the controls subsystem
906 globals->get_controls()->update(delta_time_sec);
908 hud_and_panel->apply();
911 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
912 // This only works properly if called before the panel call
913 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
914 globals->get_ATC_display()->update(delta_time_sec);
916 // update the panel subsystem
917 if ( globals->get_current_panel() != NULL ) {
918 globals->get_current_panel()->update(delta_time_sec);
922 // We can do translucent menus, so why not. :-)
924 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
926 // glDisable ( GL_BLEND ) ;
928 glEnable( GL_DEPTH_TEST );
931 // Fade out the splash screen over the first three seconds.
932 double t = globals->get_sim_time_sec();
934 fgSplashUpdate(0.0, 1.0);
935 } else if ( t <= 3.0) {
936 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
944 // Update internal time dependent calculations (i.e. flight model)
945 // FIXME: this distinction is obsolete; all subsystems now get delta
947 void fgUpdateTimeDepCalcs() {
948 static bool inited = false;
950 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
952 fgLIGHT *l = &cur_light_params;
954 // Initialize the FDM here if it hasn't been and if we have a
955 // scenery elevation hit.
957 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
958 // << " cur_elev = " << scenery.get_cur_elev() << endl;
960 if ( !cur_fdm_state->get_inited() &&
961 globals->get_scenery()->get_cur_elev() > -9990 )
963 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
964 cur_fdm_state->init();
965 if ( cur_fdm_state->get_bound() ) {
966 cur_fdm_state->unbind();
968 cur_fdm_state->bind();
971 // conceptually, the following block could be done for each fdm
973 if ( !cur_fdm_state->get_inited() ) {
974 // do nothing, fdm isn't inited yet
976 // we have been inited, and we are good to go ...
982 globals->get_autopilot()->update(delta_time_sec);
983 cur_fdm_state->update(delta_time_sec);
986 globals->get_model_mgr()->update(delta_time_sec);
987 globals->get_aircraft_model()->update(delta_time_sec);
989 // update the view angle
990 globals->get_viewmgr()->update(delta_time_sec);
994 // Update solar system
995 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
996 globals->get_time_params()->getLst(),
997 cur_fdm_state->get_Latitude() );
999 // Update radio stack model
1000 current_radiostack->update(delta_time_sec);
1004 void fgInitTimeDepCalcs( void ) {
1009 static const double alt_adjust_ft = 3.758099;
1010 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1013 // What should we do when we have nothing else to do? Let's get ready
1014 // for the next move and update the display?
1015 static void fgMainLoop( void ) {
1017 static const SGPropertyNode *longitude
1018 = fgGetNode("/position/longitude-deg");
1019 static const SGPropertyNode *latitude
1020 = fgGetNode("/position/latitude-deg");
1021 static const SGPropertyNode *altitude
1022 = fgGetNode("/position/altitude-ft");
1023 static const SGPropertyNode *clock_freeze
1024 = fgGetNode("/sim/freeze/clock", true);
1025 static const SGPropertyNode *cur_time_override
1026 = fgGetNode("/sim/time/cur-time-override", true);
1028 // Update the elapsed time.
1029 static bool first_time = true;
1031 last_time_stamp.stamp();
1035 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1036 if ( throttle_hz > 0.0 ) {
1037 // simple frame rate throttle
1038 double dt = 1000000.0 / throttle_hz;
1039 current_time_stamp.stamp();
1040 while ( current_time_stamp - last_time_stamp < dt ) {
1041 current_time_stamp.stamp();
1044 // run as fast as the app will go
1045 current_time_stamp.stamp();
1048 delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
1049 if ( clock_freeze->getBoolValue() ) {
1052 last_time_stamp = current_time_stamp;
1053 globals->inc_sim_time_sec( delta_time_sec );
1054 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1056 static long remainder = 0;
1058 #ifdef FANCY_FRAME_COUNTER
1062 static time_t last_time = 0;
1063 static int frames = 0;
1064 #endif // FANCY_FRAME_COUNTER
1066 SGTime *t = globals->get_time_params();
1068 sglog().setLogLevels( SG_ALL, (sgDebugPriority)fgGetInt("/sim/log-level") );
1069 sglog().setLogLevels( SG_ALL, SG_INFO );
1071 SGLocation * acmodel_location = 0;
1072 if(cur_fdm_state->getACModel() != 0) {
1073 acmodel_location = (SGLocation *) cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
1076 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1077 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1079 #ifdef FG_NETWORK_OLK
1080 if ( fgGetBool("/sim/networking/network-olk") ) {
1081 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
1082 // printf("FGD: Netupdate\n");
1083 fgd_send_com( "A", FGFS_host); // Send Mat4 data
1084 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
1089 #if defined( ENABLE_PLIB_JOYSTICK )
1090 // Read joystick and update control settings
1091 // if ( fgGetString("/sim/control-mode") == "joystick" )
1093 // fgJoystickRead();
1095 #elif defined( ENABLE_GLUT_JOYSTICK )
1096 // Glut joystick support works by feeding a joystick handler
1097 // function to glut. This is taken care of once in the joystick
1098 // init routine and we don't have to worry about it again.
1101 // Fix elevation. I'm just sticking this here for now, it should
1102 // probably move eventually
1104 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1105 scenery.get_cur_elev(),
1106 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1107 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1109 // Curt is this code used? I don't see any problems when I comment it out.
1110 if ( acmodel_location != 0 ) {
1111 if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
1112 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
1113 (acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0) ) {
1114 // now set aircraft altitude above ground
1115 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
1116 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1117 acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0,
1118 acmodel_location->get_cur_elev_m() + alt_adjust_m );
1119 cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m()
1120 + alt_adjust_m) * SG_METER_TO_FEET );
1121 SG_LOG( SG_ALL, SG_DEBUG,
1122 "<*> resetting altitude to "
1123 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1128 // End of code in question. (see Curt is this code used? above)
1130 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1131 scenery.get_cur_elev(),
1132 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1133 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1135 // cout << "Warp = " << globals->get_warp() << endl;
1138 static bool last_clock_freeze = false;
1140 if ( clock_freeze->getBoolValue() ) {
1141 // clock freeze requested
1142 if ( cur_time_override->getLongValue() == 0 ) {
1143 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1144 globals->set_warp( 0 );
1147 // no clock freeze requested
1148 if ( last_clock_freeze == true ) {
1149 // clock just unfroze, let's set warp as the difference
1150 // between frozen time and current time so we don't get a
1151 // time jump (and corresponding sky object and lighting
1153 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1154 fgSetLong( "/sim/time/cur-time-override", 0 );
1156 if ( globals->get_warp_delta() != 0 ) {
1157 globals->inc_warp( globals->get_warp_delta() );
1161 last_clock_freeze = clock_freeze->getBoolValue();
1163 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1164 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1165 cur_time_override->getLongValue(),
1166 globals->get_warp() );
1168 if ( globals->get_warp_delta() != 0 ) {
1169 fgUpdateSkyAndLightingParams();
1172 // update magvar model
1173 globals->get_mag()->update( longitude->getDoubleValue()
1174 * SGD_DEGREES_TO_RADIANS,
1175 latitude->getDoubleValue()
1176 * SGD_DEGREES_TO_RADIANS,
1177 altitude->getDoubleValue() * SG_FEET_TO_METER,
1178 globals->get_time_params()->getJD() );
1180 // Get elapsed time (in usec) for this past frame
1181 elapsed = fgGetTimeInterval();
1182 SG_LOG( SG_ALL, SG_DEBUG,
1183 "Elapsed time interval is = " << elapsed
1184 << ", previous remainder is = " << remainder );
1186 // Calculate frame rate average
1187 #ifdef FANCY_FRAME_COUNTER
1188 /* old fps calculation */
1189 if ( elapsed > 0 ) {
1192 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1193 tmp = general.get_frame(i);
1195 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1196 general.set_frame(i+1,tmp);
1198 tmp = 1000000.0 / (float)elapsed;
1199 general.set_frame(0,tmp);
1200 // printf("frame[0] = %.2f\n", general.frames[0]);
1202 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1203 // printf("ave = %.2f\n", general.frame_rate);
1206 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1207 general.set_frame_rate( frames );
1208 fgSetInt("/sim/frame-rate", frames);
1209 SG_LOG( SG_ALL, SG_DEBUG,
1210 "--> Frame rate is = " << general.get_frame_rate() );
1213 last_time = t->get_cur_time();
1217 // Run ATC subsystem
1218 if (fgGetBool("/sim/ATC/enabled"))
1219 globals->get_ATC_mgr()->update(delta_time_sec);
1221 // Run the AI subsystem
1222 if (fgGetBool("/sim/ai-traffic/enabled"))
1223 globals->get_AI_mgr()->update(delta_time_sec);
1227 // Calculate model iterations needed for next frame
1228 elapsed += remainder;
1230 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1231 fgGetInt("/sim/model-hz"));
1232 remainder = elapsed - ( (global_multi_loop*1000000) /
1233 fgGetInt("/sim/model-hz") );
1234 SG_LOG( SG_ALL, SG_DEBUG,
1235 "Model iterations needed = " << global_multi_loop
1236 << ", new remainder = " << remainder );
1238 // chop max interations to something reasonable if the sim was
1239 // delayed for an excesive amount of time
1240 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1241 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1246 if ( global_multi_loop > 0 ) {
1247 fgUpdateTimeDepCalcs();
1249 SG_LOG( SG_ALL, SG_DEBUG,
1250 "Elapsed time is zero ... we're zinging" );
1253 // Do any I/O channel work that might need to be done
1254 globals->get_io()->update( delta_time_sec );
1256 // see if we need to load any deferred-load textures
1257 globals->get_matlib()->load_next_deferred();
1259 // Run audio scheduler
1260 #ifdef ENABLE_AUDIO_SUPPORT
1261 if ( fgGetBool("/sim/sound/audible")
1262 && globals->get_soundmgr()->is_working() ) {
1263 globals->get_soundmgr()->update( delta_time_sec );
1267 globals->get_subsystem_mgr()->update(delta_time_sec);
1270 // Tile Manager updates - see if we need to load any new scenery tiles.
1271 // this code ties together the fdm, viewer and scenery classes...
1272 // we may want to move this to it's own class at some point
1274 double visibility_meters = fgGetDouble("/environment/visibility-m");
1275 FGViewer *current_view = globals->get_current_view();
1277 // update tile manager for FDM...
1278 // ...only if location is different than the viewer (to avoid duplicating effort)
1279 if( acmodel_location != current_view->getSGLocation() ) {
1280 if( acmodel_location != 0 ) {
1281 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1282 visibility_meters );
1283 globals->get_tile_mgr()->
1284 update( acmodel_location, visibility_meters,
1285 acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1286 // save results of update in SGLocation for fdm...
1287 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1289 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1292 set_tile_center( globals->get_scenery()->get_next_center() );
1296 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1297 visibility_meters );
1298 // update tile manager for view...
1299 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1300 // after the FDM's until all of Flight Gear code references the viewer's location
1301 // for elevation instead of the "scenery's" current elevation.
1302 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1303 globals->get_tile_mgr()->update( view_location, visibility_meters,
1304 current_view->get_absolute_view_pos() );
1305 // save results of update in SGLocation for fdm...
1306 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1307 current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1309 current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1311 // If fdm location is same as viewer's then we didn't do the update for fdm location
1312 // above so we need to save the viewer results in the fdm SGLocation as well...
1313 if( acmodel_location == current_view->getSGLocation() ) {
1314 if( acmodel_location != 0 ) {
1315 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1316 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1318 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1322 // END Tile Manager udpates
1327 SG_LOG( SG_ALL, SG_DEBUG, "" );
1331 // This is the top level master main function that is registered as
1332 // our idle funciton
1334 // The first few passes take care of initialization things (a couple
1335 // per pass) and once everything has been initialized fgMainLoop from
1338 static void fgIdleFunction ( void ) {
1339 // printf("idle state == %d\n", idle_state);
1341 if ( idle_state == 0 ) {
1342 // Initialize the splash screen right away
1343 if ( fgGetBool("/sim/startup/splash-screen") ) {
1348 } else if ( idle_state == 1 ) {
1349 // Initialize audio support
1350 #ifdef ENABLE_AUDIO_SUPPORT
1352 // Start the intro music
1353 if ( fgGetBool("/sim/startup/intro-music") ) {
1354 SGPath mp3file( globals->get_fg_root() );
1355 mp3file.append( "Sounds/intro.mp3" );
1357 SG_LOG( SG_GENERAL, SG_INFO,
1358 "Starting intro music: " << mp3file.str() );
1360 #if defined( __CYGWIN__ )
1361 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1362 #elif defined( WIN32 )
1363 string command = "start /m " + mp3file.str();
1365 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1368 system ( command.c_str() );
1373 } else if ( idle_state == 2 ) {
1374 // These are a few miscellaneous things that aren't really
1375 // "subsystems" but still need to be initialized.
1378 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1379 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1384 } else if ( idle_state == 3 ) {
1385 // This is the top level init routine which calls all the
1386 // other subsystem initialization routines. If you are adding
1387 // a subsystem to flightgear, its initialization call should
1388 // located in this routine.
1389 if( !fgInitSubsystems()) {
1390 SG_LOG( SG_GENERAL, SG_ALERT,
1391 "Subsystem initializations failed ..." );
1396 } else if ( idle_state == 4 ) {
1397 // setup OpenGL view parameters
1400 // Read the list of available aircrafts
1404 } else if ( idle_state == 5 ) {
1407 } else if ( idle_state == 6 ) {
1411 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1412 fgReshape( fgGetInt("/sim/startup/xsize"),
1413 fgGetInt("/sim/startup/ysize") );
1416 if ( idle_state == 1000 ) {
1417 // We've finished all our initialization steps, from now on we
1418 // run the main loop.
1420 glutIdleFunc(fgMainLoop);
1422 if ( fgGetBool("/sim/startup/splash-screen") ) {
1423 fgSplashUpdate(0.0, 1.0);
1428 // options.cxx needs to see this for toggle_panel()
1429 // Handle new window size or exposure
1430 void fgReshape( int width, int height ) {
1433 if ( (!fgGetBool("/sim/virtual-cockpit"))
1434 && fgPanelVisible() && idle_state == 1000 ) {
1435 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1436 globals->get_current_panel()->getYOffset()) / 768.0);
1442 FGViewMgr *viewmgr = globals->get_viewmgr();
1443 for ( int i = 0; i < viewmgr->size(); ++i ) {
1444 viewmgr->get_view(i)->
1445 set_aspect_ratio((float)view_h / (float)width);
1448 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1450 fgSetInt("/sim/startup/xsize", width);
1451 fgSetInt("/sim/startup/ysize", height);
1452 guiInitMouse(width, height);
1454 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1455 viewmgr->get_current_view()->get_v_fov() );
1459 #ifdef FG_USE_CLOUDS_3D
1460 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1461 viewmgr->get_current_view()->get_v_fov() );
1466 // Initialize GLUT and define a main window
1467 static bool fgGlutInit( int *argc, char **argv ) {
1469 #if !defined( macintosh )
1470 // GLUT will extract all glut specific options so later on we only
1471 // need wory about our own.
1472 glutInit(argc, argv);
1475 // Define Display Parameters. Clouds3d works best with --bpp32 option
1476 if ( fgGetBool("/sim/rendering/clouds3d") ) {
1477 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1479 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1482 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1483 fgGetInt("/sim/startup/xsize") << "x"
1484 << fgGetInt("/sim/startup/ysize") );
1486 // Define initial window size
1487 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1488 fgGetInt("/sim/startup/ysize") );
1490 // Initialize windows
1491 if ( !fgGetBool("/sim/startup/game-mode")) {
1492 // Open the regular window
1493 glutCreateWindow("FlightGear");
1494 #ifndef GLUT_WRONG_VERSION
1496 // Open the cool new 'game mode' window
1497 char game_mode_str[256];
1498 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1499 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1500 #ifndef ENUM_CURRENT_SETTINGS
1501 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1502 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1506 dm.dmSize = sizeof(DEVMODE);
1507 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1508 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1509 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1510 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1511 fgGetInt("/sim/startup/ysize") );
1512 sprintf( game_mode_str, "%dx%d:%d@%d",
1516 dm.dmDisplayFrequency );
1518 // Open the cool new 'game mode' window
1519 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1520 fgGetInt("/sim/startup/xsize"),
1521 fgGetInt("/sim/startup/ysize"),
1522 fgGetInt("/sim/rendering/bits-per-pixel"));
1524 #endif // HAVE_WINDOWS_H
1525 SG_LOG( SG_GENERAL, SG_INFO,
1526 "game mode params = " << game_mode_str );
1527 glutGameModeString( game_mode_str );
1528 glutEnterGameMode();
1529 #endif // GLUT_WRONG_VERSION
1532 // This seems to be the absolute earliest in the init sequence
1533 // that these calls will return valid info. Too bad it's after
1534 // we've already created and sized out window. :-(
1535 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1536 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1537 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1538 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1541 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1542 general.set_glMaxTexSize( tmp );
1543 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1545 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1546 general.set_glDepthBits( tmp );
1547 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1553 // Initialize GLUT event handlers
1554 static bool fgGlutInitEvents( void ) {
1555 // call fgReshape() on window resizes
1556 glutReshapeFunc( fgReshape );
1558 // keyboard and mouse callbacks are set in FGInput::init
1560 // call fgMainLoop() whenever there is
1561 // nothing else to do
1562 glutIdleFunc( fgIdleFunction );
1565 glutDisplayFunc( fgRenderFrame );
1570 // Main top level initialization
1571 static bool fgMainInit( int argc, char **argv ) {
1573 #if defined( macintosh )
1574 freopen ("stdout.txt", "w", stdout );
1575 freopen ("stderr.txt", "w", stderr );
1576 argc = ccommand( &argv );
1579 // set default log levels
1580 sglog().setLogLevels( SG_ALL, SG_INFO );
1583 #ifdef FLIGHTGEAR_VERSION
1584 version = FLIGHTGEAR_VERSION;
1586 version = "unknown version";
1588 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1590 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1592 // Allocate global data structures. This needs to happen before
1593 // we parse command line options
1595 globals = new FGGlobals;
1597 // seed the random number generater
1600 SGRoute *route = new SGRoute;
1601 globals->set_route( route );
1603 FGControls *controls = new FGControls;
1604 globals->set_controls( controls );
1606 string_list *col = new string_list;
1607 globals->set_channel_options_list( col );
1609 // Scan the config file(s) and command line options to see if
1610 // fg_root was specified (ignore all other options for now)
1611 fgInitFGRoot(argc, argv);
1613 // Check for the correct base package version
1614 static char required_version[] = "0.9.2";
1615 string base_version = fgBasePackageVersion();
1616 if ( !(base_version == required_version) ) {
1617 // tell the operator how to use this application
1619 cerr << endl << "Base package check failed ... " \
1620 << "Found version " << base_version << " at: " \
1621 << globals->get_fg_root() << endl;
1622 cerr << "Please upgrade to version: " << required_version << endl;
1626 // Initialize the Aircraft directory to "" (UIUC)
1629 // Load the configuration parameters. (Command line options
1630 // overrides config file options. Config file options override
1632 if ( !fgInitConfig(argc, argv) ) {
1633 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1637 // Initialize the Window/Graphics environment.
1638 if( !fgGlutInit(&argc, argv) ) {
1639 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1643 // Initialize the various GLUT Event Handlers.
1644 if( !fgGlutInitEvents() ) {
1645 SG_LOG( SG_GENERAL, SG_ALERT,
1646 "GLUT event handler initialization failed ..." );
1650 // Initialize plib net interface
1651 netInit( &argc, argv );
1653 // Initialize ssg (from plib). Needs to come before we do any
1654 // other ssg stuff, but after opengl/glut has been initialized.
1657 // Initialize the user interface (we need to do this before
1658 // passing off control to glut and before fgInitGeneral to get our
1662 // Read the list of available aircrafts
1665 #ifdef GL_EXT_texture_lod_bias
1666 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1669 // get the address of our OpenGL extensions
1670 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1673 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
1674 SGLookupFunction("glPointParameterfEXT");
1675 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
1676 SGLookupFunction("glPointParameterfvEXT");
1678 glPointParameterfEXT = (OpenGLFuncExt)
1679 SGLookupFunction("glPointParameterfEXT");
1680 glPointParameterfvEXT = (OpenGLFuncExtv)
1681 SGLookupFunction("glPointParameterfvEXT");
1685 // based on the requested presets, calculate the true starting
1690 SGTime *t = fgInitTime();
1691 globals->set_time_params( t );
1693 // Do some quick general initializations
1694 if( !fgInitGeneral()) {
1695 SG_LOG( SG_GENERAL, SG_ALERT,
1696 "General initializations failed ..." );
1700 SGPath modelpath( globals->get_fg_root() );
1701 ssgModelPath( (char *)modelpath.c_str() );
1703 ////////////////////////////////////////////////////////////////////
1704 // Initialize the property-based built-in commands
1705 ////////////////////////////////////////////////////////////////////
1708 ////////////////////////////////////////////////////////////////////
1709 // Initialize the material manager
1710 ////////////////////////////////////////////////////////////////////
1711 globals->set_matlib( new SGMaterialLib );
1713 globals->set_model_lib(new SGModelLib);
1715 ////////////////////////////////////////////////////////////////////
1716 // Initialize the TG scenery subsystem.
1717 ////////////////////////////////////////////////////////////////////
1718 globals->set_scenery( new FGScenery );
1719 globals->get_scenery()->init();
1720 globals->get_scenery()->bind();
1721 globals->set_tile_mgr( new FGTileMgr );
1723 ////////////////////////////////////////////////////////////////////
1724 // Initialize the general model subsystem.
1725 ////////////////////////////////////////////////////////////////////
1726 globals->set_model_mgr(new FGModelMgr);
1727 globals->get_model_mgr()->init();
1728 globals->get_model_mgr()->bind();
1730 ////////////////////////////////////////////////////////////////////
1731 // Initialize the 3D aircraft model subsystem (has a dependency on
1732 // the scenery subsystem.)
1733 ////////////////////////////////////////////////////////////////////
1734 globals->set_aircraft_model(new FGAircraftModel);
1735 globals->get_aircraft_model()->init();
1736 globals->get_aircraft_model()->bind();
1738 ////////////////////////////////////////////////////////////////////
1739 // Initialize the view manager subsystem.
1740 ////////////////////////////////////////////////////////////////////
1742 FGViewMgr *viewmgr = new FGViewMgr;
1743 globals->set_viewmgr( viewmgr );
1748 // Initialize the sky
1749 SGPath ephem_data_path( globals->get_fg_root() );
1750 ephem_data_path.append( "Astro" );
1751 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1752 ephem->update( globals->get_time_params()->getMjd(),
1753 globals->get_time_params()->getLst(),
1755 globals->set_ephem( ephem );
1757 // TODO: move to environment mgr
1759 SGPath texture_path(globals->get_fg_root());
1760 texture_path.append("Textures");
1761 texture_path.append("Sky");
1762 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1763 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1764 thesky->add_cloud_layer(layer);
1768 SGPath sky_tex_path( globals->get_fg_root() );
1769 sky_tex_path.append( "Textures" );
1770 sky_tex_path.append( "Sky" );
1771 thesky->texture_path( sky_tex_path.str() );
1773 // The sun and moon diameters are scaled down numbers of the
1774 // actual diameters. This was needed to fit bot the sun and the
1775 // moon within the distance to the far clip plane.
1776 // Moon diameter: 3,476 kilometers
1777 // Sun diameter: 1,390,000 kilometers
1778 thesky->build( 80000.0, 80000.0,
1780 globals->get_ephem()->getNumPlanets(),
1781 globals->get_ephem()->getPlanets(),
1782 globals->get_ephem()->getNumStars(),
1783 globals->get_ephem()->getStars() );
1785 // Initialize MagVar model
1786 SGMagVar *magvar = new SGMagVar();
1787 globals->set_mag( magvar );
1789 // airport = new ssgBranch;
1790 // airport->setName( "Airport Lighting" );
1791 // lighting->addKid( airport );
1797 #ifdef FG_NETWORK_OLK
1798 // Do the network intialization
1799 if ( fgGetBool("/sim/networking/network-olk") ) {
1800 printf("Multipilot mode %s\n",
1801 fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1805 // build our custom render states
1806 fgBuildRenderStates();
1808 // pass control off to the master GLUT event handler
1811 // we never actually get here ... but to avoid compiler warnings,
1817 // $$$ end - added VS Renganathan, 15 Oct 2K
1818 // - added Venky , 12 Nov 2K
1820 #if defined(__linux__) && defined(__i386__)
1822 static void handleFPE (int);
1827 fpu_control_t fpe_flags = 0;
1828 _FPU_GETCW(fpe_flags);
1829 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1830 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1831 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1832 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1833 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1834 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1835 _FPU_SETCW(fpe_flags);
1836 signal(SIGFPE, handleFPE);
1843 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1856 short CPSGetCurrentProcess(PSN *psn);
1857 short CPSSetProcessName (PSN *psn, char *processname);
1858 short CPSEnableForegroundOperation(PSN *psn, int _arg2, int _arg3, int _arg4, int _arg5);
1859 short CPSSetFrontProcess(PSN *psn);
1862 #define CPSEnableFG(psn) CPSEnableForegroundOperation(psn,0x03,0x3C,0x2C,0x1103)
1866 // Main entry point; catch any exceptions that have made it this far.
1867 int main ( int argc, char **argv ) {
1869 // Enable floating-point exceptions for Linux/x86
1870 #if defined(__linux__) && defined(__i386__)
1874 // Enable floating-point exceptions for Windows
1875 #if defined( _MSC_VER ) && defined( DEBUG )
1876 // Christian, we should document what this does
1877 _control87( _EM_INEXACT, _MCW_EM );
1880 #if defined( HAVE_BC5PLUS )
1881 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1884 // Keyboard focus hack
1889 glutInit (&argc, argv);
1891 CPSGetCurrentProcess(&psn);
1892 CPSSetProcessName(&psn, "FlightGear");
1894 CPSSetFrontProcess(&psn);
1898 // FIXME: add other, more specific
1901 fgMainInit(argc, argv);
1902 } catch (sg_throwable &t) {
1903 // We must use cerr rather than
1904 // logging, since logging may be
1906 cerr << "Fatal error: " << t.getFormattedMessage()
1907 << "\n (received from " << t.getOrigin() << ')' << endl;
1915 void fgLoadDCS(void) {
1917 ssgEntity *ship_obj = NULL;
1919 char obj_filename[25];
1921 for ( int k = 0; k < 32; k++ ) {
1925 SGPath tile_path( globals->get_fg_root());
1926 tile_path.append( "Scenery" );
1927 tile_path.append( "Objects.txt" );
1928 sg_gzifstream in( tile_path.str() );
1929 if ( ! in.is_open() ) {
1930 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1933 SGPath modelpath( globals->get_fg_root() );
1934 modelpath.append( "Models" );
1935 modelpath.append( "Geometry" );
1937 SGPath texturepath( globals->get_fg_root() );
1938 texturepath.append( "Models" );
1939 texturepath.append( "Textures" );
1941 ssgModelPath( (char *)modelpath.c_str() );
1942 ssgTexturePath( (char *)texturepath.c_str() );
1944 ship_sel = new ssgSelector;
1947 while ( ! in.eof() ) {
1949 if ( in.get( c ) && c == '#' ) {
1953 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1954 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1955 int chj=getchar();*/
1957 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1958 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1960 ship_pos[objc] = new ssgTransform;
1962 // type "repeat" in objects.txt to load one more
1963 // instance of the last object.
1965 if ( strcmp(obj_filename,"repeat") != 0) {
1967 globals->get_model_lib()->load_model( globals->get_fg_root(), obj_filename, globals->get_props(), globals->get_sim_time_sec() );
1970 if ( ship_obj != NULL ) {
1971 ship_obj->setName(obj_filename);
1973 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1975 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1976 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1977 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1978 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1981 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1985 // temporary hack for deck lights - ultimately should move to PLib (when??)
1986 //const char *extn = file_extension ( obj_filename ) ;
1988 // ssgVertexArray *lights = new ssgVertexArray( 100 );
1989 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1990 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1991 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1992 int ltype[500], light_type = 0;
1993 static int ltcount = 0;
1995 sgVec3 rway_dir,rway_normal,lightpt;
1997 modelpath.append(obj_filename);
1998 sg_gzifstream in1( modelpath.str() );
1999 if ( ! in1.is_open() ) {
2000 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
2002 while ( ! in1.eof() ) {
2004 if ( in1.get( c ) && c == '#' ) {
2009 //cout << token << endl;
2010 if ( token == "runway" ) {
2012 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
2013 } else if ( token == "edgelight" ) {
2015 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2017 } else if ( token == "taxi" ) {
2019 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2021 } else if ( token == "vasi" ) {
2023 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2025 } else if ( token == "threshold" ) {
2027 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2029 } else if ( token == "rabbit" ) {
2031 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2033 } else if ( token == "ols" ) {
2035 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
2037 } else if ( token == "red" ) {
2039 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2041 } else if ( token == "green" ) {
2043 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2045 } else if ( token == "lp" ) {
2047 sgSetVec3 (lightpt, node[0], node[1], node[2] );
2048 lightpoints->add( lightpt );
2049 lightnormals->add( rway_normal );
2050 lightdir->add( rway_dir );
2051 ltype[ltcount]= light_type;
2054 if (in1.eof()) break;
2059 if ( lightpoints->getNum() ) {
2060 ssgBranch *lightpoints_branch;
2061 long int dummy = -999;
2062 dummy_tile = new FGTileEntry((SGBucket)dummy);
2063 dummy_tile->lightmaps_sequence = new ssgSelector;
2064 dummy_tile->ols_transform = new ssgTransform;
2066 // call function to generate the runway lights
2067 lightpoints_branch =
2068 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
2070 lightpoints_brightness->addKid(lightpoints_branch);
2071 lightpoints_transform->addKid(lightpoints_brightness);
2072 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
2073 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
2074 lightpoints_transform->ref();
2075 globals->get_scenery()->get_gnd_lights_root()->addKid( lightpoints_transform );
2080 // end hack for deck lights
2084 if (in.eof()) break;
2088 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
2090 globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node
2097 void fgUpdateDCS (void) {
2099 // double eye_lat,eye_lon,eye_alt;
2100 // static double obj_head;
2101 double sl_radius,obj_latgc;
2102 // float nresultmat[4][4];
2103 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
2106 // Instantaneous Geodetic Lat/Lon/Alt of moving object
2107 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
2109 // Deck should be the first object in objects.txt in case of fdm=ada
2111 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
2112 if ((fdm->get_iaux(1))==1)
2114 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
2115 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
2116 obj_alt[1] = fdm->get_daux(3);
2117 obj_pitch[1] = fdm->get_faux(1);
2118 obj_roll[1] = fdm->get_faux(2);
2122 for ( int m = 0; m < objc; m++ ) {
2123 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
2126 //Geodetic to Geocentric angles for rotation
2127 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
2129 //moving object gbs-posn in cartesian coords
2130 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
2131 Point3D obj_pos = sgGeodToCart( obj_posn );
2133 // Translate moving object w.r.t eye
2134 Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
2139 // rotate dynamic objects for lat,lon & alt and other motion about its axes
2142 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
2144 sgVec3 ship_fwd,ship_rt,ship_up;
2145 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
2146 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
2147 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
2149 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
2150 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
2151 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
2152 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
2153 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
2154 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2157 sgCopyMat4( sgTUX, sgROT_hdg );
2158 sgPostMultMat4( sgTUX, sgROT_pitch );
2159 sgPostMultMat4( sgTUX, sgROT_roll );
2160 sgPostMultMat4( sgTUX, sgROT_lat );
2161 sgPostMultMat4( sgTUX, sgROT_lon );
2162 sgPostMultMat4( sgTUX, sgTRANS );
2165 sgSetCoord(&shippos, sgTUX );
2166 ship_pos[m]->setTransform( &shippos );
2167 // temporary hack for deck lights - ultimately should move to PLib (when ??)
2169 if (lightpoints_transform) {
2170 lightpoints_transform->setTransform( &shippos );
2171 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2172 if ( sun_angle > 89 ) {
2173 lightpoints_brightness->select(0x01);
2175 lightpoints_brightness->select(0x00);
2184 sgXformPnt3( rp, rway_ols, sgTUX );
2185 vp = globals->get_current_view()->get_view_pos();
2186 to[0] = rp[0]-vp[0];
2187 to[1] = rp[1]-vp[1];
2188 to[2] = rp[2]-vp[2];
2189 float dist = sgLengthVec3( to );
2190 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2192 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2194 ref_elev = elev - 3.75; // +ve above, -ve below
2198 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2199 // if (ref_elev > 0.51) sel = 0x21;
2200 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2201 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2202 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2203 // if (ref_elev < -0.51) sel = 0x30;
2204 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2205 // dummy_tile->lightmaps_sequence->select(sel);
2208 sgCopyVec3 (up, ship_up);
2210 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2212 sgScaleVec3 (up, 4.0*ref_elev);
2213 // dummy_tile->ols_transform->setTransform(up);
2214 //cout << "ref_elev " << ref_elev << endl;
2216 // end hack for deck lights
2219 if ( ship_sel != NULL ) {
2220 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2224 // $$$ end - added VS Renganathan, 15 Oct 2K
2225 // added Venky , 12 Nov 2K