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() );
339 if ( multi_pass_clouds ) {
340 // Disable depth buffer update, draw the clouds where the
341 // objects overwrite the already drawn clouds, by testing
342 // the stencil buffer against 1
343 glDepthMask( GL_FALSE );
344 glStencilFunc( GL_EQUAL, 1, 1 );
345 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
346 thesky->drawUpperClouds();
347 thesky->drawLowerClouds();
348 glDepthMask( GL_TRUE );
349 glDisable( GL_STENCIL_TEST );
351 glDepthMask( GL_FALSE );
352 thesky->drawLowerClouds();
353 glDepthMask( GL_TRUE );
357 sgSetModelFilter( false );
358 globals->get_aircraft_model()->select( true );
359 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
360 FGTileMgr::set_tile_filter( true );
361 sgSetModelFilter( true );
363 FGTileMgr::set_tile_filter( true );
364 sgSetModelFilter( true );
365 globals->get_aircraft_model()->select( true );
366 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
370 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
371 ssgSetNearFar( scene_nearplane, scene_farplane );
372 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
373 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
375 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
377 if (fgGetBool("/environment/clouds/status"))
378 thesky->drawLowerClouds();
380 globals->get_model_mgr()->draw();
381 globals->get_aircraft_model()->draw();
385 // Update all Visuals (redraws anything graphics related)
386 void fgRenderFrame() {
387 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
388 bool skyblend = fgGetBool("/sim/rendering/skyblend");
389 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
390 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
391 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
392 bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds");
394 bool multi_pass_clouds = false;
396 bool draw_clouds = fgGetBool("/environment/clouds/status");
398 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
399 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
401 // static const SGPropertyNode *longitude
402 // = fgGetNode("/position/longitude-deg");
403 // static const SGPropertyNode *latitude
404 // = fgGetNode("/position/latitude-deg");
405 // static const SGPropertyNode *altitude
406 // = fgGetNode("/position/altitude-ft");
407 static const SGPropertyNode *groundlevel_nearplane
408 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
410 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
411 static double last_visibility = -9999;
414 double actual_visibility;
415 if (fgGetBool("/environment/clouds/status"))
416 actual_visibility = thesky->get_visibility();
418 actual_visibility = fgGetDouble("/environment/visibility-m");
419 if ( actual_visibility != last_visibility ) {
420 last_visibility = actual_visibility;
422 fog_exp_density = m_log01 / actual_visibility;
423 fog_exp2_density = sqrt_m_log01 / actual_visibility;
424 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
425 if ( actual_visibility < 8000 ) {
426 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
427 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
429 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
430 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
435 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
436 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
437 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
438 // GLfloat mat_shininess[] = { 10.0 };
439 GLbitfield clear_mask;
441 if ( idle_state != 1000 ) {
442 // still initializing, draw the splash screen
443 if ( fgGetBool("/sim/startup/splash-screen") ) {
444 fgSplashUpdate(0.0, 1.0);
446 // Keep resetting sim time while the sim is initializing
447 globals->set_sim_time_sec( 0.0 );
448 SGAnimation::set_sim_time_sec( 0.0 );
450 // idle_state is now 1000 meaning we've finished all our
451 // initializations and are running the main loop, so this will
452 // now work without seg faulting the system.
454 FGViewer *current__view = globals->get_current_view();
456 // calculate our current position in cartesian space
457 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
460 fgReshape( fgGetInt("/sim/startup/xsize"),
461 fgGetInt("/sim/startup/ysize") );
463 if ( fgGetBool("/sim/rendering/clouds3d") ) {
464 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
465 cloud3d_imposter_state->force();
467 glColor4f( 1.0, 1.0, 1.0, 1.0 );
468 glEnable(GL_DEPTH_TEST);
470 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
472 #ifdef FG_USE_CLOUDS_3D
473 if ( _bcloud_orig ) {
474 Point3D c = globals->get_scenery()->get_center();
475 sgClouds3d->Set_Cloud_Orig( &c );
476 _bcloud_orig = false;
478 sgClouds3d->Update( current__view->get_absolute_view_pos() );
480 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
481 glDisable(GL_DEPTH_TEST);
484 clear_mask = GL_DEPTH_BUFFER_BIT;
485 if ( fgGetBool("/sim/rendering/wireframe") ) {
486 clear_mask |= GL_COLOR_BUFFER_BIT;
490 if ( fgGetBool("/sim/rendering/textures") ) {
491 // glClearColor(black[0], black[1], black[2], black[3]);
492 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
493 l->adj_fog_color()[2], l->adj_fog_color()[3]);
494 clear_mask |= GL_COLOR_BUFFER_BIT;
497 glClearColor(l->sky_color()[0], l->sky_color()[1],
498 l->sky_color()[2], l->sky_color()[3]);
499 clear_mask |= GL_COLOR_BUFFER_BIT;
501 if ( multi_pass_clouds && draw_clouds ) {
503 clear_mask |= GL_STENCIL_BUFFER_BIT;
505 glClear( clear_mask );
507 // Tell GL we are switching to model view parameters
509 // I really should create a derived ssg node or use a call
510 // back or something so that I can draw the sky within the
511 // ssgCullAndDraw() function, but for now I just mimic what
512 // ssg does to set up the model view matrix
513 glMatrixMode(GL_MODELVIEW);
515 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
517 // set the opengl state to known default values
518 default_state->force();
520 // update fog params if visibility has changed
521 double visibility_meters = fgGetDouble("/environment/visibility-m");
522 thesky->set_visibility(visibility_meters);
524 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
525 ( global_multi_loop * fgGetInt("/sim/speed-up") )
526 / (double)fgGetInt("/sim/model-hz") );
528 // Set correct opengl fog density
529 glFogf (GL_FOG_DENSITY, fog_exp2_density);
531 // update the sky dome
534 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
535 << l->sky_color()[0] << " "
536 << l->sky_color()[1] << " "
537 << l->sky_color()[2] << " "
538 << l->sky_color()[3] );
539 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
540 << l->fog_color()[0] << " "
541 << l->fog_color()[1] << " "
542 << l->fog_color()[2] << " "
543 << l->fog_color()[3] );
544 SG_LOG( SG_GENERAL, SG_BULK,
545 " sun_angle = " << l->sun_angle
546 << " moon_angle = " << l->moon_angle );
549 static SGSkyColor scolor;
550 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
552 scolor.sky_color = l->sky_color();
553 scolor.fog_color = l->adj_fog_color();
554 scolor.cloud_color = l->cloud_color();
555 scolor.sun_angle = l->get_sun_angle();
556 scolor.moon_angle = l->get_moon_angle();
557 scolor.nplanets = globals->get_ephem()->getNumPlanets();
558 scolor.nstars = globals->get_ephem()->getNumStars();
559 scolor.planet_data = globals->get_ephem()->getPlanets();
560 scolor.star_data = globals->get_ephem()->getStars();
562 thesky->repaint( scolor );
565 SG_LOG( SG_GENERAL, SG_BULK,
566 "thesky->reposition( view_pos = " << view_pos[0] << " "
567 << view_pos[1] << " " << view_pos[2] );
568 SG_LOG( SG_GENERAL, SG_BULK,
569 " zero_elev = " << zero_elev[0] << " "
570 << zero_elev[1] << " " << zero_elev[2]
571 << " lon = " << cur_fdm_state->get_Longitude()
572 << " lat = " << cur_fdm_state->get_Latitude() );
573 SG_LOG( SG_GENERAL, SG_BULK,
574 " sun_rot = " << l->get_sun_rotation
575 << " gst = " << SGTime::cur_time_params->getGst() );
576 SG_LOG( SG_GENERAL, SG_BULK,
577 " sun ra = " << globals->get_ephem()->getSunRightAscension()
578 << " sun dec = " << globals->get_ephem()->getSunDeclination()
579 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
580 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
583 // The sun and moon distances are scaled down versions
584 // of the actual distance to get both the moon and the sun
585 // within the range of the far clip plane.
586 // Moon distance: 384,467 kilometers
587 // Sun distance: 150,000,000 kilometers
588 double sun_horiz_eff, moon_horiz_eff;
589 if (fgGetBool("/sim/rendering/horizon-effect")) {
590 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
591 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
593 sun_horiz_eff = moon_horiz_eff = 1.0;
596 static SGSkyState sstate;
598 sstate.view_pos = current__view->get_view_pos();
599 sstate.zero_elev = current__view->get_zero_elev();
600 sstate.view_up = current__view->get_world_up();
601 sstate.lon = current__view->getLongitude_deg()
602 * SGD_DEGREES_TO_RADIANS;
603 sstate.lat = current__view->getLatitude_deg()
604 * SGD_DEGREES_TO_RADIANS;
605 sstate.alt = current__view->getAltitudeASL_ft()
607 sstate.spin = l->get_sun_rotation();
608 sstate.gst = globals->get_time_params()->getGst();
609 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
610 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
611 sstate.sun_dist = 50000.0 * sun_horiz_eff;
612 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
613 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
614 sstate.moon_dist = 40000.0 * moon_horiz_eff;
616 thesky->reposition( sstate, delta_time_sec );
619 glEnable( GL_DEPTH_TEST );
620 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
622 glFogi( GL_FOG_MODE, GL_EXP2 );
623 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
626 // set sun/lighting parameters
627 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
629 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
630 // we only update GL_AMBIENT for our lights we will never get
631 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
632 // explicitely to black.
633 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
635 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
636 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
637 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
639 // texture parameters
640 // glEnable( GL_TEXTURE_2D );
641 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
642 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
644 // glMatrixMode( GL_PROJECTION );
646 ssgSetFOV( current__view->get_h_fov(),
647 current__view->get_v_fov() );
650 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
651 - globals->get_scenery()->get_cur_elev();
654 scene_nearplane = 10.0f;
655 scene_farplane = 120000.0f;
657 scene_nearplane = groundlevel_nearplane->getDoubleValue();
658 scene_farplane = 120000.0f;
661 ssgSetNearFar( scene_nearplane, scene_farplane );
664 // Update any multiplayer models
665 globals->get_multiplayer_rx_mgr()->Update();
668 if ( draw_otw && skyblend ) {
669 // draw the sky backdrop
671 // we need a white diffuse light for the phase of the moon
672 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
673 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
675 // return to the desired diffuse color
676 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
679 // draw the ssg scene
680 glEnable( GL_DEPTH_TEST );
682 ssgSetNearFar( scene_nearplane, scene_farplane );
684 if ( fgGetBool("/sim/rendering/wireframe") ) {
686 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
692 FGTileMgr::set_tile_filter( true );
693 sgSetModelFilter( false );
694 globals->get_aircraft_model()->select( false );
695 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
697 // Disable depth buffer update, draw the clouds
698 glDepthMask( GL_FALSE );
699 thesky->drawUpperClouds();
700 if ( multi_pass_clouds ) {
701 thesky->drawLowerClouds();
703 glDepthMask( GL_TRUE );
705 if ( multi_pass_clouds ) {
706 // Draw the objects except the aircraft
707 // and update the stencil buffer with 1
708 glEnable( GL_STENCIL_TEST );
709 glStencilFunc( GL_ALWAYS, 1, 1 );
710 glStencilOp( GL_REPLACE, GL_REPLACE, GL_REPLACE );
712 FGTileMgr::set_tile_filter( false );
713 sgSetModelFilter( true );
714 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
716 if ( multi_pass_clouds ) {
717 // Disable depth buffer update, draw the clouds where the
718 // objects overwrite the already drawn clouds, by testing
719 // the stencil buffer against 1
720 glDepthMask( GL_FALSE );
721 glStencilFunc( GL_EQUAL, 1, 1 );
722 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
723 thesky->drawUpperClouds();
724 thesky->drawLowerClouds();
725 glDepthMask( GL_TRUE );
726 glDisable( GL_STENCIL_TEST );
728 glDepthMask( GL_FALSE );
729 thesky->drawLowerClouds();
730 glDepthMask( GL_TRUE );
734 sgSetModelFilter( false );
735 globals->get_aircraft_model()->select( true );
736 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
737 FGTileMgr::set_tile_filter( true );
738 sgSetModelFilter( true );
740 FGTileMgr::set_tile_filter( true );
741 sgSetModelFilter( true );
742 globals->get_aircraft_model()->select( true );
743 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
747 // This is a bit kludgy. Every 200 frames, do an extra
748 // traversal of the scene graph without drawing anything, but
749 // with the field-of-view set to 360x360 degrees. This
750 // ensures that out-of-range random objects that are not in
751 // the current view frustum will still be freed properly.
752 static int counter = 0;
754 if (counter == 200) {
757 // No need to put the near plane too close;
758 // this way, at least the aircraft can be
760 f.setNearFar(1000, 1000000);
762 ssgGetModelviewMatrix(m);
763 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
767 // change state for lighting here
769 // draw runway lighting
770 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
771 ssgSetNearFar( scene_nearplane, scene_farplane );
773 if ( enhanced_lighting ) {
775 // Enable states for drawing points with GL_extension
776 glEnable(GL_POINT_SMOOTH);
778 if ( distance_attenuation && glPointParameterIsSupported )
780 // Enable states for drawing points with GL_extension
781 glEnable(GL_POINT_SMOOTH);
783 float quadratic[3] = {1.0, 0.001, 0.0000001};
784 // makes the points fade as they move away
785 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
786 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
791 // blending function for runway lights
792 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
795 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
796 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
797 glEnable(GL_TEXTURE_GEN_S);
798 glEnable(GL_TEXTURE_GEN_T);
799 glPolygonMode(GL_FRONT, GL_POINT);
801 // draw runway lighting
803 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
804 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
807 // change punch through and then draw taxi lighting
808 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
810 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
811 // glFogfv ( GL_FOG_COLOR, taxi_fog );
813 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
817 glPolygonMode(GL_FRONT, GL_FILL);
818 glDisable(GL_TEXTURE_GEN_S);
819 glDisable(GL_TEXTURE_GEN_T);
821 //static int _frame_count = 0;
822 //if (_frame_count % 30 == 0) {
823 // printf("SSG: %s\n", ssgShowStats());
831 if ( enhanced_lighting ) {
832 if ( distance_attenuation && glPointParameterIsSupported )
834 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
835 default_attenuation);
839 glDisable(GL_POINT_SMOOTH);
842 // draw ground lighting
843 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
845 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
848 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") )
851 glDisable( GL_LIGHTING );
852 // cout << "drawing new clouds" << endl;
854 glEnable(GL_DEPTH_TEST);
856 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
859 glEnable( GL_TEXTURE_2D );
860 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
861 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
862 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
863 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
866 #ifdef FG_USE_CLOUDS_3D
867 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
870 glEnable( GL_LIGHTING );
871 glEnable( GL_DEPTH_TEST );
872 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
876 globals->get_model_mgr()->draw();
877 globals->get_aircraft_model()->draw();
880 // display HUD && Panel
882 glDisable( GL_DEPTH_TEST );
883 // glDisable( GL_CULL_FACE );
884 // glDisable( GL_TEXTURE_2D );
886 // update the controls subsystem
887 globals->get_controls()->update(delta_time_sec);
889 hud_and_panel->apply();
892 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
893 // This only works properly if called before the panel call
894 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
895 globals->get_ATC_display()->update(delta_time_sec);
897 // update the panel subsystem
898 if ( globals->get_current_panel() != NULL ) {
899 globals->get_current_panel()->update(delta_time_sec);
903 // We can do translucent menus, so why not. :-)
905 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
907 // glDisable ( GL_BLEND ) ;
909 glEnable( GL_DEPTH_TEST );
912 // Fade out the splash screen over the first three seconds.
913 double t = globals->get_sim_time_sec();
915 fgSplashUpdate(0.0, 1.0);
916 } else if ( t <= 3.0) {
917 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
923 // Update internal time dependent calculations (i.e. flight model)
924 // FIXME: this distinction is obsolete; all subsystems now get delta
926 void fgUpdateTimeDepCalcs() {
927 static bool inited = false;
929 static const SGPropertyNode *replay_master
930 = fgGetNode( "/sim/freeze/replay", true );
931 static SGPropertyNode *replay_time
932 = fgGetNode( "/sim/replay/time", true );
933 // static const SGPropertyNode *replay_end_time
934 // = fgGetNode( "/sim/replay/end-time", true );
936 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
938 // Initialize the FDM here if it hasn't been and if we have a
939 // scenery elevation hit.
941 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
942 // << " cur_elev = " << scenery.get_cur_elev() << endl;
944 if ( !cur_fdm_state->get_inited() &&
945 globals->get_scenery()->get_cur_elev() > -9990 )
947 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
948 cur_fdm_state->init();
949 if ( cur_fdm_state->get_bound() ) {
950 cur_fdm_state->unbind();
952 cur_fdm_state->bind();
955 // conceptually, the following block could be done for each fdm
957 if ( cur_fdm_state->get_inited() ) {
958 // we have been inited, and we are good to go ...
964 if ( ! replay_master->getBoolValue() ) {
965 cur_fdm_state->update( delta_time_sec );
967 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
968 r->replay( replay_time->getDoubleValue() );
969 replay_time->setDoubleValue( replay_time->getDoubleValue()
971 * fgGetInt("/sim/speed-up") ) );
974 // do nothing, fdm isn't inited yet
977 globals->get_model_mgr()->update(delta_time_sec);
978 globals->get_aircraft_model()->update(delta_time_sec);
980 // update the view angle
981 globals->get_viewmgr()->update(delta_time_sec);
983 // Update solar system
984 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
985 globals->get_time_params()->getLst(),
986 cur_fdm_state->get_Latitude() );
988 // Update radio stack model
989 current_radiostack->update(delta_time_sec);
993 void fgInitTimeDepCalcs( void ) {
998 static const double alt_adjust_ft = 3.758099;
999 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
1002 // What should we do when we have nothing else to do? Let's get ready
1003 // for the next move and update the display?
1004 static void fgMainLoop( void ) {
1005 int model_hz = fgGetInt("/sim/model-hz");
1007 static const SGPropertyNode *longitude
1008 = fgGetNode("/position/longitude-deg");
1009 static const SGPropertyNode *latitude
1010 = fgGetNode("/position/latitude-deg");
1011 static const SGPropertyNode *altitude
1012 = fgGetNode("/position/altitude-ft");
1013 static const SGPropertyNode *clock_freeze
1014 = fgGetNode("/sim/freeze/clock", true);
1015 static const SGPropertyNode *cur_time_override
1016 = fgGetNode("/sim/time/cur-time-override", true);
1017 // static const SGPropertyNode *replay_master
1018 // = fgGetNode("/sim/freeze/replay", true);
1020 // Update the elapsed time.
1021 static bool first_time = true;
1023 last_time_stamp.stamp();
1027 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
1028 if ( throttle_hz > 0.0 ) {
1029 // simple frame rate throttle
1030 double dt = 1000000.0 / throttle_hz;
1031 current_time_stamp.stamp();
1032 while ( current_time_stamp - last_time_stamp < dt ) {
1033 current_time_stamp.stamp();
1036 // run as fast as the app will go
1037 current_time_stamp.stamp();
1041 = double(current_time_stamp - last_time_stamp) / 1000000.0;
1042 if ( clock_freeze->getBoolValue() ) {
1045 delta_time_sec = real_delta_time_sec;
1047 last_time_stamp = current_time_stamp;
1048 globals->inc_sim_time_sec( delta_time_sec );
1049 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
1051 // These are useful, especially for Nasal scripts.
1052 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
1053 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
1055 static long remainder = 0;
1057 #ifdef FANCY_FRAME_COUNTER
1061 static time_t last_time = 0;
1062 static int frames = 0;
1063 #endif // FANCY_FRAME_COUNTER
1065 SGTime *t = globals->get_time_params();
1067 globals->get_event_mgr()->update(delta_time_sec);
1069 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
1070 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
1072 #if defined( ENABLE_PLIB_JOYSTICK )
1073 // Read joystick and update control settings
1074 // if ( fgGetString("/sim/control-mode") == "joystick" )
1076 // fgJoystickRead();
1080 // Fix elevation. I'm just sticking this here for now, it should
1081 // probably move eventually
1083 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1084 scenery.get_cur_elev(),
1085 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1086 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1088 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1089 scenery.get_cur_elev(),
1090 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1091 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1093 // cout << "Warp = " << globals->get_warp() << endl;
1096 static bool last_clock_freeze = false;
1098 if ( clock_freeze->getBoolValue() ) {
1099 // clock freeze requested
1100 if ( cur_time_override->getLongValue() == 0 ) {
1101 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1102 globals->set_warp( 0 );
1105 // no clock freeze requested
1106 if ( last_clock_freeze == true ) {
1107 // clock just unfroze, let's set warp as the difference
1108 // between frozen time and current time so we don't get a
1109 // time jump (and corresponding sky object and lighting
1111 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1112 fgSetLong( "/sim/time/cur-time-override", 0 );
1114 if ( globals->get_warp_delta() != 0 ) {
1115 globals->inc_warp( globals->get_warp_delta() );
1119 last_clock_freeze = clock_freeze->getBoolValue();
1121 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1122 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1123 cur_time_override->getLongValue(),
1124 globals->get_warp() );
1126 if (globals->get_warp_delta() != 0) {
1127 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1131 // update magvar model
1132 globals->get_mag()->update( longitude->getDoubleValue()
1133 * SGD_DEGREES_TO_RADIANS,
1134 latitude->getDoubleValue()
1135 * SGD_DEGREES_TO_RADIANS,
1136 altitude->getDoubleValue() * SG_FEET_TO_METER,
1137 globals->get_time_params()->getJD() );
1139 // Get elapsed time (in usec) for this past frame
1140 elapsed = fgGetTimeInterval();
1141 SG_LOG( SG_ALL, SG_DEBUG,
1142 "Elapsed time interval is = " << elapsed
1143 << ", previous remainder is = " << remainder );
1145 // Calculate frame rate average
1146 #ifdef FANCY_FRAME_COUNTER
1147 /* old fps calculation */
1148 if ( elapsed > 0 ) {
1151 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1152 tmp = general.get_frame(i);
1154 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1155 general.set_frame(i+1,tmp);
1157 tmp = 1000000.0 / (float)elapsed;
1158 general.set_frame(0,tmp);
1159 // printf("frame[0] = %.2f\n", general.frames[0]);
1161 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1162 // printf("ave = %.2f\n", general.frame_rate);
1165 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1166 general.set_frame_rate( frames );
1167 fgSetInt("/sim/frame-rate", frames);
1168 SG_LOG( SG_ALL, SG_DEBUG,
1169 "--> Frame rate is = " << general.get_frame_rate() );
1172 last_time = t->get_cur_time();
1176 // Run ATC subsystem
1177 if (fgGetBool("/sim/ATC/enabled"))
1178 globals->get_ATC_mgr()->update(delta_time_sec);
1180 // Run the AI subsystem
1181 if (fgGetBool("/sim/ai-traffic/enabled"))
1182 globals->get_AI_mgr()->update(delta_time_sec);
1186 // Calculate model iterations needed for next frame
1187 elapsed += remainder;
1189 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1190 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1191 SG_LOG( SG_ALL, SG_DEBUG,
1192 "Model iterations needed = " << global_multi_loop
1193 << ", new remainder = " << remainder );
1195 // chop max interations to something reasonable if the sim was
1196 // delayed for an excesive amount of time
1197 if ( global_multi_loop > 2.0 * model_hz ) {
1198 global_multi_loop = (int)(2.0 * model_hz );
1203 if ( global_multi_loop > 0 ) {
1204 fgUpdateTimeDepCalcs();
1206 SG_LOG( SG_ALL, SG_DEBUG,
1207 "Elapsed time is zero ... we're zinging" );
1210 // Do any I/O channel work that might need to be done
1211 globals->get_io()->update( real_delta_time_sec );
1213 // see if we need to load any deferred-load textures
1214 globals->get_matlib()->load_next_deferred();
1216 // Run audio scheduler
1217 #ifdef ENABLE_AUDIO_SUPPORT
1218 if ( fgGetBool("/sim/sound/audible")
1219 && 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_location = 0;
1236 acmodel_location = (SGLocation *) globals->get_aircraft_model()->get3DModel()->getSGLocation();
1238 // update tile manager for FDM...
1239 // ...only if location is different than the current-view location (to avoid duplicating effort)
1240 if( !fgGetBool("/sim/current-view/config/from-model") ) {
1241 if( acmodel_location != 0 ) {
1242 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1243 visibility_meters );
1244 globals->get_tile_mgr()->
1245 update( acmodel_location, visibility_meters,
1246 acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1247 // save results of update in SGLocation for fdm...
1248 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1250 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1251 fgSetDouble("/position/ground-elev-m", globals->get_scenery()->get_cur_elev());
1254 set_tile_center( globals->get_scenery()->get_next_center() );
1258 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1259 visibility_meters );
1260 // update tile manager for view...
1261 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1262 // after the FDM's until all of Flight Gear code references the viewer's location
1263 // for elevation instead of the "scenery's" current elevation.
1264 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1265 globals->get_tile_mgr()->update( view_location, visibility_meters,
1266 current_view->get_absolute_view_pos() );
1267 // save results of update in SGLocation for fdm...
1268 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1269 current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1271 current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1273 // If fdm location is same as viewer's then we didn't do the update for fdm location
1274 // above so we need to save the viewer results in the fdm SGLocation as well...
1275 if( fgGetBool("/sim/current-view/config/from-model") ) {
1276 if( acmodel_location != 0 ) {
1277 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1278 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1279 fgSetDouble("/position/ground-elev-m", globals->get_scenery()->get_cur_elev());
1281 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1285 // END Tile Manager udpates
1287 if (fgGetBool("/sim/rendering/specular-highlight")) {
1288 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1289 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1291 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1292 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1297 SG_LOG( SG_ALL, SG_DEBUG, "" );
1301 // This is the top level master main function that is registered as
1302 // our idle funciton
1304 // The first few passes take care of initialization things (a couple
1305 // per pass) and once everything has been initialized fgMainLoop from
1308 static void fgIdleFunction ( void ) {
1309 // printf("idle state == %d\n", idle_state);
1311 if ( idle_state == 0 ) {
1312 // Initialize the splash screen right away
1313 if ( fgGetBool("/sim/startup/splash-screen") ) {
1314 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1318 } else if ( idle_state == 1 ) {
1319 // Initialize audio support
1320 #ifdef ENABLE_AUDIO_SUPPORT
1322 // Start the intro music
1323 if ( fgGetBool("/sim/startup/intro-music") ) {
1324 SGPath mp3file( globals->get_fg_root() );
1325 mp3file.append( "Sounds/intro.mp3" );
1327 SG_LOG( SG_GENERAL, SG_INFO,
1328 "Starting intro music: " << mp3file.str() );
1330 #if defined( __CYGWIN__ )
1331 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1332 #elif defined( WIN32 )
1333 string command = "start /m " + mp3file.str();
1335 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1338 system ( command.c_str() );
1343 } else if ( idle_state == 2 ) {
1344 // These are a few miscellaneous things that aren't really
1345 // "subsystems" but still need to be initialized.
1348 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1349 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1354 } else if ( idle_state == 3 ) {
1355 // This is the top level init routine which calls all the
1356 // other subsystem initialization routines. If you are adding
1357 // a subsystem to flightgear, its initialization call should
1358 // located in this routine.
1359 if( !fgInitSubsystems()) {
1360 SG_LOG( SG_GENERAL, SG_ALERT,
1361 "Subsystem initializations failed ..." );
1366 } else if ( idle_state == 4 ) {
1367 // Initialize the time offset (warp) after fgInitSubsystem
1368 // (which initializes the lighting interpolation tables.)
1371 // setup OpenGL view parameters
1374 // Read the list of available aircrafts
1378 } else if ( idle_state == 5 ) {
1381 } else if ( idle_state == 6 ) {
1386 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1387 fgReshape( fgGetInt("/sim/startup/xsize"),
1388 fgGetInt("/sim/startup/ysize") );
1392 if ( idle_state == 1000 ) {
1393 // We've finished all our initialization steps, from now on we
1394 // run the main loop.
1396 fgRegisterIdleHandler(fgMainLoop);
1398 if ( fgGetBool("/sim/startup/splash-screen") ) {
1399 fgSplashUpdate(0.0, 1.0);
1404 // options.cxx needs to see this for toggle_panel()
1405 // Handle new window size or exposure
1406 void fgReshape( int width, int height ) {
1409 if ( (!fgGetBool("/sim/virtual-cockpit"))
1410 && fgPanelVisible() && idle_state == 1000 ) {
1411 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1412 globals->get_current_panel()->getYOffset()) / 768.0);
1417 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1419 fgSetInt("/sim/startup/xsize", width);
1420 fgSetInt("/sim/startup/ysize", height);
1421 guiInitMouse(width, height);
1424 FGViewMgr *viewmgr = globals->get_viewmgr();
1426 for ( int i = 0; i < viewmgr->size(); ++i ) {
1427 viewmgr->get_view(i)->
1428 set_aspect_ratio((float)view_h / (float)width);
1431 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1432 viewmgr->get_current_view()->get_v_fov() );
1434 #ifdef FG_USE_CLOUDS_3D
1435 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1436 viewmgr->get_current_view()->get_v_fov() );
1444 // Main top level initialization
1445 bool fgMainInit( int argc, char **argv ) {
1447 #if defined( macintosh )
1448 freopen ("stdout.txt", "w", stdout );
1449 freopen ("stderr.txt", "w", stderr );
1450 argc = ccommand( &argv );
1453 // set default log levels
1454 sglog().setLogLevels( SG_ALL, SG_ALERT );
1457 #ifdef FLIGHTGEAR_VERSION
1458 version = FLIGHTGEAR_VERSION;
1460 version = "unknown version";
1462 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1464 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1466 // Allocate global data structures. This needs to happen before
1467 // we parse command line options
1469 globals = new FGGlobals;
1471 // seed the random number generater
1474 FGControls *controls = new FGControls;
1475 globals->set_controls( controls );
1477 string_list *col = new string_list;
1478 globals->set_channel_options_list( col );
1480 // Scan the config file(s) and command line options to see if
1481 // fg_root was specified (ignore all other options for now)
1482 fgInitFGRoot(argc, argv);
1484 // Check for the correct base package version
1485 static char required_version[] = "0.9.4";
1486 string base_version = fgBasePackageVersion();
1487 if ( !(base_version == required_version) ) {
1488 // tell the operator how to use this application
1490 SG_LOG( SG_GENERAL, SG_ALERT, "" ); // To popup the console on windows
1491 cerr << endl << "Base package check failed ... " \
1492 << "Found version " << base_version << " at: " \
1493 << globals->get_fg_root() << endl;
1494 cerr << "Please upgrade to version: " << required_version << endl;
1496 cerr << "Hit a key to continue..." << endl;
1502 // Initialize the Aircraft directory to "" (UIUC)
1505 // Load the configuration parameters. (Command line options
1506 // overrides config file options. Config file options override
1508 if ( !fgInitConfig(argc, argv) ) {
1509 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1513 // Initialize the Window/Graphics environment.
1514 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1515 // Mac OS X command line ("non-bundle") applications call this
1516 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
1517 // feel free to add comments...
1518 fgOSInit(&argc, argv);
1521 fgRegisterWindowResizeHandler( fgReshape );
1522 fgRegisterIdleHandler( fgIdleFunction );
1523 fgRegisterDrawHandler( fgRenderFrame );
1525 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
1526 bool get_stencil_buffer = true;
1528 bool get_stencil_buffer = false;
1531 // Clouds3D requires an alpha channel
1532 // clouds may require stencil buffer
1533 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1534 fgGetInt("/sim/startup/ysize"),
1535 fgGetInt("/sim/rendering/bits-per-pixel"),
1536 fgGetBool("/sim/rendering/clouds3d"),
1537 get_stencil_buffer );
1539 // This seems to be the absolute earliest in the init sequence
1540 // that these calls will return valid info. Too bad it's after
1541 // we've already created and sized out window. :-(
1542 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1543 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1544 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1545 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1548 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1549 general.set_glMaxTexSize( tmp );
1550 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1552 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1553 general.set_glDepthBits( tmp );
1554 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1556 // Initialize plib net interface
1557 netInit( &argc, argv );
1559 // Initialize ssg (from plib). Needs to come before we do any
1560 // other ssg stuff, but after opengl has been initialized.
1563 // Initialize the user interface (we need to do this before
1564 // passing off control to the OS main loop and before
1565 // fgInitGeneral to get our fonts !!!
1568 // Read the list of available aircrafts
1571 #ifdef GL_EXT_texture_lod_bias
1572 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1575 // get the address of our OpenGL extensions
1576 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1578 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1579 glPointParameterIsSupported = true;
1580 glPointParameterfPtr = (glPointParameterfProc)
1581 SGLookupFunction("glPointParameterfEXT");
1582 glPointParameterfvPtr = (glPointParameterfvProc)
1583 SGLookupFunction("glPointParameterfvEXT");
1585 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1586 glPointParameterIsSupported = true;
1587 glPointParameterfPtr = (glPointParameterfProc)
1588 SGLookupFunction("glPointParameterfARB");
1589 glPointParameterfvPtr = (glPointParameterfvProc)
1590 SGLookupFunction("glPointParameterfvARB");
1592 glPointParameterIsSupported = false;
1595 // based on the requested presets, calculate the true starting
1600 SGTime *t = fgInitTime();
1601 globals->set_time_params( t );
1603 // Do some quick general initializations
1604 if( !fgInitGeneral()) {
1605 SG_LOG( SG_GENERAL, SG_ALERT,
1606 "General initializations failed ..." );
1610 ////////////////////////////////////////////////////////////////////
1611 // Initialize the property-based built-in commands
1612 ////////////////////////////////////////////////////////////////////
1615 ////////////////////////////////////////////////////////////////////
1616 // Initialize the material manager
1617 ////////////////////////////////////////////////////////////////////
1618 globals->set_matlib( new SGMaterialLib );
1620 globals->set_model_lib(new SGModelLib);
1622 ////////////////////////////////////////////////////////////////////
1623 // Initialize the TG scenery subsystem.
1624 ////////////////////////////////////////////////////////////////////
1625 globals->set_scenery( new FGScenery );
1626 globals->get_scenery()->init();
1627 globals->get_scenery()->bind();
1628 globals->set_tile_mgr( new FGTileMgr );
1630 ////////////////////////////////////////////////////////////////////
1631 // Initialize the general model subsystem.
1632 ////////////////////////////////////////////////////////////////////
1633 globals->set_model_mgr(new FGModelMgr);
1634 globals->get_model_mgr()->init();
1635 globals->get_model_mgr()->bind();
1637 ////////////////////////////////////////////////////////////////////
1638 // Initialize the 3D aircraft model subsystem (has a dependency on
1639 // the scenery subsystem.)
1640 ////////////////////////////////////////////////////////////////////
1641 globals->set_aircraft_model(new FGAircraftModel);
1642 globals->get_aircraft_model()->init();
1643 globals->get_aircraft_model()->bind();
1645 ////////////////////////////////////////////////////////////////////
1646 // Initialize the view manager subsystem.
1647 ////////////////////////////////////////////////////////////////////
1648 FGViewMgr *viewmgr = new FGViewMgr;
1649 globals->set_viewmgr( viewmgr );
1654 // Initialize the sky
1655 SGPath ephem_data_path( globals->get_fg_root() );
1656 ephem_data_path.append( "Astro" );
1657 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1658 ephem->update( globals->get_time_params()->getMjd(),
1659 globals->get_time_params()->getLst(),
1661 globals->set_ephem( ephem );
1663 // TODO: move to environment mgr
1665 SGPath texture_path(globals->get_fg_root());
1666 texture_path.append("Textures");
1667 texture_path.append("Sky");
1668 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1669 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1670 thesky->add_cloud_layer(layer);
1673 SGPath sky_tex_path( globals->get_fg_root() );
1674 sky_tex_path.append( "Textures" );
1675 sky_tex_path.append( "Sky" );
1676 thesky->texture_path( sky_tex_path.str() );
1678 // The sun and moon diameters are scaled down numbers of the
1679 // actual diameters. This was needed to fit bot the sun and the
1680 // moon within the distance to the far clip plane.
1681 // Moon diameter: 3,476 kilometers
1682 // Sun diameter: 1,390,000 kilometers
1683 thesky->build( 80000.0, 80000.0,
1685 globals->get_ephem()->getNumPlanets(),
1686 globals->get_ephem()->getPlanets(),
1687 globals->get_ephem()->getNumStars(),
1688 globals->get_ephem()->getStars() );
1690 // Initialize MagVar model
1691 SGMagVar *magvar = new SGMagVar();
1692 globals->set_mag( magvar );
1695 // kludge to initialize mag compass
1696 // (should only be done for in-flight
1698 // update magvar model
1699 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1700 * SGD_DEGREES_TO_RADIANS,
1701 fgGetDouble("/position/latitude-deg")
1702 * SGD_DEGREES_TO_RADIANS,
1703 fgGetDouble("/position/altitude-ft")
1705 globals->get_time_params()->getJD() );
1706 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1707 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1709 // airport = new ssgBranch;
1710 // airport->setName( "Airport Lighting" );
1711 // lighting->addKid( airport );
1713 // build our custom render states
1714 fgBuildRenderStates();
1716 // pass control off to the master event handler
1719 // we never actually get here ... but to avoid compiler warnings,