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 #include <simgear/compiler.h>
30 #if defined(__linux__) && defined(__i386__)
31 # include <fpu_control.h>
35 #ifdef SG_MATH_EXCEPTION_CLASH
45 #include <plib/netSocket.h>
47 #include <simgear/screen/extensions.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/props/props.hxx>
50 #include <simgear/scene/sky/sky.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/scene/model/animation.hxx>
53 #include <simgear/ephemeris/ephemeris.hxx>
54 #include <simgear/scene/model/placement.hxx>
55 #include <simgear/math/sg_random.h>
56 #include <simgear/scene/model/modellib.hxx>
58 #ifdef FG_USE_CLOUDS_3D
59 # include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
60 # include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
63 #include <Include/general.hxx>
64 #include <Scenery/tileentry.hxx>
65 #include <Time/light.hxx>
66 #include <Time/light.hxx>
67 #include <Aircraft/aircraft.hxx>
68 #include <Cockpit/panel.hxx>
69 #include <Cockpit/cockpit.hxx>
70 #include <Cockpit/radiostack.hxx>
71 #include <Cockpit/hud.hxx>
72 #include <Model/panelnode.hxx>
73 #include <Model/modelmgr.hxx>
74 #include <Model/acmodel.hxx>
75 #include <Scenery/scenery.hxx>
76 #include <Scenery/tilemgr.hxx>
77 #include <FDM/flight.hxx>
78 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
79 #include <FDM/ADA.hxx>
80 #include <ATC/ATCdisplay.hxx>
81 #include <ATC/ATCmgr.hxx>
82 #include <ATC/AIMgr.hxx>
83 #include <Replay/replay.hxx>
84 #include <Time/tmp.hxx>
85 #include <Time/fg_timer.hxx>
86 #include <Environment/environment_mgr.hxx>
89 #include <MultiPlayer/multiplaytxmgr.hxx>
90 #include <MultiPlayer/multiplayrxmgr.hxx>
94 #include "fg_commands.hxx"
98 float default_attenuation[3] = {1.0, 0.0, 0.0};
99 ssgSelector *ship_sel=NULL;
100 // upto 32 instances of a same object can be loaded.
101 ssgTransform *ship_pos[32];
102 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
104 ssgSelector *lightpoints_brightness = new ssgSelector;
105 ssgTransform *lightpoints_transform = new ssgTransform;
106 FGTileEntry *dummy_tile;
109 // Clip plane settings...
110 float scene_nearplane = 0.5f;
111 float scene_farplane = 120000.0f;
113 static double real_delta_time_sec = 0.0;
114 static double delta_time_sec = 0.0;
116 glPointParameterfProc glPointParameterfPtr = 0;
117 glPointParameterfvProc glPointParameterfvPtr = 0;
118 bool glPointParameterIsSupported = false;
122 # include <console.h> // -dw- for command line dialog
125 // This is a record containing a bit of global housekeeping information
128 // Specify our current idle function state. This is used to run all
129 // our initializations out of the idle callback so that we can get a
130 // splash screen up and running right away.
131 static int idle_state = 0;
132 static long global_multi_loop;
134 // fog constants. I'm a little nervous about putting actual code out
135 // here but it seems to work (?)
136 static const double m_log01 = -log( 0.01 );
137 static const double sqrt_m_log01 = sqrt( m_log01 );
138 static GLfloat fog_exp_density;
139 static GLfloat fog_exp2_density;
140 static GLfloat rwy_exp2_punch_through;
141 static GLfloat taxi_exp2_punch_through;
142 static GLfloat ground_exp2_punch_through;
147 #ifdef FG_USE_CLOUDS_3D
148 SkySceneLoader *sgClouds3d;
149 bool _bcloud_orig = true;
153 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
155 { 1.0f, 0.0f, 0.0f, 0.0f },
156 { 0.0f, 0.0f, -1.0f, 0.0f },
157 { 0.0f, 1.0f, 0.0f, 0.0f },
158 { 0.0f, 0.0f, 0.0f, 1.0f }
161 ssgSimpleState *cloud3d_imposter_state;
162 ssgSimpleState *default_state;
163 ssgSimpleState *hud_and_panel;
164 ssgSimpleState *menus;
166 SGTimeStamp last_time_stamp;
167 SGTimeStamp current_time_stamp;
170 void fgBuildRenderStates( void ) {
171 default_state = new ssgSimpleState;
172 default_state->ref();
173 default_state->disable( GL_TEXTURE_2D );
174 default_state->enable( GL_CULL_FACE );
175 default_state->enable( GL_COLOR_MATERIAL );
176 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
177 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
178 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
179 default_state->disable( GL_BLEND );
180 default_state->disable( GL_ALPHA_TEST );
181 default_state->disable( GL_LIGHTING );
183 cloud3d_imposter_state = new ssgSimpleState;
184 cloud3d_imposter_state->ref();
185 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
186 cloud3d_imposter_state->enable( GL_CULL_FACE );
187 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
188 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
189 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
190 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
191 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
192 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
193 cloud3d_imposter_state->enable( GL_BLEND );
194 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
195 cloud3d_imposter_state->disable( GL_LIGHTING );
197 hud_and_panel = new ssgSimpleState;
198 hud_and_panel->ref();
199 hud_and_panel->disable( GL_CULL_FACE );
200 hud_and_panel->disable( GL_TEXTURE_2D );
201 hud_and_panel->disable( GL_LIGHTING );
202 hud_and_panel->enable( GL_BLEND );
204 menus = new ssgSimpleState;
206 menus->disable( GL_CULL_FACE );
207 menus->disable( GL_TEXTURE_2D );
208 menus->enable( GL_BLEND );
212 // fgInitVisuals() -- Initialize various GL/view parameters
213 void fgInitVisuals( void ) {
215 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
217 // Go full screen if requested ...
218 if ( fgGetBool("/sim/startup/fullscreen") ) {
222 // If enabled, normal vectors specified with glNormal are scaled
223 // to unit length after transformation. Enabling this has
224 // performance implications. See the docs for glNormal.
225 // glEnable( GL_NORMALIZE );
227 glEnable( GL_LIGHTING );
228 glEnable( GL_LIGHT0 );
229 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
232 sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
233 ssgGetLight( 0 ) -> setPosition( sunpos );
235 glFogi (GL_FOG_MODE, GL_EXP2);
236 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
237 (!fgGetBool("/sim/rendering/shading"))) {
238 // if fastest fog requested, or if flat shading force fastest
239 glHint ( GL_FOG_HINT, GL_FASTEST );
240 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
241 glHint ( GL_FOG_HINT, GL_NICEST );
243 if ( fgGetBool("/sim/rendering/wireframe") ) {
245 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
248 // This is the default anyways, but it can't hurt
249 glFrontFace ( GL_CCW );
252 // glEnable(GL_POINT_SMOOTH);
253 // glEnable(GL_LINE_SMOOTH);
254 // glEnable(GL_POLYGON_SMOOTH);
258 // For HiRes screen Dumps using Brian Pauls TR Library
259 void trRenderFrame( void ) {
260 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
261 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds");
263 bool multi_pass_clouds = false;
265 bool draw_clouds = fgGetBool("/environment/clouds/status");
267 if ( fgPanelVisible() ) {
268 GLfloat height = fgGetInt("/sim/startup/ysize");
270 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
271 * (height / 768.0) + 1;
272 glTranslatef( 0.0, view_h, 0.0 );
275 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
276 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
278 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
280 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
281 l->adj_fog_color()[2], l->adj_fog_color()[3]);
283 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
285 // set the opengl state to known default values
286 default_state->force();
289 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
290 glFogi ( GL_FOG_MODE, GL_EXP2 );
291 glFogfv ( GL_FOG_COLOR, l->adj_fog_color() );
293 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
294 // we only update GL_AMBIENT for our lights we will never get
295 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
296 // explicitely to black.
297 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
298 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
300 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
302 // texture parameters
303 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
304 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
306 // we need a white diffuse light for the phase of the moon
307 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
308 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
311 // draw the ssg scene
312 // return to the desired diffuse color
313 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
314 glEnable( GL_DEPTH_TEST );
315 ssgSetNearFar( scene_nearplane, scene_farplane );
318 FGTileMgr::set_tile_filter( true );
319 sgSetModelFilter( false );
320 globals->get_aircraft_model()->select( false );
321 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
322 // Disable depth buffer update, draw the clouds
323 glDepthMask( GL_FALSE );
324 thesky->drawUpperClouds();
325 if ( multi_pass_clouds ) {
326 thesky->drawLowerClouds();
328 glDepthMask( GL_TRUE );
329 if ( multi_pass_clouds ) {
330 // Draw the objects except the aircraft
331 // and update the stencil buffer with 1
332 glEnable( GL_STENCIL_TEST );
333 glStencilFunc( GL_ALWAYS, 1, 1 );
334 glStencilOp( GL_REPLACE, GL_REPLACE, GL_REPLACE );
336 FGTileMgr::set_tile_filter( false );
337 sgSetModelFilter( true );
338 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
340 FGTileMgr::set_tile_filter( true );
341 sgSetModelFilter( true );
342 globals->get_aircraft_model()->select( false );
343 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
347 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
348 ssgSetNearFar( scene_nearplane, scene_farplane );
349 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
350 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
352 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
355 if ( multi_pass_clouds ) {
356 // Disable depth buffer update, draw the clouds where the
357 // objects overwrite the already drawn clouds, by testing
358 // the stencil buffer against 1
359 glDepthMask( GL_FALSE );
360 glStencilFunc( GL_EQUAL, 1, 1 );
361 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
362 thesky->drawUpperClouds();
363 thesky->drawLowerClouds();
364 glDepthMask( GL_TRUE );
365 glDisable( GL_STENCIL_TEST );
367 glDepthMask( GL_FALSE );
368 thesky->drawLowerClouds();
369 glDepthMask( GL_TRUE );
373 globals->get_aircraft_model()->select( true );
374 globals->get_model_mgr()->draw();
375 globals->get_aircraft_model()->draw();
379 // Update all Visuals (redraws anything graphics related)
380 void fgRenderFrame() {
381 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
382 bool skyblend = fgGetBool("/sim/rendering/skyblend");
383 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
384 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
385 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
386 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds");
388 bool multi_pass_clouds = false;
390 bool draw_clouds = fgGetBool("/environment/clouds/status");
392 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
393 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
395 // static const SGPropertyNode *longitude
396 // = fgGetNode("/position/longitude-deg");
397 // static const SGPropertyNode *latitude
398 // = fgGetNode("/position/latitude-deg");
399 // static const SGPropertyNode *altitude
400 // = fgGetNode("/position/altitude-ft");
401 static const SGPropertyNode *groundlevel_nearplane
402 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
404 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
405 static double last_visibility = -9999;
408 double actual_visibility;
409 if (fgGetBool("/environment/clouds/status"))
410 actual_visibility = thesky->get_visibility();
412 actual_visibility = fgGetDouble("/environment/visibility-m");
413 if ( actual_visibility != last_visibility ) {
414 last_visibility = actual_visibility;
416 fog_exp_density = m_log01 / actual_visibility;
417 fog_exp2_density = sqrt_m_log01 / actual_visibility;
418 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
419 if ( actual_visibility < 8000 ) {
420 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
421 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
423 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
424 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
429 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
430 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
431 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
432 // GLfloat mat_shininess[] = { 10.0 };
433 GLbitfield clear_mask;
435 if ( idle_state != 1000 ) {
436 // still initializing, draw the splash screen
437 if ( fgGetBool("/sim/startup/splash-screen") ) {
438 fgSplashUpdate(0.0, 1.0);
440 // Keep resetting sim time while the sim is initializing
441 globals->set_sim_time_sec( 0.0 );
442 SGAnimation::set_sim_time_sec( 0.0 );
444 // idle_state is now 1000 meaning we've finished all our
445 // initializations and are running the main loop, so this will
446 // now work without seg faulting the system.
448 FGViewer *current__view = globals->get_current_view();
450 // calculate our current position in cartesian space
451 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
454 fgReshape( fgGetInt("/sim/startup/xsize"),
455 fgGetInt("/sim/startup/ysize") );
457 if ( fgGetBool("/sim/rendering/clouds3d") ) {
458 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
459 cloud3d_imposter_state->force();
461 glColor4f( 1.0, 1.0, 1.0, 1.0 );
462 glEnable(GL_DEPTH_TEST);
464 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
466 #ifdef FG_USE_CLOUDS_3D
467 if ( _bcloud_orig ) {
468 Point3D c = globals->get_scenery()->get_center();
469 sgClouds3d->Set_Cloud_Orig( &c );
470 _bcloud_orig = false;
472 sgClouds3d->Update( current__view->get_absolute_view_pos() );
474 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
475 glDisable(GL_DEPTH_TEST);
478 clear_mask = GL_DEPTH_BUFFER_BIT;
479 if ( fgGetBool("/sim/rendering/wireframe") ) {
480 clear_mask |= GL_COLOR_BUFFER_BIT;
484 if ( fgGetBool("/sim/rendering/textures") ) {
485 // glClearColor(black[0], black[1], black[2], black[3]);
486 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
487 l->adj_fog_color()[2], l->adj_fog_color()[3]);
488 clear_mask |= GL_COLOR_BUFFER_BIT;
491 glClearColor(l->sky_color()[0], l->sky_color()[1],
492 l->sky_color()[2], l->sky_color()[3]);
493 clear_mask |= GL_COLOR_BUFFER_BIT;
495 if ( multi_pass_clouds && draw_clouds ) {
497 clear_mask |= GL_STENCIL_BUFFER_BIT;
499 glClear( clear_mask );
501 // Tell GL we are switching to model view parameters
503 // I really should create a derived ssg node or use a call
504 // back or something so that I can draw the sky within the
505 // ssgCullAndDraw() function, but for now I just mimic what
506 // ssg does to set up the model view matrix
507 glMatrixMode(GL_MODELVIEW);
509 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
511 // set the opengl state to known default values
512 default_state->force();
514 // update fog params if visibility has changed
515 double visibility_meters = fgGetDouble("/environment/visibility-m");
516 thesky->set_visibility(visibility_meters);
518 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
519 ( global_multi_loop * fgGetInt("/sim/speed-up") )
520 / (double)fgGetInt("/sim/model-hz") );
522 // Set correct opengl fog density
523 glFogf (GL_FOG_DENSITY, fog_exp2_density);
525 // update the sky dome
528 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
529 << l->sky_color()[0] << " "
530 << l->sky_color()[1] << " "
531 << l->sky_color()[2] << " "
532 << l->sky_color()[3] );
533 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
534 << l->fog_color()[0] << " "
535 << l->fog_color()[1] << " "
536 << l->fog_color()[2] << " "
537 << l->fog_color()[3] );
538 SG_LOG( SG_GENERAL, SG_BULK,
539 " sun_angle = " << l->sun_angle
540 << " moon_angle = " << l->moon_angle );
543 static SGSkyColor scolor;
544 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
546 scolor.sky_color = l->sky_color();
547 scolor.fog_color = l->adj_fog_color();
548 scolor.cloud_color = l->cloud_color();
549 scolor.sun_angle = l->get_sun_angle();
550 scolor.moon_angle = l->get_moon_angle();
551 scolor.nplanets = globals->get_ephem()->getNumPlanets();
552 scolor.nstars = globals->get_ephem()->getNumStars();
553 scolor.planet_data = globals->get_ephem()->getPlanets();
554 scolor.star_data = globals->get_ephem()->getStars();
556 thesky->repaint( scolor );
559 SG_LOG( SG_GENERAL, SG_BULK,
560 "thesky->reposition( view_pos = " << view_pos[0] << " "
561 << view_pos[1] << " " << view_pos[2] );
562 SG_LOG( SG_GENERAL, SG_BULK,
563 " zero_elev = " << zero_elev[0] << " "
564 << zero_elev[1] << " " << zero_elev[2]
565 << " lon = " << cur_fdm_state->get_Longitude()
566 << " lat = " << cur_fdm_state->get_Latitude() );
567 SG_LOG( SG_GENERAL, SG_BULK,
568 " sun_rot = " << l->get_sun_rotation
569 << " gst = " << SGTime::cur_time_params->getGst() );
570 SG_LOG( SG_GENERAL, SG_BULK,
571 " sun ra = " << globals->get_ephem()->getSunRightAscension()
572 << " sun dec = " << globals->get_ephem()->getSunDeclination()
573 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
574 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
577 // The sun and moon distances are scaled down versions
578 // of the actual distance to get both the moon and the sun
579 // within the range of the far clip plane.
580 // Moon distance: 384,467 kilometers
581 // Sun distance: 150,000,000 kilometers
582 double sun_horiz_eff, moon_horiz_eff;
583 if (fgGetBool("/sim/rendering/horizon-effect")) {
584 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
585 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
587 sun_horiz_eff = moon_horiz_eff = 1.0;
590 static SGSkyState sstate;
592 sstate.view_pos = current__view->get_view_pos();
593 sstate.zero_elev = current__view->get_zero_elev();
594 sstate.view_up = current__view->get_world_up();
595 sstate.lon = current__view->getLongitude_deg()
596 * SGD_DEGREES_TO_RADIANS;
597 sstate.lat = current__view->getLatitude_deg()
598 * SGD_DEGREES_TO_RADIANS;
599 sstate.alt = current__view->getAltitudeASL_ft()
601 sstate.spin = l->get_sun_rotation();
602 sstate.gst = globals->get_time_params()->getGst();
603 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
604 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
605 sstate.sun_dist = 50000.0 * sun_horiz_eff;
606 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
607 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
608 sstate.moon_dist = 40000.0 * moon_horiz_eff;
610 thesky->reposition( sstate, delta_time_sec );
613 glEnable( GL_DEPTH_TEST );
614 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
616 glFogi( GL_FOG_MODE, GL_EXP2 );
617 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
620 // set sun/lighting parameters
621 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
623 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
624 // we only update GL_AMBIENT for our lights we will never get
625 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
626 // explicitely to black.
627 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
629 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
630 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
631 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
633 // texture parameters
634 // glEnable( GL_TEXTURE_2D );
635 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
636 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
638 // glMatrixMode( GL_PROJECTION );
640 ssgSetFOV( current__view->get_h_fov(),
641 current__view->get_v_fov() );
644 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
645 - globals->get_scenery()->get_cur_elev();
648 scene_nearplane = 10.0f;
649 scene_farplane = 120000.0f;
651 scene_nearplane = groundlevel_nearplane->getDoubleValue();
652 scene_farplane = 120000.0f;
655 ssgSetNearFar( scene_nearplane, scene_farplane );
658 // Update any multiplayer models
659 globals->get_multiplayer_rx_mgr()->Update();
662 if ( draw_otw && skyblend ) {
663 // draw the sky backdrop
665 // we need a white diffuse light for the phase of the moon
666 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
667 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
669 // return to the desired diffuse color
670 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
673 // draw the ssg scene
674 glEnable( GL_DEPTH_TEST );
676 ssgSetNearFar( scene_nearplane, scene_farplane );
678 if ( fgGetBool("/sim/rendering/wireframe") ) {
680 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
686 FGTileMgr::set_tile_filter( true );
687 sgSetModelFilter( false );
688 globals->get_aircraft_model()->select( false );
689 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
691 // Disable depth buffer update, draw the clouds
692 glDepthMask( GL_FALSE );
693 thesky->drawUpperClouds();
694 if ( multi_pass_clouds ) {
695 thesky->drawLowerClouds();
697 glDepthMask( GL_TRUE );
699 if ( multi_pass_clouds ) {
700 // Draw the objects except the aircraft
701 // and update the stencil buffer with 1
702 glEnable( GL_STENCIL_TEST );
703 glStencilFunc( GL_ALWAYS, 1, 1 );
704 glStencilOp( GL_REPLACE, GL_REPLACE, GL_REPLACE );
706 FGTileMgr::set_tile_filter( false );
707 sgSetModelFilter( true );
708 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
710 FGTileMgr::set_tile_filter( true );
711 sgSetModelFilter( true );
712 globals->get_aircraft_model()->select( false );
713 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
717 // This is a bit kludgy. Every 200 frames, do an extra
718 // traversal of the scene graph without drawing anything, but
719 // with the field-of-view set to 360x360 degrees. This
720 // ensures that out-of-range random objects that are not in
721 // the current view frustum will still be freed properly.
722 static int counter = 0;
724 if (counter == 200) {
727 // No need to put the near plane too close;
728 // this way, at least the aircraft can be
730 f.setNearFar(1000, 1000000);
732 ssgGetModelviewMatrix(m);
733 FGTileMgr::set_tile_filter( true );
734 sgSetModelFilter( true );
735 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
739 // change state for lighting here
741 // draw runway lighting
742 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
743 ssgSetNearFar( scene_nearplane, scene_farplane );
745 if ( enhanced_lighting ) {
747 // Enable states for drawing points with GL_extension
748 glEnable(GL_POINT_SMOOTH);
750 if ( distance_attenuation && glPointParameterIsSupported )
752 // Enable states for drawing points with GL_extension
753 glEnable(GL_POINT_SMOOTH);
755 float quadratic[3] = {1.0, 0.001, 0.0000001};
756 // makes the points fade as they move away
757 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
758 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
763 // blending function for runway lights
764 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
767 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
768 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
769 glEnable(GL_TEXTURE_GEN_S);
770 glEnable(GL_TEXTURE_GEN_T);
771 glPolygonMode(GL_FRONT, GL_POINT);
773 // draw runway lighting
775 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
776 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
779 // change punch through and then draw taxi lighting
780 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
782 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
783 // glFogfv ( GL_FOG_COLOR, taxi_fog );
785 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
789 glPolygonMode(GL_FRONT, GL_FILL);
790 glDisable(GL_TEXTURE_GEN_S);
791 glDisable(GL_TEXTURE_GEN_T);
793 //static int _frame_count = 0;
794 //if (_frame_count % 30 == 0) {
795 // printf("SSG: %s\n", ssgShowStats());
803 if ( enhanced_lighting ) {
804 if ( distance_attenuation && glPointParameterIsSupported ) {
805 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
806 default_attenuation);
810 glDisable(GL_POINT_SMOOTH);
813 // draw ground lighting
814 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
816 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
819 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") ) {
821 glDisable( GL_LIGHTING );
822 // cout << "drawing new clouds" << endl;
824 glEnable(GL_DEPTH_TEST);
826 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
829 glEnable( GL_TEXTURE_2D );
830 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
831 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
832 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
833 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
836 #ifdef FG_USE_CLOUDS_3D
837 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
840 glEnable( GL_LIGHTING );
841 glEnable( GL_DEPTH_TEST );
842 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
845 if ( draw_otw && draw_clouds ) {
846 if ( multi_pass_clouds ) {
847 // Disable depth buffer update, draw the clouds where the
848 // objects overwrite the already drawn clouds, by testing
849 // the stencil buffer against 1
850 glDepthMask( GL_FALSE );
851 glStencilFunc( GL_EQUAL, 1, 1 );
852 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
853 thesky->drawUpperClouds();
854 thesky->drawLowerClouds();
855 glDepthMask( GL_TRUE );
856 glDisable( GL_STENCIL_TEST );
858 glDepthMask( GL_FALSE );
859 thesky->drawLowerClouds();
860 glDepthMask( GL_TRUE );
865 FGTileMgr::set_tile_filter( false );
866 sgSetModelFilter( false );
867 globals->get_aircraft_model()->select( true );
868 globals->get_model_mgr()->draw();
869 globals->get_aircraft_model()->draw();
870 // If the view is internal, the previous line draw the
871 // cockpit with modified near/far clip planes and deselect
872 // the aircraft in the global scenegraph
873 // Otherwise, it just enables the aircraft: The scenegraph
874 // must be drawn again to see the plane.
875 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
876 FGTileMgr::set_tile_filter( true );
877 sgSetModelFilter( true );
878 globals->get_aircraft_model()->select( true );
881 // display HUD && Panel
883 glDisable( GL_DEPTH_TEST );
884 // glDisable( GL_CULL_FACE );
885 // glDisable( GL_TEXTURE_2D );
887 // update the controls subsystem
888 globals->get_controls()->update(delta_time_sec);
890 hud_and_panel->apply();
893 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
894 // This only works properly if called before the panel call
895 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
896 globals->get_ATC_display()->update(delta_time_sec);
898 // update the panel subsystem
899 if ( globals->get_current_panel() != NULL ) {
900 globals->get_current_panel()->update(delta_time_sec);
904 // We can do translucent menus, so why not. :-)
906 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
908 // glDisable ( GL_BLEND ) ;
910 glEnable( GL_DEPTH_TEST );
913 // Fade out the splash screen over the first three seconds.
914 double t = globals->get_sim_time_sec();
916 fgSplashUpdate(0.0, 1.0);
917 } else if ( t <= 3.0) {
918 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
924 // Update internal time dependent calculations (i.e. flight model)
925 // FIXME: this distinction is obsolete; all subsystems now get delta
927 void fgUpdateTimeDepCalcs() {
928 static bool inited = false;
930 static const SGPropertyNode *replay_master
931 = fgGetNode( "/sim/freeze/replay", true );
932 static SGPropertyNode *replay_time
933 = fgGetNode( "/sim/replay/time", true );
934 // static const SGPropertyNode *replay_end_time
935 // = fgGetNode( "/sim/replay/end-time", true );
937 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
939 // Initialize the FDM here if it hasn't been and if we have a
940 // scenery elevation hit.
942 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
943 // << " cur_elev = " << scenery.get_cur_elev() << endl;
945 if ( !cur_fdm_state->get_inited() &&
946 globals->get_scenery()->get_cur_elev() > -9990 )
948 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
949 cur_fdm_state->init();
950 if ( cur_fdm_state->get_bound() ) {
951 cur_fdm_state->unbind();
953 cur_fdm_state->bind();
956 // conceptually, the following block could be done for each fdm
958 if ( cur_fdm_state->get_inited() ) {
959 // we have been inited, and we are good to go ...
965 if ( ! replay_master->getBoolValue() ) {
966 cur_fdm_state->update( delta_time_sec );
968 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
969 r->replay( replay_time->getDoubleValue() );
970 replay_time->setDoubleValue( replay_time->getDoubleValue()
972 * fgGetInt("/sim/speed-up") ) );
975 // do nothing, fdm isn't inited yet
978 globals->get_model_mgr()->update(delta_time_sec);
979 globals->get_aircraft_model()->update(delta_time_sec);
981 // update the view angle
982 globals->get_viewmgr()->update(delta_time_sec);
984 // Update solar system
985 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
986 globals->get_time_params()->getLst(),
987 cur_fdm_state->get_Latitude() );
989 // Update radio stack model
990 current_radiostack->update(delta_time_sec);
994 void fgInitTimeDepCalcs( void ) {
999 static const double alt_adjust_ft = 3.758099;
1000 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1003 // What should we do when we have nothing else to do? Let's get ready
1004 // for the next move and update the display?
1005 static void fgMainLoop( void ) {
1006 int model_hz = fgGetInt("/sim/model-hz");
1008 static const SGPropertyNode *longitude
1009 = fgGetNode("/position/longitude-deg");
1010 static const SGPropertyNode *latitude
1011 = fgGetNode("/position/latitude-deg");
1012 static const SGPropertyNode *altitude
1013 = fgGetNode("/position/altitude-ft");
1014 static const SGPropertyNode *clock_freeze
1015 = fgGetNode("/sim/freeze/clock", true);
1016 static const SGPropertyNode *cur_time_override
1017 = fgGetNode("/sim/time/cur-time-override", true);
1018 // static const SGPropertyNode *replay_master
1019 // = fgGetNode("/sim/freeze/replay", true);
1021 // Update the elapsed time.
1022 static bool first_time = true;
1024 last_time_stamp.stamp();
1028 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1029 if ( throttle_hz > 0.0 ) {
1030 // simple frame rate throttle
1031 double dt = 1000000.0 / throttle_hz;
1032 current_time_stamp.stamp();
1033 while ( current_time_stamp - last_time_stamp < dt ) {
1034 current_time_stamp.stamp();
1037 // run as fast as the app will go
1038 current_time_stamp.stamp();
1042 = double(current_time_stamp - last_time_stamp) / 1000000.0;
1043 if ( clock_freeze->getBoolValue() ) {
1046 delta_time_sec = real_delta_time_sec;
1048 last_time_stamp = current_time_stamp;
1049 globals->inc_sim_time_sec( delta_time_sec );
1050 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1052 // These are useful, especially for Nasal scripts.
1053 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
1054 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
1056 static long remainder = 0;
1058 #ifdef FANCY_FRAME_COUNTER
1062 static time_t last_time = 0;
1063 static int frames = 0;
1064 #endif // FANCY_FRAME_COUNTER
1066 SGTime *t = globals->get_time_params();
1068 globals->get_event_mgr()->update(delta_time_sec);
1070 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1071 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1073 #if defined( ENABLE_PLIB_JOYSTICK )
1074 // Read joystick and update control settings
1075 // if ( fgGetString("/sim/control-mode") == "joystick" )
1077 // fgJoystickRead();
1081 // Fix elevation. I'm just sticking this here for now, it should
1082 // probably move eventually
1084 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1085 scenery.get_cur_elev(),
1086 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1087 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1089 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1090 scenery.get_cur_elev(),
1091 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1092 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1094 // cout << "Warp = " << globals->get_warp() << endl;
1097 static bool last_clock_freeze = false;
1099 if ( clock_freeze->getBoolValue() ) {
1100 // clock freeze requested
1101 if ( cur_time_override->getLongValue() == 0 ) {
1102 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1103 globals->set_warp( 0 );
1106 // no clock freeze requested
1107 if ( last_clock_freeze == true ) {
1108 // clock just unfroze, let's set warp as the difference
1109 // between frozen time and current time so we don't get a
1110 // time jump (and corresponding sky object and lighting
1112 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1113 fgSetLong( "/sim/time/cur-time-override", 0 );
1115 if ( globals->get_warp_delta() != 0 ) {
1116 globals->inc_warp( globals->get_warp_delta() );
1120 last_clock_freeze = clock_freeze->getBoolValue();
1122 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1123 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1124 cur_time_override->getLongValue(),
1125 globals->get_warp() );
1127 if (globals->get_warp_delta() != 0) {
1128 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1132 // update magvar model
1133 globals->get_mag()->update( longitude->getDoubleValue()
1134 * SGD_DEGREES_TO_RADIANS,
1135 latitude->getDoubleValue()
1136 * SGD_DEGREES_TO_RADIANS,
1137 altitude->getDoubleValue() * SG_FEET_TO_METER,
1138 globals->get_time_params()->getJD() );
1140 // Get elapsed time (in usec) for this past frame
1141 elapsed = fgGetTimeInterval();
1142 SG_LOG( SG_ALL, SG_DEBUG,
1143 "Elapsed time interval is = " << elapsed
1144 << ", previous remainder is = " << remainder );
1146 // Calculate frame rate average
1147 #ifdef FANCY_FRAME_COUNTER
1148 /* old fps calculation */
1149 if ( elapsed > 0 ) {
1152 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1153 tmp = general.get_frame(i);
1155 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1156 general.set_frame(i+1,tmp);
1158 tmp = 1000000.0 / (float)elapsed;
1159 general.set_frame(0,tmp);
1160 // printf("frame[0] = %.2f\n", general.frames[0]);
1162 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1163 // printf("ave = %.2f\n", general.frame_rate);
1166 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1167 general.set_frame_rate( frames );
1168 fgSetInt("/sim/frame-rate", frames);
1169 SG_LOG( SG_ALL, SG_DEBUG,
1170 "--> Frame rate is = " << general.get_frame_rate() );
1173 last_time = t->get_cur_time();
1177 // Run ATC subsystem
1178 if (fgGetBool("/sim/ATC/enabled"))
1179 globals->get_ATC_mgr()->update(delta_time_sec);
1181 // Run the AI subsystem
1182 if (fgGetBool("/sim/ai-traffic/enabled"))
1183 globals->get_AI_mgr()->update(delta_time_sec);
1187 // Calculate model iterations needed for next frame
1188 elapsed += remainder;
1190 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1191 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1192 SG_LOG( SG_ALL, SG_DEBUG,
1193 "Model iterations needed = " << global_multi_loop
1194 << ", new remainder = " << remainder );
1196 // chop max interations to something reasonable if the sim was
1197 // delayed for an excesive amount of time
1198 if ( global_multi_loop > 2.0 * model_hz ) {
1199 global_multi_loop = (int)(2.0 * model_hz );
1204 if ( global_multi_loop > 0 ) {
1205 fgUpdateTimeDepCalcs();
1207 SG_LOG( SG_ALL, SG_DEBUG,
1208 "Elapsed time is zero ... we're zinging" );
1211 // Do any I/O channel work that might need to be done
1212 globals->get_io()->update( real_delta_time_sec );
1214 // see if we need to load any deferred-load textures
1215 globals->get_matlib()->load_next_deferred();
1217 // Run audio scheduler
1218 #ifdef ENABLE_AUDIO_SUPPORT
1219 if ( globals->get_soundmgr()->is_working() ) {
1220 globals->get_soundmgr()->update( delta_time_sec );
1224 globals->get_subsystem_mgr()->update(delta_time_sec);
1227 // Tile Manager updates - see if we need to load any new scenery tiles.
1228 // this code ties together the fdm, viewer and scenery classes...
1229 // we may want to move this to it's own class at some point
1231 double visibility_meters = fgGetDouble("/environment/visibility-m");
1232 FGViewer *current_view = globals->get_current_view();
1234 // get the location data for the primary FDM (now hardcoded to ac model)...
1235 SGLocation *acmodel_loc = NULL;
1236 acmodel_loc = (SGLocation *)globals->
1237 get_aircraft_model()->get3DModel()->getSGLocation();
1239 // update tile manager for FDM...
1240 // ...only if location is different than the current-view location
1241 // (to avoid duplicating effort)
1242 if( !fgGetBool("/sim/current-view/config/from-model") ) {
1243 if( acmodel_loc != NULL ) {
1244 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_loc,
1245 visibility_meters );
1246 globals->get_tile_mgr()->
1247 update( acmodel_loc, visibility_meters,
1249 get_absolute_view_pos(globals->
1250 get_scenery()->get_center()) );
1251 // save results of update in SGLocation for fdm...
1252 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1254 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1255 fgSetDouble("/position/ground-elev-m",
1256 globals->get_scenery()->get_cur_elev());
1259 set_tile_center( globals->get_scenery()->get_next_center() );
1263 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1264 visibility_meters );
1265 // update tile manager for view...
1266 // IMPORTANT!!! the tilemgr update for view location _must_ be
1267 // done last after the FDM's until all of Flight Gear code
1268 // references the viewer's location for elevation instead of the
1269 // "scenery's" current elevation.
1270 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1271 globals->get_tile_mgr()->update( view_location, visibility_meters,
1272 current_view->get_absolute_view_pos() );
1273 // save results of update in SGLocation for fdm...
1274 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1275 current_view->getSGLocation()->
1276 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1278 current_view->getSGLocation()->
1279 set_tile_center( globals->get_scenery()->get_next_center() );
1281 #ifdef ENABLE_AUDIO_SUPPORT
1282 // Right now we make a simplifying assumption that the primary
1283 // aircraft is the source of all sounds and that all sounds are
1284 // positioned relative to the current view position.
1286 static sgVec3 last_pos_offset;
1288 // set positional offset for sources
1289 sgVec3 source_pos_offset;
1290 sgSubVec3( source_pos_offset,
1291 view_location->get_view_pos(), acmodel_loc->get_view_pos() );
1292 // cout << "pos all = " << source_pos_offset[0] << " " << source_pos_offset[1] << " " << source_pos_offset[2] << endl;
1293 globals->get_soundmgr()->set_source_pos_all( source_pos_offset );
1297 sgSubVec3( source_vel, source_pos_offset, last_pos_offset );
1298 sgScaleVec3( source_vel, delta_time_sec );
1299 sgCopyVec3( last_pos_offset, source_pos_offset );
1300 // cout << "vel = " << source_vel[0] << " " << source_vel[1] << " " << source_vel[2] << endl;
1301 globals->get_soundmgr()->set_source_vel_all( source_vel );
1303 // Right now we make a simplifying assumption that the listener is
1304 // always positioned at the origin.
1305 sgVec3 listener_pos;
1306 sgSetVec3( listener_pos, 0.0, 0.0, 0.0 );
1307 // cout << "listener = " << listener_pos[0] << " " << listener_pos[1] << " " << listener_pos[2] << endl;
1308 globals->get_soundmgr()->set_listener_pos( listener_pos );
1311 // If fdm location is same as viewer's then we didn't do the
1312 // update for fdm location above so we need to save the viewer
1313 // results in the fdm SGLocation as well...
1314 if( fgGetBool("/sim/current-view/config/from-model") ) {
1315 if( acmodel_loc != 0 ) {
1316 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1317 acmodel_loc->set_cur_elev_m( globals->get_scenery()->
1319 fgSetDouble("/position/ground-elev-m",
1320 globals->get_scenery()->get_cur_elev());
1322 acmodel_loc->set_tile_center( globals->get_scenery()->
1323 get_next_center() );
1327 // END Tile Manager udpates
1329 if (fgGetBool("/sim/rendering/specular-highlight")) {
1330 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1331 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1333 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1334 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1339 SG_LOG( SG_ALL, SG_DEBUG, "" );
1343 // This is the top level master main function that is registered as
1344 // our idle funciton
1346 // The first few passes take care of initialization things (a couple
1347 // per pass) and once everything has been initialized fgMainLoop from
1350 static void fgIdleFunction ( void ) {
1351 // printf("idle state == %d\n", idle_state);
1353 if ( idle_state == 0 ) {
1354 fgSetBool("sim/initialised", false);
1356 // Initialize the splash screen right away
1357 if ( fgGetBool("/sim/startup/splash-screen") ) {
1358 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1362 } else if ( idle_state == 1 ) {
1363 // Initialize audio support
1364 #ifdef ENABLE_AUDIO_SUPPORT
1366 // Start the intro music
1367 if ( fgGetBool("/sim/startup/intro-music") ) {
1368 SGPath mp3file( globals->get_fg_root() );
1369 mp3file.append( "Sounds/intro.mp3" );
1371 SG_LOG( SG_GENERAL, SG_INFO,
1372 "Starting intro music: " << mp3file.str() );
1374 #if defined( __CYGWIN__ )
1375 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1376 #elif defined( WIN32 )
1377 string command = "start /m " + mp3file.str();
1379 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1382 system ( command.c_str() );
1387 } else if ( idle_state == 2 ) {
1388 // These are a few miscellaneous things that aren't really
1389 // "subsystems" but still need to be initialized.
1392 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1393 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1398 } else if ( idle_state == 3 ) {
1399 // This is the top level init routine which calls all the
1400 // other subsystem initialization routines. If you are adding
1401 // a subsystem to flightgear, its initialization call should
1402 // located in this routine.
1403 if( !fgInitSubsystems()) {
1404 SG_LOG( SG_GENERAL, SG_ALERT,
1405 "Subsystem initializations failed ..." );
1410 } else if ( idle_state == 4 ) {
1411 // Initialize the time offset (warp) after fgInitSubsystem
1412 // (which initializes the lighting interpolation tables.)
1415 // setup OpenGL view parameters
1418 // Read the list of available aircrafts
1422 } else if ( idle_state == 5 ) {
1425 } else if ( idle_state == 6 ) {
1430 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1431 fgReshape( fgGetInt("/sim/startup/xsize"),
1432 fgGetInt("/sim/startup/ysize") );
1436 if ( idle_state == 1000 ) {
1437 // We've finished all our initialization steps, from now on we
1438 // run the main loop.
1439 fgSetBool("sim/initialised",true);
1441 fgRegisterIdleHandler(fgMainLoop);
1443 if ( fgGetBool("/sim/startup/splash-screen") ) {
1444 fgSplashUpdate(0.0, 1.0);
1449 // options.cxx needs to see this for toggle_panel()
1450 // Handle new window size or exposure
1451 void fgReshape( int width, int height ) {
1454 if ( (!fgGetBool("/sim/virtual-cockpit"))
1455 && fgPanelVisible() && idle_state == 1000 ) {
1456 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1457 globals->get_current_panel()->getYOffset()) / 768.0);
1462 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1464 fgSetInt("/sim/startup/xsize", width);
1465 fgSetInt("/sim/startup/ysize", height);
1466 guiInitMouse(width, height);
1469 FGViewMgr *viewmgr = globals->get_viewmgr();
1471 for ( int i = 0; i < viewmgr->size(); ++i ) {
1472 viewmgr->get_view(i)->
1473 set_aspect_ratio((float)view_h / (float)width);
1476 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1477 viewmgr->get_current_view()->get_v_fov() );
1479 #ifdef FG_USE_CLOUDS_3D
1480 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1481 viewmgr->get_current_view()->get_v_fov() );
1490 // do some clean up on exit. Specifically we want to call alutExit()
1491 // which happens in the sound manager destructor.
1492 void fgExitCleanup() {
1498 // Main top level initialization
1499 bool fgMainInit( int argc, char **argv ) {
1501 #if defined( macintosh )
1502 freopen ("stdout.txt", "w", stdout );
1503 freopen ("stderr.txt", "w", stderr );
1504 argc = ccommand( &argv );
1507 // set default log levels
1508 sglog().setLogLevels( SG_ALL, SG_ALERT );
1510 atexit(fgExitCleanup);
1513 #ifdef FLIGHTGEAR_VERSION
1514 version = FLIGHTGEAR_VERSION;
1516 version = "unknown version";
1518 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1520 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1522 // Allocate global data structures. This needs to happen before
1523 // we parse command line options
1525 globals = new FGGlobals;
1527 // seed the random number generater
1530 FGControls *controls = new FGControls;
1531 globals->set_controls( controls );
1533 string_list *col = new string_list;
1534 globals->set_channel_options_list( col );
1536 // Scan the config file(s) and command line options to see if
1537 // fg_root was specified (ignore all other options for now)
1538 fgInitFGRoot(argc, argv);
1540 // Check for the correct base package version
1541 static char required_version[] = "0.9.4";
1542 string base_version = fgBasePackageVersion();
1543 if ( !(base_version == required_version) ) {
1544 // tell the operator how to use this application
1546 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1547 cerr << endl << "Base package check failed ... " \
1548 << "Found version " << base_version << " at: " \
1549 << globals->get_fg_root() << endl;
1550 cerr << "Please upgrade to version: " << required_version << endl;
1552 cerr << "Hit a key to continue..." << endl;
1558 // Initialize the Aircraft directory to "" (UIUC)
1561 // Load the configuration parameters. (Command line options
1562 // overrides config file options. Config file options override
1564 if ( !fgInitConfig(argc, argv) ) {
1565 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1569 // Initialize the Window/Graphics environment.
1570 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1571 // Mac OS X command line ("non-bundle") applications call this
1572 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
1573 // feel free to add comments...
1574 fgOSInit(&argc, argv);
1577 fgRegisterWindowResizeHandler( fgReshape );
1578 fgRegisterIdleHandler( fgIdleFunction );
1579 fgRegisterDrawHandler( fgRenderFrame );
1581 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1582 bool get_stencil_buffer = true;
1584 bool get_stencil_buffer = false;
1587 // Clouds3D requires an alpha channel
1588 // clouds may require stencil buffer
1589 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1590 fgGetInt("/sim/startup/ysize"),
1591 fgGetInt("/sim/rendering/bits-per-pixel"),
1592 fgGetBool("/sim/rendering/clouds3d"),
1594 fgGetBool("/sim/startup/fullscreen") );
1596 // This seems to be the absolute earliest in the init sequence
1597 // that these calls will return valid info. Too bad it's after
1598 // we've already created and sized out window. :-(
1599 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1600 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1601 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1602 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1605 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1606 general.set_glMaxTexSize( tmp );
1607 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1609 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1610 general.set_glDepthBits( tmp );
1611 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1613 // Initialize plib net interface
1614 netInit( &argc, argv );
1616 // Initialize ssg (from plib). Needs to come before we do any
1617 // other ssg stuff, but after opengl has been initialized.
1620 // Initialize the user interface (we need to do this before
1621 // passing off control to the OS main loop and before
1622 // fgInitGeneral to get our fonts !!!
1625 // Read the list of available aircrafts
1628 #ifdef GL_EXT_texture_lod_bias
1629 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1632 // get the address of our OpenGL extensions
1633 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1635 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1636 glPointParameterIsSupported = true;
1637 glPointParameterfPtr = (glPointParameterfProc)
1638 SGLookupFunction("glPointParameterfEXT");
1639 glPointParameterfvPtr = (glPointParameterfvProc)
1640 SGLookupFunction("glPointParameterfvEXT");
1642 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1643 glPointParameterIsSupported = true;
1644 glPointParameterfPtr = (glPointParameterfProc)
1645 SGLookupFunction("glPointParameterfARB");
1646 glPointParameterfvPtr = (glPointParameterfvProc)
1647 SGLookupFunction("glPointParameterfvARB");
1649 glPointParameterIsSupported = false;
1652 // based on the requested presets, calculate the true starting
1657 SGTime *t = fgInitTime();
1658 globals->set_time_params( t );
1660 // Do some quick general initializations
1661 if( !fgInitGeneral()) {
1662 SG_LOG( SG_GENERAL, SG_ALERT,
1663 "General initializations failed ..." );
1667 ////////////////////////////////////////////////////////////////////
1668 // Initialize the property-based built-in commands
1669 ////////////////////////////////////////////////////////////////////
1672 ////////////////////////////////////////////////////////////////////
1673 // Initialize the material manager
1674 ////////////////////////////////////////////////////////////////////
1675 globals->set_matlib( new SGMaterialLib );
1677 globals->set_model_lib(new SGModelLib);
1679 ////////////////////////////////////////////////////////////////////
1680 // Initialize the TG scenery subsystem.
1681 ////////////////////////////////////////////////////////////////////
1682 globals->set_scenery( new FGScenery );
1683 globals->get_scenery()->init();
1684 globals->get_scenery()->bind();
1685 globals->set_tile_mgr( new FGTileMgr );
1687 ////////////////////////////////////////////////////////////////////
1688 // Initialize the general model subsystem.
1689 ////////////////////////////////////////////////////////////////////
1690 globals->set_model_mgr(new FGModelMgr);
1691 globals->get_model_mgr()->init();
1692 globals->get_model_mgr()->bind();
1694 ////////////////////////////////////////////////////////////////////
1695 // Initialize the 3D aircraft model subsystem (has a dependency on
1696 // the scenery subsystem.)
1697 ////////////////////////////////////////////////////////////////////
1698 globals->set_aircraft_model(new FGAircraftModel);
1699 globals->get_aircraft_model()->init();
1700 globals->get_aircraft_model()->bind();
1702 ////////////////////////////////////////////////////////////////////
1703 // Initialize the view manager subsystem.
1704 ////////////////////////////////////////////////////////////////////
1705 FGViewMgr *viewmgr = new FGViewMgr;
1706 globals->set_viewmgr( viewmgr );
1711 // Initialize the sky
1712 SGPath ephem_data_path( globals->get_fg_root() );
1713 ephem_data_path.append( "Astro" );
1714 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1715 ephem->update( globals->get_time_params()->getMjd(),
1716 globals->get_time_params()->getLst(),
1718 globals->set_ephem( ephem );
1720 // TODO: move to environment mgr
1722 SGPath texture_path(globals->get_fg_root());
1723 texture_path.append("Textures");
1724 texture_path.append("Sky");
1725 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1726 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1727 thesky->add_cloud_layer(layer);
1730 SGPath sky_tex_path( globals->get_fg_root() );
1731 sky_tex_path.append( "Textures" );
1732 sky_tex_path.append( "Sky" );
1733 thesky->texture_path( sky_tex_path.str() );
1735 // The sun and moon diameters are scaled down numbers of the
1736 // actual diameters. This was needed to fit bot the sun and the
1737 // moon within the distance to the far clip plane.
1738 // Moon diameter: 3,476 kilometers
1739 // Sun diameter: 1,390,000 kilometers
1740 thesky->build( 80000.0, 80000.0,
1742 globals->get_ephem()->getNumPlanets(),
1743 globals->get_ephem()->getPlanets(),
1744 globals->get_ephem()->getNumStars(),
1745 globals->get_ephem()->getStars() );
1747 // Initialize MagVar model
1748 SGMagVar *magvar = new SGMagVar();
1749 globals->set_mag( magvar );
1752 // kludge to initialize mag compass
1753 // (should only be done for in-flight
1755 // update magvar model
1756 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1757 * SGD_DEGREES_TO_RADIANS,
1758 fgGetDouble("/position/latitude-deg")
1759 * SGD_DEGREES_TO_RADIANS,
1760 fgGetDouble("/position/altitude-ft")
1762 globals->get_time_params()->getJD() );
1763 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1764 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1766 // airport = new ssgBranch;
1767 // airport->setName( "Airport Lighting" );
1768 // lighting->addKid( airport );
1770 // build our custom render states
1771 fgBuildRenderStates();
1773 // pass control off to the master event handler
1776 // we never actually get here ... but to avoid compiler warnings,