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>
43 #include <Environment/environment_mgr.hxx>
45 #ifdef SG_MATH_EXCEPTION_CLASH
57 #include <string.h> // for strcmp()
64 #ifdef HAVE_SYS_STAT_H
65 # include <sys/stat.h> // for stat()
69 # include <unistd.h> // for stat()
72 #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/scene/material/matlib.hxx>
83 #include <simgear/scene/model/animation.hxx>
84 #include <simgear/scene/model/location.hxx>
85 #include <simgear/scene/model/model.hxx>
86 #include <simgear/scene/model/modellib.hxx>
87 #ifdef FG_USE_CLOUDS_3D
88 # include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
89 # include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
91 #include <simgear/scene/sky/sky.hxx>
92 #include <simgear/timing/sg_time.hxx>
94 #include <Include/general.hxx>
96 #include <Aircraft/aircraft.hxx>
98 #include <ATC/ATCmgr.hxx>
99 #include <ATC/ATCdisplay.hxx>
100 #include <ATC/AIMgr.hxx>
102 #include <Autopilot/newauto.hxx>
104 #include <Cockpit/hud.hxx>
105 #include <Cockpit/cockpit.hxx>
106 #include <Cockpit/radiostack.hxx>
108 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
110 #include <Model/acmodel.hxx>
111 #include <Model/modelmgr.hxx>
112 #include <Model/panelnode.hxx>
113 #ifdef FG_NETWORK_OLK
114 #include <NetworkOLK/network.h>
118 #include <MultiPlayer/multiplaytxmgr.hxx>
119 #include <MultiPlayer/multiplayrxmgr.hxx>
122 #include <Scenery/scenery.hxx>
123 #include <Scenery/tilemgr.hxx>
124 #ifdef ENABLE_AUDIO_SUPPORT
125 # include <Sound/fg_fx.hxx>
126 # include <Sound/morse.hxx>
128 #include <Systems/system_mgr.hxx>
129 #include <Instrumentation/instrument_mgr.hxx>
130 #include <Time/FGEventMgr.hxx>
131 #include <Time/fg_timer.hxx>
132 #include <Time/light.hxx>
133 #include <Time/sunpos.hxx>
134 #include <Time/tmp.hxx>
137 #include <simgear/misc/sgstream.hxx>
138 #include <simgear/math/point3d.hxx>
139 #include <FDM/flight.hxx>
140 #include <FDM/ADA.hxx>
141 #include <Scenery/tileentry.hxx>
143 #include "fg_commands.hxx"
145 #ifdef FG_EXPERIMENTAL_POINT_LIGHTING
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;
165 float default_attenuation[3] = {1.0, 0.0, 0.0};
166 //Required for using GL_extensions
167 void fgLoadDCS (void);
168 void fgUpdateDCS (void);
169 ssgSelector *ship_sel=NULL;
170 // upto 32 instances of a same object can be loaded.
171 ssgTransform *ship_pos[32];
172 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
174 ssgSelector *lightpoints_brightness = new ssgSelector;
175 ssgTransform *lightpoints_transform = new ssgTransform;
176 FGTileEntry *dummy_tile;
179 // Clip plane settings...
180 float scene_nearplane = 0.5f;
181 float scene_farplane = 120000.0f;
183 static double delta_time_sec = 0;
187 # include <WeatherCM/FGLocalWeatherDatabase.h>
192 #include "fg_init.hxx"
194 #include "fg_props.hxx"
195 #include "globals.hxx"
196 #include "splash.hxx"
197 #include "viewmgr.hxx"
198 #include "options.hxx"
199 #include "logger.hxx"
202 # include <console.h> // -dw- for command line dialog
206 FGEventMgr global_events;
208 // This is a record containing a bit of global housekeeping information
211 // Specify our current idle function state. This is used to run all
212 // our initializations out of the glutIdleLoop() so that we can get a
213 // splash screen up and running right away.
214 static int idle_state = 0;
215 static long global_multi_loop;
217 // fog constants. I'm a little nervous about putting actual code out
218 // here but it seems to work (?)
219 static const double m_log01 = -log( 0.01 );
220 static const double sqrt_m_log01 = sqrt( m_log01 );
221 static GLfloat fog_exp_density;
222 static GLfloat fog_exp2_density;
223 static GLfloat rwy_exp2_punch_through;
224 static GLfloat taxi_exp2_punch_through;
225 static GLfloat ground_exp2_punch_through;
227 #ifdef FG_NETWORK_OLK
228 ssgSelector *fgd_sel = NULL;
229 ssgTransform *fgd_pos = NULL;
235 #ifdef FG_USE_CLOUDS_3D
236 SkySceneLoader *sgClouds3d;
237 bool _bcloud_orig = true;
241 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
243 { 1.0f, 0.0f, 0.0f, 0.0f },
244 { 0.0f, 0.0f, -1.0f, 0.0f },
245 { 0.0f, 1.0f, 0.0f, 0.0f },
246 { 0.0f, 0.0f, 0.0f, 1.0f }
249 // The following defines flightgear options. Because glutlib will also
250 // want to parse its own options, those options must not be included here
251 // or they will get parsed by the main program option parser. Hence case
252 // is significant for any option added that might be in conflict with
255 // glutlib parses for:
257 // -direct (invalid in Win32)
261 // -indirect (invalid in Win32)
264 // Note that glutlib depends upon strings while this program's
265 // option parser wants only initial characters followed by numbers
270 ssgSimpleState *cloud3d_imposter_state;
271 ssgSimpleState *default_state;
272 ssgSimpleState *hud_and_panel;
273 ssgSimpleState *menus;
275 SGTimeStamp last_time_stamp;
276 SGTimeStamp current_time_stamp;
279 void fgBuildRenderStates( void ) {
280 default_state = new ssgSimpleState;
281 default_state->ref();
282 default_state->disable( GL_TEXTURE_2D );
283 default_state->enable( GL_CULL_FACE );
284 default_state->enable( GL_COLOR_MATERIAL );
285 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
286 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
287 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
288 default_state->disable( GL_BLEND );
289 default_state->disable( GL_ALPHA_TEST );
290 default_state->disable( GL_LIGHTING );
292 cloud3d_imposter_state = new ssgSimpleState;
293 cloud3d_imposter_state->ref();
294 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
295 cloud3d_imposter_state->enable( GL_CULL_FACE );
296 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
297 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
298 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
299 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
300 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
301 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
302 cloud3d_imposter_state->enable( GL_BLEND );
303 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
304 cloud3d_imposter_state->disable( GL_LIGHTING );
306 hud_and_panel = new ssgSimpleState;
307 hud_and_panel->ref();
308 hud_and_panel->disable( GL_CULL_FACE );
309 hud_and_panel->disable( GL_TEXTURE_2D );
310 hud_and_panel->disable( GL_LIGHTING );
311 hud_and_panel->enable( GL_BLEND );
313 menus = new ssgSimpleState;
315 menus->disable( GL_CULL_FACE );
316 menus->disable( GL_TEXTURE_2D );
317 menus->enable( GL_BLEND );
321 // fgInitVisuals() -- Initialize various GL/view parameters
322 void fgInitVisuals( void ) {
325 l = &cur_light_params;
327 #ifndef GLUT_WRONG_VERSION
328 // Go full screen if requested ...
329 if ( fgGetBool("/sim/startup/fullscreen") ) {
334 // If enabled, normal vectors specified with glNormal are scaled
335 // to unit length after transformation. Enabling this has
336 // performance implications. See the docs for glNormal.
337 // glEnable( GL_NORMALIZE );
339 glEnable( GL_LIGHTING );
340 glEnable( GL_LIGHT0 );
341 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
344 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
345 ssgGetLight( 0 ) -> setPosition( sunpos );
347 glFogi (GL_FOG_MODE, GL_EXP2);
348 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
349 (!fgGetBool("/sim/rendering/shading"))) {
350 // if fastest fog requested, or if flat shading force fastest
351 glHint ( GL_FOG_HINT, GL_FASTEST );
352 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
353 glHint ( GL_FOG_HINT, GL_NICEST );
355 if ( fgGetBool("/sim/rendering/wireframe") ) {
357 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
360 // This is the default anyways, but it can't hurt
361 glFrontFace ( GL_CCW );
364 // glEnable(GL_POINT_SMOOTH);
365 // glEnable(GL_LINE_SMOOTH);
366 // glEnable(GL_POLYGON_SMOOTH);
370 // For HiRes screen Dumps using Brian Pauls TR Library
371 void trRenderFrame( void ) {
373 if ( fgPanelVisible() ) {
374 GLfloat height = fgGetInt("/sim/startup/ysize");
376 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
377 * (height / 768.0) + 1;
378 glTranslatef( 0.0, view_h, 0.0 );
381 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
382 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
384 fgLIGHT *l = &cur_light_params;
386 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
387 l->adj_fog_color[2], l->adj_fog_color[3]);
389 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
391 // set the opengl state to known default values
392 default_state->force();
395 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
396 glFogi ( GL_FOG_MODE, GL_EXP2 );
397 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
399 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
400 // we only update GL_AMBIENT for our lights we will never get
401 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
402 // explicitely to black.
403 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
404 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
406 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
408 // texture parameters
409 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
410 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
412 // we need a white diffuse light for the phase of the moon
413 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
416 // draw the ssg scene
417 // return to the desired diffuse color
418 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
419 glEnable( GL_DEPTH_TEST );
420 ssgSetNearFar( scene_nearplane, scene_farplane );
421 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
424 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
425 ssgSetNearFar( scene_nearplane, scene_farplane );
426 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
428 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
430 if (fgGetBool("/environment/clouds/status"))
431 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
433 globals->get_model_mgr()->draw();
434 globals->get_aircraft_model()->draw();
438 // Update all Visuals (redraws anything graphics related)
439 void fgRenderFrame() {
441 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
442 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
444 // Process/manage pending events
445 global_events.update( delta_time_sec );
447 // static const SGPropertyNode *longitude
448 // = fgGetNode("/position/longitude-deg");
449 // static const SGPropertyNode *latitude
450 // = fgGetNode("/position/latitude-deg");
451 // static const SGPropertyNode *altitude
452 // = fgGetNode("/position/altitude-ft");
453 static const SGPropertyNode *groundlevel_nearplane
454 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
456 // Update the default (kludged) properties.
459 FGViewer *current__view = globals->get_current_view();
461 fgLIGHT *l = &cur_light_params;
462 static double last_visibility = -9999;
465 double actual_visibility;
466 if (fgGetBool("/environment/clouds/status"))
467 actual_visibility = thesky->get_visibility();
469 actual_visibility = fgGetDouble("/environment/visibility-m");
470 if ( actual_visibility != last_visibility ) {
471 last_visibility = actual_visibility;
473 fog_exp_density = m_log01 / actual_visibility;
474 fog_exp2_density = sqrt_m_log01 / actual_visibility;
475 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
476 if ( actual_visibility < 8000 ) {
477 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
478 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
480 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
481 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
486 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
487 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
488 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
489 // GLfloat mat_shininess[] = { 10.0 };
490 GLbitfield clear_mask;
492 if ( idle_state != 1000 ) {
493 // still initializing, draw the splash screen
494 if ( fgGetBool("/sim/startup/splash-screen") ) {
495 fgSplashUpdate(0.0, 1.0);
497 // Keep resetting sim time while the sim is initializing
498 globals->set_sim_time_sec( 0.0 );
499 SGAnimation::set_sim_time_sec( 0.0 );
501 // idle_state is now 1000 meaning we've finished all our
502 // initializations and are running the main loop, so this will
503 // now work without seg faulting the system.
505 // calculate our current position in cartesian space
506 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
509 fgReshape( fgGetInt("/sim/startup/xsize"),
510 fgGetInt("/sim/startup/ysize") );
512 if ( fgGetBool("/sim/rendering/clouds3d") ) {
513 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
514 cloud3d_imposter_state->force();
516 glColor4f( 1.0, 1.0, 1.0, 1.0 );
517 glEnable(GL_DEPTH_TEST);
519 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
521 #ifdef FG_USE_CLOUDS_3D
522 if ( _bcloud_orig ) {
523 Point3D c = globals->get_scenery()->get_center();
524 sgClouds3d->Set_Cloud_Orig( &c );
525 _bcloud_orig = false;
527 sgClouds3d->Update( current__view->get_absolute_view_pos() );
529 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
530 glDisable(GL_DEPTH_TEST);
533 clear_mask = GL_DEPTH_BUFFER_BIT;
534 if ( fgGetBool("/sim/rendering/wireframe") ) {
535 clear_mask |= GL_COLOR_BUFFER_BIT;
538 if ( fgGetBool("/sim/rendering/skyblend") ) {
539 if ( fgGetBool("/sim/rendering/textures") ) {
540 // glClearColor(black[0], black[1], black[2], black[3]);
541 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
542 l->adj_fog_color[2], l->adj_fog_color[3]);
543 clear_mask |= GL_COLOR_BUFFER_BIT;
546 glClearColor(l->sky_color[0], l->sky_color[1],
547 l->sky_color[2], l->sky_color[3]);
548 clear_mask |= GL_COLOR_BUFFER_BIT;
550 glClear( clear_mask );
552 // Tell GL we are switching to model view parameters
554 // I really should create a derived ssg node or use a call
555 // back or something so that I can draw the sky within the
556 // ssgCullAndDraw() function, but for now I just mimic what
557 // ssg does to set up the model view matrix
558 glMatrixMode(GL_MODELVIEW);
560 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
562 // set the opengl state to known default values
563 default_state->force();
565 // update fog params if visibility has changed
566 double visibility_meters = fgGetDouble("/environment/visibility-m");
567 thesky->set_visibility(visibility_meters);
569 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
570 ( global_multi_loop * fgGetInt("/sim/speed-up") )
571 / (double)fgGetInt("/sim/model-hz") );
573 // Set correct opengl fog density
574 glFogf (GL_FOG_DENSITY, fog_exp2_density);
576 // update the sky dome
577 if ( fgGetBool("/sim/rendering/skyblend") ) {
579 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
580 << cur_light_params.sky_color[0] << " "
581 << cur_light_params.sky_color[1] << " "
582 << cur_light_params.sky_color[2] << " "
583 << cur_light_params.sky_color[3] );
584 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
585 << cur_light_params.fog_color[0] << " "
586 << cur_light_params.fog_color[1] << " "
587 << cur_light_params.fog_color[2] << " "
588 << cur_light_params.fog_color[3] );
589 SG_LOG( SG_GENERAL, SG_BULK,
590 " sun_angle = " << cur_light_params.sun_angle
591 << " moon_angle = " << cur_light_params.moon_angle );
593 thesky->repaint( cur_light_params.sky_color,
594 cur_light_params.adj_fog_color,
595 cur_light_params.cloud_color,
596 cur_light_params.sun_angle,
597 cur_light_params.moon_angle,
598 globals->get_ephem()->getNumPlanets(),
599 globals->get_ephem()->getPlanets(),
600 globals->get_ephem()->getNumStars(),
601 globals->get_ephem()->getStars() );
604 SG_LOG( SG_GENERAL, SG_BULK,
605 "thesky->reposition( view_pos = " << view_pos[0] << " "
606 << view_pos[1] << " " << view_pos[2] );
607 SG_LOG( SG_GENERAL, SG_BULK,
608 " zero_elev = " << zero_elev[0] << " "
609 << zero_elev[1] << " " << zero_elev[2]
610 << " lon = " << cur_fdm_state->get_Longitude()
611 << " lat = " << cur_fdm_state->get_Latitude() );
612 SG_LOG( SG_GENERAL, SG_BULK,
613 " sun_rot = " << cur_light_params.sun_rotation
614 << " gst = " << SGTime::cur_time_params->getGst() );
615 SG_LOG( SG_GENERAL, SG_BULK,
616 " sun ra = " << globals->get_ephem()->getSunRightAscension()
617 << " sun dec = " << globals->get_ephem()->getSunDeclination()
618 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
619 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
622 // The sun and moon distances are scaled down versions
623 // of the actual distance to get both the moon and the sun
624 // within the range of the far clip plane.
625 // Moon distance: 384,467 kilometers
626 // Sun distance: 150,000,000 kilometers
627 double sun_eye_eff = 0.67+pow(0.5+cos(cur_light_params.sun_angle*2)/2,0.33)/3;
628 double moon_eye_eff = 0.67+pow(0.5+cos(cur_light_params.moon_angle*2)/2,0.33)/3;
629 thesky->reposition( current__view->get_view_pos(),
630 current__view->get_zero_elev(),
631 current__view->get_world_up(),
632 current__view->getLongitude_deg()
633 * SGD_DEGREES_TO_RADIANS,
634 current__view->getLatitude_deg()
635 * SGD_DEGREES_TO_RADIANS,
636 current__view->getAltitudeASL_ft()
638 cur_light_params.sun_rotation,
639 globals->get_time_params()->getGst(),
640 globals->get_ephem()->getSunRightAscension(),
641 globals->get_ephem()->getSunDeclination(),
642 50000.0 * sun_eye_eff,
643 globals->get_ephem()->getMoonRightAscension(),
644 globals->get_ephem()->getMoonDeclination(),
645 40000.0 * moon_eye_eff );
648 glEnable( GL_DEPTH_TEST );
649 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
651 glFogi( GL_FOG_MODE, GL_EXP2 );
652 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
655 // set sun/lighting parameters
656 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
658 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
659 // we only update GL_AMBIENT for our lights we will never get
660 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
661 // explicitely to black.
662 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
664 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
665 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
666 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular );
668 // texture parameters
669 // glEnable( GL_TEXTURE_2D );
670 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
671 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
673 // glMatrixMode( GL_PROJECTION );
675 ssgSetFOV( current__view->get_h_fov(),
676 current__view->get_v_fov() );
679 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
680 - globals->get_scenery()->get_cur_elev();
683 scene_nearplane = 10.0f;
684 scene_farplane = 120000.0f;
686 scene_nearplane = groundlevel_nearplane->getDoubleValue();
687 scene_farplane = 120000.0f;
690 ssgSetNearFar( scene_nearplane, scene_farplane );
692 // $$$ begin - added VS Renganthan 17 Oct 2K
695 // $$$ end - added VS Renganthan 17 Oct 2K
697 # ifdef FG_NETWORK_OLK
698 if ( fgGetBool("/sim/networking/network-olk") ) {
700 other = head->next; /* put listpointer to start */
701 while ( other != tail) { /* display all except myself */
702 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
703 other->fgd_sel->select(1);
704 sgSetCoord( &fgdpos, other->sgFGD_COORD );
705 other->fgd_pos->setTransform( &fgdpos );
710 // fgd_sel->select(1);
711 // sgCopyMat4( sgTUX, current_view.sgVIEW);
713 // sgSetCoord( &fgdpos, sgFGD_VIEW );
714 // fgd_pos->setTransform( &fgdpos);
719 // Update any multiplayer models
720 globals->get_multiplayer_rx_mgr()->Update();
723 if ( fgGetBool("/sim/rendering/skyblend") &&
724 fgGetBool("/sim/rendering/draw-otw") )
726 // draw the sky backdrop
728 // we need a white diffuse light for the phase of the moon
729 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
733 // return to the desired diffuse color
734 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
737 // draw the ssg scene
738 glEnable( GL_DEPTH_TEST );
740 ssgSetNearFar( scene_nearplane, scene_farplane );
742 if ( fgGetBool("/sim/rendering/wireframe") ) {
744 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
746 if ( fgGetBool("/sim/rendering/draw-otw") ) {
747 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
750 // This is a bit kludgy. Every 200 frames, do an extra
751 // traversal of the scene graph without drawing anything, but
752 // with the field-of-view set to 360x360 degrees. This
753 // ensures that out-of-range random objects that are not in
754 // the current view frustum will still be freed properly.
755 static int counter = 0;
757 if (counter == 200) {
760 // No need to put the near plane too close;
761 // this way, at least the aircraft can be
763 f.setNearFar(1000, 1000000);
765 ssgGetModelviewMatrix(m);
766 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
770 // change state for lighting here
772 // draw runway lighting
773 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
774 ssgSetNearFar( scene_nearplane, scene_farplane );
776 #ifdef FG_EXPERIMENTAL_POINT_LIGHTING
777 // Enable states for drawing points with GL_extension
778 glEnable(GL_POINT_SMOOTH);
780 if ( fgGetBool("/sim/rendering/distance-attenuation")
781 && glutExtensionSupported("GL_EXT_point_parameters") )
783 float quadratic[3] = {1.0, 0.001, 0.0000001};
784 // makes the points fade as they move away
785 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
786 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
790 // blending function for runway lights
791 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
794 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
795 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
796 glEnable(GL_TEXTURE_GEN_S);
797 glEnable(GL_TEXTURE_GEN_T);
798 glPolygonMode(GL_FRONT, GL_POINT);
800 // draw runway lighting
801 if ( fgGetBool("/sim/rendering/draw-otw") ) {
802 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
805 // change punch through and then draw taxi lighting
806 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
808 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
809 // glFogfv ( GL_FOG_COLOR, taxi_fog );
810 if ( fgGetBool("/sim/rendering/draw-otw") ) {
811 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
815 glPolygonMode(GL_FRONT, GL_FILL);
816 glDisable(GL_TEXTURE_GEN_S);
817 glDisable(GL_TEXTURE_GEN_T);
819 //static int _frame_count = 0;
820 //if (_frame_count % 30 == 0) {
821 // printf("SSG: %s\n", ssgShowStats());
829 #ifdef FG_EXPERIMENTAL_POINT_LIGHTING
830 if ( fgGetBool("/sim/rendering/distance-attenuation")
831 && glutExtensionSupported("GL_EXT_point_parameters") )
833 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
834 default_attenuation);
838 glDisable(GL_POINT_SMOOTH);
841 // draw ground lighting
842 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
843 if ( fgGetBool("/sim/rendering/draw-otw") ) {
844 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
847 if ( fgGetBool("/sim/rendering/skyblend") ) {
848 // draw the sky cloud layers
849 if ( fgGetBool("/environment/clouds/status") &&
850 fgGetBool("/sim/rendering/draw-otw") )
852 thesky->postDraw( cur_fdm_state->get_Altitude()
853 * SG_FEET_TO_METER );
857 if ( fgGetBool("/sim/rendering/clouds3d") &&
858 fgGetBool("/sim/rendering/draw-otw") )
861 glDisable( GL_LIGHTING );
862 // cout << "drawing new clouds" << endl;
864 glEnable(GL_DEPTH_TEST);
866 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
869 glEnable( GL_TEXTURE_2D );
870 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
871 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
872 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
873 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
876 #ifdef FG_USE_CLOUDS_3D
877 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
880 glEnable( GL_LIGHTING );
881 glEnable( GL_DEPTH_TEST );
882 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
885 if ( fgGetBool("/sim/rendering/draw-otw") ) {
886 globals->get_model_mgr()->draw();
887 globals->get_aircraft_model()->draw();
890 // display HUD && Panel
892 glDisable( GL_DEPTH_TEST );
893 // glDisable( GL_CULL_FACE );
894 // glDisable( GL_TEXTURE_2D );
896 // update the controls subsystem
897 globals->get_controls()->update(delta_time_sec);
899 hud_and_panel->apply();
902 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
903 // This only works properly if called before the panel call
904 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
905 globals->get_ATC_display()->update(delta_time_sec);
907 // update the panel subsystem
908 if ( globals->get_current_panel() != NULL ) {
909 globals->get_current_panel()->update(delta_time_sec);
913 // We can do translucent menus, so why not. :-)
915 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
917 // glDisable ( GL_BLEND ) ;
919 glEnable( GL_DEPTH_TEST );
922 // Fade out the splash screen over the first three seconds.
923 double t = globals->get_sim_time_sec();
925 fgSplashUpdate(0.0, 1.0);
926 } else if ( t <= 3.0) {
927 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
935 // Update internal time dependent calculations (i.e. flight model)
936 // FIXME: this distinction is obsolete; all subsystems now get delta
938 void fgUpdateTimeDepCalcs() {
939 static bool inited = false;
941 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
943 fgLIGHT *l = &cur_light_params;
945 // Initialize the FDM here if it hasn't been and if we have a
946 // scenery elevation hit.
948 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
949 // << " cur_elev = " << scenery.get_cur_elev() << endl;
951 if ( !cur_fdm_state->get_inited() &&
952 globals->get_scenery()->get_cur_elev() > -9990 )
954 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
955 cur_fdm_state->init();
956 if ( cur_fdm_state->get_bound() ) {
957 cur_fdm_state->unbind();
959 cur_fdm_state->bind();
962 // conceptually, the following block could be done for each fdm
964 if ( !cur_fdm_state->get_inited() ) {
965 // do nothing, fdm isn't inited yet
967 // we have been inited, and we are good to go ...
973 globals->get_autopilot()->update(delta_time_sec);
974 cur_fdm_state->update(delta_time_sec);
977 globals->get_model_mgr()->update(delta_time_sec);
978 globals->get_aircraft_model()->update(delta_time_sec);
980 // update the view angle
981 globals->get_viewmgr()->update(delta_time_sec);
985 // Update solar system
986 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
987 globals->get_time_params()->getLst(),
988 cur_fdm_state->get_Latitude() );
990 // Update radio stack model
991 current_radiostack->update(delta_time_sec);
995 void fgInitTimeDepCalcs( void ) {
1000 static const double alt_adjust_ft = 3.758099;
1001 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1004 // What should we do when we have nothing else to do? Let's get ready
1005 // for the next move and update the display?
1006 static void fgMainLoop( void ) {
1008 static const SGPropertyNode *longitude
1009 = fgGetNode("/position/longitude-deg");
1010 static const SGPropertyNode *latitude
1011 = fgGetNode("/position/latitude-deg");
1012 static const SGPropertyNode *altitude
1013 = fgGetNode("/position/altitude-ft");
1014 static const SGPropertyNode *clock_freeze
1015 = fgGetNode("/sim/freeze/clock", true);
1016 static const SGPropertyNode *cur_time_override
1017 = fgGetNode("/sim/time/cur-time-override", true);
1019 // Update the elapsed time.
1020 static bool first_time = true;
1022 last_time_stamp.stamp();
1026 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1027 if ( throttle_hz > 0.0 ) {
1028 // simple frame rate throttle
1029 double dt = 1000000.0 / throttle_hz;
1030 current_time_stamp.stamp();
1031 while ( current_time_stamp - last_time_stamp < dt ) {
1032 current_time_stamp.stamp();
1035 // run as fast as the app will go
1036 current_time_stamp.stamp();
1039 delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
1040 if ( clock_freeze->getBoolValue() ) {
1043 last_time_stamp = current_time_stamp;
1044 globals->inc_sim_time_sec( delta_time_sec );
1045 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1047 static long remainder = 0;
1049 #ifdef FANCY_FRAME_COUNTER
1053 static time_t last_time = 0;
1054 static int frames = 0;
1055 #endif // FANCY_FRAME_COUNTER
1057 SGTime *t = globals->get_time_params();
1059 sglog().setLogLevels( SG_ALL, (sgDebugPriority)fgGetInt("/sim/log-level") );
1060 sglog().setLogLevels( SG_ALL, SG_INFO );
1062 SGLocation * acmodel_location = 0;
1063 if(cur_fdm_state->getACModel() != 0) {
1064 acmodel_location = (SGLocation *) cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
1067 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1068 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1070 #ifdef FG_NETWORK_OLK
1071 if ( fgGetBool("/sim/networking/network-olk") ) {
1072 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
1073 // printf("FGD: Netupdate\n");
1074 fgd_send_com( "A", FGFS_host); // Send Mat4 data
1075 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
1080 #if defined( ENABLE_PLIB_JOYSTICK )
1081 // Read joystick and update control settings
1082 // if ( fgGetString("/sim/control-mode") == "joystick" )
1084 // fgJoystickRead();
1086 #elif defined( ENABLE_GLUT_JOYSTICK )
1087 // Glut joystick support works by feeding a joystick handler
1088 // function to glut. This is taken care of once in the joystick
1089 // init routine and we don't have to worry about it again.
1092 // Fix elevation. I'm just sticking this here for now, it should
1093 // probably move eventually
1095 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1096 scenery.get_cur_elev(),
1097 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1098 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1100 // Curt is this code used? I don't see any problems when I comment it out.
1101 if ( acmodel_location != 0 ) {
1102 if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
1103 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
1104 (acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0) ) {
1105 // now set aircraft altitude above ground
1106 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
1107 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1108 acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0,
1109 acmodel_location->get_cur_elev_m() + alt_adjust_m );
1110 cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m()
1111 + alt_adjust_m) * SG_METER_TO_FEET );
1112 SG_LOG( SG_ALL, SG_DEBUG,
1113 "<*> resetting altitude to "
1114 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1119 // End of code in question. (see Curt is this code used? above)
1121 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1122 scenery.get_cur_elev(),
1123 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1124 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1126 // cout << "Warp = " << globals->get_warp() << endl;
1129 static bool last_clock_freeze = false;
1131 if ( clock_freeze->getBoolValue() ) {
1132 // clock freeze requested
1133 if ( cur_time_override->getLongValue() == 0 ) {
1134 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1135 globals->set_warp( 0 );
1138 // no clock freeze requested
1139 if ( last_clock_freeze == true ) {
1140 // clock just unfroze, let's set warp as the difference
1141 // between frozen time and current time so we don't get a
1142 // time jump (and corresponding sky object and lighting
1144 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1145 fgSetLong( "/sim/time/cur-time-override", 0 );
1147 if ( globals->get_warp_delta() != 0 ) {
1148 globals->inc_warp( globals->get_warp_delta() );
1152 last_clock_freeze = clock_freeze->getBoolValue();
1154 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1155 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1156 cur_time_override->getLongValue(),
1157 globals->get_warp() );
1159 if ( globals->get_warp_delta() != 0 ) {
1160 fgUpdateSkyAndLightingParams();
1163 // update magvar model
1164 globals->get_mag()->update( longitude->getDoubleValue()
1165 * SGD_DEGREES_TO_RADIANS,
1166 latitude->getDoubleValue()
1167 * SGD_DEGREES_TO_RADIANS,
1168 altitude->getDoubleValue() * SG_FEET_TO_METER,
1169 globals->get_time_params()->getJD() );
1171 // Get elapsed time (in usec) for this past frame
1172 elapsed = fgGetTimeInterval();
1173 SG_LOG( SG_ALL, SG_DEBUG,
1174 "Elapsed time interval is = " << elapsed
1175 << ", previous remainder is = " << remainder );
1177 // Calculate frame rate average
1178 #ifdef FANCY_FRAME_COUNTER
1179 /* old fps calculation */
1180 if ( elapsed > 0 ) {
1183 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1184 tmp = general.get_frame(i);
1186 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1187 general.set_frame(i+1,tmp);
1189 tmp = 1000000.0 / (float)elapsed;
1190 general.set_frame(0,tmp);
1191 // printf("frame[0] = %.2f\n", general.frames[0]);
1193 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1194 // printf("ave = %.2f\n", general.frame_rate);
1197 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1198 general.set_frame_rate( frames );
1199 fgSetInt("/sim/frame-rate", frames);
1200 SG_LOG( SG_ALL, SG_DEBUG,
1201 "--> Frame rate is = " << general.get_frame_rate() );
1204 last_time = t->get_cur_time();
1208 // Run ATC subsystem
1209 if (fgGetBool("/sim/ATC/enabled"))
1210 globals->get_ATC_mgr()->update(delta_time_sec);
1212 // Run the AI subsystem
1213 if (fgGetBool("/sim/ai-traffic/enabled"))
1214 globals->get_AI_mgr()->update(delta_time_sec);
1218 // Calculate model iterations needed for next frame
1219 elapsed += remainder;
1221 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1222 fgGetInt("/sim/model-hz"));
1223 remainder = elapsed - ( (global_multi_loop*1000000) /
1224 fgGetInt("/sim/model-hz") );
1225 SG_LOG( SG_ALL, SG_DEBUG,
1226 "Model iterations needed = " << global_multi_loop
1227 << ", new remainder = " << remainder );
1229 // chop max interations to something reasonable if the sim was
1230 // delayed for an excesive amount of time
1231 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1232 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1237 if ( global_multi_loop > 0 ) {
1238 fgUpdateTimeDepCalcs();
1240 SG_LOG( SG_ALL, SG_DEBUG,
1241 "Elapsed time is zero ... we're zinging" );
1244 // Do any I/O channel work that might need to be done
1245 globals->get_io()->update( delta_time_sec );
1247 // see if we need to load any deferred-load textures
1248 globals->get_matlib()->load_next_deferred();
1250 // Run audio scheduler
1251 #ifdef ENABLE_AUDIO_SUPPORT
1252 if ( fgGetBool("/sim/sound/audible")
1253 && globals->get_soundmgr()->is_working() ) {
1254 globals->get_soundmgr()->update( delta_time_sec );
1258 globals->get_subsystem_mgr()->update(delta_time_sec);
1261 // Tile Manager updates - see if we need to load any new scenery tiles.
1262 // this code ties together the fdm, viewer and scenery classes...
1263 // we may want to move this to it's own class at some point
1265 double visibility_meters = fgGetDouble("/environment/visibility-m");
1266 FGViewer *current_view = globals->get_current_view();
1268 // update tile manager for FDM...
1269 // ...only if location is different than the viewer (to avoid duplicating effort)
1270 if( acmodel_location != current_view->getSGLocation() ) {
1271 if( acmodel_location != 0 ) {
1272 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1273 visibility_meters );
1274 globals->get_tile_mgr()->
1275 update( acmodel_location, visibility_meters,
1276 acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1277 // save results of update in SGLocation for fdm...
1278 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1280 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1283 set_tile_center( globals->get_scenery()->get_next_center() );
1287 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1288 visibility_meters );
1289 // update tile manager for view...
1290 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1291 // after the FDM's until all of Flight Gear code references the viewer's location
1292 // for elevation instead of the "scenery's" current elevation.
1293 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1294 globals->get_tile_mgr()->update( view_location, visibility_meters,
1295 current_view->get_absolute_view_pos() );
1296 // save results of update in SGLocation for fdm...
1297 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1298 current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1300 current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1302 // If fdm location is same as viewer's then we didn't do the update for fdm location
1303 // above so we need to save the viewer results in the fdm SGLocation as well...
1304 if( acmodel_location == current_view->getSGLocation() ) {
1305 if( acmodel_location != 0 ) {
1306 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1307 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1309 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1313 // END Tile Manager udpates
1318 SG_LOG( SG_ALL, SG_DEBUG, "" );
1322 // This is the top level master main function that is registered as
1323 // our idle funciton
1325 // The first few passes take care of initialization things (a couple
1326 // per pass) and once everything has been initialized fgMainLoop from
1329 static void fgIdleFunction ( void ) {
1330 // printf("idle state == %d\n", idle_state);
1332 if ( idle_state == 0 ) {
1333 // Initialize the splash screen right away
1334 if ( fgGetBool("/sim/startup/splash-screen") ) {
1339 } else if ( idle_state == 1 ) {
1340 // Initialize audio support
1341 #ifdef ENABLE_AUDIO_SUPPORT
1343 // Start the intro music
1344 if ( fgGetBool("/sim/startup/intro-music") ) {
1345 SGPath mp3file( globals->get_fg_root() );
1346 mp3file.append( "Sounds/intro.mp3" );
1348 SG_LOG( SG_GENERAL, SG_INFO,
1349 "Starting intro music: " << mp3file.str() );
1351 #if defined( __CYGWIN__ )
1352 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1353 #elif defined( WIN32 )
1354 string command = "start /m " + mp3file.str();
1356 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1359 system ( command.c_str() );
1364 } else if ( idle_state == 2 ) {
1365 // These are a few miscellaneous things that aren't really
1366 // "subsystems" but still need to be initialized.
1369 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1370 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1375 } else if ( idle_state == 3 ) {
1376 // This is the top level init routine which calls all the
1377 // other subsystem initialization routines. If you are adding
1378 // a subsystem to flightgear, its initialization call should
1379 // located in this routine.
1380 if( !fgInitSubsystems()) {
1381 SG_LOG( SG_GENERAL, SG_ALERT,
1382 "Subsystem initializations failed ..." );
1387 } else if ( idle_state == 4 ) {
1388 // setup OpenGL view parameters
1391 // Read the list of available aircrafts
1395 } else if ( idle_state == 5 ) {
1398 } else if ( idle_state == 6 ) {
1402 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1403 fgReshape( fgGetInt("/sim/startup/xsize"),
1404 fgGetInt("/sim/startup/ysize") );
1407 if ( idle_state == 1000 ) {
1408 // We've finished all our initialization steps, from now on we
1409 // run the main loop.
1411 glutIdleFunc(fgMainLoop);
1413 if ( fgGetBool("/sim/startup/splash-screen") ) {
1414 fgSplashUpdate(0.0, 1.0);
1419 // options.cxx needs to see this for toggle_panel()
1420 // Handle new window size or exposure
1421 void fgReshape( int width, int height ) {
1424 if ( (!fgGetBool("/sim/virtual-cockpit"))
1425 && fgPanelVisible() && idle_state == 1000 ) {
1426 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1427 globals->get_current_panel()->getYOffset()) / 768.0);
1433 FGViewMgr *viewmgr = globals->get_viewmgr();
1434 for ( int i = 0; i < viewmgr->size(); ++i ) {
1435 viewmgr->get_view(i)->
1436 set_aspect_ratio((float)view_h / (float)width);
1439 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1441 fgSetInt("/sim/startup/xsize", width);
1442 fgSetInt("/sim/startup/ysize", height);
1443 guiInitMouse(width, height);
1445 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1446 viewmgr->get_current_view()->get_v_fov() );
1450 #ifdef FG_USE_CLOUDS_3D
1451 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1452 viewmgr->get_current_view()->get_v_fov() );
1457 // Initialize GLUT and define a main window
1458 static bool fgGlutInit( int *argc, char **argv ) {
1460 #if !defined( macintosh )
1461 // GLUT will extract all glut specific options so later on we only
1462 // need wory about our own.
1463 glutInit(argc, argv);
1466 // Define Display Parameters. Clouds3d works best with --bpp32 option
1467 if ( fgGetBool("/sim/rendering/clouds3d") ) {
1468 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1470 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1473 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1474 fgGetInt("/sim/startup/xsize") << "x"
1475 << fgGetInt("/sim/startup/ysize") );
1477 // Define initial window size
1478 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1479 fgGetInt("/sim/startup/ysize") );
1481 // Initialize windows
1482 if ( !fgGetBool("/sim/startup/game-mode")) {
1483 // Open the regular window
1484 glutCreateWindow("FlightGear");
1485 #ifndef GLUT_WRONG_VERSION
1487 // Open the cool new 'game mode' window
1488 char game_mode_str[256];
1489 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1490 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1491 #ifndef ENUM_CURRENT_SETTINGS
1492 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1493 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1497 dm.dmSize = sizeof(DEVMODE);
1498 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1499 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1500 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1501 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1502 fgGetInt("/sim/startup/ysize") );
1503 sprintf( game_mode_str, "%dx%d:%d@%d",
1507 dm.dmDisplayFrequency );
1509 // Open the cool new 'game mode' window
1510 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1511 fgGetInt("/sim/startup/xsize"),
1512 fgGetInt("/sim/startup/ysize"),
1513 fgGetInt("/sim/rendering/bits-per-pixel"));
1515 #endif // HAVE_WINDOWS_H
1516 SG_LOG( SG_GENERAL, SG_INFO,
1517 "game mode params = " << game_mode_str );
1518 glutGameModeString( game_mode_str );
1519 glutEnterGameMode();
1520 #endif // GLUT_WRONG_VERSION
1523 // This seems to be the absolute earliest in the init sequence
1524 // that these calls will return valid info. Too bad it's after
1525 // we've already created and sized out window. :-(
1526 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1527 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1528 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1529 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1532 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1533 general.set_glMaxTexSize( tmp );
1534 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1536 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1537 general.set_glDepthBits( tmp );
1538 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1544 // Initialize GLUT event handlers
1545 static bool fgGlutInitEvents( void ) {
1546 // call fgReshape() on window resizes
1547 glutReshapeFunc( fgReshape );
1549 // keyboard and mouse callbacks are set in FGInput::init
1551 // call fgMainLoop() whenever there is
1552 // nothing else to do
1553 glutIdleFunc( fgIdleFunction );
1556 glutDisplayFunc( fgRenderFrame );
1561 // Main top level initialization
1562 static bool fgMainInit( int argc, char **argv ) {
1564 #if defined( macintosh )
1565 freopen ("stdout.txt", "w", stdout );
1566 freopen ("stderr.txt", "w", stderr );
1567 argc = ccommand( &argv );
1570 // set default log levels
1571 sglog().setLogLevels( SG_ALL, SG_INFO );
1574 #ifdef FLIGHTGEAR_VERSION
1575 version = FLIGHTGEAR_VERSION;
1577 version = "unknown version";
1579 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1581 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1583 // Allocate global data structures. This needs to happen before
1584 // we parse command line options
1586 globals = new FGGlobals;
1588 // seed the random number generater
1591 SGRoute *route = new SGRoute;
1592 globals->set_route( route );
1594 FGControls *controls = new FGControls;
1595 globals->set_controls( controls );
1597 string_list *col = new string_list;
1598 globals->set_channel_options_list( col );
1600 // Scan the config file(s) and command line options to see if
1601 // fg_root was specified (ignore all other options for now)
1602 fgInitFGRoot(argc, argv);
1604 // Check for the correct base package version
1605 static char required_version[] = "0.9.2";
1606 string base_version = fgBasePackageVersion();
1607 if ( !(base_version == required_version) ) {
1608 // tell the operator how to use this application
1610 cerr << endl << "Base package check failed ... " \
1611 << "Found version " << base_version << " at: " \
1612 << globals->get_fg_root() << endl;
1613 cerr << "Please upgrade to version: " << required_version << endl;
1617 // Initialize the Aircraft directory to "" (UIUC)
1620 // Load the configuration parameters. (Command line options
1621 // overrides config file options. Config file options override
1623 if ( !fgInitConfig(argc, argv) ) {
1624 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1628 // Initialize the Window/Graphics environment.
1629 if( !fgGlutInit(&argc, argv) ) {
1630 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1634 // Initialize the various GLUT Event Handlers.
1635 if( !fgGlutInitEvents() ) {
1636 SG_LOG( SG_GENERAL, SG_ALERT,
1637 "GLUT event handler initialization failed ..." );
1641 // Initialize plib net interface
1642 netInit( &argc, argv );
1644 // Initialize ssg (from plib). Needs to come before we do any
1645 // other ssg stuff, but after opengl/glut has been initialized.
1648 // Initialize the user interface (we need to do this before
1649 // passing off control to glut and before fgInitGeneral to get our
1653 // Read the list of available aircrafts
1656 #ifdef GL_EXT_texture_lod_bias
1657 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1660 #ifdef FG_EXPERIMENTAL_POINT_LIGHTING
1661 // get the address of our OpenGL extensions
1662 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1665 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
1666 wglGetProcAddress("glPointParameterfEXT");
1667 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
1668 wglGetProcAddress("glPointParameterfvEXT");
1670 glPointParameterfEXT = (OpenGLFuncExt)
1671 glXGetProcAddressARB((GLubyte *)"glPointParameterfEXT");
1672 glPointParameterfvEXT = (OpenGLFuncExtv)
1673 glXGetProcAddressARB((GLubyte *)"glPointParameterfvEXT");
1678 // based on the requested presets, calculate the true starting
1683 SGTime *t = fgInitTime();
1684 globals->set_time_params( t );
1686 // Do some quick general initializations
1687 if( !fgInitGeneral()) {
1688 SG_LOG( SG_GENERAL, SG_ALERT,
1689 "General initializations failed ..." );
1693 SGPath modelpath( globals->get_fg_root() );
1694 ssgModelPath( (char *)modelpath.c_str() );
1696 ////////////////////////////////////////////////////////////////////
1697 // Initialize the property-based built-in commands
1698 ////////////////////////////////////////////////////////////////////
1701 ////////////////////////////////////////////////////////////////////
1702 // Initialize the material manager
1703 ////////////////////////////////////////////////////////////////////
1704 globals->set_matlib( new SGMaterialLib );
1706 globals->set_model_lib(new SGModelLib);
1708 ////////////////////////////////////////////////////////////////////
1709 // Initialize the TG scenery subsystem.
1710 ////////////////////////////////////////////////////////////////////
1711 globals->set_scenery( new FGScenery );
1712 globals->get_scenery()->init();
1713 globals->get_scenery()->bind();
1714 globals->set_tile_mgr( new FGTileMgr );
1716 ////////////////////////////////////////////////////////////////////
1717 // Initialize the general model subsystem.
1718 ////////////////////////////////////////////////////////////////////
1719 globals->set_model_mgr(new FGModelMgr);
1720 globals->get_model_mgr()->init();
1721 globals->get_model_mgr()->bind();
1723 ////////////////////////////////////////////////////////////////////
1724 // Initialize the 3D aircraft model subsystem (has a dependency on
1725 // the scenery subsystem.)
1726 ////////////////////////////////////////////////////////////////////
1727 globals->set_aircraft_model(new FGAircraftModel);
1728 globals->get_aircraft_model()->init();
1729 globals->get_aircraft_model()->bind();
1731 ////////////////////////////////////////////////////////////////////
1732 // Initialize the view manager subsystem.
1733 ////////////////////////////////////////////////////////////////////
1735 FGViewMgr *viewmgr = new FGViewMgr;
1736 globals->set_viewmgr( viewmgr );
1741 // Initialize the sky
1742 SGPath ephem_data_path( globals->get_fg_root() );
1743 ephem_data_path.append( "Astro" );
1744 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1745 ephem->update( globals->get_time_params()->getMjd(),
1746 globals->get_time_params()->getLst(),
1748 globals->set_ephem( ephem );
1750 // TODO: move to environment mgr
1752 SGPath texture_path(globals->get_fg_root());
1753 texture_path.append("Textures");
1754 texture_path.append("Sky");
1755 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1756 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1757 thesky->add_cloud_layer(layer);
1761 SGPath sky_tex_path( globals->get_fg_root() );
1762 sky_tex_path.append( "Textures" );
1763 sky_tex_path.append( "Sky" );
1764 thesky->texture_path( sky_tex_path.str() );
1766 // The sun and moon diameters are scaled down numbers of the
1767 // actual diameters. This was needed to fit bot the sun and the
1768 // moon within the distance to the far clip plane.
1769 // Moon diameter: 3,476 kilometers
1770 // Sun diameter: 1,390,000 kilometers
1771 thesky->build( 80000.0, 80000.0,
1773 globals->get_ephem()->getNumPlanets(),
1774 globals->get_ephem()->getPlanets(),
1775 globals->get_ephem()->getNumStars(),
1776 globals->get_ephem()->getStars() );
1778 // Initialize MagVar model
1779 SGMagVar *magvar = new SGMagVar();
1780 globals->set_mag( magvar );
1782 // airport = new ssgBranch;
1783 // airport->setName( "Airport Lighting" );
1784 // lighting->addKid( airport );
1790 #ifdef FG_NETWORK_OLK
1791 // Do the network intialization
1792 if ( fgGetBool("/sim/networking/network-olk") ) {
1793 printf("Multipilot mode %s\n",
1794 fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1798 // build our custom render states
1799 fgBuildRenderStates();
1801 // pass control off to the master GLUT event handler
1804 // we never actually get here ... but to avoid compiler warnings,
1810 // $$$ end - added VS Renganathan, 15 Oct 2K
1811 // - added Venky , 12 Nov 2K
1813 #if defined(__linux__) && defined(__i386__)
1815 static void handleFPE (int);
1820 fpu_control_t fpe_flags = 0;
1821 _FPU_GETCW(fpe_flags);
1822 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1823 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1824 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1825 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1826 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1827 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1828 _FPU_SETCW(fpe_flags);
1829 signal(SIGFPE, handleFPE);
1836 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1849 short CPSGetCurrentProcess(PSN *psn);
1850 short CPSSetProcessName (PSN *psn, char *processname);
1851 short CPSEnableForegroundOperation(PSN *psn, int _arg2, int _arg3, int _arg4, int _arg5);
1852 short CPSSetFrontProcess(PSN *psn);
1855 #define CPSEnableFG(psn) CPSEnableForegroundOperation(psn,0x03,0x3C,0x2C,0x1103)
1859 // Main entry point; catch any exceptions that have made it this far.
1860 int main ( int argc, char **argv ) {
1862 // Enable floating-point exceptions for Linux/x86
1863 #if defined(__linux__) && defined(__i386__)
1867 // Enable floating-point exceptions for Windows
1868 #if defined( _MSC_VER ) && defined( DEBUG )
1869 // Christian, we should document what this does
1870 _control87( _EM_INEXACT, _MCW_EM );
1873 #if defined( HAVE_BC5PLUS )
1874 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1877 // Keyboard focus hack
1882 glutInit (&argc, argv);
1884 CPSGetCurrentProcess(&psn);
1885 CPSSetProcessName(&psn, "FlightGear");
1887 CPSSetFrontProcess(&psn);
1891 // FIXME: add other, more specific
1894 fgMainInit(argc, argv);
1895 } catch (sg_throwable &t) {
1896 // We must use cerr rather than
1897 // logging, since logging may be
1899 cerr << "Fatal error: " << t.getFormattedMessage()
1900 << "\n (received from " << t.getOrigin() << ')' << endl;
1908 void fgLoadDCS(void) {
1910 ssgEntity *ship_obj = NULL;
1912 char obj_filename[25];
1914 for ( int k = 0; k < 32; k++ ) {
1918 SGPath tile_path( globals->get_fg_root());
1919 tile_path.append( "Scenery" );
1920 tile_path.append( "Objects.txt" );
1921 sg_gzifstream in( tile_path.str() );
1922 if ( ! in.is_open() ) {
1923 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1926 SGPath modelpath( globals->get_fg_root() );
1927 modelpath.append( "Models" );
1928 modelpath.append( "Geometry" );
1930 SGPath texturepath( globals->get_fg_root() );
1931 texturepath.append( "Models" );
1932 texturepath.append( "Textures" );
1934 ssgModelPath( (char *)modelpath.c_str() );
1935 ssgTexturePath( (char *)texturepath.c_str() );
1937 ship_sel = new ssgSelector;
1940 while ( ! in.eof() ) {
1942 if ( in.get( c ) && c == '#' ) {
1946 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1947 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1948 int chj=getchar();*/
1950 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1951 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1953 ship_pos[objc] = new ssgTransform;
1955 // type "repeat" in objects.txt to load one more
1956 // instance of the last object.
1958 if ( strcmp(obj_filename,"repeat") != 0) {
1960 globals->get_model_lib()->load_model( globals->get_fg_root(), obj_filename, globals->get_props(), globals->get_sim_time_sec() );
1963 if ( ship_obj != NULL ) {
1964 ship_obj->setName(obj_filename);
1966 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1968 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1969 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1970 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1971 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1974 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1978 // temporary hack for deck lights - ultimately should move to PLib (when??)
1979 //const char *extn = file_extension ( obj_filename ) ;
1981 // ssgVertexArray *lights = new ssgVertexArray( 100 );
1982 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1983 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1984 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1985 int ltype[500], light_type = 0;
1986 static int ltcount = 0;
1988 sgVec3 rway_dir,rway_normal,lightpt;
1990 modelpath.append(obj_filename);
1991 sg_gzifstream in1( modelpath.str() );
1992 if ( ! in1.is_open() ) {
1993 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1995 while ( ! in1.eof() ) {
1997 if ( in1.get( c ) && c == '#' ) {
2002 //cout << token << endl;
2003 if ( token == "runway" ) {
2005 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
2006 } else if ( token == "edgelight" ) {
2008 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2010 } else if ( token == "taxi" ) {
2012 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2014 } else if ( token == "vasi" ) {
2016 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2018 } else if ( token == "threshold" ) {
2020 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2022 } else if ( token == "rabbit" ) {
2024 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2026 } else if ( token == "ols" ) {
2028 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
2030 } else if ( token == "red" ) {
2032 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2034 } else if ( token == "green" ) {
2036 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2038 } else if ( token == "lp" ) {
2040 sgSetVec3 (lightpt, node[0], node[1], node[2] );
2041 lightpoints->add( lightpt );
2042 lightnormals->add( rway_normal );
2043 lightdir->add( rway_dir );
2044 ltype[ltcount]= light_type;
2047 if (in1.eof()) break;
2052 if ( lightpoints->getNum() ) {
2053 ssgBranch *lightpoints_branch;
2054 long int dummy = -999;
2055 dummy_tile = new FGTileEntry((SGBucket)dummy);
2056 dummy_tile->lightmaps_sequence = new ssgSelector;
2057 dummy_tile->ols_transform = new ssgTransform;
2059 // call function to generate the runway lights
2060 lightpoints_branch =
2061 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
2063 lightpoints_brightness->addKid(lightpoints_branch);
2064 lightpoints_transform->addKid(lightpoints_brightness);
2065 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
2066 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
2067 lightpoints_transform->ref();
2068 globals->get_scenery()->get_gnd_lights_root()->addKid( lightpoints_transform );
2073 // end hack for deck lights
2077 if (in.eof()) break;
2081 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
2083 globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node
2090 void fgUpdateDCS (void) {
2092 // double eye_lat,eye_lon,eye_alt;
2093 // static double obj_head;
2094 double sl_radius,obj_latgc;
2095 // float nresultmat[4][4];
2096 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
2099 // Instantaneous Geodetic Lat/Lon/Alt of moving object
2100 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
2102 // Deck should be the first object in objects.txt in case of fdm=ada
2104 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
2105 if ((fdm->get_iaux(1))==1)
2107 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
2108 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
2109 obj_alt[1] = fdm->get_daux(3);
2110 obj_pitch[1] = fdm->get_faux(1);
2111 obj_roll[1] = fdm->get_faux(2);
2115 for ( int m = 0; m < objc; m++ ) {
2116 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
2119 //Geodetic to Geocentric angles for rotation
2120 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
2122 //moving object gbs-posn in cartesian coords
2123 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
2124 Point3D obj_pos = sgGeodToCart( obj_posn );
2126 // Translate moving object w.r.t eye
2127 Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
2132 // rotate dynamic objects for lat,lon & alt and other motion about its axes
2135 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
2137 sgVec3 ship_fwd,ship_rt,ship_up;
2138 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
2139 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
2140 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
2142 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
2143 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
2144 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
2145 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
2146 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
2147 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2150 sgCopyMat4( sgTUX, sgROT_hdg );
2151 sgPostMultMat4( sgTUX, sgROT_pitch );
2152 sgPostMultMat4( sgTUX, sgROT_roll );
2153 sgPostMultMat4( sgTUX, sgROT_lat );
2154 sgPostMultMat4( sgTUX, sgROT_lon );
2155 sgPostMultMat4( sgTUX, sgTRANS );
2158 sgSetCoord(&shippos, sgTUX );
2159 ship_pos[m]->setTransform( &shippos );
2160 // temporary hack for deck lights - ultimately should move to PLib (when ??)
2162 if (lightpoints_transform) {
2163 lightpoints_transform->setTransform( &shippos );
2164 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2165 if ( sun_angle > 89 ) {
2166 lightpoints_brightness->select(0x01);
2168 lightpoints_brightness->select(0x00);
2177 sgXformPnt3( rp, rway_ols, sgTUX );
2178 vp = globals->get_current_view()->get_view_pos();
2179 to[0] = rp[0]-vp[0];
2180 to[1] = rp[1]-vp[1];
2181 to[2] = rp[2]-vp[2];
2182 float dist = sgLengthVec3( to );
2183 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2185 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2187 ref_elev = elev - 3.75; // +ve above, -ve below
2191 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2192 // if (ref_elev > 0.51) sel = 0x21;
2193 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2194 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2195 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2196 // if (ref_elev < -0.51) sel = 0x30;
2197 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2198 // dummy_tile->lightmaps_sequence->select(sel);
2201 sgCopyVec3 (up, ship_up);
2203 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2205 sgScaleVec3 (up, 4.0*ref_elev);
2206 // dummy_tile->ols_transform->setTransform(up);
2207 //cout << "ref_elev " << ref_elev << endl;
2209 // end hack for deck lights
2212 if ( ship_sel != NULL ) {
2213 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2217 // $$$ end - added VS Renganathan, 15 Oct 2K
2218 // added Venky , 12 Nov 2K