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"
146 glPointParameterfProc glPointParameterfPtr = 0;
147 glPointParameterfvProc glPointParameterfvPtr = 0;
148 bool glPointParameterIsSupported = false;
150 float default_attenuation[3] = {1.0, 0.0, 0.0};
151 //Required for using GL_extensions
152 void fgLoadDCS (void);
153 void fgUpdateDCS (void);
154 ssgSelector *ship_sel=NULL;
155 // upto 32 instances of a same object can be loaded.
156 ssgTransform *ship_pos[32];
157 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
159 ssgSelector *lightpoints_brightness = new ssgSelector;
160 ssgTransform *lightpoints_transform = new ssgTransform;
161 FGTileEntry *dummy_tile;
164 // Clip plane settings...
165 float scene_nearplane = 0.5f;
166 float scene_farplane = 120000.0f;
168 static double delta_time_sec = 0;
172 # include <WeatherCM/FGLocalWeatherDatabase.h>
177 #include "fg_init.hxx"
179 #include "fg_props.hxx"
180 #include "globals.hxx"
181 #include "splash.hxx"
182 #include "viewmgr.hxx"
183 #include "options.hxx"
184 #include "logger.hxx"
187 # include <console.h> // -dw- for command line dialog
191 FGEventMgr global_events;
193 // This is a record containing a bit of global housekeeping information
196 // Specify our current idle function state. This is used to run all
197 // our initializations out of the glutIdleLoop() so that we can get a
198 // splash screen up and running right away.
199 static int idle_state = 0;
200 static long global_multi_loop;
202 // fog constants. I'm a little nervous about putting actual code out
203 // here but it seems to work (?)
204 static const double m_log01 = -log( 0.01 );
205 static const double sqrt_m_log01 = sqrt( m_log01 );
206 static GLfloat fog_exp_density;
207 static GLfloat fog_exp2_density;
208 static GLfloat rwy_exp2_punch_through;
209 static GLfloat taxi_exp2_punch_through;
210 static GLfloat ground_exp2_punch_through;
212 #ifdef FG_NETWORK_OLK
213 ssgSelector *fgd_sel = NULL;
214 ssgTransform *fgd_pos = NULL;
220 #ifdef FG_USE_CLOUDS_3D
221 SkySceneLoader *sgClouds3d;
222 bool _bcloud_orig = true;
226 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
228 { 1.0f, 0.0f, 0.0f, 0.0f },
229 { 0.0f, 0.0f, -1.0f, 0.0f },
230 { 0.0f, 1.0f, 0.0f, 0.0f },
231 { 0.0f, 0.0f, 0.0f, 1.0f }
234 // The following defines flightgear options. Because glutlib will also
235 // want to parse its own options, those options must not be included here
236 // or they will get parsed by the main program option parser. Hence case
237 // is significant for any option added that might be in conflict with
240 // glutlib parses for:
242 // -direct (invalid in Win32)
246 // -indirect (invalid in Win32)
249 // Note that glutlib depends upon strings while this program's
250 // option parser wants only initial characters followed by numbers
255 ssgSimpleState *cloud3d_imposter_state;
256 ssgSimpleState *default_state;
257 ssgSimpleState *hud_and_panel;
258 ssgSimpleState *menus;
260 SGTimeStamp last_time_stamp;
261 SGTimeStamp current_time_stamp;
264 void fgBuildRenderStates( void ) {
265 default_state = new ssgSimpleState;
266 default_state->ref();
267 default_state->disable( GL_TEXTURE_2D );
268 default_state->enable( GL_CULL_FACE );
269 default_state->enable( GL_COLOR_MATERIAL );
270 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
271 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
272 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
273 default_state->disable( GL_BLEND );
274 default_state->disable( GL_ALPHA_TEST );
275 default_state->disable( GL_LIGHTING );
277 cloud3d_imposter_state = new ssgSimpleState;
278 cloud3d_imposter_state->ref();
279 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
280 cloud3d_imposter_state->enable( GL_CULL_FACE );
281 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
282 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
283 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
284 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
285 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
286 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
287 cloud3d_imposter_state->enable( GL_BLEND );
288 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
289 cloud3d_imposter_state->disable( GL_LIGHTING );
291 hud_and_panel = new ssgSimpleState;
292 hud_and_panel->ref();
293 hud_and_panel->disable( GL_CULL_FACE );
294 hud_and_panel->disable( GL_TEXTURE_2D );
295 hud_and_panel->disable( GL_LIGHTING );
296 hud_and_panel->enable( GL_BLEND );
298 menus = new ssgSimpleState;
300 menus->disable( GL_CULL_FACE );
301 menus->disable( GL_TEXTURE_2D );
302 menus->enable( GL_BLEND );
306 // fgInitVisuals() -- Initialize various GL/view parameters
307 void fgInitVisuals( void ) {
310 l = &cur_light_params;
312 #ifndef GLUT_WRONG_VERSION
313 // Go full screen if requested ...
314 if ( fgGetBool("/sim/startup/fullscreen") ) {
319 // If enabled, normal vectors specified with glNormal are scaled
320 // to unit length after transformation. Enabling this has
321 // performance implications. See the docs for glNormal.
322 // glEnable( GL_NORMALIZE );
324 glEnable( GL_LIGHTING );
325 glEnable( GL_LIGHT0 );
326 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
329 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
330 ssgGetLight( 0 ) -> setPosition( sunpos );
332 glFogi (GL_FOG_MODE, GL_EXP2);
333 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
334 (!fgGetBool("/sim/rendering/shading"))) {
335 // if fastest fog requested, or if flat shading force fastest
336 glHint ( GL_FOG_HINT, GL_FASTEST );
337 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
338 glHint ( GL_FOG_HINT, GL_NICEST );
340 if ( fgGetBool("/sim/rendering/wireframe") ) {
342 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
345 // This is the default anyways, but it can't hurt
346 glFrontFace ( GL_CCW );
349 // glEnable(GL_POINT_SMOOTH);
350 // glEnable(GL_LINE_SMOOTH);
351 // glEnable(GL_POLYGON_SMOOTH);
355 // For HiRes screen Dumps using Brian Pauls TR Library
356 void trRenderFrame( void ) {
358 if ( fgPanelVisible() ) {
359 GLfloat height = fgGetInt("/sim/startup/ysize");
361 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
362 * (height / 768.0) + 1;
363 glTranslatef( 0.0, view_h, 0.0 );
366 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
367 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
369 fgLIGHT *l = &cur_light_params;
371 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
372 l->adj_fog_color[2], l->adj_fog_color[3]);
374 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
376 // set the opengl state to known default values
377 default_state->force();
380 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
381 glFogi ( GL_FOG_MODE, GL_EXP2 );
382 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
384 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
385 // we only update GL_AMBIENT for our lights we will never get
386 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
387 // explicitely to black.
388 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
389 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
391 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
393 // texture parameters
394 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
395 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
397 // we need a white diffuse light for the phase of the moon
398 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
401 // draw the ssg scene
402 // return to the desired diffuse color
403 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
404 glEnable( GL_DEPTH_TEST );
405 ssgSetNearFar( scene_nearplane, scene_farplane );
406 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
409 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
410 ssgSetNearFar( scene_nearplane, scene_farplane );
411 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
413 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
415 if (fgGetBool("/environment/clouds/status"))
416 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
418 globals->get_model_mgr()->draw();
419 globals->get_aircraft_model()->draw();
423 // Update all Visuals (redraws anything graphics related)
424 void fgRenderFrame() {
426 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
427 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
429 // Process/manage pending events
430 global_events.update( delta_time_sec );
432 // static const SGPropertyNode *longitude
433 // = fgGetNode("/position/longitude-deg");
434 // static const SGPropertyNode *latitude
435 // = fgGetNode("/position/latitude-deg");
436 // static const SGPropertyNode *altitude
437 // = fgGetNode("/position/altitude-ft");
438 static const SGPropertyNode *groundlevel_nearplane
439 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
441 // Update the default (kludged) properties.
444 FGViewer *current__view = globals->get_current_view();
446 fgLIGHT *l = &cur_light_params;
447 static double last_visibility = -9999;
450 double actual_visibility;
451 if (fgGetBool("/environment/clouds/status"))
452 actual_visibility = thesky->get_visibility();
454 actual_visibility = fgGetDouble("/environment/visibility-m");
455 if ( actual_visibility != last_visibility ) {
456 last_visibility = actual_visibility;
458 fog_exp_density = m_log01 / actual_visibility;
459 fog_exp2_density = sqrt_m_log01 / actual_visibility;
460 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
461 if ( actual_visibility < 8000 ) {
462 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
463 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
465 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
466 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
471 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
472 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
473 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
474 // GLfloat mat_shininess[] = { 10.0 };
475 GLbitfield clear_mask;
477 if ( idle_state != 1000 ) {
478 // still initializing, draw the splash screen
479 if ( fgGetBool("/sim/startup/splash-screen") ) {
480 fgSplashUpdate(0.0, 1.0);
482 // Keep resetting sim time while the sim is initializing
483 globals->set_sim_time_sec( 0.0 );
484 SGAnimation::set_sim_time_sec( 0.0 );
486 // idle_state is now 1000 meaning we've finished all our
487 // initializations and are running the main loop, so this will
488 // now work without seg faulting the system.
490 // calculate our current position in cartesian space
491 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
494 fgReshape( fgGetInt("/sim/startup/xsize"),
495 fgGetInt("/sim/startup/ysize") );
497 if ( fgGetBool("/sim/rendering/clouds3d") ) {
498 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
499 cloud3d_imposter_state->force();
501 glColor4f( 1.0, 1.0, 1.0, 1.0 );
502 glEnable(GL_DEPTH_TEST);
504 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
506 #ifdef FG_USE_CLOUDS_3D
507 if ( _bcloud_orig ) {
508 Point3D c = globals->get_scenery()->get_center();
509 sgClouds3d->Set_Cloud_Orig( &c );
510 _bcloud_orig = false;
512 sgClouds3d->Update( current__view->get_absolute_view_pos() );
514 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
515 glDisable(GL_DEPTH_TEST);
518 clear_mask = GL_DEPTH_BUFFER_BIT;
519 if ( fgGetBool("/sim/rendering/wireframe") ) {
520 clear_mask |= GL_COLOR_BUFFER_BIT;
523 if ( fgGetBool("/sim/rendering/skyblend") ) {
524 if ( fgGetBool("/sim/rendering/textures") ) {
525 // glClearColor(black[0], black[1], black[2], black[3]);
526 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
527 l->adj_fog_color[2], l->adj_fog_color[3]);
528 clear_mask |= GL_COLOR_BUFFER_BIT;
531 glClearColor(l->sky_color[0], l->sky_color[1],
532 l->sky_color[2], l->sky_color[3]);
533 clear_mask |= GL_COLOR_BUFFER_BIT;
535 glClear( clear_mask );
537 // Tell GL we are switching to model view parameters
539 // I really should create a derived ssg node or use a call
540 // back or something so that I can draw the sky within the
541 // ssgCullAndDraw() function, but for now I just mimic what
542 // ssg does to set up the model view matrix
543 glMatrixMode(GL_MODELVIEW);
545 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
547 // set the opengl state to known default values
548 default_state->force();
550 // update fog params if visibility has changed
551 double visibility_meters = fgGetDouble("/environment/visibility-m");
552 thesky->set_visibility(visibility_meters);
554 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
555 ( global_multi_loop * fgGetInt("/sim/speed-up") )
556 / (double)fgGetInt("/sim/model-hz") );
558 // Set correct opengl fog density
559 glFogf (GL_FOG_DENSITY, fog_exp2_density);
561 // update the sky dome
562 if ( fgGetBool("/sim/rendering/skyblend") ) {
564 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
565 << cur_light_params.sky_color[0] << " "
566 << cur_light_params.sky_color[1] << " "
567 << cur_light_params.sky_color[2] << " "
568 << cur_light_params.sky_color[3] );
569 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
570 << cur_light_params.fog_color[0] << " "
571 << cur_light_params.fog_color[1] << " "
572 << cur_light_params.fog_color[2] << " "
573 << cur_light_params.fog_color[3] );
574 SG_LOG( SG_GENERAL, SG_BULK,
575 " sun_angle = " << cur_light_params.sun_angle
576 << " moon_angle = " << cur_light_params.moon_angle );
578 thesky->repaint( cur_light_params.sky_color,
579 cur_light_params.adj_fog_color,
580 cur_light_params.cloud_color,
581 cur_light_params.sun_angle,
582 cur_light_params.moon_angle,
583 globals->get_ephem()->getNumPlanets(),
584 globals->get_ephem()->getPlanets(),
585 globals->get_ephem()->getNumStars(),
586 globals->get_ephem()->getStars() );
589 SG_LOG( SG_GENERAL, SG_BULK,
590 "thesky->reposition( view_pos = " << view_pos[0] << " "
591 << view_pos[1] << " " << view_pos[2] );
592 SG_LOG( SG_GENERAL, SG_BULK,
593 " zero_elev = " << zero_elev[0] << " "
594 << zero_elev[1] << " " << zero_elev[2]
595 << " lon = " << cur_fdm_state->get_Longitude()
596 << " lat = " << cur_fdm_state->get_Latitude() );
597 SG_LOG( SG_GENERAL, SG_BULK,
598 " sun_rot = " << cur_light_params.sun_rotation
599 << " gst = " << SGTime::cur_time_params->getGst() );
600 SG_LOG( SG_GENERAL, SG_BULK,
601 " sun ra = " << globals->get_ephem()->getSunRightAscension()
602 << " sun dec = " << globals->get_ephem()->getSunDeclination()
603 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
604 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
607 // The sun and moon distances are scaled down versions
608 // of the actual distance to get both the moon and the sun
609 // within the range of the far clip plane.
610 // Moon distance: 384,467 kilometers
611 // Sun distance: 150,000,000 kilometers
612 double sun_horiz_eff, moon_horiz_eff;
613 if (fgGetBool("/sim/rendering/horizon-effect")) {
614 sun_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.sun_angle*2)/2,0.33)/3;
615 moon_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.moon_angle*2)/2,0.33)/3;
617 sun_horiz_eff = moon_horiz_eff = 1.0;
619 thesky->reposition( current__view->get_view_pos(),
620 current__view->get_zero_elev(),
621 current__view->get_world_up(),
622 current__view->getLongitude_deg()
623 * SGD_DEGREES_TO_RADIANS,
624 current__view->getLatitude_deg()
625 * SGD_DEGREES_TO_RADIANS,
626 current__view->getAltitudeASL_ft()
628 cur_light_params.sun_rotation,
629 globals->get_time_params()->getGst(),
630 globals->get_ephem()->getSunRightAscension(),
631 globals->get_ephem()->getSunDeclination(),
632 50000.0 * sun_horiz_eff,
633 globals->get_ephem()->getMoonRightAscension(),
634 globals->get_ephem()->getMoonDeclination(),
635 40000.0 * moon_horiz_eff );
638 glEnable( GL_DEPTH_TEST );
639 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
641 glFogi( GL_FOG_MODE, GL_EXP2 );
642 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
645 // set sun/lighting parameters
646 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
648 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
649 // we only update GL_AMBIENT for our lights we will never get
650 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
651 // explicitely to black.
652 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
654 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
655 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
656 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular );
658 // texture parameters
659 // glEnable( GL_TEXTURE_2D );
660 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
661 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
663 // glMatrixMode( GL_PROJECTION );
665 ssgSetFOV( current__view->get_h_fov(),
666 current__view->get_v_fov() );
669 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
670 - globals->get_scenery()->get_cur_elev();
673 scene_nearplane = 10.0f;
674 scene_farplane = 120000.0f;
676 scene_nearplane = groundlevel_nearplane->getDoubleValue();
677 scene_farplane = 120000.0f;
680 ssgSetNearFar( scene_nearplane, scene_farplane );
682 // $$$ begin - added VS Renganthan 17 Oct 2K
685 // $$$ end - added VS Renganthan 17 Oct 2K
687 # ifdef FG_NETWORK_OLK
688 if ( fgGetBool("/sim/networking/network-olk") ) {
690 other = head->next; /* put listpointer to start */
691 while ( other != tail) { /* display all except myself */
692 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
693 other->fgd_sel->select(1);
694 sgSetCoord( &fgdpos, other->sgFGD_COORD );
695 other->fgd_pos->setTransform( &fgdpos );
700 // fgd_sel->select(1);
701 // sgCopyMat4( sgTUX, current_view.sgVIEW);
703 // sgSetCoord( &fgdpos, sgFGD_VIEW );
704 // fgd_pos->setTransform( &fgdpos);
709 // Update any multiplayer models
710 globals->get_multiplayer_rx_mgr()->Update();
713 if ( fgGetBool("/sim/rendering/skyblend") &&
714 fgGetBool("/sim/rendering/draw-otw") )
716 // draw the sky backdrop
718 // we need a white diffuse light for the phase of the moon
719 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
723 // return to the desired diffuse color
724 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
727 // draw the ssg scene
728 glEnable( GL_DEPTH_TEST );
730 ssgSetNearFar( scene_nearplane, scene_farplane );
732 if ( fgGetBool("/sim/rendering/wireframe") ) {
734 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
736 if ( fgGetBool("/sim/rendering/draw-otw") ) {
737 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
740 // This is a bit kludgy. Every 200 frames, do an extra
741 // traversal of the scene graph without drawing anything, but
742 // with the field-of-view set to 360x360 degrees. This
743 // ensures that out-of-range random objects that are not in
744 // the current view frustum will still be freed properly.
745 static int counter = 0;
747 if (counter == 200) {
750 // No need to put the near plane too close;
751 // this way, at least the aircraft can be
753 f.setNearFar(1000, 1000000);
755 ssgGetModelviewMatrix(m);
756 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
760 // change state for lighting here
762 // draw runway lighting
763 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
764 ssgSetNearFar( scene_nearplane, scene_farplane );
766 if (fgGetBool("/sim/rendering/enhanced-lighting")) {
768 // Enable states for drawing points with GL_extension
769 glEnable(GL_POINT_SMOOTH);
771 if ( fgGetBool("/sim/rendering/distance-attenuation") &&
772 glPointParameterIsSupported )
774 // Enable states for drawing points with GL_extension
775 glEnable(GL_POINT_SMOOTH);
777 float quadratic[3] = {1.0, 0.001, 0.0000001};
778 // makes the points fade as they move away
779 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
780 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
785 // blending function for runway lights
786 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
789 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
790 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
791 glEnable(GL_TEXTURE_GEN_S);
792 glEnable(GL_TEXTURE_GEN_T);
793 glPolygonMode(GL_FRONT, GL_POINT);
795 // draw runway lighting
796 if ( fgGetBool("/sim/rendering/draw-otw") ) {
797 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
800 // change punch through and then draw taxi lighting
801 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
803 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
804 // glFogfv ( GL_FOG_COLOR, taxi_fog );
805 if ( fgGetBool("/sim/rendering/draw-otw") ) {
806 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
810 glPolygonMode(GL_FRONT, GL_FILL);
811 glDisable(GL_TEXTURE_GEN_S);
812 glDisable(GL_TEXTURE_GEN_T);
814 //static int _frame_count = 0;
815 //if (_frame_count % 30 == 0) {
816 // printf("SSG: %s\n", ssgShowStats());
824 if (fgGetBool("/sim/rendering/enhanced-lighting")) {
825 if ( fgGetBool("/sim/rendering/distance-attenuation") &&
826 glPointParameterIsSupported )
828 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
829 default_attenuation);
833 glDisable(GL_POINT_SMOOTH);
836 // draw ground lighting
837 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
838 if ( fgGetBool("/sim/rendering/draw-otw") ) {
839 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
842 if ( fgGetBool("/sim/rendering/skyblend") ) {
843 // draw the sky cloud layers
844 if ( fgGetBool("/environment/clouds/status") &&
845 fgGetBool("/sim/rendering/draw-otw") )
847 thesky->postDraw( cur_fdm_state->get_Altitude()
848 * SG_FEET_TO_METER );
852 if ( fgGetBool("/sim/rendering/clouds3d") &&
853 fgGetBool("/sim/rendering/draw-otw") )
856 glDisable( GL_LIGHTING );
857 // cout << "drawing new clouds" << endl;
859 glEnable(GL_DEPTH_TEST);
861 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
864 glEnable( GL_TEXTURE_2D );
865 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
866 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
867 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
868 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
871 #ifdef FG_USE_CLOUDS_3D
872 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
875 glEnable( GL_LIGHTING );
876 glEnable( GL_DEPTH_TEST );
877 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
880 if ( fgGetBool("/sim/rendering/draw-otw") ) {
881 globals->get_model_mgr()->draw();
882 globals->get_aircraft_model()->draw();
885 // display HUD && Panel
887 glDisable( GL_DEPTH_TEST );
888 // glDisable( GL_CULL_FACE );
889 // glDisable( GL_TEXTURE_2D );
891 // update the controls subsystem
892 globals->get_controls()->update(delta_time_sec);
894 hud_and_panel->apply();
897 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
898 // This only works properly if called before the panel call
899 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
900 globals->get_ATC_display()->update(delta_time_sec);
902 // update the panel subsystem
903 if ( globals->get_current_panel() != NULL ) {
904 globals->get_current_panel()->update(delta_time_sec);
908 // We can do translucent menus, so why not. :-)
910 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
912 // glDisable ( GL_BLEND ) ;
914 glEnable( GL_DEPTH_TEST );
917 // Fade out the splash screen over the first three seconds.
918 double t = globals->get_sim_time_sec();
920 fgSplashUpdate(0.0, 1.0);
921 } else if ( t <= 3.0) {
922 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
930 // Update internal time dependent calculations (i.e. flight model)
931 // FIXME: this distinction is obsolete; all subsystems now get delta
933 void fgUpdateTimeDepCalcs() {
934 static bool inited = false;
936 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
938 fgLIGHT *l = &cur_light_params;
940 // Initialize the FDM here if it hasn't been and if we have a
941 // scenery elevation hit.
943 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
944 // << " cur_elev = " << scenery.get_cur_elev() << endl;
946 if ( !cur_fdm_state->get_inited() &&
947 globals->get_scenery()->get_cur_elev() > -9990 )
949 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
950 cur_fdm_state->init();
951 if ( cur_fdm_state->get_bound() ) {
952 cur_fdm_state->unbind();
954 cur_fdm_state->bind();
957 // conceptually, the following block could be done for each fdm
959 if ( !cur_fdm_state->get_inited() ) {
960 // do nothing, fdm isn't inited yet
962 // we have been inited, and we are good to go ...
968 globals->get_autopilot()->update(delta_time_sec);
969 cur_fdm_state->update(delta_time_sec);
972 globals->get_model_mgr()->update(delta_time_sec);
973 globals->get_aircraft_model()->update(delta_time_sec);
975 // update the view angle
976 globals->get_viewmgr()->update(delta_time_sec);
980 // Update solar system
981 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
982 globals->get_time_params()->getLst(),
983 cur_fdm_state->get_Latitude() );
985 // Update radio stack model
986 current_radiostack->update(delta_time_sec);
990 void fgInitTimeDepCalcs( void ) {
995 static const double alt_adjust_ft = 3.758099;
996 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
999 // What should we do when we have nothing else to do? Let's get ready
1000 // for the next move and update the display?
1001 static void fgMainLoop( void ) {
1003 static const SGPropertyNode *longitude
1004 = fgGetNode("/position/longitude-deg");
1005 static const SGPropertyNode *latitude
1006 = fgGetNode("/position/latitude-deg");
1007 static const SGPropertyNode *altitude
1008 = fgGetNode("/position/altitude-ft");
1009 static const SGPropertyNode *clock_freeze
1010 = fgGetNode("/sim/freeze/clock", true);
1011 static const SGPropertyNode *cur_time_override
1012 = fgGetNode("/sim/time/cur-time-override", true);
1014 // Update the elapsed time.
1015 static bool first_time = true;
1017 last_time_stamp.stamp();
1021 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1022 if ( throttle_hz > 0.0 ) {
1023 // simple frame rate throttle
1024 double dt = 1000000.0 / throttle_hz;
1025 current_time_stamp.stamp();
1026 while ( current_time_stamp - last_time_stamp < dt ) {
1027 current_time_stamp.stamp();
1030 // run as fast as the app will go
1031 current_time_stamp.stamp();
1034 delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
1035 if ( clock_freeze->getBoolValue() ) {
1038 last_time_stamp = current_time_stamp;
1039 globals->inc_sim_time_sec( delta_time_sec );
1040 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1042 static long remainder = 0;
1044 #ifdef FANCY_FRAME_COUNTER
1048 static time_t last_time = 0;
1049 static int frames = 0;
1050 #endif // FANCY_FRAME_COUNTER
1052 SGTime *t = globals->get_time_params();
1054 sglog().setLogLevels( SG_ALL, (sgDebugPriority)fgGetInt("/sim/log-level") );
1055 sglog().setLogLevels( SG_ALL, SG_INFO );
1057 SGLocation * acmodel_location = 0;
1058 if(cur_fdm_state->getACModel() != 0) {
1059 acmodel_location = (SGLocation *) cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
1062 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1063 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1065 #ifdef FG_NETWORK_OLK
1066 if ( fgGetBool("/sim/networking/network-olk") ) {
1067 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
1068 // printf("FGD: Netupdate\n");
1069 fgd_send_com( "A", FGFS_host); // Send Mat4 data
1070 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
1075 #if defined( ENABLE_PLIB_JOYSTICK )
1076 // Read joystick and update control settings
1077 // if ( fgGetString("/sim/control-mode") == "joystick" )
1079 // fgJoystickRead();
1081 #elif defined( ENABLE_GLUT_JOYSTICK )
1082 // Glut joystick support works by feeding a joystick handler
1083 // function to glut. This is taken care of once in the joystick
1084 // init routine and we don't have to worry about it again.
1087 // Fix elevation. I'm just sticking this here for now, it should
1088 // probably move eventually
1090 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1091 scenery.get_cur_elev(),
1092 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1093 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1095 // Curt is this code used? I don't see any problems when I comment it out.
1096 if ( acmodel_location != 0 ) {
1097 if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
1098 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
1099 (acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0) ) {
1100 // now set aircraft altitude above ground
1101 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
1102 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1103 acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0,
1104 acmodel_location->get_cur_elev_m() + alt_adjust_m );
1105 cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m()
1106 + alt_adjust_m) * SG_METER_TO_FEET );
1107 SG_LOG( SG_ALL, SG_DEBUG,
1108 "<*> resetting altitude to "
1109 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1114 // End of code in question. (see Curt is this code used? above)
1116 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1117 scenery.get_cur_elev(),
1118 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1119 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1121 // cout << "Warp = " << globals->get_warp() << endl;
1124 static bool last_clock_freeze = false;
1126 if ( clock_freeze->getBoolValue() ) {
1127 // clock freeze requested
1128 if ( cur_time_override->getLongValue() == 0 ) {
1129 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1130 globals->set_warp( 0 );
1133 // no clock freeze requested
1134 if ( last_clock_freeze == true ) {
1135 // clock just unfroze, let's set warp as the difference
1136 // between frozen time and current time so we don't get a
1137 // time jump (and corresponding sky object and lighting
1139 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1140 fgSetLong( "/sim/time/cur-time-override", 0 );
1142 if ( globals->get_warp_delta() != 0 ) {
1143 globals->inc_warp( globals->get_warp_delta() );
1147 last_clock_freeze = clock_freeze->getBoolValue();
1149 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1150 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1151 cur_time_override->getLongValue(),
1152 globals->get_warp() );
1154 if ( globals->get_warp_delta() != 0 ) {
1155 fgUpdateSkyAndLightingParams();
1158 // update magvar model
1159 globals->get_mag()->update( longitude->getDoubleValue()
1160 * SGD_DEGREES_TO_RADIANS,
1161 latitude->getDoubleValue()
1162 * SGD_DEGREES_TO_RADIANS,
1163 altitude->getDoubleValue() * SG_FEET_TO_METER,
1164 globals->get_time_params()->getJD() );
1166 // Get elapsed time (in usec) for this past frame
1167 elapsed = fgGetTimeInterval();
1168 SG_LOG( SG_ALL, SG_DEBUG,
1169 "Elapsed time interval is = " << elapsed
1170 << ", previous remainder is = " << remainder );
1172 // Calculate frame rate average
1173 #ifdef FANCY_FRAME_COUNTER
1174 /* old fps calculation */
1175 if ( elapsed > 0 ) {
1178 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1179 tmp = general.get_frame(i);
1181 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1182 general.set_frame(i+1,tmp);
1184 tmp = 1000000.0 / (float)elapsed;
1185 general.set_frame(0,tmp);
1186 // printf("frame[0] = %.2f\n", general.frames[0]);
1188 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1189 // printf("ave = %.2f\n", general.frame_rate);
1192 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1193 general.set_frame_rate( frames );
1194 fgSetInt("/sim/frame-rate", frames);
1195 SG_LOG( SG_ALL, SG_DEBUG,
1196 "--> Frame rate is = " << general.get_frame_rate() );
1199 last_time = t->get_cur_time();
1203 // Run ATC subsystem
1204 if (fgGetBool("/sim/ATC/enabled"))
1205 globals->get_ATC_mgr()->update(delta_time_sec);
1207 // Run the AI subsystem
1208 if (fgGetBool("/sim/ai-traffic/enabled"))
1209 globals->get_AI_mgr()->update(delta_time_sec);
1213 // Calculate model iterations needed for next frame
1214 elapsed += remainder;
1216 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1217 fgGetInt("/sim/model-hz"));
1218 remainder = elapsed - ( (global_multi_loop*1000000) /
1219 fgGetInt("/sim/model-hz") );
1220 SG_LOG( SG_ALL, SG_DEBUG,
1221 "Model iterations needed = " << global_multi_loop
1222 << ", new remainder = " << remainder );
1224 // chop max interations to something reasonable if the sim was
1225 // delayed for an excesive amount of time
1226 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1227 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1232 if ( global_multi_loop > 0 ) {
1233 fgUpdateTimeDepCalcs();
1235 SG_LOG( SG_ALL, SG_DEBUG,
1236 "Elapsed time is zero ... we're zinging" );
1239 // Do any I/O channel work that might need to be done
1240 globals->get_io()->update( delta_time_sec );
1242 // see if we need to load any deferred-load textures
1243 globals->get_matlib()->load_next_deferred();
1245 // Run audio scheduler
1246 #ifdef ENABLE_AUDIO_SUPPORT
1247 if ( fgGetBool("/sim/sound/audible")
1248 && globals->get_soundmgr()->is_working() ) {
1249 globals->get_soundmgr()->update( delta_time_sec );
1253 globals->get_subsystem_mgr()->update(delta_time_sec);
1256 // Tile Manager updates - see if we need to load any new scenery tiles.
1257 // this code ties together the fdm, viewer and scenery classes...
1258 // we may want to move this to it's own class at some point
1260 double visibility_meters = fgGetDouble("/environment/visibility-m");
1261 FGViewer *current_view = globals->get_current_view();
1263 // update tile manager for FDM...
1264 // ...only if location is different than the viewer (to avoid duplicating effort)
1265 if( acmodel_location != current_view->getSGLocation() ) {
1266 if( acmodel_location != 0 ) {
1267 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1268 visibility_meters );
1269 globals->get_tile_mgr()->
1270 update( acmodel_location, visibility_meters,
1271 acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1272 // save results of update in SGLocation for fdm...
1273 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1275 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1278 set_tile_center( globals->get_scenery()->get_next_center() );
1282 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1283 visibility_meters );
1284 // update tile manager for view...
1285 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1286 // after the FDM's until all of Flight Gear code references the viewer's location
1287 // for elevation instead of the "scenery's" current elevation.
1288 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1289 globals->get_tile_mgr()->update( view_location, visibility_meters,
1290 current_view->get_absolute_view_pos() );
1291 // save results of update in SGLocation for fdm...
1292 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1293 current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1295 current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1297 // If fdm location is same as viewer's then we didn't do the update for fdm location
1298 // above so we need to save the viewer results in the fdm SGLocation as well...
1299 if( acmodel_location == current_view->getSGLocation() ) {
1300 if( acmodel_location != 0 ) {
1301 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1302 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1304 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1308 // END Tile Manager udpates
1313 SG_LOG( SG_ALL, SG_DEBUG, "" );
1317 // This is the top level master main function that is registered as
1318 // our idle funciton
1320 // The first few passes take care of initialization things (a couple
1321 // per pass) and once everything has been initialized fgMainLoop from
1324 static void fgIdleFunction ( void ) {
1325 // printf("idle state == %d\n", idle_state);
1327 if ( idle_state == 0 ) {
1328 // Initialize the splash screen right away
1329 if ( fgGetBool("/sim/startup/splash-screen") ) {
1334 } else if ( idle_state == 1 ) {
1335 // Initialize audio support
1336 #ifdef ENABLE_AUDIO_SUPPORT
1338 // Start the intro music
1339 if ( fgGetBool("/sim/startup/intro-music") ) {
1340 SGPath mp3file( globals->get_fg_root() );
1341 mp3file.append( "Sounds/intro.mp3" );
1343 SG_LOG( SG_GENERAL, SG_INFO,
1344 "Starting intro music: " << mp3file.str() );
1346 #if defined( __CYGWIN__ )
1347 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1348 #elif defined( WIN32 )
1349 string command = "start /m " + mp3file.str();
1351 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1354 system ( command.c_str() );
1359 } else if ( idle_state == 2 ) {
1360 // These are a few miscellaneous things that aren't really
1361 // "subsystems" but still need to be initialized.
1364 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1365 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1370 } else if ( idle_state == 3 ) {
1371 // This is the top level init routine which calls all the
1372 // other subsystem initialization routines. If you are adding
1373 // a subsystem to flightgear, its initialization call should
1374 // located in this routine.
1375 if( !fgInitSubsystems()) {
1376 SG_LOG( SG_GENERAL, SG_ALERT,
1377 "Subsystem initializations failed ..." );
1382 } else if ( idle_state == 4 ) {
1383 // setup OpenGL view parameters
1386 // Read the list of available aircrafts
1390 } else if ( idle_state == 5 ) {
1393 } else if ( idle_state == 6 ) {
1397 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1398 fgReshape( fgGetInt("/sim/startup/xsize"),
1399 fgGetInt("/sim/startup/ysize") );
1402 if ( idle_state == 1000 ) {
1403 // We've finished all our initialization steps, from now on we
1404 // run the main loop.
1406 glutIdleFunc(fgMainLoop);
1408 if ( fgGetBool("/sim/startup/splash-screen") ) {
1409 fgSplashUpdate(0.0, 1.0);
1414 // options.cxx needs to see this for toggle_panel()
1415 // Handle new window size or exposure
1416 void fgReshape( int width, int height ) {
1419 if ( (!fgGetBool("/sim/virtual-cockpit"))
1420 && fgPanelVisible() && idle_state == 1000 ) {
1421 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1422 globals->get_current_panel()->getYOffset()) / 768.0);
1428 FGViewMgr *viewmgr = globals->get_viewmgr();
1429 for ( int i = 0; i < viewmgr->size(); ++i ) {
1430 viewmgr->get_view(i)->
1431 set_aspect_ratio((float)view_h / (float)width);
1434 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1436 fgSetInt("/sim/startup/xsize", width);
1437 fgSetInt("/sim/startup/ysize", height);
1438 guiInitMouse(width, height);
1440 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1441 viewmgr->get_current_view()->get_v_fov() );
1445 #ifdef FG_USE_CLOUDS_3D
1446 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1447 viewmgr->get_current_view()->get_v_fov() );
1452 // Initialize GLUT and define a main window
1453 static bool fgGlutInit( int *argc, char **argv ) {
1455 #if !defined( macintosh )
1456 // GLUT will extract all glut specific options so later on we only
1457 // need wory about our own.
1458 glutInit(argc, argv);
1461 // Define Display Parameters. Clouds3d works best with --bpp32 option
1462 if ( fgGetBool("/sim/rendering/clouds3d") ) {
1463 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1465 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1468 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1469 fgGetInt("/sim/startup/xsize") << "x"
1470 << fgGetInt("/sim/startup/ysize") );
1472 // Define initial window size
1473 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1474 fgGetInt("/sim/startup/ysize") );
1476 // Initialize windows
1477 if ( !fgGetBool("/sim/startup/game-mode")) {
1478 // Open the regular window
1479 glutCreateWindow("FlightGear");
1480 #ifndef GLUT_WRONG_VERSION
1482 // Open the cool new 'game mode' window
1483 char game_mode_str[256];
1484 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1485 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1486 #ifndef ENUM_CURRENT_SETTINGS
1487 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1488 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1492 dm.dmSize = sizeof(DEVMODE);
1493 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1494 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1495 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1496 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1497 fgGetInt("/sim/startup/ysize") );
1498 sprintf( game_mode_str, "%dx%d:%d@%d",
1502 dm.dmDisplayFrequency );
1504 // Open the cool new 'game mode' window
1505 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1506 fgGetInt("/sim/startup/xsize"),
1507 fgGetInt("/sim/startup/ysize"),
1508 fgGetInt("/sim/rendering/bits-per-pixel"));
1510 #endif // HAVE_WINDOWS_H
1511 SG_LOG( SG_GENERAL, SG_INFO,
1512 "game mode params = " << game_mode_str );
1513 glutGameModeString( game_mode_str );
1514 glutEnterGameMode();
1515 #endif // GLUT_WRONG_VERSION
1518 // This seems to be the absolute earliest in the init sequence
1519 // that these calls will return valid info. Too bad it's after
1520 // we've already created and sized out window. :-(
1521 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1522 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1523 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1524 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1527 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1528 general.set_glMaxTexSize( tmp );
1529 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1531 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1532 general.set_glDepthBits( tmp );
1533 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1539 // Initialize GLUT event handlers
1540 static bool fgGlutInitEvents( void ) {
1541 // call fgReshape() on window resizes
1542 glutReshapeFunc( fgReshape );
1544 // keyboard and mouse callbacks are set in FGInput::init
1546 // call fgMainLoop() whenever there is
1547 // nothing else to do
1548 glutIdleFunc( fgIdleFunction );
1551 glutDisplayFunc( fgRenderFrame );
1556 // Main top level initialization
1557 static bool fgMainInit( int argc, char **argv ) {
1559 #if defined( macintosh )
1560 freopen ("stdout.txt", "w", stdout );
1561 freopen ("stderr.txt", "w", stderr );
1562 argc = ccommand( &argv );
1565 // set default log levels
1566 sglog().setLogLevels( SG_ALL, SG_INFO );
1569 #ifdef FLIGHTGEAR_VERSION
1570 version = FLIGHTGEAR_VERSION;
1572 version = "unknown version";
1574 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1576 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1578 // Allocate global data structures. This needs to happen before
1579 // we parse command line options
1581 globals = new FGGlobals;
1583 // seed the random number generater
1586 SGRoute *route = new SGRoute;
1587 globals->set_route( route );
1589 FGControls *controls = new FGControls;
1590 globals->set_controls( controls );
1592 string_list *col = new string_list;
1593 globals->set_channel_options_list( col );
1595 // Scan the config file(s) and command line options to see if
1596 // fg_root was specified (ignore all other options for now)
1597 fgInitFGRoot(argc, argv);
1599 // Check for the correct base package version
1600 static char required_version[] = "0.9.2";
1601 string base_version = fgBasePackageVersion();
1602 if ( !(base_version == required_version) ) {
1603 // tell the operator how to use this application
1605 cerr << endl << "Base package check failed ... " \
1606 << "Found version " << base_version << " at: " \
1607 << globals->get_fg_root() << endl;
1608 cerr << "Please upgrade to version: " << required_version << endl;
1612 // Initialize the Aircraft directory to "" (UIUC)
1615 // Load the configuration parameters. (Command line options
1616 // overrides config file options. Config file options override
1618 if ( !fgInitConfig(argc, argv) ) {
1619 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1623 // Initialize the Window/Graphics environment.
1624 if( !fgGlutInit(&argc, argv) ) {
1625 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1629 // Initialize the various GLUT Event Handlers.
1630 if( !fgGlutInitEvents() ) {
1631 SG_LOG( SG_GENERAL, SG_ALERT,
1632 "GLUT event handler initialization failed ..." );
1636 // Initialize plib net interface
1637 netInit( &argc, argv );
1639 // Initialize ssg (from plib). Needs to come before we do any
1640 // other ssg stuff, but after opengl/glut has been initialized.
1643 // Initialize the user interface (we need to do this before
1644 // passing off control to glut and before fgInitGeneral to get our
1648 // Read the list of available aircrafts
1651 #ifdef GL_EXT_texture_lod_bias
1652 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1655 // get the address of our OpenGL extensions
1656 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1658 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1659 glPointParameterIsSupported = true;
1660 glPointParameterfPtr = (glPointParameterfProc)
1661 SGLookupFunction("glPointParameterfEXT");
1662 glPointParameterfvPtr = (glPointParameterfvProc)
1663 SGLookupFunction("glPointParameterfvEXT");
1665 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1666 glPointParameterIsSupported = true;
1667 glPointParameterfPtr = (glPointParameterfProc)
1668 SGLookupFunction("glPointParameterfARB");
1669 glPointParameterfvPtr = (glPointParameterfvProc)
1670 SGLookupFunction("glPointParameterfvARB");
1672 glPointParameterIsSupported = false;
1675 // based on the requested presets, calculate the true starting
1680 SGTime *t = fgInitTime();
1681 globals->set_time_params( t );
1683 // Do some quick general initializations
1684 if( !fgInitGeneral()) {
1685 SG_LOG( SG_GENERAL, SG_ALERT,
1686 "General initializations failed ..." );
1690 SGPath modelpath( globals->get_fg_root() );
1691 ssgModelPath( (char *)modelpath.c_str() );
1693 ////////////////////////////////////////////////////////////////////
1694 // Initialize the property-based built-in commands
1695 ////////////////////////////////////////////////////////////////////
1698 ////////////////////////////////////////////////////////////////////
1699 // Initialize the material manager
1700 ////////////////////////////////////////////////////////////////////
1701 globals->set_matlib( new SGMaterialLib );
1703 globals->set_model_lib(new SGModelLib);
1705 ////////////////////////////////////////////////////////////////////
1706 // Initialize the TG scenery subsystem.
1707 ////////////////////////////////////////////////////////////////////
1708 globals->set_scenery( new FGScenery );
1709 globals->get_scenery()->init();
1710 globals->get_scenery()->bind();
1711 globals->set_tile_mgr( new FGTileMgr );
1713 ////////////////////////////////////////////////////////////////////
1714 // Initialize the general model subsystem.
1715 ////////////////////////////////////////////////////////////////////
1716 globals->set_model_mgr(new FGModelMgr);
1717 globals->get_model_mgr()->init();
1718 globals->get_model_mgr()->bind();
1720 ////////////////////////////////////////////////////////////////////
1721 // Initialize the 3D aircraft model subsystem (has a dependency on
1722 // the scenery subsystem.)
1723 ////////////////////////////////////////////////////////////////////
1724 globals->set_aircraft_model(new FGAircraftModel);
1725 globals->get_aircraft_model()->init();
1726 globals->get_aircraft_model()->bind();
1728 ////////////////////////////////////////////////////////////////////
1729 // Initialize the view manager subsystem.
1730 ////////////////////////////////////////////////////////////////////
1732 FGViewMgr *viewmgr = new FGViewMgr;
1733 globals->set_viewmgr( viewmgr );
1738 // Initialize the sky
1739 SGPath ephem_data_path( globals->get_fg_root() );
1740 ephem_data_path.append( "Astro" );
1741 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1742 ephem->update( globals->get_time_params()->getMjd(),
1743 globals->get_time_params()->getLst(),
1745 globals->set_ephem( ephem );
1747 // TODO: move to environment mgr
1749 SGPath texture_path(globals->get_fg_root());
1750 texture_path.append("Textures");
1751 texture_path.append("Sky");
1752 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1753 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1754 thesky->add_cloud_layer(layer);
1758 SGPath sky_tex_path( globals->get_fg_root() );
1759 sky_tex_path.append( "Textures" );
1760 sky_tex_path.append( "Sky" );
1761 thesky->texture_path( sky_tex_path.str() );
1763 // The sun and moon diameters are scaled down numbers of the
1764 // actual diameters. This was needed to fit bot the sun and the
1765 // moon within the distance to the far clip plane.
1766 // Moon diameter: 3,476 kilometers
1767 // Sun diameter: 1,390,000 kilometers
1768 thesky->build( 80000.0, 80000.0,
1770 globals->get_ephem()->getNumPlanets(),
1771 globals->get_ephem()->getPlanets(),
1772 globals->get_ephem()->getNumStars(),
1773 globals->get_ephem()->getStars() );
1775 // Initialize MagVar model
1776 SGMagVar *magvar = new SGMagVar();
1777 globals->set_mag( magvar );
1779 // airport = new ssgBranch;
1780 // airport->setName( "Airport Lighting" );
1781 // lighting->addKid( airport );
1787 #ifdef FG_NETWORK_OLK
1788 // Do the network intialization
1789 if ( fgGetBool("/sim/networking/network-olk") ) {
1790 printf("Multipilot mode %s\n",
1791 fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1795 // build our custom render states
1796 fgBuildRenderStates();
1798 // pass control off to the master GLUT event handler
1801 // we never actually get here ... but to avoid compiler warnings,
1807 // $$$ end - added VS Renganathan, 15 Oct 2K
1808 // - added Venky , 12 Nov 2K
1810 #if defined(__linux__) && defined(__i386__)
1812 static void handleFPE (int);
1817 fpu_control_t fpe_flags = 0;
1818 _FPU_GETCW(fpe_flags);
1819 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1820 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1821 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1822 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1823 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1824 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1825 _FPU_SETCW(fpe_flags);
1826 signal(SIGFPE, handleFPE);
1833 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1846 short CPSGetCurrentProcess(PSN *psn);
1847 short CPSSetProcessName (PSN *psn, char *processname);
1848 short CPSEnableForegroundOperation(PSN *psn, int _arg2, int _arg3, int _arg4, int _arg5);
1849 short CPSSetFrontProcess(PSN *psn);
1852 #define CPSEnableFG(psn) CPSEnableForegroundOperation(psn,0x03,0x3C,0x2C,0x1103)
1856 // Main entry point; catch any exceptions that have made it this far.
1857 int main ( int argc, char **argv ) {
1859 // Enable floating-point exceptions for Linux/x86
1860 #if defined(__linux__) && defined(__i386__)
1864 // Enable floating-point exceptions for Windows
1865 #if defined( _MSC_VER ) && defined( DEBUG )
1866 // Christian, we should document what this does
1867 _control87( _EM_INEXACT, _MCW_EM );
1870 #if defined( HAVE_BC5PLUS )
1871 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1874 // Keyboard focus hack
1879 glutInit (&argc, argv);
1881 CPSGetCurrentProcess(&psn);
1882 CPSSetProcessName(&psn, "FlightGear");
1884 CPSSetFrontProcess(&psn);
1888 // FIXME: add other, more specific
1891 fgMainInit(argc, argv);
1892 } catch (sg_throwable &t) {
1893 // We must use cerr rather than
1894 // logging, since logging may be
1896 cerr << "Fatal error: " << t.getFormattedMessage()
1897 << "\n (received from " << t.getOrigin() << ')' << endl;
1905 void fgLoadDCS(void) {
1907 ssgEntity *ship_obj = NULL;
1909 char obj_filename[25];
1911 for ( int k = 0; k < 32; k++ ) {
1915 SGPath tile_path( globals->get_fg_root());
1916 tile_path.append( "Scenery" );
1917 tile_path.append( "Objects.txt" );
1918 sg_gzifstream in( tile_path.str() );
1919 if ( ! in.is_open() ) {
1920 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1923 SGPath modelpath( globals->get_fg_root() );
1924 modelpath.append( "Models" );
1925 modelpath.append( "Geometry" );
1927 SGPath texturepath( globals->get_fg_root() );
1928 texturepath.append( "Models" );
1929 texturepath.append( "Textures" );
1931 ssgModelPath( (char *)modelpath.c_str() );
1932 ssgTexturePath( (char *)texturepath.c_str() );
1934 ship_sel = new ssgSelector;
1937 while ( ! in.eof() ) {
1939 if ( in.get( c ) && c == '#' ) {
1943 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1944 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1945 int chj=getchar();*/
1947 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1948 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1950 ship_pos[objc] = new ssgTransform;
1952 // type "repeat" in objects.txt to load one more
1953 // instance of the last object.
1955 if ( strcmp(obj_filename,"repeat") != 0) {
1957 globals->get_model_lib()->load_model( globals->get_fg_root(), obj_filename, globals->get_props(), globals->get_sim_time_sec() );
1960 if ( ship_obj != NULL ) {
1961 ship_obj->setName(obj_filename);
1963 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1965 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1966 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1967 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1968 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1971 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1975 // temporary hack for deck lights - ultimately should move to PLib (when??)
1976 //const char *extn = file_extension ( obj_filename ) ;
1978 // ssgVertexArray *lights = new ssgVertexArray( 100 );
1979 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1980 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1981 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1982 int ltype[500], light_type = 0;
1983 static int ltcount = 0;
1985 sgVec3 rway_dir,rway_normal,lightpt;
1987 modelpath.append(obj_filename);
1988 sg_gzifstream in1( modelpath.str() );
1989 if ( ! in1.is_open() ) {
1990 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1992 while ( ! in1.eof() ) {
1994 if ( in1.get( c ) && c == '#' ) {
1999 //cout << token << endl;
2000 if ( token == "runway" ) {
2002 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
2003 } else if ( token == "edgelight" ) {
2005 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2007 } else if ( token == "taxi" ) {
2009 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2011 } else if ( token == "vasi" ) {
2013 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2015 } else if ( token == "threshold" ) {
2017 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2019 } else if ( token == "rabbit" ) {
2021 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2023 } else if ( token == "ols" ) {
2025 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
2027 } else if ( token == "red" ) {
2029 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2031 } else if ( token == "green" ) {
2033 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2035 } else if ( token == "lp" ) {
2037 sgSetVec3 (lightpt, node[0], node[1], node[2] );
2038 lightpoints->add( lightpt );
2039 lightnormals->add( rway_normal );
2040 lightdir->add( rway_dir );
2041 ltype[ltcount]= light_type;
2044 if (in1.eof()) break;
2049 if ( lightpoints->getNum() ) {
2050 ssgBranch *lightpoints_branch;
2051 long int dummy = -999;
2052 dummy_tile = new FGTileEntry((SGBucket)dummy);
2053 dummy_tile->lightmaps_sequence = new ssgSelector;
2054 dummy_tile->ols_transform = new ssgTransform;
2056 // call function to generate the runway lights
2057 lightpoints_branch =
2058 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
2060 lightpoints_brightness->addKid(lightpoints_branch);
2061 lightpoints_transform->addKid(lightpoints_brightness);
2062 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
2063 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
2064 lightpoints_transform->ref();
2065 globals->get_scenery()->get_gnd_lights_root()->addKid( lightpoints_transform );
2070 // end hack for deck lights
2074 if (in.eof()) break;
2078 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
2080 globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node
2087 void fgUpdateDCS (void) {
2089 // double eye_lat,eye_lon,eye_alt;
2090 // static double obj_head;
2091 double sl_radius,obj_latgc;
2092 // float nresultmat[4][4];
2093 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
2096 // Instantaneous Geodetic Lat/Lon/Alt of moving object
2097 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
2099 // Deck should be the first object in objects.txt in case of fdm=ada
2101 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
2102 if ((fdm->get_iaux(1))==1)
2104 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
2105 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
2106 obj_alt[1] = fdm->get_daux(3);
2107 obj_pitch[1] = fdm->get_faux(1);
2108 obj_roll[1] = fdm->get_faux(2);
2112 for ( int m = 0; m < objc; m++ ) {
2113 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
2116 //Geodetic to Geocentric angles for rotation
2117 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
2119 //moving object gbs-posn in cartesian coords
2120 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
2121 Point3D obj_pos = sgGeodToCart( obj_posn );
2123 // Translate moving object w.r.t eye
2124 Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
2129 // rotate dynamic objects for lat,lon & alt and other motion about its axes
2132 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
2134 sgVec3 ship_fwd,ship_rt,ship_up;
2135 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
2136 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
2137 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
2139 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
2140 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
2141 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
2142 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
2143 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
2144 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2147 sgCopyMat4( sgTUX, sgROT_hdg );
2148 sgPostMultMat4( sgTUX, sgROT_pitch );
2149 sgPostMultMat4( sgTUX, sgROT_roll );
2150 sgPostMultMat4( sgTUX, sgROT_lat );
2151 sgPostMultMat4( sgTUX, sgROT_lon );
2152 sgPostMultMat4( sgTUX, sgTRANS );
2155 sgSetCoord(&shippos, sgTUX );
2156 ship_pos[m]->setTransform( &shippos );
2157 // temporary hack for deck lights - ultimately should move to PLib (when ??)
2159 if (lightpoints_transform) {
2160 lightpoints_transform->setTransform( &shippos );
2161 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2162 if ( sun_angle > 89 ) {
2163 lightpoints_brightness->select(0x01);
2165 lightpoints_brightness->select(0x00);
2174 sgXformPnt3( rp, rway_ols, sgTUX );
2175 vp = globals->get_current_view()->get_view_pos();
2176 to[0] = rp[0]-vp[0];
2177 to[1] = rp[1]-vp[1];
2178 to[2] = rp[2]-vp[2];
2179 float dist = sgLengthVec3( to );
2180 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2182 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2184 ref_elev = elev - 3.75; // +ve above, -ve below
2188 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2189 // if (ref_elev > 0.51) sel = 0x21;
2190 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2191 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2192 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2193 // if (ref_elev < -0.51) sel = 0x30;
2194 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2195 // dummy_tile->lightmaps_sequence->select(sel);
2198 sgCopyVec3 (up, ship_up);
2200 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2202 sgScaleVec3 (up, 4.0*ref_elev);
2203 // dummy_tile->ols_transform->setTransform(up);
2204 //cout << "ref_elev " << ref_elev << endl;
2206 // end hack for deck lights
2209 if ( ship_sel != NULL ) {
2210 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2214 // $$$ end - added VS Renganathan, 15 Oct 2K
2215 // added Venky , 12 Nov 2K