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
46 #include <plib/netSocket.h>
48 #include <simgear/screen/extensions.hxx>
49 #include <simgear/scene/material/matlib.hxx>
50 #include <simgear/props/props.hxx>
51 #include <simgear/scene/sky/sky.hxx>
52 #include <simgear/timing/sg_time.hxx>
53 #include <simgear/scene/model/animation.hxx>
54 #include <simgear/ephemeris/ephemeris.hxx>
55 #include <simgear/scene/model/placement.hxx>
56 #include <simgear/math/sg_random.h>
57 #include <simgear/scene/model/modellib.hxx>
59 #ifdef FG_USE_CLOUDS_3D
60 # include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
61 # include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
64 #include <Include/general.hxx>
65 #include <Scenery/tileentry.hxx>
66 #include <Time/light.hxx>
67 #include <Time/light.hxx>
68 #include <Aircraft/aircraft.hxx>
69 #include <Cockpit/panel.hxx>
70 #include <Cockpit/cockpit.hxx>
71 #include <Cockpit/radiostack.hxx>
72 #include <Cockpit/hud.hxx>
73 #include <Model/panelnode.hxx>
74 #include <Model/modelmgr.hxx>
75 #include <Model/acmodel.hxx>
76 #include <Scenery/scenery.hxx>
77 #include <Scenery/tilemgr.hxx>
78 #include <FDM/flight.hxx>
79 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
80 #include <FDM/ADA.hxx>
81 #include <ATC/ATCdisplay.hxx>
82 #include <ATC/ATCmgr.hxx>
83 #include <ATC/AIMgr.hxx>
84 #include <Replay/replay.hxx>
85 #include <Time/tmp.hxx>
86 #include <Time/fg_timer.hxx>
87 #include <Environment/environment_mgr.hxx>
90 #include <MultiPlayer/multiplaytxmgr.hxx>
91 #include <MultiPlayer/multiplayrxmgr.hxx>
95 #include "fg_commands.hxx"
99 float default_attenuation[3] = {1.0, 0.0, 0.0};
100 ssgSelector *ship_sel=NULL;
101 // upto 32 instances of a same object can be loaded.
102 ssgTransform *ship_pos[32];
103 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
105 ssgSelector *lightpoints_brightness = new ssgSelector;
106 ssgTransform *lightpoints_transform = new ssgTransform;
107 FGTileEntry *dummy_tile;
110 // Clip plane settings...
111 float scene_nearplane = 0.5f;
112 float scene_farplane = 120000.0f;
114 static double real_delta_time_sec = 0.0;
115 static double delta_time_sec = 0.0;
117 glPointParameterfProc glPointParameterfPtr = 0;
118 glPointParameterfvProc glPointParameterfvPtr = 0;
119 bool glPointParameterIsSupported = false;
123 # include <console.h> // -dw- for command line dialog
126 // This is a record containing a bit of global housekeeping information
129 // Specify our current idle function state. This is used to run all
130 // our initializations out of the glutIdleLoop() so that we can get a
131 // splash screen up and running right away.
132 static int idle_state = 0;
133 static long global_multi_loop;
135 // fog constants. I'm a little nervous about putting actual code out
136 // here but it seems to work (?)
137 static const double m_log01 = -log( 0.01 );
138 static const double sqrt_m_log01 = sqrt( m_log01 );
139 static GLfloat fog_exp_density;
140 static GLfloat fog_exp2_density;
141 static GLfloat rwy_exp2_punch_through;
142 static GLfloat taxi_exp2_punch_through;
143 static GLfloat ground_exp2_punch_through;
148 #ifdef FG_USE_CLOUDS_3D
149 SkySceneLoader *sgClouds3d;
150 bool _bcloud_orig = true;
154 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
156 { 1.0f, 0.0f, 0.0f, 0.0f },
157 { 0.0f, 0.0f, -1.0f, 0.0f },
158 { 0.0f, 1.0f, 0.0f, 0.0f },
159 { 0.0f, 0.0f, 0.0f, 1.0f }
162 // The following defines flightgear options. Because glutlib will also
163 // want to parse its own options, those options must not be included here
164 // or they will get parsed by the main program option parser. Hence case
165 // is significant for any option added that might be in conflict with
168 // glutlib parses for:
170 // -direct (invalid in Win32)
174 // -indirect (invalid in Win32)
177 // Note that glutlib depends upon strings while this program's
178 // option parser wants only initial characters followed by numbers
183 ssgSimpleState *cloud3d_imposter_state;
184 ssgSimpleState *default_state;
185 ssgSimpleState *hud_and_panel;
186 ssgSimpleState *menus;
188 SGTimeStamp last_time_stamp;
189 SGTimeStamp current_time_stamp;
192 void fgBuildRenderStates( void ) {
193 default_state = new ssgSimpleState;
194 default_state->ref();
195 default_state->disable( GL_TEXTURE_2D );
196 default_state->enable( GL_CULL_FACE );
197 default_state->enable( GL_COLOR_MATERIAL );
198 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
199 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
200 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
201 default_state->disable( GL_BLEND );
202 default_state->disable( GL_ALPHA_TEST );
203 default_state->disable( GL_LIGHTING );
205 cloud3d_imposter_state = new ssgSimpleState;
206 cloud3d_imposter_state->ref();
207 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
208 cloud3d_imposter_state->enable( GL_CULL_FACE );
209 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
210 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
211 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
212 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
213 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
214 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
215 cloud3d_imposter_state->enable( GL_BLEND );
216 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
217 cloud3d_imposter_state->disable( GL_LIGHTING );
219 hud_and_panel = new ssgSimpleState;
220 hud_and_panel->ref();
221 hud_and_panel->disable( GL_CULL_FACE );
222 hud_and_panel->disable( GL_TEXTURE_2D );
223 hud_and_panel->disable( GL_LIGHTING );
224 hud_and_panel->enable( GL_BLEND );
226 menus = new ssgSimpleState;
228 menus->disable( GL_CULL_FACE );
229 menus->disable( GL_TEXTURE_2D );
230 menus->enable( GL_BLEND );
234 // fgInitVisuals() -- Initialize various GL/view parameters
235 void fgInitVisuals( void ) {
237 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
239 #ifndef GLUT_WRONG_VERSION
240 // Go full screen if requested ...
241 if ( fgGetBool("/sim/startup/fullscreen") ) {
246 // If enabled, normal vectors specified with glNormal are scaled
247 // to unit length after transformation. Enabling this has
248 // performance implications. See the docs for glNormal.
249 // glEnable( GL_NORMALIZE );
251 glEnable( GL_LIGHTING );
252 glEnable( GL_LIGHT0 );
253 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
256 sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
257 ssgGetLight( 0 ) -> setPosition( sunpos );
259 glFogi (GL_FOG_MODE, GL_EXP2);
260 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
261 (!fgGetBool("/sim/rendering/shading"))) {
262 // if fastest fog requested, or if flat shading force fastest
263 glHint ( GL_FOG_HINT, GL_FASTEST );
264 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
265 glHint ( GL_FOG_HINT, GL_NICEST );
267 if ( fgGetBool("/sim/rendering/wireframe") ) {
269 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
272 // This is the default anyways, but it can't hurt
273 glFrontFace ( GL_CCW );
276 // glEnable(GL_POINT_SMOOTH);
277 // glEnable(GL_LINE_SMOOTH);
278 // glEnable(GL_POLYGON_SMOOTH);
282 // For HiRes screen Dumps using Brian Pauls TR Library
283 void trRenderFrame( void ) {
285 if ( fgPanelVisible() ) {
286 GLfloat height = fgGetInt("/sim/startup/ysize");
288 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
289 * (height / 768.0) + 1;
290 glTranslatef( 0.0, view_h, 0.0 );
293 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
294 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
296 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
298 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
299 l->adj_fog_color()[2], l->adj_fog_color()[3]);
301 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
303 // set the opengl state to known default values
304 default_state->force();
307 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
308 glFogi ( GL_FOG_MODE, GL_EXP2 );
309 glFogfv ( GL_FOG_COLOR, l->adj_fog_color() );
311 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
312 // we only update GL_AMBIENT for our lights we will never get
313 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
314 // explicitely to black.
315 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
316 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
318 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
320 // texture parameters
321 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
322 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
324 // we need a white diffuse light for the phase of the moon
325 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
326 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER, fog_exp2_density );
328 // draw the ssg scene
329 // return to the desired diffuse color
330 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
331 glEnable( GL_DEPTH_TEST );
332 ssgSetNearFar( scene_nearplane, scene_farplane );
333 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
336 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
337 ssgSetNearFar( scene_nearplane, scene_farplane );
338 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
339 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
341 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
343 if (fgGetBool("/environment/clouds/status"))
344 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
346 globals->get_model_mgr()->draw();
347 globals->get_aircraft_model()->draw();
351 // Update all Visuals (redraws anything graphics related)
352 void fgRenderFrame() {
353 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
354 bool skyblend = fgGetBool("/sim/rendering/skyblend");
355 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
356 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
358 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
359 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
361 // static const SGPropertyNode *longitude
362 // = fgGetNode("/position/longitude-deg");
363 // static const SGPropertyNode *latitude
364 // = fgGetNode("/position/latitude-deg");
365 // static const SGPropertyNode *altitude
366 // = fgGetNode("/position/altitude-ft");
367 static const SGPropertyNode *groundlevel_nearplane
368 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
370 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
371 static double last_visibility = -9999;
374 double actual_visibility;
375 if (fgGetBool("/environment/clouds/status"))
376 actual_visibility = thesky->get_visibility();
378 actual_visibility = fgGetDouble("/environment/visibility-m");
379 if ( actual_visibility != last_visibility ) {
380 last_visibility = actual_visibility;
382 fog_exp_density = m_log01 / actual_visibility;
383 fog_exp2_density = sqrt_m_log01 / actual_visibility;
384 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
385 if ( actual_visibility < 8000 ) {
386 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
387 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
389 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
390 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
395 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
396 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
397 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
398 // GLfloat mat_shininess[] = { 10.0 };
399 GLbitfield clear_mask;
401 if ( idle_state != 1000 ) {
402 // still initializing, draw the splash screen
403 if ( fgGetBool("/sim/startup/splash-screen") ) {
404 fgSplashUpdate(0.0, 1.0);
406 // Keep resetting sim time while the sim is initializing
407 globals->set_sim_time_sec( 0.0 );
408 SGAnimation::set_sim_time_sec( 0.0 );
410 // idle_state is now 1000 meaning we've finished all our
411 // initializations and are running the main loop, so this will
412 // now work without seg faulting the system.
414 FGViewer *current__view = globals->get_current_view();
416 // calculate our current position in cartesian space
417 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
420 fgReshape( fgGetInt("/sim/startup/xsize"),
421 fgGetInt("/sim/startup/ysize") );
423 if ( fgGetBool("/sim/rendering/clouds3d") ) {
424 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
425 cloud3d_imposter_state->force();
427 glColor4f( 1.0, 1.0, 1.0, 1.0 );
428 glEnable(GL_DEPTH_TEST);
430 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
432 #ifdef FG_USE_CLOUDS_3D
433 if ( _bcloud_orig ) {
434 Point3D c = globals->get_scenery()->get_center();
435 sgClouds3d->Set_Cloud_Orig( &c );
436 _bcloud_orig = false;
438 sgClouds3d->Update( current__view->get_absolute_view_pos() );
440 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
441 glDisable(GL_DEPTH_TEST);
444 clear_mask = GL_DEPTH_BUFFER_BIT;
445 if ( fgGetBool("/sim/rendering/wireframe") ) {
446 clear_mask |= GL_COLOR_BUFFER_BIT;
450 if ( fgGetBool("/sim/rendering/textures") ) {
451 // glClearColor(black[0], black[1], black[2], black[3]);
452 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
453 l->adj_fog_color()[2], l->adj_fog_color()[3]);
454 clear_mask |= GL_COLOR_BUFFER_BIT;
457 glClearColor(l->sky_color()[0], l->sky_color()[1],
458 l->sky_color()[2], l->sky_color()[3]);
459 clear_mask |= GL_COLOR_BUFFER_BIT;
461 glClear( clear_mask );
463 // Tell GL we are switching to model view parameters
465 // I really should create a derived ssg node or use a call
466 // back or something so that I can draw the sky within the
467 // ssgCullAndDraw() function, but for now I just mimic what
468 // ssg does to set up the model view matrix
469 glMatrixMode(GL_MODELVIEW);
471 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
473 // set the opengl state to known default values
474 default_state->force();
476 // update fog params if visibility has changed
477 double visibility_meters = fgGetDouble("/environment/visibility-m");
478 thesky->set_visibility(visibility_meters);
480 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
481 ( global_multi_loop * fgGetInt("/sim/speed-up") )
482 / (double)fgGetInt("/sim/model-hz") );
484 // Set correct opengl fog density
485 glFogf (GL_FOG_DENSITY, fog_exp2_density);
487 // update the sky dome
490 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
491 << l->sky_color()[0] << " "
492 << l->sky_color()[1] << " "
493 << l->sky_color()[2] << " "
494 << l->sky_color()[3] );
495 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
496 << l->fog_color()[0] << " "
497 << l->fog_color()[1] << " "
498 << l->fog_color()[2] << " "
499 << l->fog_color()[3] );
500 SG_LOG( SG_GENERAL, SG_BULK,
501 " sun_angle = " << l->sun_angle
502 << " moon_angle = " << l->moon_angle );
505 static SGSkyColor scolor;
506 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
508 scolor.sky_color = l->sky_color();
509 scolor.fog_color = l->adj_fog_color();
510 scolor.cloud_color = l->cloud_color();
511 scolor.sun_angle = l->get_sun_angle();
512 scolor.moon_angle = l->get_moon_angle();
513 scolor.nplanets = globals->get_ephem()->getNumPlanets();
514 scolor.nstars = globals->get_ephem()->getNumStars();
515 scolor.planet_data = globals->get_ephem()->getPlanets();
516 scolor.star_data = globals->get_ephem()->getStars();
518 thesky->repaint( scolor );
521 SG_LOG( SG_GENERAL, SG_BULK,
522 "thesky->reposition( view_pos = " << view_pos[0] << " "
523 << view_pos[1] << " " << view_pos[2] );
524 SG_LOG( SG_GENERAL, SG_BULK,
525 " zero_elev = " << zero_elev[0] << " "
526 << zero_elev[1] << " " << zero_elev[2]
527 << " lon = " << cur_fdm_state->get_Longitude()
528 << " lat = " << cur_fdm_state->get_Latitude() );
529 SG_LOG( SG_GENERAL, SG_BULK,
530 " sun_rot = " << l->get_sun_rotation
531 << " gst = " << SGTime::cur_time_params->getGst() );
532 SG_LOG( SG_GENERAL, SG_BULK,
533 " sun ra = " << globals->get_ephem()->getSunRightAscension()
534 << " sun dec = " << globals->get_ephem()->getSunDeclination()
535 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
536 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
539 // The sun and moon distances are scaled down versions
540 // of the actual distance to get both the moon and the sun
541 // within the range of the far clip plane.
542 // Moon distance: 384,467 kilometers
543 // Sun distance: 150,000,000 kilometers
544 double sun_horiz_eff, moon_horiz_eff;
545 if (fgGetBool("/sim/rendering/horizon-effect")) {
546 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
547 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
549 sun_horiz_eff = moon_horiz_eff = 1.0;
552 static SGSkyState sstate;
554 sstate.view_pos = current__view->get_view_pos();
555 sstate.zero_elev = current__view->get_zero_elev();
556 sstate.view_up = current__view->get_world_up();
557 sstate.lon = current__view->getLongitude_deg()
558 * SGD_DEGREES_TO_RADIANS;
559 sstate.lat = current__view->getLatitude_deg()
560 * SGD_DEGREES_TO_RADIANS;
561 sstate.alt = current__view->getAltitudeASL_ft()
563 sstate.spin = l->get_sun_rotation();
564 sstate.gst = globals->get_time_params()->getGst();
565 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
566 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
567 sstate.sun_dist = 50000.0 * sun_horiz_eff;
568 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
569 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
570 sstate.moon_dist = 40000.0 * moon_horiz_eff;
572 thesky->reposition( sstate, delta_time_sec );
575 glEnable( GL_DEPTH_TEST );
576 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
578 glFogi( GL_FOG_MODE, GL_EXP2 );
579 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
582 // set sun/lighting parameters
583 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
585 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
586 // we only update GL_AMBIENT for our lights we will never get
587 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
588 // explicitely to black.
589 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
591 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
592 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
593 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
595 // texture parameters
596 // glEnable( GL_TEXTURE_2D );
597 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
598 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
600 // glMatrixMode( GL_PROJECTION );
602 ssgSetFOV( current__view->get_h_fov(),
603 current__view->get_v_fov() );
606 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
607 - globals->get_scenery()->get_cur_elev();
610 scene_nearplane = 10.0f;
611 scene_farplane = 120000.0f;
613 scene_nearplane = groundlevel_nearplane->getDoubleValue();
614 scene_farplane = 120000.0f;
617 ssgSetNearFar( scene_nearplane, scene_farplane );
620 // Update any multiplayer models
621 globals->get_multiplayer_rx_mgr()->Update();
624 if ( draw_otw && skyblend )
626 // draw the sky backdrop
628 // we need a white diffuse light for the phase of the moon
629 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
631 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER, fog_exp2_density );
633 // return to the desired diffuse color
634 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
637 // draw the ssg scene
638 glEnable( GL_DEPTH_TEST );
640 ssgSetNearFar( scene_nearplane, scene_farplane );
642 if ( fgGetBool("/sim/rendering/wireframe") ) {
644 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
647 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
650 // This is a bit kludgy. Every 200 frames, do an extra
651 // traversal of the scene graph without drawing anything, but
652 // with the field-of-view set to 360x360 degrees. This
653 // ensures that out-of-range random objects that are not in
654 // the current view frustum will still be freed properly.
655 static int counter = 0;
657 if (counter == 200) {
660 // No need to put the near plane too close;
661 // this way, at least the aircraft can be
663 f.setNearFar(1000, 1000000);
665 ssgGetModelviewMatrix(m);
666 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
670 // change state for lighting here
672 // draw runway lighting
673 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
674 ssgSetNearFar( scene_nearplane, scene_farplane );
676 if ( enhanced_lighting ) {
678 // Enable states for drawing points with GL_extension
679 glEnable(GL_POINT_SMOOTH);
681 if ( distance_attenuation && glPointParameterIsSupported )
683 // Enable states for drawing points with GL_extension
684 glEnable(GL_POINT_SMOOTH);
686 float quadratic[3] = {1.0, 0.001, 0.0000001};
687 // makes the points fade as they move away
688 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
689 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
694 // blending function for runway lights
695 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
698 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
699 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
700 glEnable(GL_TEXTURE_GEN_S);
701 glEnable(GL_TEXTURE_GEN_T);
702 glPolygonMode(GL_FRONT, GL_POINT);
704 // draw runway lighting
706 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
707 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
710 // change punch through and then draw taxi lighting
711 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
713 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
714 // glFogfv ( GL_FOG_COLOR, taxi_fog );
716 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
720 glPolygonMode(GL_FRONT, GL_FILL);
721 glDisable(GL_TEXTURE_GEN_S);
722 glDisable(GL_TEXTURE_GEN_T);
724 //static int _frame_count = 0;
725 //if (_frame_count % 30 == 0) {
726 // printf("SSG: %s\n", ssgShowStats());
734 if ( enhanced_lighting ) {
735 if ( distance_attenuation && glPointParameterIsSupported )
737 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
738 default_attenuation);
742 glDisable(GL_POINT_SMOOTH);
745 // draw ground lighting
746 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
748 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
752 // draw the sky cloud layers
753 if ( draw_otw && fgGetBool("/environment/clouds/status") )
755 thesky->postDraw( cur_fdm_state->get_Altitude()
756 * SG_FEET_TO_METER );
760 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") )
763 glDisable( GL_LIGHTING );
764 // cout << "drawing new clouds" << endl;
766 glEnable(GL_DEPTH_TEST);
768 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
771 glEnable( GL_TEXTURE_2D );
772 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
773 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
774 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
775 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
778 #ifdef FG_USE_CLOUDS_3D
779 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
782 glEnable( GL_LIGHTING );
783 glEnable( GL_DEPTH_TEST );
784 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
788 globals->get_model_mgr()->draw();
789 globals->get_aircraft_model()->draw();
792 // display HUD && Panel
794 glDisable( GL_DEPTH_TEST );
795 // glDisable( GL_CULL_FACE );
796 // glDisable( GL_TEXTURE_2D );
798 // update the controls subsystem
799 globals->get_controls()->update(delta_time_sec);
801 hud_and_panel->apply();
804 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
805 // This only works properly if called before the panel call
806 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
807 globals->get_ATC_display()->update(delta_time_sec);
809 // update the panel subsystem
810 if ( globals->get_current_panel() != NULL ) {
811 globals->get_current_panel()->update(delta_time_sec);
815 // We can do translucent menus, so why not. :-)
817 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
819 // glDisable ( GL_BLEND ) ;
821 glEnable( GL_DEPTH_TEST );
824 // Fade out the splash screen over the first three seconds.
825 double t = globals->get_sim_time_sec();
827 fgSplashUpdate(0.0, 1.0);
828 } else if ( t <= 3.0) {
829 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
837 // Update internal time dependent calculations (i.e. flight model)
838 // FIXME: this distinction is obsolete; all subsystems now get delta
840 void fgUpdateTimeDepCalcs() {
841 static bool inited = false;
843 static const SGPropertyNode *replay_master
844 = fgGetNode( "/sim/freeze/replay", true );
845 static SGPropertyNode *replay_time
846 = fgGetNode( "/sim/replay/time", true );
847 static const SGPropertyNode *replay_end_time
848 = fgGetNode( "/sim/replay/end-time", true );
850 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
852 // Initialize the FDM here if it hasn't been and if we have a
853 // scenery elevation hit.
855 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
856 // << " cur_elev = " << scenery.get_cur_elev() << endl;
858 if ( !cur_fdm_state->get_inited() &&
859 globals->get_scenery()->get_cur_elev() > -9990 )
861 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
862 cur_fdm_state->init();
863 if ( cur_fdm_state->get_bound() ) {
864 cur_fdm_state->unbind();
866 cur_fdm_state->bind();
869 // conceptually, the following block could be done for each fdm
871 if ( cur_fdm_state->get_inited() ) {
872 // we have been inited, and we are good to go ...
878 if ( ! replay_master->getBoolValue() ) {
879 cur_fdm_state->update( delta_time_sec );
881 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
882 r->replay( replay_time->getDoubleValue() );
883 replay_time->setDoubleValue( replay_time->getDoubleValue()
885 * fgGetInt("/sim/speed-up") ) );
888 // do nothing, fdm isn't inited yet
891 globals->get_model_mgr()->update(delta_time_sec);
892 globals->get_aircraft_model()->update(delta_time_sec);
894 // update the view angle
895 globals->get_viewmgr()->update(delta_time_sec);
897 // Update solar system
898 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
899 globals->get_time_params()->getLst(),
900 cur_fdm_state->get_Latitude() );
902 // Update radio stack model
903 current_radiostack->update(delta_time_sec);
907 void fgInitTimeDepCalcs( void ) {
912 static const double alt_adjust_ft = 3.758099;
913 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
916 // What should we do when we have nothing else to do? Let's get ready
917 // for the next move and update the display?
918 static void fgMainLoop( void ) {
919 int model_hz = fgGetInt("/sim/model-hz");
921 static const SGPropertyNode *longitude
922 = fgGetNode("/position/longitude-deg");
923 static const SGPropertyNode *latitude
924 = fgGetNode("/position/latitude-deg");
925 static const SGPropertyNode *altitude
926 = fgGetNode("/position/altitude-ft");
927 static const SGPropertyNode *clock_freeze
928 = fgGetNode("/sim/freeze/clock", true);
929 static const SGPropertyNode *cur_time_override
930 = fgGetNode("/sim/time/cur-time-override", true);
931 static const SGPropertyNode *replay_master
932 = fgGetNode("/sim/freeze/replay", true);
934 // Update the elapsed time.
935 static bool first_time = true;
937 last_time_stamp.stamp();
941 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
942 if ( throttle_hz > 0.0 ) {
943 // simple frame rate throttle
944 double dt = 1000000.0 / throttle_hz;
945 current_time_stamp.stamp();
946 while ( current_time_stamp - last_time_stamp < dt ) {
947 current_time_stamp.stamp();
950 // run as fast as the app will go
951 current_time_stamp.stamp();
955 = double(current_time_stamp - last_time_stamp) / 1000000.0;
956 if ( clock_freeze->getBoolValue() ) {
959 delta_time_sec = real_delta_time_sec;
961 last_time_stamp = current_time_stamp;
962 globals->inc_sim_time_sec( delta_time_sec );
963 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
965 // These are useful, especially for Nasal scripts.
966 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
967 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
969 static long remainder = 0;
971 #ifdef FANCY_FRAME_COUNTER
975 static time_t last_time = 0;
976 static int frames = 0;
977 #endif // FANCY_FRAME_COUNTER
979 SGTime *t = globals->get_time_params();
981 globals->get_event_mgr()->update(delta_time_sec);
983 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
984 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
986 #if defined( ENABLE_PLIB_JOYSTICK )
987 // Read joystick and update control settings
988 // if ( fgGetString("/sim/control-mode") == "joystick" )
992 #elif defined( ENABLE_GLUT_JOYSTICK )
993 // Glut joystick support works by feeding a joystick handler
994 // function to glut. This is taken care of once in the joystick
995 // init routine and we don't have to worry about it again.
998 // Fix elevation. I'm just sticking this here for now, it should
999 // probably move eventually
1001 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
1002 scenery.get_cur_elev(),
1003 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1004 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1006 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
1007 scenery.get_cur_elev(),
1008 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
1009 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
1011 // cout << "Warp = " << globals->get_warp() << endl;
1014 static bool last_clock_freeze = false;
1016 if ( clock_freeze->getBoolValue() ) {
1017 // clock freeze requested
1018 if ( cur_time_override->getLongValue() == 0 ) {
1019 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1020 globals->set_warp( 0 );
1023 // no clock freeze requested
1024 if ( last_clock_freeze == true ) {
1025 // clock just unfroze, let's set warp as the difference
1026 // between frozen time and current time so we don't get a
1027 // time jump (and corresponding sky object and lighting
1029 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1030 fgSetLong( "/sim/time/cur-time-override", 0 );
1032 if ( globals->get_warp_delta() != 0 ) {
1033 globals->inc_warp( globals->get_warp_delta() );
1037 last_clock_freeze = clock_freeze->getBoolValue();
1039 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1040 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1041 cur_time_override->getLongValue(),
1042 globals->get_warp() );
1044 if (globals->get_warp_delta() != 0) {
1045 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1049 // update magvar model
1050 globals->get_mag()->update( longitude->getDoubleValue()
1051 * SGD_DEGREES_TO_RADIANS,
1052 latitude->getDoubleValue()
1053 * SGD_DEGREES_TO_RADIANS,
1054 altitude->getDoubleValue() * SG_FEET_TO_METER,
1055 globals->get_time_params()->getJD() );
1057 // Get elapsed time (in usec) for this past frame
1058 elapsed = fgGetTimeInterval();
1059 SG_LOG( SG_ALL, SG_DEBUG,
1060 "Elapsed time interval is = " << elapsed
1061 << ", previous remainder is = " << remainder );
1063 // Calculate frame rate average
1064 #ifdef FANCY_FRAME_COUNTER
1065 /* old fps calculation */
1066 if ( elapsed > 0 ) {
1069 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1070 tmp = general.get_frame(i);
1072 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1073 general.set_frame(i+1,tmp);
1075 tmp = 1000000.0 / (float)elapsed;
1076 general.set_frame(0,tmp);
1077 // printf("frame[0] = %.2f\n", general.frames[0]);
1079 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1080 // printf("ave = %.2f\n", general.frame_rate);
1083 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1084 general.set_frame_rate( frames );
1085 fgSetInt("/sim/frame-rate", frames);
1086 SG_LOG( SG_ALL, SG_DEBUG,
1087 "--> Frame rate is = " << general.get_frame_rate() );
1090 last_time = t->get_cur_time();
1094 // Run ATC subsystem
1095 if (fgGetBool("/sim/ATC/enabled"))
1096 globals->get_ATC_mgr()->update(delta_time_sec);
1098 // Run the AI subsystem
1099 if (fgGetBool("/sim/ai-traffic/enabled"))
1100 globals->get_AI_mgr()->update(delta_time_sec);
1104 // Calculate model iterations needed for next frame
1105 elapsed += remainder;
1107 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1108 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1109 SG_LOG( SG_ALL, SG_DEBUG,
1110 "Model iterations needed = " << global_multi_loop
1111 << ", new remainder = " << remainder );
1113 // chop max interations to something reasonable if the sim was
1114 // delayed for an excesive amount of time
1115 if ( global_multi_loop > 2.0 * model_hz ) {
1116 global_multi_loop = (int)(2.0 * model_hz );
1121 if ( global_multi_loop > 0 ) {
1122 fgUpdateTimeDepCalcs();
1124 SG_LOG( SG_ALL, SG_DEBUG,
1125 "Elapsed time is zero ... we're zinging" );
1128 // Do any I/O channel work that might need to be done
1129 globals->get_io()->update( real_delta_time_sec );
1131 // see if we need to load any deferred-load textures
1132 globals->get_matlib()->load_next_deferred();
1134 // Run audio scheduler
1135 #ifdef ENABLE_AUDIO_SUPPORT
1136 if ( fgGetBool("/sim/sound/audible")
1137 && globals->get_soundmgr()->is_working() ) {
1138 globals->get_soundmgr()->update( delta_time_sec );
1142 globals->get_subsystem_mgr()->update(delta_time_sec);
1145 // Tile Manager updates - see if we need to load any new scenery tiles.
1146 // this code ties together the fdm, viewer and scenery classes...
1147 // we may want to move this to it's own class at some point
1149 double visibility_meters = fgGetDouble("/environment/visibility-m");
1150 FGViewer *current_view = globals->get_current_view();
1152 // get the location data for the primary FDM (now hardcoded to ac model)...
1153 SGLocation * acmodel_location = 0;
1154 acmodel_location = (SGLocation *) globals->get_aircraft_model()->get3DModel()->getSGLocation();
1156 // update tile manager for FDM...
1157 // ...only if location is different than the current-view location (to avoid duplicating effort)
1158 if( !fgGetBool("/sim/current-view/config/from-model") ) {
1159 if( acmodel_location != 0 ) {
1160 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1161 visibility_meters );
1162 globals->get_tile_mgr()->
1163 update( acmodel_location, visibility_meters,
1164 acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1165 // save results of update in SGLocation for fdm...
1166 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1168 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1169 fgSetDouble("/position/ground-elev-m", globals->get_scenery()->get_cur_elev());
1172 set_tile_center( globals->get_scenery()->get_next_center() );
1176 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1177 visibility_meters );
1178 // update tile manager for view...
1179 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1180 // after the FDM's until all of Flight Gear code references the viewer's location
1181 // for elevation instead of the "scenery's" current elevation.
1182 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1183 globals->get_tile_mgr()->update( view_location, visibility_meters,
1184 current_view->get_absolute_view_pos() );
1185 // save results of update in SGLocation for fdm...
1186 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1187 current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1189 current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1191 // If fdm location is same as viewer's then we didn't do the update for fdm location
1192 // above so we need to save the viewer results in the fdm SGLocation as well...
1193 if( fgGetBool("/sim/current-view/config/from-model") ) {
1194 if( acmodel_location != 0 ) {
1195 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1196 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1197 fgSetDouble("/position/ground-elev-m", globals->get_scenery()->get_cur_elev());
1199 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1203 // END Tile Manager udpates
1205 if (fgGetBool("/sim/rendering/specular-highlight")) {
1206 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1207 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1209 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1210 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1216 SG_LOG( SG_ALL, SG_DEBUG, "" );
1220 // This is the top level master main function that is registered as
1221 // our idle funciton
1223 // The first few passes take care of initialization things (a couple
1224 // per pass) and once everything has been initialized fgMainLoop from
1227 static void fgIdleFunction ( void ) {
1228 // printf("idle state == %d\n", idle_state);
1230 if ( idle_state == 0 ) {
1231 // Initialize the splash screen right away
1232 if ( fgGetBool("/sim/startup/splash-screen") ) {
1233 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1237 } else if ( idle_state == 1 ) {
1238 // Initialize audio support
1239 #ifdef ENABLE_AUDIO_SUPPORT
1241 // Start the intro music
1242 if ( fgGetBool("/sim/startup/intro-music") ) {
1243 SGPath mp3file( globals->get_fg_root() );
1244 mp3file.append( "Sounds/intro.mp3" );
1246 SG_LOG( SG_GENERAL, SG_INFO,
1247 "Starting intro music: " << mp3file.str() );
1249 #if defined( __CYGWIN__ )
1250 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1251 #elif defined( WIN32 )
1252 string command = "start /m " + mp3file.str();
1254 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1257 system ( command.c_str() );
1262 } else if ( idle_state == 2 ) {
1263 // These are a few miscellaneous things that aren't really
1264 // "subsystems" but still need to be initialized.
1267 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1268 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1273 } else if ( idle_state == 3 ) {
1274 // This is the top level init routine which calls all the
1275 // other subsystem initialization routines. If you are adding
1276 // a subsystem to flightgear, its initialization call should
1277 // located in this routine.
1278 if( !fgInitSubsystems()) {
1279 SG_LOG( SG_GENERAL, SG_ALERT,
1280 "Subsystem initializations failed ..." );
1285 } else if ( idle_state == 4 ) {
1286 // Initialize the time offset (warp) after fgInitSubsystem
1287 // (which initializes the lighting interpolation tables.)
1290 // setup OpenGL view parameters
1293 // Read the list of available aircrafts
1297 } else if ( idle_state == 5 ) {
1300 } else if ( idle_state == 6 ) {
1305 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1306 fgReshape( fgGetInt("/sim/startup/xsize"),
1307 fgGetInt("/sim/startup/ysize") );
1311 if ( idle_state == 1000 ) {
1312 // We've finished all our initialization steps, from now on we
1313 // run the main loop.
1315 glutIdleFunc(fgMainLoop);
1317 if ( fgGetBool("/sim/startup/splash-screen") ) {
1318 fgSplashUpdate(0.0, 1.0);
1323 // options.cxx needs to see this for toggle_panel()
1324 // Handle new window size or exposure
1325 void fgReshape( int width, int height ) {
1328 if ( (!fgGetBool("/sim/virtual-cockpit"))
1329 && fgPanelVisible() && idle_state == 1000 ) {
1330 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1331 globals->get_current_panel()->getYOffset()) / 768.0);
1336 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1338 fgSetInt("/sim/startup/xsize", width);
1339 fgSetInt("/sim/startup/ysize", height);
1340 guiInitMouse(width, height);
1343 FGViewMgr *viewmgr = globals->get_viewmgr();
1345 for ( int i = 0; i < viewmgr->size(); ++i ) {
1346 viewmgr->get_view(i)->
1347 set_aspect_ratio((float)view_h / (float)width);
1350 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1351 viewmgr->get_current_view()->get_v_fov() );
1353 #ifdef FG_USE_CLOUDS_3D
1354 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1355 viewmgr->get_current_view()->get_v_fov() );
1363 // Initialize GLUT and define a main window
1364 static bool fgGlutInit( int *argc, char **argv ) {
1366 #if !defined( macintosh )
1367 // GLUT will extract all glut specific options so later on we only
1368 // need wory about our own.
1369 glutInit(argc, argv);
1372 // Define Display Parameters. Clouds3d works best with --bpp32 option
1373 if ( fgGetBool("/sim/rendering/clouds3d") ) {
1374 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA );
1376 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1379 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1380 fgGetInt("/sim/startup/xsize") << "x"
1381 << fgGetInt("/sim/startup/ysize") );
1383 // Define initial window size
1384 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1385 fgGetInt("/sim/startup/ysize") );
1387 // Initialize windows
1388 if ( !fgGetBool("/sim/startup/game-mode")) {
1389 // Open the regular window
1390 glutCreateWindow("FlightGear");
1391 #ifndef GLUT_WRONG_VERSION
1393 // Open the cool new 'game mode' window
1394 char game_mode_str[256];
1395 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1396 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1397 #ifndef ENUM_CURRENT_SETTINGS
1398 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1399 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1403 dm.dmSize = sizeof(DEVMODE);
1404 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1405 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1406 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1407 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1408 fgGetInt("/sim/startup/ysize") );
1409 sprintf( game_mode_str, "%dx%d:%d@%d",
1413 dm.dmDisplayFrequency );
1415 // Open the cool new 'game mode' window
1416 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1417 fgGetInt("/sim/startup/xsize"),
1418 fgGetInt("/sim/startup/ysize"),
1419 fgGetInt("/sim/rendering/bits-per-pixel"));
1421 #endif // HAVE_WINDOWS_H
1422 SG_LOG( SG_GENERAL, SG_INFO,
1423 "game mode params = " << game_mode_str );
1424 glutGameModeString( game_mode_str );
1425 glutEnterGameMode();
1426 #endif // GLUT_WRONG_VERSION
1429 // This seems to be the absolute earliest in the init sequence
1430 // that these calls will return valid info. Too bad it's after
1431 // we've already created and sized out window. :-(
1432 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1433 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1434 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1435 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1438 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1439 general.set_glMaxTexSize( tmp );
1440 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1442 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1443 general.set_glDepthBits( tmp );
1444 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1450 // Initialize GLUT event handlers
1451 static bool fgGlutInitEvents( void ) {
1452 // call fgReshape() on window resizes
1453 glutReshapeFunc( fgReshape );
1455 // keyboard and mouse callbacks are set in FGInput::init
1457 // call fgMainLoop() whenever there is
1458 // nothing else to do
1459 glutIdleFunc( fgIdleFunction );
1462 glutDisplayFunc( fgRenderFrame );
1467 // Main top level initialization
1468 bool fgMainInit( int argc, char **argv ) {
1470 #if defined( macintosh )
1471 freopen ("stdout.txt", "w", stdout );
1472 freopen ("stderr.txt", "w", stderr );
1473 argc = ccommand( &argv );
1476 // set default log levels
1477 sglog().setLogLevels( SG_ALL, SG_ALERT );
1480 #ifdef FLIGHTGEAR_VERSION
1481 version = FLIGHTGEAR_VERSION;
1483 version = "unknown version";
1485 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1487 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1489 // Allocate global data structures. This needs to happen before
1490 // we parse command line options
1492 globals = new FGGlobals;
1494 // seed the random number generater
1497 FGControls *controls = new FGControls;
1498 globals->set_controls( controls );
1500 string_list *col = new string_list;
1501 globals->set_channel_options_list( col );
1503 // Scan the config file(s) and command line options to see if
1504 // fg_root was specified (ignore all other options for now)
1505 fgInitFGRoot(argc, argv);
1507 // Check for the correct base package version
1508 static char required_version[] = "0.9.4";
1509 string base_version = fgBasePackageVersion();
1510 if ( !(base_version == required_version) ) {
1511 // tell the operator how to use this application
1513 SG_LOG( SG_GENERAL, SG_ALERT, endl << "Base package check failed ... " \
1514 << "Found version " << base_version << " at: " \
1515 << globals->get_fg_root() );
1516 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version: " << required_version );
1518 SG_LOG( SG_GENERAL, SG_ALERT, "Hit a key to continue..." );
1524 // Initialize the Aircraft directory to "" (UIUC)
1527 // Load the configuration parameters. (Command line options
1528 // overrides config file options. Config file options override
1530 if ( !fgInitConfig(argc, argv) ) {
1531 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1535 // Initialize the Window/Graphics environment.
1536 if( !fgGlutInit(&argc, argv) ) {
1537 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1541 // Initialize the various GLUT Event Handlers.
1542 if( !fgGlutInitEvents() ) {
1543 SG_LOG( SG_GENERAL, SG_ALERT,
1544 "GLUT event handler initialization failed ..." );
1548 // Initialize plib net interface
1549 netInit( &argc, argv );
1551 // Initialize ssg (from plib). Needs to come before we do any
1552 // other ssg stuff, but after opengl/glut has been initialized.
1555 // Initialize the user interface (we need to do this before
1556 // passing off control to glut and before fgInitGeneral to get our
1560 // Read the list of available aircrafts
1563 #ifdef GL_EXT_texture_lod_bias
1564 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1567 // get the address of our OpenGL extensions
1568 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1570 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1571 glPointParameterIsSupported = true;
1572 glPointParameterfPtr = (glPointParameterfProc)
1573 SGLookupFunction("glPointParameterfEXT");
1574 glPointParameterfvPtr = (glPointParameterfvProc)
1575 SGLookupFunction("glPointParameterfvEXT");
1577 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1578 glPointParameterIsSupported = true;
1579 glPointParameterfPtr = (glPointParameterfProc)
1580 SGLookupFunction("glPointParameterfARB");
1581 glPointParameterfvPtr = (glPointParameterfvProc)
1582 SGLookupFunction("glPointParameterfvARB");
1584 glPointParameterIsSupported = false;
1587 // based on the requested presets, calculate the true starting
1592 SGTime *t = fgInitTime();
1593 globals->set_time_params( t );
1595 // Do some quick general initializations
1596 if( !fgInitGeneral()) {
1597 SG_LOG( SG_GENERAL, SG_ALERT,
1598 "General initializations failed ..." );
1602 ////////////////////////////////////////////////////////////////////
1603 // Initialize the property-based built-in commands
1604 ////////////////////////////////////////////////////////////////////
1607 ////////////////////////////////////////////////////////////////////
1608 // Initialize the material manager
1609 ////////////////////////////////////////////////////////////////////
1610 globals->set_matlib( new SGMaterialLib );
1612 globals->set_model_lib(new SGModelLib);
1614 ////////////////////////////////////////////////////////////////////
1615 // Initialize the TG scenery subsystem.
1616 ////////////////////////////////////////////////////////////////////
1617 globals->set_scenery( new FGScenery );
1618 globals->get_scenery()->init();
1619 globals->get_scenery()->bind();
1620 globals->set_tile_mgr( new FGTileMgr );
1622 ////////////////////////////////////////////////////////////////////
1623 // Initialize the general model subsystem.
1624 ////////////////////////////////////////////////////////////////////
1625 globals->set_model_mgr(new FGModelMgr);
1626 globals->get_model_mgr()->init();
1627 globals->get_model_mgr()->bind();
1629 ////////////////////////////////////////////////////////////////////
1630 // Initialize the 3D aircraft model subsystem (has a dependency on
1631 // the scenery subsystem.)
1632 ////////////////////////////////////////////////////////////////////
1633 globals->set_aircraft_model(new FGAircraftModel);
1634 globals->get_aircraft_model()->init();
1635 globals->get_aircraft_model()->bind();
1637 ////////////////////////////////////////////////////////////////////
1638 // Initialize the view manager subsystem.
1639 ////////////////////////////////////////////////////////////////////
1640 FGViewMgr *viewmgr = new FGViewMgr;
1641 globals->set_viewmgr( viewmgr );
1646 // Initialize the sky
1647 SGPath ephem_data_path( globals->get_fg_root() );
1648 ephem_data_path.append( "Astro" );
1649 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1650 ephem->update( globals->get_time_params()->getMjd(),
1651 globals->get_time_params()->getLst(),
1653 globals->set_ephem( ephem );
1655 // TODO: move to environment mgr
1657 SGPath texture_path(globals->get_fg_root());
1658 texture_path.append("Textures");
1659 texture_path.append("Sky");
1660 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1661 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1662 thesky->add_cloud_layer(layer);
1665 SGPath sky_tex_path( globals->get_fg_root() );
1666 sky_tex_path.append( "Textures" );
1667 sky_tex_path.append( "Sky" );
1668 thesky->texture_path( sky_tex_path.str() );
1670 // The sun and moon diameters are scaled down numbers of the
1671 // actual diameters. This was needed to fit bot the sun and the
1672 // moon within the distance to the far clip plane.
1673 // Moon diameter: 3,476 kilometers
1674 // Sun diameter: 1,390,000 kilometers
1675 thesky->build( 80000.0, 80000.0,
1677 globals->get_ephem()->getNumPlanets(),
1678 globals->get_ephem()->getPlanets(),
1679 globals->get_ephem()->getNumStars(),
1680 globals->get_ephem()->getStars() );
1682 // Initialize MagVar model
1683 SGMagVar *magvar = new SGMagVar();
1684 globals->set_mag( magvar );
1687 // kludge to initialize mag compass
1688 // (should only be done for in-flight
1690 // update magvar model
1691 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1692 * SGD_DEGREES_TO_RADIANS,
1693 fgGetDouble("/position/latitude-deg")
1694 * SGD_DEGREES_TO_RADIANS,
1695 fgGetDouble("/position/altitude-ft")
1697 globals->get_time_params()->getJD() );
1698 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1699 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1701 // airport = new ssgBranch;
1702 // airport->setName( "Airport Lighting" );
1703 // lighting->addKid( airport );
1705 // build our custom render states
1706 fgBuildRenderStates();
1708 // pass control off to the master GLUT event handler
1711 // we never actually get here ... but to avoid compiler warnings,