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 <Replay/replay.hxx>
124 #include <Scenery/scenery.hxx>
125 #include <Scenery/tilemgr.hxx>
126 #ifdef ENABLE_AUDIO_SUPPORT
127 # include <Sound/fg_fx.hxx>
128 # include <Sound/morse.hxx>
130 #include <Systems/system_mgr.hxx>
131 #include <Instrumentation/instrument_mgr.hxx>
132 #include <Time/FGEventMgr.hxx>
133 #include <Time/fg_timer.hxx>
134 #include <Time/light.hxx>
135 #include <Time/sunpos.hxx>
136 #include <Time/tmp.hxx>
139 #include <simgear/misc/sgstream.hxx>
140 #include <simgear/math/point3d.hxx>
141 #include <FDM/flight.hxx>
142 #include <FDM/ADA.hxx>
143 #include <Scenery/tileentry.hxx>
145 #include "fg_commands.hxx"
147 glPointParameterfProc glPointParameterfPtr = 0;
148 glPointParameterfvProc glPointParameterfvPtr = 0;
149 bool glPointParameterIsSupported = false;
151 float default_attenuation[3] = {1.0, 0.0, 0.0};
152 //Required for using GL_extensions
153 void fgLoadDCS (void);
154 void fgUpdateDCS (void);
155 ssgSelector *ship_sel=NULL;
156 // upto 32 instances of a same object can be loaded.
157 ssgTransform *ship_pos[32];
158 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
160 ssgSelector *lightpoints_brightness = new ssgSelector;
161 ssgTransform *lightpoints_transform = new ssgTransform;
162 FGTileEntry *dummy_tile;
165 // Clip plane settings...
166 float scene_nearplane = 0.5f;
167 float scene_farplane = 120000.0f;
169 static double delta_time_sec = 0.0;
173 # include <WeatherCM/FGLocalWeatherDatabase.h>
178 #include "fg_init.hxx"
180 #include "fg_props.hxx"
181 #include "globals.hxx"
182 #include "splash.hxx"
183 #include "viewmgr.hxx"
184 #include "options.hxx"
185 #include "logger.hxx"
188 # include <console.h> // -dw- for command line dialog
192 FGEventMgr global_events;
194 // This is a record containing a bit of global housekeeping information
197 // Specify our current idle function state. This is used to run all
198 // our initializations out of the glutIdleLoop() so that we can get a
199 // splash screen up and running right away.
200 static int idle_state = 0;
201 static long global_multi_loop;
203 // fog constants. I'm a little nervous about putting actual code out
204 // here but it seems to work (?)
205 static const double m_log01 = -log( 0.01 );
206 static const double sqrt_m_log01 = sqrt( m_log01 );
207 static GLfloat fog_exp_density;
208 static GLfloat fog_exp2_density;
209 static GLfloat rwy_exp2_punch_through;
210 static GLfloat taxi_exp2_punch_through;
211 static GLfloat ground_exp2_punch_through;
213 #ifdef FG_NETWORK_OLK
214 ssgSelector *fgd_sel = NULL;
215 ssgTransform *fgd_pos = NULL;
221 #ifdef FG_USE_CLOUDS_3D
222 SkySceneLoader *sgClouds3d;
223 bool _bcloud_orig = true;
227 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
229 { 1.0f, 0.0f, 0.0f, 0.0f },
230 { 0.0f, 0.0f, -1.0f, 0.0f },
231 { 0.0f, 1.0f, 0.0f, 0.0f },
232 { 0.0f, 0.0f, 0.0f, 1.0f }
235 // The following defines flightgear options. Because glutlib will also
236 // want to parse its own options, those options must not be included here
237 // or they will get parsed by the main program option parser. Hence case
238 // is significant for any option added that might be in conflict with
241 // glutlib parses for:
243 // -direct (invalid in Win32)
247 // -indirect (invalid in Win32)
250 // Note that glutlib depends upon strings while this program's
251 // option parser wants only initial characters followed by numbers
256 ssgSimpleState *cloud3d_imposter_state;
257 ssgSimpleState *default_state;
258 ssgSimpleState *hud_and_panel;
259 ssgSimpleState *menus;
261 SGTimeStamp last_time_stamp;
262 SGTimeStamp current_time_stamp;
265 void fgBuildRenderStates( void ) {
266 default_state = new ssgSimpleState;
267 default_state->ref();
268 default_state->disable( GL_TEXTURE_2D );
269 default_state->enable( GL_CULL_FACE );
270 default_state->enable( GL_COLOR_MATERIAL );
271 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
272 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
273 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
274 default_state->disable( GL_BLEND );
275 default_state->disable( GL_ALPHA_TEST );
276 default_state->disable( GL_LIGHTING );
278 cloud3d_imposter_state = new ssgSimpleState;
279 cloud3d_imposter_state->ref();
280 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
281 cloud3d_imposter_state->enable( GL_CULL_FACE );
282 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
283 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
284 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
285 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
286 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
287 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
288 cloud3d_imposter_state->enable( GL_BLEND );
289 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
290 cloud3d_imposter_state->disable( GL_LIGHTING );
292 hud_and_panel = new ssgSimpleState;
293 hud_and_panel->ref();
294 hud_and_panel->disable( GL_CULL_FACE );
295 hud_and_panel->disable( GL_TEXTURE_2D );
296 hud_and_panel->disable( GL_LIGHTING );
297 hud_and_panel->enable( GL_BLEND );
299 menus = new ssgSimpleState;
301 menus->disable( GL_CULL_FACE );
302 menus->disable( GL_TEXTURE_2D );
303 menus->enable( GL_BLEND );
307 // fgInitVisuals() -- Initialize various GL/view parameters
308 void fgInitVisuals( void ) {
311 l = &cur_light_params;
313 #ifndef GLUT_WRONG_VERSION
314 // Go full screen if requested ...
315 if ( fgGetBool("/sim/startup/fullscreen") ) {
320 // If enabled, normal vectors specified with glNormal are scaled
321 // to unit length after transformation. Enabling this has
322 // performance implications. See the docs for glNormal.
323 // glEnable( GL_NORMALIZE );
325 glEnable( GL_LIGHTING );
326 glEnable( GL_LIGHT0 );
327 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
330 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
331 ssgGetLight( 0 ) -> setPosition( sunpos );
333 glFogi (GL_FOG_MODE, GL_EXP2);
334 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
335 (!fgGetBool("/sim/rendering/shading"))) {
336 // if fastest fog requested, or if flat shading force fastest
337 glHint ( GL_FOG_HINT, GL_FASTEST );
338 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
339 glHint ( GL_FOG_HINT, GL_NICEST );
341 if ( fgGetBool("/sim/rendering/wireframe") ) {
343 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
346 // This is the default anyways, but it can't hurt
347 glFrontFace ( GL_CCW );
350 // glEnable(GL_POINT_SMOOTH);
351 // glEnable(GL_LINE_SMOOTH);
352 // glEnable(GL_POLYGON_SMOOTH);
356 // For HiRes screen Dumps using Brian Pauls TR Library
357 void trRenderFrame( void ) {
359 if ( fgPanelVisible() ) {
360 GLfloat height = fgGetInt("/sim/startup/ysize");
362 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
363 * (height / 768.0) + 1;
364 glTranslatef( 0.0, view_h, 0.0 );
367 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
368 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
370 fgLIGHT *l = &cur_light_params;
372 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
373 l->adj_fog_color[2], l->adj_fog_color[3]);
375 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
377 // set the opengl state to known default values
378 default_state->force();
381 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
382 glFogi ( GL_FOG_MODE, GL_EXP2 );
383 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
385 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
386 // we only update GL_AMBIENT for our lights we will never get
387 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
388 // explicitely to black.
389 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
390 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
392 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
394 // texture parameters
395 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
396 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
398 // we need a white diffuse light for the phase of the moon
399 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
402 // draw the ssg scene
403 // return to the desired diffuse color
404 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
405 glEnable( GL_DEPTH_TEST );
406 ssgSetNearFar( scene_nearplane, scene_farplane );
407 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
410 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
411 ssgSetNearFar( scene_nearplane, scene_farplane );
412 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
414 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
416 if (fgGetBool("/environment/clouds/status"))
417 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
419 globals->get_model_mgr()->draw();
420 globals->get_aircraft_model()->draw();
424 // Update all Visuals (redraws anything graphics related)
425 void fgRenderFrame() {
426 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
427 bool skyblend = fgGetBool("/sim/rendering/skyblend");
428 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
429 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
431 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
432 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
434 // Process/manage pending events
435 global_events.update( delta_time_sec );
437 // static const SGPropertyNode *longitude
438 // = fgGetNode("/position/longitude-deg");
439 // static const SGPropertyNode *latitude
440 // = fgGetNode("/position/latitude-deg");
441 // static const SGPropertyNode *altitude
442 // = fgGetNode("/position/altitude-ft");
443 static const SGPropertyNode *groundlevel_nearplane
444 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
446 // Update the default (kludged) properties.
449 FGViewer *current__view = globals->get_current_view();
451 fgLIGHT *l = &cur_light_params;
452 static double last_visibility = -9999;
455 double actual_visibility;
456 if (fgGetBool("/environment/clouds/status"))
457 actual_visibility = thesky->get_visibility();
459 actual_visibility = fgGetDouble("/environment/visibility-m");
460 if ( actual_visibility != last_visibility ) {
461 last_visibility = actual_visibility;
463 fog_exp_density = m_log01 / actual_visibility;
464 fog_exp2_density = sqrt_m_log01 / actual_visibility;
465 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
466 if ( actual_visibility < 8000 ) {
467 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
468 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
470 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
471 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
476 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
477 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
478 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
479 // GLfloat mat_shininess[] = { 10.0 };
480 GLbitfield clear_mask;
482 if ( idle_state != 1000 ) {
483 // still initializing, draw the splash screen
484 if ( fgGetBool("/sim/startup/splash-screen") ) {
485 fgSplashUpdate(0.0, 1.0);
487 // Keep resetting sim time while the sim is initializing
488 globals->set_sim_time_sec( 0.0 );
489 SGAnimation::set_sim_time_sec( 0.0 );
491 // idle_state is now 1000 meaning we've finished all our
492 // initializations and are running the main loop, so this will
493 // now work without seg faulting the system.
495 // calculate our current position in cartesian space
496 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
499 fgReshape( fgGetInt("/sim/startup/xsize"),
500 fgGetInt("/sim/startup/ysize") );
502 if ( fgGetBool("/sim/rendering/clouds3d") ) {
503 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
504 cloud3d_imposter_state->force();
506 glColor4f( 1.0, 1.0, 1.0, 1.0 );
507 glEnable(GL_DEPTH_TEST);
509 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
511 #ifdef FG_USE_CLOUDS_3D
512 if ( _bcloud_orig ) {
513 Point3D c = globals->get_scenery()->get_center();
514 sgClouds3d->Set_Cloud_Orig( &c );
515 _bcloud_orig = false;
517 sgClouds3d->Update( current__view->get_absolute_view_pos() );
519 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
520 glDisable(GL_DEPTH_TEST);
523 clear_mask = GL_DEPTH_BUFFER_BIT;
524 if ( fgGetBool("/sim/rendering/wireframe") ) {
525 clear_mask |= GL_COLOR_BUFFER_BIT;
529 if ( fgGetBool("/sim/rendering/textures") ) {
530 // glClearColor(black[0], black[1], black[2], black[3]);
531 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
532 l->adj_fog_color[2], l->adj_fog_color[3]);
533 clear_mask |= GL_COLOR_BUFFER_BIT;
536 glClearColor(l->sky_color[0], l->sky_color[1],
537 l->sky_color[2], l->sky_color[3]);
538 clear_mask |= GL_COLOR_BUFFER_BIT;
540 glClear( clear_mask );
542 // Tell GL we are switching to model view parameters
544 // I really should create a derived ssg node or use a call
545 // back or something so that I can draw the sky within the
546 // ssgCullAndDraw() function, but for now I just mimic what
547 // ssg does to set up the model view matrix
548 glMatrixMode(GL_MODELVIEW);
550 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
552 // set the opengl state to known default values
553 default_state->force();
555 // update fog params if visibility has changed
556 double visibility_meters = fgGetDouble("/environment/visibility-m");
557 thesky->set_visibility(visibility_meters);
559 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
560 ( global_multi_loop * fgGetInt("/sim/speed-up") )
561 / (double)fgGetInt("/sim/model-hz") );
563 // Set correct opengl fog density
564 glFogf (GL_FOG_DENSITY, fog_exp2_density);
566 // update the sky dome
569 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
570 << cur_light_params.sky_color[0] << " "
571 << cur_light_params.sky_color[1] << " "
572 << cur_light_params.sky_color[2] << " "
573 << cur_light_params.sky_color[3] );
574 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
575 << cur_light_params.fog_color[0] << " "
576 << cur_light_params.fog_color[1] << " "
577 << cur_light_params.fog_color[2] << " "
578 << cur_light_params.fog_color[3] );
579 SG_LOG( SG_GENERAL, SG_BULK,
580 " sun_angle = " << cur_light_params.sun_angle
581 << " moon_angle = " << cur_light_params.moon_angle );
584 static SGSkyColor scolor;
586 scolor.sky_color = cur_light_params.sky_color;
587 scolor.fog_color = cur_light_params.adj_fog_color;
588 scolor.cloud_color = cur_light_params.cloud_color;
589 scolor.sun_angle = cur_light_params.sun_angle;
590 scolor.moon_angle = cur_light_params.moon_angle;
591 scolor.nplanets = globals->get_ephem()->getNumPlanets();
592 scolor.nstars = globals->get_ephem()->getNumStars();
593 scolor.planet_data = globals->get_ephem()->getPlanets();
594 scolor.star_data = globals->get_ephem()->getStars();
596 thesky->repaint( scolor );
599 SG_LOG( SG_GENERAL, SG_BULK,
600 "thesky->reposition( view_pos = " << view_pos[0] << " "
601 << view_pos[1] << " " << view_pos[2] );
602 SG_LOG( SG_GENERAL, SG_BULK,
603 " zero_elev = " << zero_elev[0] << " "
604 << zero_elev[1] << " " << zero_elev[2]
605 << " lon = " << cur_fdm_state->get_Longitude()
606 << " lat = " << cur_fdm_state->get_Latitude() );
607 SG_LOG( SG_GENERAL, SG_BULK,
608 " sun_rot = " << cur_light_params.sun_rotation
609 << " gst = " << SGTime::cur_time_params->getGst() );
610 SG_LOG( SG_GENERAL, SG_BULK,
611 " sun ra = " << globals->get_ephem()->getSunRightAscension()
612 << " sun dec = " << globals->get_ephem()->getSunDeclination()
613 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
614 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
617 // The sun and moon distances are scaled down versions
618 // of the actual distance to get both the moon and the sun
619 // within the range of the far clip plane.
620 // Moon distance: 384,467 kilometers
621 // Sun distance: 150,000,000 kilometers
622 double sun_horiz_eff, moon_horiz_eff;
623 if (fgGetBool("/sim/rendering/horizon-effect")) {
624 sun_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.sun_angle*2)/2,0.33)/3;
625 moon_horiz_eff = 0.67+pow(0.5+cos(cur_light_params.moon_angle*2)/2,0.33)/3;
627 sun_horiz_eff = moon_horiz_eff = 1.0;
630 static SGSkyState sstate;
632 sstate.view_pos = current__view->get_view_pos();
633 sstate.zero_elev = current__view->get_zero_elev();
634 sstate.view_up = current__view->get_world_up();
635 sstate.lon = current__view->getLongitude_deg()
636 * SGD_DEGREES_TO_RADIANS;
637 sstate.lat = current__view->getLatitude_deg()
638 * SGD_DEGREES_TO_RADIANS;
639 sstate.alt = current__view->getAltitudeASL_ft()
641 sstate.spin = cur_light_params.sun_rotation;
642 sstate.gst = globals->get_time_params()->getGst();
643 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
644 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
645 sstate.sun_dist = 50000.0 * sun_horiz_eff;
646 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
647 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
648 sstate.moon_dist = 40000.0 * moon_horiz_eff;
650 thesky->reposition( sstate, delta_time_sec );
653 glEnable( GL_DEPTH_TEST );
654 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
656 glFogi( GL_FOG_MODE, GL_EXP2 );
657 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
660 // set sun/lighting parameters
661 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
663 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
664 // we only update GL_AMBIENT for our lights we will never get
665 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
666 // explicitely to black.
667 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
669 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
670 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
671 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular );
673 // texture parameters
674 // glEnable( GL_TEXTURE_2D );
675 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
676 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
678 // glMatrixMode( GL_PROJECTION );
680 ssgSetFOV( current__view->get_h_fov(),
681 current__view->get_v_fov() );
684 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
685 - globals->get_scenery()->get_cur_elev();
688 scene_nearplane = 10.0f;
689 scene_farplane = 120000.0f;
691 scene_nearplane = groundlevel_nearplane->getDoubleValue();
692 scene_farplane = 120000.0f;
695 ssgSetNearFar( scene_nearplane, scene_farplane );
697 // $$$ begin - added VS Renganthan 17 Oct 2K
700 // $$$ end - added VS Renganthan 17 Oct 2K
702 # ifdef FG_NETWORK_OLK
703 if ( fgGetBool("/sim/networking/network-olk") ) {
705 other = head->next; /* put listpointer to start */
706 while ( other != tail) { /* display all except myself */
707 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
708 other->fgd_sel->select(1);
709 sgSetCoord( &fgdpos, other->sgFGD_COORD );
710 other->fgd_pos->setTransform( &fgdpos );
715 // fgd_sel->select(1);
716 // sgCopyMat4( sgTUX, current_view.sgVIEW);
718 // sgSetCoord( &fgdpos, sgFGD_VIEW );
719 // fgd_pos->setTransform( &fgdpos);
724 // Update any multiplayer models
725 globals->get_multiplayer_rx_mgr()->Update();
728 if ( draw_otw && skyblend )
730 // draw the sky backdrop
732 // we need a white diffuse light for the phase of the moon
733 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
737 // return to the desired diffuse color
738 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
741 // draw the ssg scene
742 glEnable( GL_DEPTH_TEST );
744 ssgSetNearFar( scene_nearplane, scene_farplane );
746 if ( fgGetBool("/sim/rendering/wireframe") ) {
748 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
751 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
754 // This is a bit kludgy. Every 200 frames, do an extra
755 // traversal of the scene graph without drawing anything, but
756 // with the field-of-view set to 360x360 degrees. This
757 // ensures that out-of-range random objects that are not in
758 // the current view frustum will still be freed properly.
759 static int counter = 0;
761 if (counter == 200) {
764 // No need to put the near plane too close;
765 // this way, at least the aircraft can be
767 f.setNearFar(1000, 1000000);
769 ssgGetModelviewMatrix(m);
770 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
774 // change state for lighting here
776 // draw runway lighting
777 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
778 ssgSetNearFar( scene_nearplane, scene_farplane );
780 if ( enhanced_lighting ) {
782 // Enable states for drawing points with GL_extension
783 glEnable(GL_POINT_SMOOTH);
785 if ( distance_attenuation && glPointParameterIsSupported )
787 // Enable states for drawing points with GL_extension
788 glEnable(GL_POINT_SMOOTH);
790 float quadratic[3] = {1.0, 0.001, 0.0000001};
791 // makes the points fade as they move away
792 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
793 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
798 // blending function for runway lights
799 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
802 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
803 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
804 glEnable(GL_TEXTURE_GEN_S);
805 glEnable(GL_TEXTURE_GEN_T);
806 glPolygonMode(GL_FRONT, GL_POINT);
808 // draw runway lighting
810 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
813 // change punch through and then draw taxi lighting
814 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
816 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
817 // glFogfv ( GL_FOG_COLOR, taxi_fog );
819 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
823 glPolygonMode(GL_FRONT, GL_FILL);
824 glDisable(GL_TEXTURE_GEN_S);
825 glDisable(GL_TEXTURE_GEN_T);
827 //static int _frame_count = 0;
828 //if (_frame_count % 30 == 0) {
829 // printf("SSG: %s\n", ssgShowStats());
837 if ( enhanced_lighting ) {
838 if ( distance_attenuation && glPointParameterIsSupported )
840 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
841 default_attenuation);
845 glDisable(GL_POINT_SMOOTH);
848 // draw ground lighting
849 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
851 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
855 // draw the sky cloud layers
856 if ( draw_otw && fgGetBool("/environment/clouds/status") )
858 thesky->postDraw( cur_fdm_state->get_Altitude()
859 * SG_FEET_TO_METER );
863 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") )
866 glDisable( GL_LIGHTING );
867 // cout << "drawing new clouds" << endl;
869 glEnable(GL_DEPTH_TEST);
871 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
874 glEnable( GL_TEXTURE_2D );
875 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
876 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
877 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
878 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
881 #ifdef FG_USE_CLOUDS_3D
882 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
885 glEnable( GL_LIGHTING );
886 glEnable( GL_DEPTH_TEST );
887 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
891 globals->get_model_mgr()->draw();
892 globals->get_aircraft_model()->draw();
895 // display HUD && Panel
897 glDisable( GL_DEPTH_TEST );
898 // glDisable( GL_CULL_FACE );
899 // glDisable( GL_TEXTURE_2D );
901 // update the controls subsystem
902 globals->get_controls()->update(delta_time_sec);
904 hud_and_panel->apply();
907 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
908 // This only works properly if called before the panel call
909 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
910 globals->get_ATC_display()->update(delta_time_sec);
912 // update the panel subsystem
913 if ( globals->get_current_panel() != NULL ) {
914 globals->get_current_panel()->update(delta_time_sec);
918 // We can do translucent menus, so why not. :-)
920 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
922 // glDisable ( GL_BLEND ) ;
924 glEnable( GL_DEPTH_TEST );
927 // Fade out the splash screen over the first three seconds.
928 double t = globals->get_sim_time_sec();
930 fgSplashUpdate(0.0, 1.0);
931 } else if ( t <= 3.0) {
932 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
940 // Update internal time dependent calculations (i.e. flight model)
941 // FIXME: this distinction is obsolete; all subsystems now get delta
943 void fgUpdateTimeDepCalcs() {
944 static bool inited = false;
946 static const SGPropertyNode *replay_master
947 = fgGetNode( "/sim/freeze/replay", true );
948 static SGPropertyNode *replay_time
949 = fgGetNode( "/sim/replay/time", true );
950 static const SGPropertyNode *replay_end_time
951 = fgGetNode( "/sim/replay/end-time", true );
953 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
955 fgLIGHT *l = &cur_light_params;
957 // Initialize the FDM here if it hasn't been and if we have a
958 // scenery elevation hit.
960 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
961 // << " cur_elev = " << scenery.get_cur_elev() << endl;
963 if ( !cur_fdm_state->get_inited() &&
964 globals->get_scenery()->get_cur_elev() > -9990 )
966 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
967 cur_fdm_state->init();
968 if ( cur_fdm_state->get_bound() ) {
969 cur_fdm_state->unbind();
971 cur_fdm_state->bind();
974 // conceptually, the following block could be done for each fdm
976 if ( cur_fdm_state->get_inited() ) {
977 // we have been inited, and we are good to go ...
983 if ( ! replay_master->getBoolValue() ) {
984 globals->get_autopilot()->update( delta_time_sec );
985 cur_fdm_state->update( delta_time_sec );
987 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
988 r->replay( replay_time->getDoubleValue() );
989 replay_time->setDoubleValue( replay_time->getDoubleValue()
991 * fgGetInt("/sim/speed-up") ) );
994 // do nothing, fdm isn't inited yet
997 globals->get_model_mgr()->update(delta_time_sec);
998 globals->get_aircraft_model()->update(delta_time_sec);
1000 // update the view angle
1001 globals->get_viewmgr()->update(delta_time_sec);
1005 // Update solar system
1006 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
1007 globals->get_time_params()->getLst(),
1008 cur_fdm_state->get_Latitude() );
1010 // Update radio stack model
1011 current_radiostack->update(delta_time_sec);
1015 void fgInitTimeDepCalcs( void ) {
1020 static const double alt_adjust_ft = 3.758099;
1021 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1024 // What should we do when we have nothing else to do? Let's get ready
1025 // for the next move and update the display?
1026 static void fgMainLoop( void ) {
1027 int model_hz = fgGetInt("/sim/model-hz");
1029 static const SGPropertyNode *longitude
1030 = fgGetNode("/position/longitude-deg");
1031 static const SGPropertyNode *latitude
1032 = fgGetNode("/position/latitude-deg");
1033 static const SGPropertyNode *altitude
1034 = fgGetNode("/position/altitude-ft");
1035 static const SGPropertyNode *clock_freeze
1036 = fgGetNode("/sim/freeze/clock", true);
1037 static const SGPropertyNode *cur_time_override
1038 = fgGetNode("/sim/time/cur-time-override", true);
1039 static const SGPropertyNode *replay_master
1040 = fgGetNode("/sim/freeze/replay", true);
1042 // Update the elapsed time.
1043 static bool first_time = true;
1045 last_time_stamp.stamp();
1049 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1050 if ( throttle_hz > 0.0 ) {
1051 // simple frame rate throttle
1052 double dt = 1000000.0 / throttle_hz;
1053 current_time_stamp.stamp();
1054 while ( current_time_stamp - last_time_stamp < dt ) {
1055 current_time_stamp.stamp();
1058 // run as fast as the app will go
1059 current_time_stamp.stamp();
1062 delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
1063 if ( clock_freeze->getBoolValue() ) {
1066 last_time_stamp = current_time_stamp;
1067 globals->inc_sim_time_sec( delta_time_sec );
1068 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1070 static long remainder = 0;
1072 #ifdef FANCY_FRAME_COUNTER
1076 static time_t last_time = 0;
1077 static int frames = 0;
1078 #endif // FANCY_FRAME_COUNTER
1080 SGTime *t = globals->get_time_params();
1082 sglog().setLogLevels( SG_ALL, (sgDebugPriority)fgGetInt("/sim/log-level") );
1083 sglog().setLogLevels( SG_ALL, SG_INFO );
1085 SGLocation * acmodel_location = 0;
1086 if(cur_fdm_state->getACModel() != 0) {
1087 acmodel_location = (SGLocation *) cur_fdm_state->getACModel()->get3DModel()->getSGLocation();
1090 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1091 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1093 #ifdef FG_NETWORK_OLK
1094 if ( fgGetBool("/sim/networking/network-olk") ) {
1095 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
1096 // printf("FGD: Netupdate\n");
1097 fgd_send_com( "A", FGFS_host); // Send Mat4 data
1098 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
1103 #if defined( ENABLE_PLIB_JOYSTICK )
1104 // Read joystick and update control settings
1105 // if ( fgGetString("/sim/control-mode") == "joystick" )
1107 // fgJoystickRead();
1109 #elif defined( ENABLE_GLUT_JOYSTICK )
1110 // Glut joystick support works by feeding a joystick handler
1111 // function to glut. This is taken care of once in the joystick
1112 // init routine and we don't have to worry about it again.
1115 // Fix elevation. I'm just sticking this here for now, it should
1116 // probably move eventually
1118 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1119 scenery.get_cur_elev(),
1120 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1121 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1124 // This code is used by LaRCsim/UIUC to position the aircraft at a proper
1125 // place. This code should eventually go into the LaRCsim directory.
1126 // Commented out at Jul 27 2003 because tests show it is not needed.
1127 // Can probbaly be safely removed after Spet. 2003 - EMH
1129 if ( acmodel_location != 0 ) {
1130 if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
1131 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
1132 (acmodel_location->get_cur_elev_m() + alt_adjust_m - 130.0) ) {
1133 // now set aircraft altitude above ground
1134 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
1135 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
1136 acmodel_location->get_cur_elev_m() + alt_adjust_m - 130.0,
1137 acmodel_location->get_cur_elev_m() + alt_adjust_m );
1138 cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m()
1139 + alt_adjust_m) * SG_METER_TO_FEET );
1140 SG_LOG( SG_ALL, SG_DEBUG,
1141 "<*> resetting altitude to "
1142 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
1147 // End of code in question. (see Curt is this code used? above)
1150 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1151 scenery.get_cur_elev(),
1152 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1153 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1155 // cout << "Warp = " << globals->get_warp() << endl;
1158 static bool last_clock_freeze = false;
1160 if ( clock_freeze->getBoolValue() ) {
1161 // clock freeze requested
1162 if ( cur_time_override->getLongValue() == 0 ) {
1163 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1164 globals->set_warp( 0 );
1167 // no clock freeze requested
1168 if ( last_clock_freeze == true ) {
1169 // clock just unfroze, let's set warp as the difference
1170 // between frozen time and current time so we don't get a
1171 // time jump (and corresponding sky object and lighting
1173 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1174 fgSetLong( "/sim/time/cur-time-override", 0 );
1176 if ( globals->get_warp_delta() != 0 ) {
1177 globals->inc_warp( globals->get_warp_delta() );
1181 last_clock_freeze = clock_freeze->getBoolValue();
1183 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1184 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1185 cur_time_override->getLongValue(),
1186 globals->get_warp() );
1188 if ( globals->get_warp_delta() != 0 ) {
1189 fgUpdateSkyAndLightingParams();
1192 // update magvar model
1193 globals->get_mag()->update( longitude->getDoubleValue()
1194 * SGD_DEGREES_TO_RADIANS,
1195 latitude->getDoubleValue()
1196 * SGD_DEGREES_TO_RADIANS,
1197 altitude->getDoubleValue() * SG_FEET_TO_METER,
1198 globals->get_time_params()->getJD() );
1200 // Get elapsed time (in usec) for this past frame
1201 elapsed = fgGetTimeInterval();
1202 SG_LOG( SG_ALL, SG_DEBUG,
1203 "Elapsed time interval is = " << elapsed
1204 << ", previous remainder is = " << remainder );
1206 // Calculate frame rate average
1207 #ifdef FANCY_FRAME_COUNTER
1208 /* old fps calculation */
1209 if ( elapsed > 0 ) {
1212 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1213 tmp = general.get_frame(i);
1215 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1216 general.set_frame(i+1,tmp);
1218 tmp = 1000000.0 / (float)elapsed;
1219 general.set_frame(0,tmp);
1220 // printf("frame[0] = %.2f\n", general.frames[0]);
1222 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1223 // printf("ave = %.2f\n", general.frame_rate);
1226 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1227 general.set_frame_rate( frames );
1228 fgSetInt("/sim/frame-rate", frames);
1229 SG_LOG( SG_ALL, SG_DEBUG,
1230 "--> Frame rate is = " << general.get_frame_rate() );
1233 last_time = t->get_cur_time();
1237 // Run ATC subsystem
1238 if (fgGetBool("/sim/ATC/enabled"))
1239 globals->get_ATC_mgr()->update(delta_time_sec);
1241 // Run the AI subsystem
1242 if (fgGetBool("/sim/ai-traffic/enabled"))
1243 globals->get_AI_mgr()->update(delta_time_sec);
1247 // Calculate model iterations needed for next frame
1248 elapsed += remainder;
1250 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1251 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1252 SG_LOG( SG_ALL, SG_DEBUG,
1253 "Model iterations needed = " << global_multi_loop
1254 << ", new remainder = " << remainder );
1256 // chop max interations to something reasonable if the sim was
1257 // delayed for an excesive amount of time
1258 if ( global_multi_loop > 2.0 * model_hz ) {
1259 global_multi_loop = (int)(2.0 * model_hz );
1264 if ( global_multi_loop > 0 ) {
1265 fgUpdateTimeDepCalcs();
1267 SG_LOG( SG_ALL, SG_DEBUG,
1268 "Elapsed time is zero ... we're zinging" );
1271 // Do any I/O channel work that might need to be done
1272 globals->get_io()->update( delta_time_sec );
1274 // see if we need to load any deferred-load textures
1275 globals->get_matlib()->load_next_deferred();
1277 // Run audio scheduler
1278 #ifdef ENABLE_AUDIO_SUPPORT
1279 if ( fgGetBool("/sim/sound/audible")
1280 && globals->get_soundmgr()->is_working() ) {
1281 globals->get_soundmgr()->update( delta_time_sec );
1285 globals->get_subsystem_mgr()->update(delta_time_sec);
1288 // Tile Manager updates - see if we need to load any new scenery tiles.
1289 // this code ties together the fdm, viewer and scenery classes...
1290 // we may want to move this to it's own class at some point
1292 double visibility_meters = fgGetDouble("/environment/visibility-m");
1293 FGViewer *current_view = globals->get_current_view();
1295 // update tile manager for FDM...
1296 // ...only if location is different than the viewer (to avoid duplicating effort)
1297 if( acmodel_location != current_view->getSGLocation() ) {
1298 if( acmodel_location != 0 ) {
1299 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1300 visibility_meters );
1301 globals->get_tile_mgr()->
1302 update( acmodel_location, visibility_meters,
1303 acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1304 // save results of update in SGLocation for fdm...
1305 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1307 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1310 set_tile_center( globals->get_scenery()->get_next_center() );
1314 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1315 visibility_meters );
1316 // update tile manager for view...
1317 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1318 // after the FDM's until all of Flight Gear code references the viewer's location
1319 // for elevation instead of the "scenery's" current elevation.
1320 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1321 globals->get_tile_mgr()->update( view_location, visibility_meters,
1322 current_view->get_absolute_view_pos() );
1323 // save results of update in SGLocation for fdm...
1324 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1325 current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1327 current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1329 // If fdm location is same as viewer's then we didn't do the update for fdm location
1330 // above so we need to save the viewer results in the fdm SGLocation as well...
1331 if( acmodel_location == current_view->getSGLocation() ) {
1332 if( acmodel_location != 0 ) {
1333 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1334 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1336 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1340 // END Tile Manager udpates
1345 SG_LOG( SG_ALL, SG_DEBUG, "" );
1349 // This is the top level master main function that is registered as
1350 // our idle funciton
1352 // The first few passes take care of initialization things (a couple
1353 // per pass) and once everything has been initialized fgMainLoop from
1356 static void fgIdleFunction ( void ) {
1357 // printf("idle state == %d\n", idle_state);
1359 if ( idle_state == 0 ) {
1360 // Initialize the splash screen right away
1361 if ( fgGetBool("/sim/startup/splash-screen") ) {
1366 } else if ( idle_state == 1 ) {
1367 // Initialize audio support
1368 #ifdef ENABLE_AUDIO_SUPPORT
1370 // Start the intro music
1371 if ( fgGetBool("/sim/startup/intro-music") ) {
1372 SGPath mp3file( globals->get_fg_root() );
1373 mp3file.append( "Sounds/intro.mp3" );
1375 SG_LOG( SG_GENERAL, SG_INFO,
1376 "Starting intro music: " << mp3file.str() );
1378 #if defined( __CYGWIN__ )
1379 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1380 #elif defined( WIN32 )
1381 string command = "start /m " + mp3file.str();
1383 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1386 system ( command.c_str() );
1391 } else if ( idle_state == 2 ) {
1392 // These are a few miscellaneous things that aren't really
1393 // "subsystems" but still need to be initialized.
1396 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1397 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1402 } else if ( idle_state == 3 ) {
1403 // This is the top level init routine which calls all the
1404 // other subsystem initialization routines. If you are adding
1405 // a subsystem to flightgear, its initialization call should
1406 // located in this routine.
1407 if( !fgInitSubsystems()) {
1408 SG_LOG( SG_GENERAL, SG_ALERT,
1409 "Subsystem initializations failed ..." );
1414 } else if ( idle_state == 4 ) {
1415 // setup OpenGL view parameters
1418 // Read the list of available aircrafts
1422 } else if ( idle_state == 5 ) {
1425 } else if ( idle_state == 6 ) {
1429 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1430 fgReshape( fgGetInt("/sim/startup/xsize"),
1431 fgGetInt("/sim/startup/ysize") );
1434 if ( idle_state == 1000 ) {
1435 // We've finished all our initialization steps, from now on we
1436 // run the main loop.
1438 glutIdleFunc(fgMainLoop);
1440 if ( fgGetBool("/sim/startup/splash-screen") ) {
1441 fgSplashUpdate(0.0, 1.0);
1446 // options.cxx needs to see this for toggle_panel()
1447 // Handle new window size or exposure
1448 void fgReshape( int width, int height ) {
1451 if ( (!fgGetBool("/sim/virtual-cockpit"))
1452 && fgPanelVisible() && idle_state == 1000 ) {
1453 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1454 globals->get_current_panel()->getYOffset()) / 768.0);
1460 FGViewMgr *viewmgr = globals->get_viewmgr();
1461 for ( int i = 0; i < viewmgr->size(); ++i ) {
1462 viewmgr->get_view(i)->
1463 set_aspect_ratio((float)view_h / (float)width);
1466 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1468 fgSetInt("/sim/startup/xsize", width);
1469 fgSetInt("/sim/startup/ysize", height);
1470 guiInitMouse(width, height);
1472 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1473 viewmgr->get_current_view()->get_v_fov() );
1477 #ifdef FG_USE_CLOUDS_3D
1478 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1479 viewmgr->get_current_view()->get_v_fov() );
1484 // Initialize GLUT and define a main window
1485 static bool fgGlutInit( int *argc, char **argv ) {
1487 #if !defined( macintosh )
1488 // GLUT will extract all glut specific options so later on we only
1489 // need wory about our own.
1490 glutInit(argc, argv);
1493 // Define Display Parameters. Clouds3d works best with --bpp32 option
1494 if ( fgGetBool("/sim/rendering/clouds3d") ) {
1495 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1497 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1500 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1501 fgGetInt("/sim/startup/xsize") << "x"
1502 << fgGetInt("/sim/startup/ysize") );
1504 // Define initial window size
1505 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1506 fgGetInt("/sim/startup/ysize") );
1508 // Initialize windows
1509 if ( !fgGetBool("/sim/startup/game-mode")) {
1510 // Open the regular window
1511 glutCreateWindow("FlightGear");
1512 #ifndef GLUT_WRONG_VERSION
1514 // Open the cool new 'game mode' window
1515 char game_mode_str[256];
1516 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1517 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1518 #ifndef ENUM_CURRENT_SETTINGS
1519 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1520 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1524 dm.dmSize = sizeof(DEVMODE);
1525 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1526 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1527 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1528 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1529 fgGetInt("/sim/startup/ysize") );
1530 sprintf( game_mode_str, "%dx%d:%d@%d",
1534 dm.dmDisplayFrequency );
1536 // Open the cool new 'game mode' window
1537 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1538 fgGetInt("/sim/startup/xsize"),
1539 fgGetInt("/sim/startup/ysize"),
1540 fgGetInt("/sim/rendering/bits-per-pixel"));
1542 #endif // HAVE_WINDOWS_H
1543 SG_LOG( SG_GENERAL, SG_INFO,
1544 "game mode params = " << game_mode_str );
1545 glutGameModeString( game_mode_str );
1546 glutEnterGameMode();
1547 #endif // GLUT_WRONG_VERSION
1550 // This seems to be the absolute earliest in the init sequence
1551 // that these calls will return valid info. Too bad it's after
1552 // we've already created and sized out window. :-(
1553 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1554 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1555 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1556 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1559 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1560 general.set_glMaxTexSize( tmp );
1561 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1563 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1564 general.set_glDepthBits( tmp );
1565 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1571 // Initialize GLUT event handlers
1572 static bool fgGlutInitEvents( void ) {
1573 // call fgReshape() on window resizes
1574 glutReshapeFunc( fgReshape );
1576 // keyboard and mouse callbacks are set in FGInput::init
1578 // call fgMainLoop() whenever there is
1579 // nothing else to do
1580 glutIdleFunc( fgIdleFunction );
1583 glutDisplayFunc( fgRenderFrame );
1588 // Main top level initialization
1589 static bool fgMainInit( int argc, char **argv ) {
1591 #if defined( macintosh )
1592 freopen ("stdout.txt", "w", stdout );
1593 freopen ("stderr.txt", "w", stderr );
1594 argc = ccommand( &argv );
1597 // set default log levels
1598 sglog().setLogLevels( SG_ALL, SG_INFO );
1601 #ifdef FLIGHTGEAR_VERSION
1602 version = FLIGHTGEAR_VERSION;
1604 version = "unknown version";
1606 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1608 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1610 // Allocate global data structures. This needs to happen before
1611 // we parse command line options
1613 globals = new FGGlobals;
1615 // seed the random number generater
1618 SGRoute *route = new SGRoute;
1619 globals->set_route( route );
1621 FGControls *controls = new FGControls;
1622 globals->set_controls( controls );
1624 string_list *col = new string_list;
1625 globals->set_channel_options_list( col );
1627 // Scan the config file(s) and command line options to see if
1628 // fg_root was specified (ignore all other options for now)
1629 fgInitFGRoot(argc, argv);
1631 // Check for the correct base package version
1632 static char required_version[] = "0.9.2";
1633 string base_version = fgBasePackageVersion();
1634 if ( !(base_version == required_version) ) {
1635 // tell the operator how to use this application
1637 cerr << endl << "Base package check failed ... " \
1638 << "Found version " << base_version << " at: " \
1639 << globals->get_fg_root() << endl;
1640 cerr << "Please upgrade to version: " << required_version << endl;
1644 // Initialize the Aircraft directory to "" (UIUC)
1647 // Load the configuration parameters. (Command line options
1648 // overrides config file options. Config file options override
1650 if ( !fgInitConfig(argc, argv) ) {
1651 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1655 // Initialize the Window/Graphics environment.
1656 if( !fgGlutInit(&argc, argv) ) {
1657 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1661 // Initialize the various GLUT Event Handlers.
1662 if( !fgGlutInitEvents() ) {
1663 SG_LOG( SG_GENERAL, SG_ALERT,
1664 "GLUT event handler initialization failed ..." );
1668 // Initialize plib net interface
1669 netInit( &argc, argv );
1671 // Initialize ssg (from plib). Needs to come before we do any
1672 // other ssg stuff, but after opengl/glut has been initialized.
1675 // Initialize the user interface (we need to do this before
1676 // passing off control to glut and before fgInitGeneral to get our
1680 // Read the list of available aircrafts
1683 #ifdef GL_EXT_texture_lod_bias
1684 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1687 // get the address of our OpenGL extensions
1688 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1690 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1691 glPointParameterIsSupported = true;
1692 glPointParameterfPtr = (glPointParameterfProc)
1693 SGLookupFunction("glPointParameterfEXT");
1694 glPointParameterfvPtr = (glPointParameterfvProc)
1695 SGLookupFunction("glPointParameterfvEXT");
1697 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1698 glPointParameterIsSupported = true;
1699 glPointParameterfPtr = (glPointParameterfProc)
1700 SGLookupFunction("glPointParameterfARB");
1701 glPointParameterfvPtr = (glPointParameterfvProc)
1702 SGLookupFunction("glPointParameterfvARB");
1704 glPointParameterIsSupported = false;
1707 // based on the requested presets, calculate the true starting
1712 SGTime *t = fgInitTime();
1713 globals->set_time_params( t );
1715 // Do some quick general initializations
1716 if( !fgInitGeneral()) {
1717 SG_LOG( SG_GENERAL, SG_ALERT,
1718 "General initializations failed ..." );
1722 SGPath modelpath( globals->get_fg_root() );
1723 ssgModelPath( (char *)modelpath.c_str() );
1725 ////////////////////////////////////////////////////////////////////
1726 // Initialize the property-based built-in commands
1727 ////////////////////////////////////////////////////////////////////
1730 ////////////////////////////////////////////////////////////////////
1731 // Initialize the material manager
1732 ////////////////////////////////////////////////////////////////////
1733 globals->set_matlib( new SGMaterialLib );
1735 globals->set_model_lib(new SGModelLib);
1737 ////////////////////////////////////////////////////////////////////
1738 // Initialize the TG scenery subsystem.
1739 ////////////////////////////////////////////////////////////////////
1740 globals->set_scenery( new FGScenery );
1741 globals->get_scenery()->init();
1742 globals->get_scenery()->bind();
1743 globals->set_tile_mgr( new FGTileMgr );
1745 ////////////////////////////////////////////////////////////////////
1746 // Initialize the general model subsystem.
1747 ////////////////////////////////////////////////////////////////////
1748 globals->set_model_mgr(new FGModelMgr);
1749 globals->get_model_mgr()->init();
1750 globals->get_model_mgr()->bind();
1752 ////////////////////////////////////////////////////////////////////
1753 // Initialize the 3D aircraft model subsystem (has a dependency on
1754 // the scenery subsystem.)
1755 ////////////////////////////////////////////////////////////////////
1756 globals->set_aircraft_model(new FGAircraftModel);
1757 globals->get_aircraft_model()->init();
1758 globals->get_aircraft_model()->bind();
1760 ////////////////////////////////////////////////////////////////////
1761 // Initialize the view manager subsystem.
1762 ////////////////////////////////////////////////////////////////////
1763 FGViewMgr *viewmgr = new FGViewMgr;
1764 globals->set_viewmgr( viewmgr );
1769 // Initialize the sky
1770 SGPath ephem_data_path( globals->get_fg_root() );
1771 ephem_data_path.append( "Astro" );
1772 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1773 ephem->update( globals->get_time_params()->getMjd(),
1774 globals->get_time_params()->getLst(),
1776 globals->set_ephem( ephem );
1778 // TODO: move to environment mgr
1780 SGPath texture_path(globals->get_fg_root());
1781 texture_path.append("Textures");
1782 texture_path.append("Sky");
1783 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1784 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1785 thesky->add_cloud_layer(layer);
1789 SGPath sky_tex_path( globals->get_fg_root() );
1790 sky_tex_path.append( "Textures" );
1791 sky_tex_path.append( "Sky" );
1792 thesky->texture_path( sky_tex_path.str() );
1794 // The sun and moon diameters are scaled down numbers of the
1795 // actual diameters. This was needed to fit bot the sun and the
1796 // moon within the distance to the far clip plane.
1797 // Moon diameter: 3,476 kilometers
1798 // Sun diameter: 1,390,000 kilometers
1799 thesky->build( 80000.0, 80000.0,
1801 globals->get_ephem()->getNumPlanets(),
1802 globals->get_ephem()->getPlanets(),
1803 globals->get_ephem()->getNumStars(),
1804 globals->get_ephem()->getStars() );
1806 // Initialize MagVar model
1807 SGMagVar *magvar = new SGMagVar();
1808 globals->set_mag( magvar );
1811 // kludge to initialize mag compass
1812 // (should only be done for in-flight
1814 // update magvar model
1815 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1816 * SGD_DEGREES_TO_RADIANS,
1817 fgGetDouble("/position/latitude-deg")
1818 * SGD_DEGREES_TO_RADIANS,
1819 fgGetDouble("/position/altitude-ft")
1821 globals->get_time_params()->getJD() );
1822 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1823 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1825 // airport = new ssgBranch;
1826 // airport->setName( "Airport Lighting" );
1827 // lighting->addKid( airport );
1833 #ifdef FG_NETWORK_OLK
1834 // Do the network intialization
1835 if ( fgGetBool("/sim/networking/network-olk") ) {
1836 printf("Multipilot mode %s\n",
1837 fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1841 // build our custom render states
1842 fgBuildRenderStates();
1844 // pass control off to the master GLUT event handler
1847 // we never actually get here ... but to avoid compiler warnings,
1853 // $$$ end - added VS Renganathan, 15 Oct 2K
1854 // - added Venky , 12 Nov 2K
1856 #if defined(__linux__) && defined(__i386__)
1858 static void handleFPE (int);
1863 fpu_control_t fpe_flags = 0;
1864 _FPU_GETCW(fpe_flags);
1865 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1866 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1867 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1868 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1869 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1870 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1871 _FPU_SETCW(fpe_flags);
1872 signal(SIGFPE, handleFPE);
1879 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1892 short CPSGetCurrentProcess(PSN *psn);
1893 short CPSSetProcessName (PSN *psn, char *processname);
1894 short CPSEnableForegroundOperation(PSN *psn, int _arg2, int _arg3, int _arg4, int _arg5);
1895 short CPSSetFrontProcess(PSN *psn);
1898 #define CPSEnableFG(psn) CPSEnableForegroundOperation(psn,0x03,0x3C,0x2C,0x1103)
1902 // Main entry point; catch any exceptions that have made it this far.
1903 int main ( int argc, char **argv ) {
1905 // Enable floating-point exceptions for Linux/x86
1906 #if defined(__linux__) && defined(__i386__)
1910 // Enable floating-point exceptions for Windows
1911 #if defined( _MSC_VER ) && defined( DEBUG )
1912 // Christian, we should document what this does
1913 _control87( _EM_INEXACT, _MCW_EM );
1916 #if defined( HAVE_BC5PLUS )
1917 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1920 // Keyboard focus hack
1925 glutInit (&argc, argv);
1927 CPSGetCurrentProcess(&psn);
1928 CPSSetProcessName(&psn, "FlightGear");
1930 CPSSetFrontProcess(&psn);
1934 // FIXME: add other, more specific
1937 fgMainInit(argc, argv);
1938 } catch (sg_throwable &t) {
1939 // We must use cerr rather than
1940 // logging, since logging may be
1942 cerr << "Fatal error: " << t.getFormattedMessage()
1943 << "\n (received from " << t.getOrigin() << ')' << endl;
1951 void fgLoadDCS(void) {
1953 ssgEntity *ship_obj = NULL;
1955 char obj_filename[25];
1957 for ( int k = 0; k < 32; k++ ) {
1961 SGPath tile_path( globals->get_fg_root());
1962 tile_path.append( "Scenery" );
1963 tile_path.append( "Objects.txt" );
1964 sg_gzifstream in( tile_path.str() );
1965 if ( ! in.is_open() ) {
1966 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1969 SGPath modelpath( globals->get_fg_root() );
1970 modelpath.append( "Models" );
1971 modelpath.append( "Geometry" );
1973 SGPath texturepath( globals->get_fg_root() );
1974 texturepath.append( "Models" );
1975 texturepath.append( "Textures" );
1977 ssgModelPath( (char *)modelpath.c_str() );
1978 ssgTexturePath( (char *)texturepath.c_str() );
1980 ship_sel = new ssgSelector;
1983 while ( ! in.eof() ) {
1985 if ( in.get( c ) && c == '#' ) {
1989 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1990 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1991 int chj=getchar();*/
1993 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1994 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1996 ship_pos[objc] = new ssgTransform;
1998 // type "repeat" in objects.txt to load one more
1999 // instance of the last object.
2001 if ( strcmp(obj_filename,"repeat") != 0) {
2003 globals->get_model_lib()->load_model( globals->get_fg_root(), obj_filename, globals->get_props(), globals->get_sim_time_sec() );
2006 if ( ship_obj != NULL ) {
2007 ship_obj->setName(obj_filename);
2009 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
2011 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
2012 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
2013 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
2014 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
2017 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
2021 // temporary hack for deck lights - ultimately should move to PLib (when??)
2022 //const char *extn = file_extension ( obj_filename ) ;
2024 // ssgVertexArray *lights = new ssgVertexArray( 100 );
2025 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
2026 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
2027 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
2028 int ltype[500], light_type = 0;
2029 static int ltcount = 0;
2031 sgVec3 rway_dir,rway_normal,lightpt;
2033 modelpath.append(obj_filename);
2034 sg_gzifstream in1( modelpath.str() );
2035 if ( ! in1.is_open() ) {
2036 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
2038 while ( ! in1.eof() ) {
2040 if ( in1.get( c ) && c == '#' ) {
2045 //cout << token << endl;
2046 if ( token == "runway" ) {
2048 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
2049 } else if ( token == "edgelight" ) {
2051 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2053 } else if ( token == "taxi" ) {
2055 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2057 } else if ( token == "vasi" ) {
2059 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2061 } else if ( token == "threshold" ) {
2063 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2065 } else if ( token == "rabbit" ) {
2067 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2069 } else if ( token == "ols" ) {
2071 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
2073 } else if ( token == "red" ) {
2075 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2077 } else if ( token == "green" ) {
2079 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
2081 } else if ( token == "lp" ) {
2083 sgSetVec3 (lightpt, node[0], node[1], node[2] );
2084 lightpoints->add( lightpt );
2085 lightnormals->add( rway_normal );
2086 lightdir->add( rway_dir );
2087 ltype[ltcount]= light_type;
2090 if (in1.eof()) break;
2095 if ( lightpoints->getNum() ) {
2096 ssgBranch *lightpoints_branch;
2097 long int dummy = -999;
2098 dummy_tile = new FGTileEntry((SGBucket)dummy);
2099 dummy_tile->lightmaps_sequence = new ssgSelector;
2100 dummy_tile->ols_transform = new ssgTransform;
2102 // call function to generate the runway lights
2103 lightpoints_branch =
2104 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
2106 lightpoints_brightness->addKid(lightpoints_branch);
2107 lightpoints_transform->addKid(lightpoints_brightness);
2108 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
2109 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
2110 lightpoints_transform->ref();
2111 globals->get_scenery()->get_gnd_lights_root()->addKid( lightpoints_transform );
2116 // end hack for deck lights
2120 if (in.eof()) break;
2124 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
2126 globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node
2133 void fgUpdateDCS (void) {
2135 // double eye_lat,eye_lon,eye_alt;
2136 // static double obj_head;
2137 double sl_radius,obj_latgc;
2138 // float nresultmat[4][4];
2139 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
2142 // Instantaneous Geodetic Lat/Lon/Alt of moving object
2143 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
2145 // Deck should be the first object in objects.txt in case of fdm=ada
2147 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
2148 if ((fdm->get_iaux(1))==1)
2150 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
2151 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
2152 obj_alt[1] = fdm->get_daux(3);
2153 obj_pitch[1] = fdm->get_faux(1);
2154 obj_roll[1] = fdm->get_faux(2);
2158 for ( int m = 0; m < objc; m++ ) {
2159 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
2162 //Geodetic to Geocentric angles for rotation
2163 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
2165 //moving object gbs-posn in cartesian coords
2166 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
2167 Point3D obj_pos = sgGeodToCart( obj_posn );
2169 // Translate moving object w.r.t eye
2170 Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
2175 // rotate dynamic objects for lat,lon & alt and other motion about its axes
2178 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
2180 sgVec3 ship_fwd,ship_rt,ship_up;
2181 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
2182 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
2183 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
2185 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
2186 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
2187 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
2188 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
2189 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
2190 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2193 sgCopyMat4( sgTUX, sgROT_hdg );
2194 sgPostMultMat4( sgTUX, sgROT_pitch );
2195 sgPostMultMat4( sgTUX, sgROT_roll );
2196 sgPostMultMat4( sgTUX, sgROT_lat );
2197 sgPostMultMat4( sgTUX, sgROT_lon );
2198 sgPostMultMat4( sgTUX, sgTRANS );
2201 sgSetCoord(&shippos, sgTUX );
2202 ship_pos[m]->setTransform( &shippos );
2203 // temporary hack for deck lights - ultimately should move to PLib (when ??)
2205 if (lightpoints_transform) {
2206 lightpoints_transform->setTransform( &shippos );
2207 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2208 if ( sun_angle > 89 ) {
2209 lightpoints_brightness->select(0x01);
2211 lightpoints_brightness->select(0x00);
2220 sgXformPnt3( rp, rway_ols, sgTUX );
2221 vp = globals->get_current_view()->get_view_pos();
2222 to[0] = rp[0]-vp[0];
2223 to[1] = rp[1]-vp[1];
2224 to[2] = rp[2]-vp[2];
2225 float dist = sgLengthVec3( to );
2226 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2228 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2230 ref_elev = elev - 3.75; // +ve above, -ve below
2234 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2235 // if (ref_elev > 0.51) sel = 0x21;
2236 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2237 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2238 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2239 // if (ref_elev < -0.51) sel = 0x30;
2240 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2241 // dummy_tile->lightmaps_sequence->select(sel);
2244 sgCopyVec3 (up, ship_up);
2246 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2248 sgScaleVec3 (up, 4.0*ref_elev);
2249 // dummy_tile->ols_transform->setTransform(up);
2250 //cout << "ref_elev " << ref_elev << endl;
2252 // end hack for deck lights
2255 if ( ship_sel != NULL ) {
2256 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2260 // $$$ end - added VS Renganathan, 15 Oct 2K
2261 // added Venky , 12 Nov 2K